prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>stdlib.js<|end_file_name|><|fim▁begin|>var NULL = null; function NOP() {} function NOT_IMPLEMENTED() { throw new Error("not implemented."); } function int(x) { return x|0; } function pointer(src, offset, length) { offset = src.byteOffset + offset * src.BYTES_PER_ELEMENT; if (typeof length === "number") { return new src.constructor(src.buffer, offset, length); } else { return new src.constructor(src.buffer, offset); } } var uint8 = 0; var int32 = 1; function calloc(n, type) { switch (type) { case uint8: return new Uint8Array(n); case int32: return new Int32Array(n); }<|fim▁hole|> function realloc(src, newSize) { var ret = new src.constructor(newSize); ret.set(src); return ret; } function copy(dst, src, offset) { dst.set(src, offset||0); }<|fim▁end|>
throw new Error("calloc failed."); }
<|file_name|>basecalloptimizer.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # # qooxdoo - the new era of web development # # http://qooxdoo.org # # Copyright: # 2006-2008 1&1 Internet AG, Germany, http://www.1und1.de # # License: # LGPL: http://www.gnu.org/licenses/lgpl.html # EPL: http://www.eclipse.org/org/documents/epl-v10.php # See the LICENSE file in the project's top-level directory for details. # # Authors: # * Sebastian Werner (wpbasti) # * Fabian Jakobs (fjakobs) # * Thomas Herchenroeder (thron7) # ################################################################################ import re, sys from ecmascript.frontend import tree, treeutil ## # Run through all the qx.*.define nodes of a tree. This will cover multiple # classes defined in single file, as well as nested calls to qx.*.define. # # - interface function def patch(node): patchCount = 0 classDefNodes = list(treeutil.findQxDefineR(node)) for classDefNode in classDefNodes: patchCount += optimize(classDefNode, classDefNodes,) return patchCount ## # Optimize a single class definition; treats 'construct' and 'member' sections def optimize(classDefine, classDefNodes): patchCount = 0 # get class map try: classMap = treeutil.getClassMap(classDefine) except tree.NodeAccessException: # this might happen when the second param is not a map literal return 0 if not "extend" in classMap: return 0 if classMap["extend"].type == "variable": superClass = treeutil.assembleVariable(classMap["extend"])[0] else: return 0 # interfaces can have a list-valued "extend", but we currently don't optimize those if "construct" in classMap: patchCount = optimizeConstruct(classMap["construct"], superClass, "construct", classDefNodes) if not "members" in classMap: return patchCount members = classMap["members"] for methodName, methodNode in members.items(): patchCount += optimizeConstruct(methodNode, superClass, methodName, classDefNodes) return patchCount ## # Optimize calls to this.base in a tree (e.g. a method); this will skip nested # calls to qx.*.define, as they are handled on a higher level def optimizeConstruct(node, superClass, methodName, classDefNodes): patchCount = 0 # Need to run through all the nodes, to skip embedded qx.*.define(), # which will be treated separately # Handle Node # skip embedded qx.*.define() if node in classDefNodes: return 0 elif node.type == "variable" and node.hasParentContext("call/operand"): varName, complete = treeutil.assembleVariable(node) if not (complete and varName == "this.base"): return 0 call = node.parent.parent try: firstArgName = treeutil.selectNode(call, "params/1/identifier/@name") except tree.NodeAccessException: return 0 if firstArgName != "arguments": return 0 # "construct" if methodName == "construct":<|fim▁hole|> else: newCall = treeutil.compileString("%s.prototype.%s.call()" % (superClass, methodName)) newCall.replaceChild(newCall.getChild("params"), call.getChild("params")) # replace with old arglist treeutil.selectNode(newCall, "params/1/identifier").set("name", "this") # arguments -> this call.parent.replaceChild(call, newCall) patchCount += 1 # Handle Children if node.hasChildren(): for child in node.children: patchCount += optimizeConstruct(child, superClass, methodName, classDefNodes) return patchCount if __name__ == "__main__": cls = """qx.Class.define("qx.Car", { extend: qx.core.Object, construct : function() { this.base(arguments, "2") }, members : { foo : function() { return this.base(arguments) } } })""" node = treeutil.compileString(cls) patch(node) print node.toJavascript()<|fim▁end|>
newCall = treeutil.compileString("%s.call()" % superClass) # "member"
<|file_name|>MainActivity.java<|end_file_name|><|fim▁begin|>package com.example.a226; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { EditText et; @Override protected void onCreate(Bundle savedInstanceState) {<|fim▁hole|> super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button b = (Button) findViewById(R.id.button1); et = (EditText) findViewById(R.id.EditText1); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String s = et.getText().toString(); Intent intent = new Intent("com.example.translate"); intent.putExtra("word", s); startActivity(intent); } }); } }<|fim▁end|>
<|file_name|>ofc_utils.py<|end_file_name|><|fim▁begin|>from suds.client import Client from nova import exception from nova import db import logging logging.getLogger('suds').setLevel(logging.INFO) def update_for_run_instance(service_url, region_name, server_port1, server_port2, dpid1, dpid2): # check region name client = Client(service_url + "?wsdl") client.service.setServerPort(dpid1, server_port1, region_name) client.service.setServerPort(dpid2, server_port2, region_name) client.service.save() def update_for_terminate_instance(service_url, region_name, server_port1, server_port2, dpid1, dpid2, vlan_id): client = Client(service_url + "?wsdl") client.service.clearServerPort(dpid1, server_port1) client.service.clearServerPort(dpid2, server_port2) client.service.save() dpid_datas = client.service.showSwitchDatapathId() for dpid_data in dpid_datas: ports = client.service.showPorts(dpid_data.dpid) for port in ports: if port.type != "ServerPort": continue if port.regionName == region_name: return remove_region(service_url, region_name, vlan_id) def create_region(service_url, region_name, vlan_id): client = Client(service_url + "?wsdl") try: client.service.createRegion(region_name) client.service.save() except: raise exception.OFCRegionCreationFailed(region_name=region_name) try: switches = db.switch_get_all(None) for switch in switches: client.service.setOuterPortAssociationSetting(switch["dpid"], switch["outer_port"], vlan_id, 65535, region_name) client.service.save() except: client.service.destroyRegion(region_name) client.service.save() raise exception.OFCRegionSettingOuterPortAssocFailed(region_name=region_name, vlan_id=vlan_id) def remove_region(service_url, region_name, vlan_id): client = Client(service_url + "?wsdl") try: switches = db.switch_get_all(None) for switch in switches: client.service.clearOuterPortAssociationSetting(switch["dpid"], switch["outer_port"], vlan_id) client.service.save() except: pass client.service.destroyRegion(region_name) client.service.save()<|fim▁hole|> client = Client(service_url + "?wsdl") return region_name in [x.regionName for x in client.service.showRegion()]<|fim▁end|>
def has_region(service_url, region_name):
<|file_name|>basewidget.py<|end_file_name|><|fim▁begin|>from pygame.sprite import DirtySprite from pygame import draw class BaseWidget(DirtySprite): """clase base para todos los widgets""" focusable = True # si no es focusable, no se le llaman focusin y focusout # (por ejemplo, un contenedor, una etiqueta de texto) hasFocus = False # indica si el widget está en foco o no. enabled = True # un widget con enabled==False no recibe ningun evento nombre = '' # identifica al widget en el renderer hasMouseOver = False # indica si el widget tuvo el mouse encima o no, por el onMouseOut opciones = None # las opciones con las que se inicializo setFocus_onIn = False # if True: Renderer.setFocus se dispara onMouseIn también. KeyCombination = '' layer = 0 rect = None x, y = 0, 0 def __init__(self, parent=None, **opciones): if parent is not None: self.parent = parent self.layer = self.parent.layer + 1 self.opciones = opciones super().__init__() def on_focus_in(self): self.hasFocus = True def on_focus_out(self): self.hasFocus = False def on_mouse_down(self, mousedata): pass def on_mouse_up(self, mousedata): pass def on_mouse_over(self): pass def on_mouse_in(self): self.hasMouseOver = True def on_mouse_out(self): self.hasMouseOver = False <|fim▁hole|> pass def on_destruction(self): # esta funcion se llama cuando el widget es quitado del renderer. pass @staticmethod def _biselar(imagen, color_luz, color_sombra): w, h = imagen.get_size() draw.line(imagen, color_sombra, (0, h - 2), (w - 1, h - 2), 2) draw.line(imagen, color_sombra, (w - 2, h - 2), (w - 2, 0), 2) draw.lines(imagen, color_luz, 0, [(w - 2, 0), (0, 0), (0, h - 4)], 2) return imagen def reubicar_en_ventana(self, dx=0, dy=0): self.rect.move_ip(dx, dy) self.x += dx self.y += dy self.dirty = 1 def __repr__(self): return self.nombre def is_visible(self): return self._visible<|fim▁end|>
def on_key_down(self, keydata): pass def on_key_up(self, keydata):
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import functools<|fim▁hole|>import pfp.interp def native(name, ret, interp=None, send_interp=False): """Used as a decorator to add the decorated function to the pfp interpreter so that it can be used from within scripts. :param str name: The name of the function as it will be exposed in template scripts. :param pfp.fields.Field ret: The return type of the function (a class) :param pfp.interp.PfpInterp interp: The specific interpreter to add the function to :param bool send_interp: If the current interpreter should be passed to the function. Examples: The example below defines a ``Sum`` function that will return the sum of all parameters passed to the function: :: from pfp.fields import PYVAL @native(name="Sum", ret=pfp.fields.Int64) def sum_numbers(params, ctxt, scope, stream, coord): res = 0 for param in params: res += PYVAL(param) return res The code below is the code for the :any:`Int3 <pfp.native.dbg.int3>` function. Notice that it requires that the interpreter be sent as a parameter: :: @native(name="Int3", ret=pfp.fields.Void, send_interp=True) def int3(params, ctxt, scope, stream, coord, interp): if interp._no_debug: return if interp._int3: interp.debugger = PfpDbg(interp) interp.debugger.cmdloop() """ def native_decorator(func): @functools.wraps(func) def native_wrapper(*args, **kwargs): return func(*args, **kwargs) pfp.interp.PfpInterp.add_native(name, func, ret, interp=interp, send_interp=send_interp) return native_wrapper return native_decorator def predefine(template): pfp.interp.PfpInterp.add_predefine(template)<|fim▁end|>
<|file_name|>broker_reader_test.cpp<|end_file_name|><|fim▁begin|>// Licensed to the Apache Software Foundation (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 // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations<|fim▁hole|>#include <gtest/gtest.h> #include <map> #include <string> #include <vector> #include "common/status.h" #include "gen_cpp/PaloBrokerService_types.h" #include "gen_cpp/PaloBrokerService_types.h" #include "gen_cpp/TPaloBrokerService.h" #include "util/cpu_info.h" #include "util/stopwatch.hpp" namespace doris { class RuntimeState; class BrokerReaderTest : public testing::Test { public: BrokerReaderTest() { init(); } void init(); protected: virtual void SetUp() { } virtual void TearDown() { } private: ExecEnv* _env; std::map<std::string, std::string> _properties; std::vector<TNetworkAddress> _addresses; }; void BrokerReaderTest::init() { _properties["username"] = "root"; _properties["password"] = "passwd"; TNetworkAddress addr; addr.__set_hostname("host"); addr.__set_port(9999); _addresses.push_back(addr); } TEST_F(BrokerReaderTest, normal) { std::string path = "hdfs://host:port/dir"; BrokerReader reader(_env, _addresses, _properties, path, 0); auto st = reader.open(); ASSERT_TRUE(st.ok()); uint8_t buf[128 * 1024]; MonotonicStopWatch watch; watch.start(); bool eof = false; size_t total_size = 0; while (!eof) { size_t buf_len = 128 * 1024; st = reader.read(buf, &buf_len, &eof); ASSERT_TRUE(st.ok()); total_size += buf_len; } LOG(INFO) << "get from broker " << total_size << " bytes using " << watch.elapsed_time(); } } // end namespace doris int main(int argc, char** argv) { // std::string conffile = std::string(getenv("DORIS_HOME")) + "/conf/be.conf"; // if (!doris::config::init(conffile.c_str(), false)) { // fprintf(stderr, "error read config file. \n"); // return -1; // } // doris::init_glog("be-test"); doris::CpuInfo::init(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<|fim▁end|>
// under the License. #include "exec/broker_reader.h"
<|file_name|>scorers.py<|end_file_name|><|fim▁begin|>''' Auxiliary code providing vector-valued scoring functions for convenient use in the parameter-free Ladder Mechanism. Original algorithm by Avrim Blum and Moritz Hardt Python implementation by Jamie Hall and Moritz Hardt MIT License ''' from sklearn.utils import check_consistent_length from functools import wraps import numpy as np def validate_input(metric): @wraps(metric) def wrapped(y, y_pred): _check_y_shapes(y, y_pred) return metric(y, y_pred) return wrapped @validate_input def squared_error(y, y_pred): return ((y - y_pred)**2) @validate_input def absolute_error(y, y_pred): return np.abs(y-y_pred) @validate_input def zero_one_loss(y, y_pred): return np.sum(y != y_pred) def _check_y_shapes(y_true, y_pred): ''' Check that two target vectors are compatible. This is based on sklearn's validation in sklearn.metrics.regression._check_reg_targets and sklearn.metrics.classification._check_targets. ''' check_consistent_length(y_true, y_pred) if y_true.ndim == 1: y_true = y_true.reshape((-1, 1)) if y_pred.ndim == 1: y_pred = y_pred.reshape((-1, 1)) if y_true.shape[1] != y_pred.shape[1]: raise ValueError("y_true and y_pred have different number of output "<|fim▁hole|><|fim▁end|>
"({0}!={1})".format(y_true.shape[1], y_pred.shape[1]))
<|file_name|>sql.rs<|end_file_name|><|fim▁begin|>use std::str::FromStr; use crate::parsers::parser; pub use crate::parsers::sql::clause::Limit; pub use crate::parsers::sql::clause::OrderBy; use crate::parsers::sql::Field; pub use crate::parsers::sql::WhereCond; #[derive(Debug, Default, Clone, PartialEq)] pub struct Sql { pub select_clause: Vec<Field>, pub calc_clause: Vec<Field>, pub from_clause: Vec<Field>, pub left_join_clause: Vec<Field>, pub where_clause: Option<Box<WhereCond>>, pub orderby: Option<OrderBy>, pub limit: Option<Limit>, } <|fim▁hole|> fn from_str(s: &str) -> anyhow::Result<Self> { parser::select_statement::from_str(s) } }<|fim▁end|>
impl FromStr for Sql { type Err = anyhow::Error;
<|file_name|>Helpers.ts<|end_file_name|><|fim▁begin|>import { Assertions, Mouse, UiFinder } from '@ephox/agar'; import { Obj, Type } from '@ephox/katamari'; import { Attribute, Checked, Class, Focus, SugarBody, SugarElement, Traverse, Value } from '@ephox/sugar'; import { assert } from 'chai'; import Editor from 'tinymce/core/api/Editor'; export interface ImageDialogData { src: {<|fim▁hole|> value: string; }; alt: string; title: string; decorative: boolean; dimensions: { width: string; height: string; }; caption: boolean; class: string; border: string; hspace: string; vspace: string; borderstyle: string; } export const generalTabSelectors = { src: 'label.tox-label:contains("Source") + div.tox-form__controls-h-stack div.tox-control-wrap input.tox-textfield', title: 'label.tox-label:contains("Image title") + input.tox-textfield', alt: 'label.tox-label:contains("Alternative description") + input.tox-textfield', width: 'div.tox-form__controls-h-stack div label:contains("Width") + input.tox-textfield', height: 'div.tox-form__controls-h-stack div label:contains("Height") + input.tox-textfield', caption: 'label.tox-label:contains("Caption") + label input.tox-checkbox__input', class: 'label.tox-label:contains("Class") + div.tox-listboxfield > .tox-listbox', images: 'label.tox-label:contains("Image list") + div.tox-listboxfield > .tox-listbox', decorative: 'label.tox-label:contains("Accessibility") + label.tox-checkbox>input' }; export const advancedTabSelectors = { border: 'label.tox-label:contains("Border width") + input.tox-textfield', hspace: 'label.tox-label:contains("Horizontal space") + input.tox-textfield', vspace: 'label.tox-label:contains("Vertical space") + input.tox-textfield', borderstyle: 'label.tox-label:contains("Border style") + div.tox-listboxfield > .tox-listbox' }; const isObjWithValue = (value: ImageDialogData[keyof ImageDialogData]): value is { value: string } => Type.isObject(value) && Obj.has(value as Record<string, any>, 'value'); const gotoAdvancedTab = (): void => { const tab = UiFinder.findIn(SugarBody.body(), 'div.tox-tab:contains(Advanced)').getOrDie(); Mouse.click(tab); }; const setFieldValue = (selector: string, value: string | boolean): SugarElement<HTMLElement> => { const element = UiFinder.findIn<HTMLInputElement>(SugarBody.body(), selector).getOrDie(); Focus.focus(element); if (element.dom.type === 'checkbox' && Type.isBoolean(value)) { Checked.set(element, value); } else if (Class.has(element, 'tox-listbox')) { Attribute.set(element, 'data-value', value); } else { Value.set(element, String(value)); } return element; }; const setTabFieldValues = (data: Partial<ImageDialogData>, tabSelectors: Record<string, string>): void => { Obj.each(tabSelectors, (value, key: keyof Omit<ImageDialogData, 'dimensions'>) => { if (Obj.has(data, key)) { const obj = data[key]; const newValue = isObjWithValue(obj) ? obj.value : obj; setFieldValue(tabSelectors[key], newValue); } else if (Obj.has(data, 'dimensions') && Obj.has(data.dimensions as Record<string, string>, key)) { setFieldValue(tabSelectors[key], data.dimensions[key]); } }); }; const fillActiveDialog = (data: Partial<ImageDialogData>, hasAdvanced = false): void => { setTabFieldValues(data, generalTabSelectors); if (hasAdvanced) { gotoAdvancedTab(); setTabFieldValues(data, advancedTabSelectors); } }; const fakeEvent = (elm: SugarElement<Node>, name: string): void => { const evt = document.createEvent('HTMLEvents'); evt.initEvent(name, true, true); elm.dom.dispatchEvent(evt); }; const setInputValue = (selector: string, value: string): SugarElement<HTMLElement> => { const field = setFieldValue(selector, value); fakeEvent(field, 'input'); return field; }; const setSelectValue = (selector: string, value: string): SugarElement<HTMLElement> => { const field = setFieldValue(selector, value); fakeEvent(field, 'change'); return field; }; const cleanHtml = (html: string): string => html.replace(/<p>(&nbsp;|<br[^>]+>)<\/p>$/, ''); const assertCleanHtml = (label: string, editor: Editor, expected: string): void => Assertions.assertHtml(label, expected, cleanHtml(editor.getContent())); const assertInputValue = (selector: string, expected: string): void => { const element = UiFinder.findIn<HTMLInputElement>(SugarBody.body(), selector).getOrDie(); const value = Value.get(element); assert.equal(value, expected, `input value should be ${expected}`); }; const assertInputCheckbox = (selector: string, expectedState: boolean): void => { const element = UiFinder.findIn<HTMLInputElement>(SugarBody.body(), selector).getOrDie(); const value = Checked.get(element); assert.equal(value, expectedState, `input value should be ${expectedState}`); }; const pSetListBoxItem = async (selector: string, itemText: string): Promise<void> => { const listBox = UiFinder.findIn(SugarBody.body(), selector).getOrDie(); Mouse.click(listBox); await UiFinder.pWaitForVisible('Wait for list to open', SugarBody.body(), '.tox-menu.tox-collection--list'); const item = UiFinder.findIn(SugarBody.body(), '.tox-collection__item-label:contains(' + itemText + ')').getOrDie(); const itemParent = Traverse.parent(item).getOrDie('Failed to find list box item parent'); Mouse.click(itemParent); }; export { fillActiveDialog, fakeEvent, setInputValue, setSelectValue, assertCleanHtml, assertInputValue, assertInputCheckbox, pSetListBoxItem };<|fim▁end|>
<|file_name|>index.controller.js<|end_file_name|><|fim▁begin|>(function() {<|fim▁hole|> angular.module('newApp') .controller('newAppCtrl', newAppCtrl); function newAppCtrl() { } })();<|fim▁end|>
'use strict';
<|file_name|>NotificationWorker.java<|end_file_name|><|fim▁begin|>/** * The MIT License (MIT) * * Copyright (c) 2015 Vincent Vergnolle * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.vas.notification; import java.time.LocalDateTime; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.vas.domain.repository.Address; import org.vas.domain.repository.User; import org.vas.notification.domain.repository.NotificationService; /** * Notification worker for limited users * */ public class NotificationWorker implements Runnable { <|fim▁hole|> protected final Logger logger = LoggerFactory.getLogger(getClass()); protected final List<User> users; protected final Notifier notifier; protected final NotificationService notificationService; public NotificationWorker(List<User> users, NotificationService notificationService, Notifier notifier) { super(); this.users = users; this.notifier = notifier; this.notificationService = notificationService; } @Override public void run() { if(logger.isTraceEnabled()) { logger.trace("Start worker with {} users", users); } users.forEach(this::notifyUser); } protected void notifyUser(User user) { user.addresses.forEach((address) -> notifyAddress(user, address)); } protected void notifyAddress(User user, Address address) { if(logger.isTraceEnabled()) { logger.trace("Notify address {} - {}", user.username, address.label); } notificationService.listByAddress(address).forEach(notif -> doNotify(user, address, notif)); } protected void doNotify(User user, Address address, Notification notification) { if(notification.isTime(LocalDateTime.now())) { dispatch(user, address, notification); } } protected void dispatch(User user, Address address, Notification notification) { if(logger.isTraceEnabled()) { logger.trace("Dispatch notification n-{}", notification.id); } notifier.dispatch(user, address, notification); } }<|fim▁end|>
<|file_name|>product-info.controller.js<|end_file_name|><|fim▁begin|>angular.module('elementBoxApp.products.productInfo') .controller('ProductInfoCtrl', [ '$scope', '$rootScope', '$state', '$stateParams', '$timeout', 'ModalAlert', 'ProductsService', 'UserService', 'CommentsService', 'EVENT_NAMES', function($scope, $rootScope, $state, $stateParams, $timeout, ModalAlert, ProductsService, UserService, CommentsService, EVENT_NAMES) { $scope.slides = []; $scope.slidesIndex = 0; $scope.userHasRated = false; $scope.rateVal = null; $scope.newComment = ''; $scope.commentSent = false; var ratingInProcess = false; $rootScope.$emit('title', 'TITLE_MY_PRODUCT_INFO'); // Comments pagination: $scope.comments = []; $scope.commentsData = { page: 1, pageSize: 3, totalPages: 0, totalComments: 0 }; var onNeedToLogin = function() { ModalAlert.alert({ title: 'PRODUCTS.PLEASE_SIGNIN', msg: 'PRODUCTS.PLEASE_SIGNIN_TO_ACCESS' }); }; // $scope.myInterval = 5000; // $scope.slides2 = []; // Fetching product: $scope.product = ProductsService.get({ id: $stateParams.productId }, function(p) { // success cbk. p.images = p.images ? p.images : []; p.images.forEach(function(image, index) { $scope.slides.push({ url: image.url, index: index+1 }); }); // p.rating.value = parseInt(p.rating.value); }, function(err) { // error cbk. $state.go('main.products.info-404'); }); $scope.fetchPage = function() { CommentsService.query({ prodId: $stateParams.productId, page: $scope.commentsData.page, pageSize: $scope.commentsData.pageSize }) .$promise.then(function(res) { $scope.comments = res.results; $scope.commentsData.page = res.page; $scope.commentsData.totalPages = res.totalPages; $scope.commentsData.totalComments = res.total; $scope.commentsData.pageSize = res.pageSize; }); }; $scope.addComment = function(commentTxt) { if (!commentTxt || !commentTxt.trim()) { return; } if (!$scope.currentUser || !$scope.currentUser.id) { onNeedToLogin(); return; } var newComment = { prodId: $stateParams.productId, text: commentTxt }; CommentsService.save(newComment, function(data) { $scope.fetchPage(); $rootScope.$emit(EVENT_NAMES.addComment, newComment); $scope.newComment = '';<|fim▁hole|> }); }; $scope.$watch('commentsData.page', function(newVal, oldVal) { $scope.fetchPage(); }); $scope.rate = function(val) { if ($scope.rateVal || ratingInProcess) { return; } if (!$scope.currentUser || !$scope.currentUser.id) { onNeedToLogin(); return; } ratingInProcess = true; ProductsService.rate({_id: $scope.product._id, rating: val}, function() { // success cbk. $scope.userHasRated = true; $scope.rateVal = val; ratingInProcess = false; }, function() { // err cbk. ratingInProcess = false; }); }; $scope.addToWishList = function() { if (!$scope.currentUser || !$scope.currentUser.id) { return onNeedToLogin(); } UserService.addToWishList({ prodId: $scope.product._id }, function() { $rootScope.$emit(EVENT_NAMES.addWishList, $scope.product); }); }; $scope.removeFromWishList = function() { UserService.removeFromWishList({ itemId: $scope.product._id }, function() { $rootScope.$emit(EVENT_NAMES.removeWishList, $scope.product); }); }; $scope.hasWishListedProduct = function() { if (!$scope.currentUser || !$scope.product) { return false; } if (!$scope.currentUser.wishList) { $scope.currentUser.wishList = []; } return $scope.currentUser.wishList.indexOf($scope.product._id) >= 0; }; // $scope.fetchPage(); // fetching first page. } ]);<|fim▁end|>
$scope.commentSent = true;
<|file_name|>pointCloudJsonUtils.js<|end_file_name|><|fim▁begin|>// COPYRIGHT © 2017 Esri // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // This material is licensed for use under the Esri Master License // Agreement (MLA), and is bound by the terms of that agreement. // You may redistribute and use this code without modification, // provided you adhere to the terms of the MLA and include this // copyright notice. // // See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english // // For additional information, contact: // Environmental Systems Research Institute, Inc. // Attn: Contracts and Legal Services Department // 380 New York Street // Redlands, California, USA 92373 // USA // // email: contracts@esri.com // // See http://js.arcgis.com/4.4/esri/copyright.txt for details.<|fim▁hole|>define(["require","exports","../../core/Warning","../PointCloudClassBreaksRenderer","../PointCloudRGBRenderer","../PointCloudStretchRenderer","../PointCloudUniqueValueRenderer"],function(e,r,n,o,t,u,d){function i(e){return e?a[e.type]||null:null}function l(e,r,o){var t=i(e);if(t){var u=new t;return u.read(e,o),u}return o&&o.messages&&e&&o.messages.push(new n("renderer:unsupported","Renderers of type '"+(e.type||"unknown")+"' are not supported",{definition:e,context:o})),null}function s(e){var r=i(e);return r?r.fromJSON(e):null}Object.defineProperty(r,"__esModule",{value:!0});var a={pointCloudClassBreaksRenderer:o,pointCloudRGBRenderer:t,pointCloudStretchRenderer:u,pointCloudUniqueValueRenderer:d};r.read=l,r.fromJSON=s});<|fim▁end|>
<|file_name|>UseDefaultArchivesAction.java<|end_file_name|><|fim▁begin|>/******************************************************************************* * Copyright (c) 2010 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.trends.databrowser2.propsheet; import org.csstudio.swt.rtplot.undo.UndoableActionManager; import org.csstudio.trends.databrowser2.Activator; import org.csstudio.trends.databrowser2.Messages; import org.csstudio.trends.databrowser2.model.PVItem; import org.csstudio.trends.databrowser2.preferences.Preferences; import org.eclipse.jface.action.Action; /** Action that configures PVs to use default archive data sources. * @author Kay Kasemir */ public class UseDefaultArchivesAction extends Action { final private UndoableActionManager operations_manager; final private PVItem pvs[]; /** Initialize * @param shell Parent shell for dialog * @param pvs PVs that should use default archives */ public UseDefaultArchivesAction(final UndoableActionManager operations_manager, final PVItem pvs[]) { super(Messages.UseDefaultArchives, Activator.getDefault().getImageDescriptor("icons/archive.gif")); //$NON-NLS-1$ this.operations_manager = operations_manager; this.pvs = pvs; } @Override<|fim▁hole|>}<|fim▁end|>
public void run() { new AddArchiveCommand(operations_manager, pvs, Preferences.getArchives(), true); }
<|file_name|>testSocketIO.js<|end_file_name|><|fim▁begin|>var net = require('net'); Stomp = require('./stomp'); wrapTCP = function(port, host) { var socket, ws; socket = null; ws = { url: 'tcp:// ' + host + ':' + port, send: function(d) { return socket.write(d); }, close: function() {<|fim▁hole|> socket = net.connect(port, host, function(e) { return ws.onopen(); }); socket.on('error', function(e) { return typeof ws.onclose === "function" ? ws.onclose(e) : void 0; }); socket.on('close', function(e) { return typeof ws.onclose === "function" ? ws.onclose(e) : void 0; }); socket.on('data', function(data) { var event; event = { 'data': data.toString() }; return ws.onmessage(event); }); return ws; };<|fim▁end|>
return socket.end(); } };
<|file_name|>live.py<|end_file_name|><|fim▁begin|>from envs.common import * DEBUG = False TEMPLATE_DEBUG = DEBUG # EMAIL_BACKEND = 'django_ses.SESBackend' STATIC_URL = 'http://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME COMPRESS_URL = STATIC_URL FAVICON_URL = "%sfavicon.ico" % STATIC_URL DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' STATICFILES_STORAGE = "backends.CachedS3BotoStorage" COMPRESS_STORAGE = STATICFILES_STORAGE <|fim▁hole|>COMPRESS_ENABLED = True COMPRESS_OFFLINE = True<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016-2021, NVIDIA CORPORATION.<|fim▁hole|><|fim▁end|>
# SPDX-License-Identifier: Apache-2.0
<|file_name|>docs.py<|end_file_name|><|fim▁begin|># Module: docs # Date: 03rd April 2013 # Author: James Mills, j dot mills at griffith dot edu dot au """Documentation Tasks""" from fabric.api import lcd, local, task from .utils import pip, requires<|fim▁hole|> PACKAGE = "mio" @task() @requires("make", "sphinx-apidoc") def clean(): """Delete Generated Documentation""" with lcd("docs"): local("make clean") @task(default=True) @requires("make") def build(**options): """Build the Documentation""" pip(requirements="docs/requirements.txt") if PACKAGE is not None: local("sphinx-apidoc -f -T -o docs/source/api {0:s}".format(PACKAGE)) with lcd("docs"): local("make html") @task() @requires("open") def view(**options): """View the Documentation""" with lcd("docs"): local("open build/html/index.html")<|fim▁end|>
<|file_name|>socialcoffee.js<|end_file_name|><|fim▁begin|>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //var MODAL = $("#modalProducto"); var URL = Define.URL_BASE; window.onload=function(){ //toastr.error("Ingresaaaaaaaaa"); var url_ajax = URL + Define.URL_OLVIDE; //le decimos a qué url tiene que mandar la información var data = { action: 'validar' }; httpPetition.ajxPost(url_ajax, data, function (data) { if(data.mensaje == "Ok"){ toastr.success("Bienvenido amante del cafe, esto es Coffee Market House"); redireccionar(Define.URL_BASE + "socialcoffee"); } }); }; function redireccionar(url_direccionar){ setTimeout(function(){ location.href=url_direccionar; }, 5000); //tiempo expresado en milisegundos } $("#olvide").delegate('#semeolvido', 'click', function () {//buscar pedido en bd var usuario_a_buscar = $("#username").val(); var url_ajax = URL + Define.URL_OLVIDE; //le decimos a qué url tiene que mandar la información var data = { action: 'semeolvido', username: usuario_a_buscar }; if(!SOLICITUSEMEOLVIDO){ httpPetition.ajxPost(url_ajax, data, function (data) { if(data.itemsCount != 0){ SOLICITUSEMEOLVIDO = true; url_direccionar = Define.URL_BASE + "cuenta/login" toastr.warning("Hola " + data.data[0].usuarioNombres + ", se te enviará la nueva contraseña al correo: " + data.data[0].usuarioEmail); redireccionar(url_direccionar); }else{ toastr.error("No existe una cuenta asociada a ese nombre de usuario."); } }); }else{ toastr.error("La solicitud ya fue enviada, revisa tu correo."); }; }); $("#login").delegate('#ingresoLogin', 'click', function () {//validar usuario var url_ajax = URL + Define.URL_LOGIN; //le decimos a qué url tiene que mandar la información var usuario_a_buscar = $("#name").val(); var passwd_user = $("#pswd").val(); var recordame_ve = false; if($('#recuerdame').is(':checked')){ recordame_ve = true;<|fim▁hole|> alert(recordame_ve); var data = { action: 'ingresar', username: usuario_a_buscar, password_user: passwd_user, recuerdame: recordame_ve }; if(usuario_a_buscar == '' || passwd_user == ''){ toastr.error("Username y/o contraseña vacíos, por favor digite un valor"); }else{ httpPetition.ajxPost(url_ajax, data, function (data) { if(data.mensaje == "Ok"){ toastr.success("Bienvenido amante del cafe, esto es Coffee Market House"); redireccionar(Define.URL_BASE + "socialcoffee"); } }); }; });<|fim▁end|>
}
<|file_name|>authentication.py<|end_file_name|><|fim▁begin|>import datetime from rest_framework.authentication import TokenAuthentication from rest_framework import exceptions from factotum.environment import env class ExpiringTokenAuthentication(TokenAuthentication): keyword = "Bearer" def authenticate_credentials(self, key):<|fim▁hole|> token = model.objects.get(key=key) except model.DoesNotExist: raise exceptions.AuthenticationFailed("Invalid token") if not token.user.is_active: raise exceptions.AuthenticationFailed("User inactive or deleted") now = datetime.datetime.now() if token.created < now - datetime.timedelta( milliseconds=env.FACTOTUM_WS_TOKEN_TTL ): raise exceptions.AuthenticationFailed("Token has expired") return token.user, token<|fim▁end|>
model = self.get_model() try:
<|file_name|>fsdev_disks.py<|end_file_name|><|fim▁begin|>import sys, os, re, string from autotest_lib.client.bin import utils, fsinfo, fsdev_mgr, partition from autotest_lib.client.common_lib import error fd_mgr = fsdev_mgr.FsdevManager() # For unmounting / formatting file systems we may have to use a device name # that is different from the real device name that we have to use to set I/O # scheduler tunables. _DISKPART_FILE = '/proc/partitions' ############################################################################## # # The 'disk_list' array returned by get_disk_list() has an entry for each # disk drive we find on the box. Each of these entries is a map with the # following 3 string values: # # 'device' disk device name (i.e. the part after /dev/) # 'mountpt' disk mount path # 'tunable' disk name for setting scheduler tunables (/sys/block/sd??) # # The last value is an integer that indicates the current mount status # of the drive: # # 'mounted' 0 = not currently mounted # 1 = mounted r/w on the expected path # -1 = mounted readonly or at an unexpected path # # When the 'std_mounts_only' argument is True we don't include drives # mounted on 'unusual' mount points in the result. # ############################################################################## def get_disk_list(std_mounts_only=True): # Get hold of the currently mounted file systems mounts = utils.system_output('mount').splitlines() # Grab all the interesting disk partition names from /proc/partitions, # and build up the table of drives present in the system. hd_list = [] hd_regexp = re.compile("([hs]d[a-z]+3)$") partfile = open(_DISKPART_FILE) for partline in partfile: parts = partline.strip().split() if len(parts) != 4 or partline.startswith('major'): continue # Get hold of the partition name partname = parts[3] # The partition name better end with a digit if not partname[-1:].isdigit(): continue # Process any site-specific filters on the partition name if not fd_mgr.use_partition(partname): continue # We need to know the IDE/SATA/... device name for setting tunables tunepath = fd_mgr.map_drive_name(partname) # Check whether the device is mounted (and how) mstat = 0 fstype = '' fsopts = '' fsmkfs = '?' # Prepare the full device path for matching chkdev = '/dev/' + partname # If the partition is mounted, we'll record the mount point mountpt = None for mln in mounts: splt = mln.split() # Typical 'mount' output line looks like this (indices # for the split() result shown below): # # <device> on <mount_point> type <fstp> <options> # 0 1 2 3 4 5 if splt[0] == chkdev: # Make sure the mount point looks reasonable mountpt = fd_mgr.check_mount_point(partname, splt[2]) if not mountpt: mstat = -1 break # Grab the file system type and mount options fstype = splt[4] fsopts = splt[5] # Check for something other than a r/w mount if fsopts[:3] != '(rw': mstat = -1 break # The drive is mounted at the 'normal' mount point mstat = 1 # Does the caller only want to allow 'standard' mount points? if std_mounts_only and mstat < 0: continue # Was this partition mounted at all? if not mountpt: # Ask the client where we should mount this partition mountpt = fd_mgr.check_mount_point(partname, None) if not mountpt: # Client doesn't know where to mount partition - ignore it continue # Looks like we have a valid disk drive, add it to the list hd_list.append({ 'device' : partname, 'mountpt': mountpt, 'tunable': tunepath, 'fs_type': fstype, 'fs_opts': fsopts, 'fs_mkfs': fsmkfs, 'mounted': mstat }) return hd_list def mkfs_all_disks(job, disk_list, fs_type, fs_makeopt, fs_mnt_opt): """ Prepare all the drives in 'disk_list' for testing. For each disk this means unmounting any mount points that use the disk, running mkfs with 'fs_type' as the file system type and 'fs_makeopt' as the 'mkfs' options, and finally remounting the freshly formatted drive using the flags in 'fs_mnt_opt'. """ for disk in disk_list: # For now, ext4 isn't quite ready for prime time if fs_type == "ext4": fs_type = "ext4dev" # Grab the device and mount paths for the drive dev_path = os.path.join('/dev', disk["device"]) mnt_path = disk['mountpt'] # Create a file system instance try: fs = job.filesystem(device=dev_path, mountpoint=mnt_path) except: raise Exception("Could not create a filesystem on '%s'" % dev_path) # Make sure the volume is unmounted if disk["mounted"]: try: fs.unmount(mnt_path) except Exception, info: raise Exception("umount failed: exception = %s, args = %s" % (sys.exc_info()[0], info.args)) except: raise Exception("Could not unmount device ", dev_path) # Is the drive already formatted with the right file system? skip_mkfs = match_fs(disk, dev_path, fs_type, fs_makeopt)<|fim▁hole|> try: if not skip_mkfs: fs.mkfs(fstype = fs_type, args = fs_makeopt) except: raise Exception("Could not 'mkfs " + "-t " + fs_type + " " + fs_makeopt + " " + dev_path + "'") # Mount the drive with the appropriate FS options try: opts = "" if fs_mnt_opt != "": opts += " -o " + fs_mnt_opt fs.mount(mountpoint = mnt_path, fstype = fs_type, args = opts) except NameError, info: raise Exception("mount name error: %s" % info) except Exception, info: raise Exception("mount failed: exception = %s, args = %s" % (type(info), info.args)) # If we skipped mkfs we need to wipe the partition clean if skip_mkfs: fs.wipe() # Record the new file system type and options in the disk list disk["mounted"] = True disk["fs_type"] = fs_type disk["fs_mkfs"] = fs_makeopt disk["fs_opts"] = fs_mnt_opt # Try to wipe the file system slate clean utils.drop_caches() # XXX(gps): Remove this code once refactoring is complete to get rid of these # nasty test description strings. def _legacy_str_to_test_flags(fs_desc_string): """Convert a legacy FS_LIST string into a partition.FsOptions instance.""" match = re.search('(.*?)/(.*?)/(.*?)/(.*)$', fs_desc_string.strip()) if not match: raise ValueError('unrecognized FS list entry %r' % fs_desc_string) flags_obj = partition.FsOptions(fstype=match.group(1).strip(), mkfs_flags=match.group(2).strip(), mount_options=match.group(3).strip(), fs_tag=match.group(4).strip()) return flags_obj def prepare_disks(job, fs_desc, disk1_only=False, disk_list=None): """ Prepare drive(s) to contain the file system type / options given in the description line 'fs_desc'. When 'disk_list' is not None, we prepare all the drives in that list; otherwise we pick the first available data drive (which is usually hdc3) and prepare just that one drive. Args: fs_desc: A partition.FsOptions instance describing the test -OR- a legacy string describing the same in '/' separated format: 'fstype / mkfs opts / mount opts / short name'. disk1_only: Boolean, defaults to False. If True, only test the first disk. disk_list: A list of disks to prepare. If None is given we default to asking get_disk_list(). Returns: (mount path of the first disk, short name of the test, list of disks) OR (None, '', None) if no fs_desc was given. """ # Special case - do nothing if caller passes no description. if not fs_desc: return (None, '', None) if not isinstance(fs_desc, partition.FsOptions): fs_desc = _legacy_str_to_test_flags(fs_desc) # If no disk list was given, we'll get it ourselves if not disk_list: disk_list = get_disk_list() # Make sure we have the appropriate 'mkfs' binary for the file system mkfs_bin = 'mkfs.' + fs_desc.filesystem if fs_desc.filesystem == 'ext4': mkfs_bin = 'mkfs.ext4dev' try: utils.system('which ' + mkfs_bin) except Exception: try: mkfs_bin = os.path.join(job.toolsdir, mkfs_bin) utils.system('cp -ufp %s /sbin' % mkfs_bin) except Exception: raise error.TestError('No mkfs binary available for ' + fs_desc.filesystem) # For 'ext4' we need to add '-E test_fs' to the mkfs options if fs_desc.filesystem == 'ext4': fs_desc.mkfs_flags += ' -E test_fs' # If the caller only needs one drive, grab the first one only if disk1_only: disk_list = disk_list[0:1] # We have all the info we need to format the drives mkfs_all_disks(job, disk_list, fs_desc.filesystem, fs_desc.mkfs_flags, fs_desc.mount_options) # Return(mount path of the first disk, test tag value, disk_list) return (disk_list[0]['mountpt'], fs_desc.fs_tag, disk_list) def restore_disks(job, restore=False, disk_list=None): """ Restore ext2 on the drives in 'disk_list' if 'restore' is True; when disk_list is None, we do nothing. """ if restore and disk_list is not None: prepare_disks(job, 'ext2 / -q -i20480 -m1 / / restore_ext2', disk1_only=False, disk_list=disk_list) def wipe_disks(job, disk_list): """ Wipe all of the drives in 'disk_list' using the 'wipe' functionality in the filesystem class. """ for disk in disk_list: partition.wipe_filesystem(job, disk['mountpt']) def match_fs(disk, dev_path, fs_type, fs_makeopt): """ Matches the user provided fs_type and fs_makeopt with the current disk. """ if disk["fs_type"] != fs_type: return False elif disk["fs_mkfs"] == fs_makeopt: # No need to mkfs the volume, we only need to remount it return True elif fsinfo.match_mkfs_option(fs_type, dev_path, fs_makeopt): if disk["fs_mkfs"] != '?': raise Exception("mkfs option strings differ but auto-detection" " code thinks they're identical") else: return True else: return False ############################################################################## # The following variables/methods are used to invoke fsdev in 'library' mode FSDEV_JOB = None FSDEV_FS_DESC = None FSDEV_RESTORE = None FSDEV_PREP_CNT = 0 FSDEV_DISK1_ONLY = None FSDEV_DISKLIST = None def use_fsdev_lib(fs_desc, disk1_only, reinit_disks): """ Called from the control file to indicate that fsdev is to be used. """ global FSDEV_FS_DESC global FSDEV_RESTORE global FSDEV_DISK1_ONLY global FSDEV_PREP_CNT # This is a bit tacky - we simply save the arguments in global variables FSDEV_FS_DESC = fs_desc FSDEV_DISK1_ONLY = disk1_only FSDEV_RESTORE = reinit_disks # We need to keep track how many times 'prepare' is called FSDEV_PREP_CNT = 0 def prepare_fsdev(job): """ Called from the test file to get the necessary drive(s) ready; return a pair of values: the absolute path to the first drive's mount point plus the complete disk list (which is useful for tests that need to use more than one drive). """ global FSDEV_JOB global FSDEV_DISKLIST global FSDEV_PREP_CNT if not FSDEV_FS_DESC: return (None, None) # Avoid preparing the same thing more than once FSDEV_PREP_CNT += 1 if FSDEV_PREP_CNT > 1: return (FSDEV_DISKLIST[0]['mountpt'],FSDEV_DISKLIST) FSDEV_JOB = job (path,toss,disks) = prepare_disks(job, fs_desc = FSDEV_FS_DESC, disk1_only = FSDEV_DISK1_ONLY, disk_list = None) FSDEV_DISKLIST = disks return (path,disks) def finish_fsdev(force_cleanup=False): """ This method can be called from the test file to optionally restore all the drives used by the test to a standard ext2 format. Note that if use_fsdev_lib() was invoked with 'reinit_disks' not set to True, this method does nothing. Note also that only fsdev "server-side" dynamic control files should ever set force_cleanup to True. """ if FSDEV_PREP_CNT == 1 or force_cleanup: restore_disks(job = FSDEV_JOB, restore = FSDEV_RESTORE, disk_list = FSDEV_DISKLIST) ############################################################################## class fsdev_disks: """ Disk drive handling class used for file system development """ def __init__(self, job): self.job = job # Some clients need to access the 'fsdev manager' instance directly def get_fsdev_mgr(self): return fd_mgr def config_sched_tunables(self, desc_file): # Parse the file that describes the scheduler tunables and their paths self.tune_loc = eval(open(desc_file).read()) # Figure out what kernel we're running on kver = utils.system_output('uname -r') kver = re.match("([0-9]+\.[0-9]+\.[0-9]+).*", kver) kver = kver.group(1) # Make sure we know how to handle the kernel we're running on tune_files = self.tune_loc[kver] if tune_files is None: raise Exception("Scheduler tunables not available for kernel " + kver) # Save the kernel version for later self.kernel_ver = kver # For now we always use 'anticipatory' tune_paths = tune_files["anticipatory"] # Create a dictionary out of the tunables array self.tune_loc = {} for tx in range(len(tune_paths)): # Grab the next tunable path from the array tpath = tune_paths[tx] # Strip any leading directory names tuner = tpath while 1: slash = tuner.find("/") if slash < 0: break tuner = tuner[slash+1:] # Add mapping to the dictionary self.tune_loc[tuner] = tpath def load_sched_tunable_values(self, val_file): # Prepare the array of tunable values self.tune_list = [] # Read the config parameters and find the values that match our kernel for cfgline in open(val_file): cfgline = cfgline.strip() if len(cfgline) == 0: continue if cfgline.startswith("#"): continue if cfgline.startswith("tune[") == 0: raise Exception("Config entry not recognized: " + cfgline) endKV = cfgline.find("]:") if endKV < 0: raise Exception("Config entry missing closing bracket: " + cfgline) if cfgline[5:endKV] != self.kernel_ver[0:endKV-5]: continue tune_parm = cfgline[endKV+2:].strip() equal = tune_parm.find("=") if equal < 1 or equal == len(tune_parm) - 1: raise Exception("Config entry doesn't have 'parameter=value' :" + cfgline) tune_name = tune_parm[:equal] tune_val = tune_parm[equal+1:] # See if we have a matching entry in the path dictionary try: tune_path = self.tune_loc[tune_name] except: raise Exception("Unknown config entry: " + cfgline) self.tune_list.append((tune_name, tune_path, tune_val)) def set_sched_tunables(self, disks): """ Given a list of disks in the format returned by get_disk_list() above, set the I/O scheduler values on all the disks to the values loaded earlier by load_sched_tunables(). """ for dx in range(len(disks)): disk = disks[dx]['tunable'] # Set the scheduler first before setting any other tunables self.set_tunable(disk, "scheduler", self.tune_loc["scheduler"], "anticipatory") # Now set all the tunable parameters we've been given for tune_desc in self.tune_list: self.set_tunable(disk, tune_desc[0], tune_desc[1], tune_desc[2]) def set_tunable(self, disk, name, path, val): """ Given a disk name, a path to a tunable value under _TUNE_PATH and the new value for the parameter, set the value and verify that the value has been successfully set. """ fpath = partition.get_iosched_path(disk, path) # Things might go wrong so we'll catch exceptions try: step = "open tunable path" tunef = open(fpath, 'w', buffering=-1) step = "write new tunable value" tunef.write(val) step = "close the tunable path" tunef.close() step = "read back new tunable value" nval = open(fpath, 'r', buffering=-1).read().strip() # For 'scheduler' we need to fish out the bracketed value if name == "scheduler": nval = re.match(".*\[(.*)\].*", nval).group(1) except IOError, info: # Special case: for some reason 'max_sectors_kb' often doesn't work # with large values; try '128' if we haven't tried it already. if name == "max_sectors_kb" and info.errno == 22 and val != '128': self.set_tunable(disk, name, path, '128') return; # Something went wrong, probably a 'config' problem of some kind raise Exception("Unable to set tunable value '" + name + "' at step '" + step + "': " + str(info)) except Exception: # We should only ever see 'IOError' above, but just in case ... raise Exception("Unable to set tunable value for " + name) # Make sure the new value is what we expected if nval != val: raise Exception("Unable to correctly set tunable value for " + name +": desired " + val + ", but found " + nval) return<|fim▁end|>
# Next step is to create a fresh file system (if we need to)
<|file_name|>is-jetpack-product-site.ts<|end_file_name|><|fim▁begin|>import getRawSite from 'calypso/state/selectors/get-raw-site'; import isAtomicSite from 'calypso/state/selectors/is-site-automated-transfer'; import { AppState } from 'calypso/types'; type Site = { options?: { jetpack_connection_active_plugins?: string[]; }; }; /** * Returns true if site is a Jetpack site with a standalone product plugin installed ( i.e. Jetpack * Backup ), false if the site has the full Jetpack plugin or is hosted on WordPress.com, or null * if the site is unknown. * * @param {AppState} state Global state tree * @param {number} siteId Site ID * @returns {boolean|null} Whether site is a Jetpack site with a standalone product plugin */ export default function isJetpackProductSite( state: AppState, siteId: number ): boolean | null { const site = getRawSite( state, siteId ) as Site;<|fim▁hole|> if ( isAtomicSite( state, siteId ) ) { return false; } return ( ( site.options?.jetpack_connection_active_plugins || [] ).filter( ( plugin ) => plugin !== 'jetpack' ).length > 0 ); }<|fim▁end|>
if ( ! site ) { return null; }
<|file_name|>optimize_test.cc<|end_file_name|><|fim▁begin|>#include <cassert> #include <iostream> #include <sstream> #include <boost/program_options/variables_map.hpp> #include "optimize.h" #include "online_optimizer.h" #include "sparse_vector.h" #include "fdict.h" using namespace std; double TestOptimizer(BatchOptimizer* opt) { cerr << "TESTING NON-PERSISTENT OPTIMIZER\n"; // f(x,y) = 4x1^2 + x1*x2 + x2^2 + x3^2 + 6x3 + 5 // df/dx1 = 8*x1 + x2 // df/dx2 = 2*x2 + x1 // df/dx3 = 2*x3 + 6 vector<double> x(3); vector<double> g(3); x[0] = 8; x[1] = 8; x[2] = 8; double obj = 0; do { g[0] = 8 * x[0] + x[1]; g[1] = 2 * x[1] + x[0]; g[2] = 2 * x[2] + 6; obj = 4 * x[0]*x[0] + x[0] * x[1] + x[1]*x[1] + x[2]*x[2] + 6 * x[2] + 5; opt->Optimize(obj, g, &x); cerr << x[0] << " " << x[1] << " " << x[2] << endl; cerr << " obj=" << obj << "\td/dx1=" << g[0] << " d/dx2=" << g[1] << " d/dx3=" << g[2] << endl; } while (!opt->HasConverged()); return obj; } double TestPersistentOptimizer(BatchOptimizer* opt) { cerr << "\nTESTING PERSISTENT OPTIMIZER\n"; // f(x,y) = 4x1^2 + x1*x2 + x2^2 + x3^2 + 6x3 + 5 // df/dx1 = 8*x1 + x2 // df/dx2 = 2*x2 + x1 // df/dx3 = 2*x3 + 6 vector<double> x(3); vector<double> g(3); x[0] = 8; x[1] = 8; x[2] = 8; double obj = 0; string state; bool converged = false; while (!converged) { g[0] = 8 * x[0] + x[1]; g[1] = 2 * x[1] + x[0]; g[2] = 2 * x[2] + 6; obj = 4 * x[0]*x[0] + x[0] * x[1] + x[1]*x[1] + x[2]*x[2] + 6 * x[2] + 5; { if (state.size() > 0) { istringstream is(state, ios::binary); opt->Load(&is); } opt->Optimize(obj, g, &x); ostringstream os(ios::binary); opt->Save(&os); state = os.str(); } cerr << x[0] << " " << x[1] << " " << x[2] << endl; cerr << " obj=" << obj << "\td/dx1=" << g[0] << " d/dx2=" << g[1] << " d/dx3=" << g[2] << endl; converged = opt->HasConverged(); if (!converged) { // now screw up the state (should be undone by Load) obj += 2.0; g[1] = -g[2]; vector<double> x2 = x; try { opt->Optimize(obj, g, &x2); } catch (...) { } } } return obj; } template <class O> void TestOptimizerVariants(int num_vars) { O oa(num_vars); cerr << "-------------------------------------------------------------------------\n"; cerr << "TESTING: " << oa.Name() << endl; double o1 = TestOptimizer(&oa); O ob(num_vars); double o2 = TestPersistentOptimizer(&ob); if (o1 != o2) { cerr << oa.Name() << " VARIANTS PERFORMED DIFFERENTLY!\n" << o1 << " vs. " << o2 << endl; exit(1); } cerr << oa.Name() << " SUCCESS\n"; }<|fim▁hole|> size_t N = 20; double C = 1.0; double eta0 = 0.2; std::tr1::shared_ptr<LearningRateSchedule> r(new ExponentialDecayLearningRate(N, eta0, 0.85)); //shared_ptr<LearningRateSchedule> r(new StandardLearningRate(N, eta0)); CumulativeL1OnlineOptimizer opt(r, N, C, std::vector<int>()); assert(r->eta(10) < r->eta(1)); } int main() { int n = 3; TestOptimizerVariants<LBFGSOptimizer>(n); TestOptimizerVariants<RPropOptimizer>(n); TestOnline(); return 0; }<|fim▁end|>
using namespace std::tr1; void TestOnline() {
<|file_name|>SimpleDataCoding.java<|end_file_name|><|fim▁begin|>/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.bean; /** * This is simple DataCoding. Only contains Alphabet (DEFAULT and 8-bit) and * Message Class. * * @author uudashr * */ public class SimpleDataCoding implements DataCoding { private final Alphabet alphabet; private final MessageClass messageClass; /** * Construct Data Coding using default Alphabet and * {@link MessageClass#CLASS1} Message Class. */ public SimpleDataCoding() { this(Alphabet.ALPHA_DEFAULT, MessageClass.CLASS1); } /** * Construct Data Coding using specified Alphabet and Message Class. * * @param alphabet is the alphabet. Only support * {@link Alphabet#ALPHA_DEFAULT} and {@link Alphabet#ALPHA_8_BIT}. * @param messageClass * @throws IllegalArgumentException if alphabet is <tt>null</tt> or using * non {@link Alphabet#ALPHA_DEFAULT} and * {@link Alphabet#ALPHA_8_BIT} alphabet or * <code>messageClass</code> is null. */ public SimpleDataCoding(Alphabet alphabet, MessageClass messageClass) throws IllegalArgumentException { if (alphabet == null) { throw new IllegalArgumentException( "Alphabet is mandatory, can't be null"); } if (alphabet.equals(Alphabet.ALPHA_UCS2) || alphabet.isReserved()) { throw new IllegalArgumentException( "Supported alphabet for SimpleDataCoding does not include " + Alphabet.ALPHA_UCS2 + " or " + "reserved alphabet codes. Current alphabet is " + alphabet); } if (messageClass == null) { throw new IllegalArgumentException( "MessageClass is mandatory, can't be null"); } this.alphabet = alphabet; this.messageClass = messageClass; } public Alphabet getAlphabet() { return alphabet; } public MessageClass getMessageClass() { return messageClass; } public byte toByte() { // base byte is 11110xxx or 0xf0, others injected byte value = (byte)0xf0; value |= alphabet.value(); value |= messageClass.value(); return value; } @Override<|fim▁hole|> int result = 1; result = prime * result + ((alphabet == null) ? 0 : alphabet.hashCode()); result = prime * result + ((messageClass == null) ? 0 : messageClass.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SimpleDataCoding other = (SimpleDataCoding)obj; if (alphabet == null) { if (other.alphabet != null) return false; } else if (!alphabet.equals(other.alphabet)) return false; if (messageClass == null) { if (other.messageClass != null) return false; } else if (!messageClass.equals(other.messageClass)) return false; return true; } @Override public String toString() { return "DataCoding:" + (0xff & toByte()); } }<|fim▁end|>
public int hashCode() { final int prime = 31;
<|file_name|>foreach_object.js<|end_file_name|><|fim▁begin|>var jazz = require("../lib/jazz"); var fs = require("fs"); var data = fs.readFileSync(__dirname + "/foreach_object.jazz", "utf8"); var template = jazz.compile(data); template.eval({"doc": {<|fim▁hole|><|fim▁end|>
"title": "First", "content": "Some content" }}, function(data) { console.log(data); });
<|file_name|>path.rs<|end_file_name|><|fim▁begin|>use crate::factory::IFactory; use crate::geometry::IGeometry; use crate::resource::IResource; use com_wrapper::ComWrapper; use dcommon::Error; use winapi::shared::winerror::SUCCEEDED; use winapi::um::d2d1::{ID2D1Geometry, ID2D1PathGeometry, ID2D1Resource}; use wio::com::ComPtr; pub use self::builder::*;<|fim▁hole|>#[derive(ComWrapper, Clone)] #[com(send, sync, debug)] /// Custom-shaped geometry made of lines and curves pub struct PathGeometry { ptr: ComPtr<ID2D1PathGeometry>, } impl PathGeometry { pub fn create(factory: &dyn IFactory) -> Result<PathBuilder, Error> { unsafe { let mut ptr = std::ptr::null_mut(); let hr = factory.raw_f().CreatePathGeometry(&mut ptr); if SUCCEEDED(hr) { let path = PathGeometry::from_raw(ptr); let mut ptr = std::ptr::null_mut(); let hr = path.ptr.Open(&mut ptr); if SUCCEEDED(hr) { Ok(PathBuilder { path: path, sink: ComPtr::from_raw(ptr), }) } else { Err(hr.into()) } } else { Err(hr.into()) } } } pub fn segment_count(&self) -> Result<u32, Error> { unsafe { let mut count = 0; let result = self.ptr.GetSegmentCount(&mut count); if SUCCEEDED(result) { Ok(count) } else { Err(From::from(result)) } } } pub fn figure_count(&self) -> Result<u32, Error> { unsafe { let mut count = 0; let result = self.ptr.GetFigureCount(&mut count); if SUCCEEDED(result) { Ok(count) } else { Err(From::from(result)) } } } } unsafe impl IResource for PathGeometry { unsafe fn raw_resource(&self) -> &ID2D1Resource { &self.ptr } } unsafe impl IGeometry for PathGeometry { unsafe fn raw_geom(&self) -> &ID2D1Geometry { &self.ptr } } unsafe impl super::GeometryType for PathGeometry {}<|fim▁end|>
pub mod builder; #[repr(transparent)]
<|file_name|>0006_add_jsonb_index_for_fileversions.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-04-03 20:50 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): <|fim▁hole|> dependencies = [ ('osf', '0005_merge'), ] operations = [ migrations.RunSQL( [ """ CREATE INDEX fileversion_metadata_sha_arch_vault_index ON osf_fileversion ((osf_fileversion.metadata -> 'sha256'), (osf_fileversion.metadata -> 'archive'), ( osf_fileversion.metadata -> 'vault')); """ ], [ """ DROP INDEX fileversion_metadata_sha_arch_vault_index; """ ] ) ]<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""<|fim▁hole|>"""<|fim▁end|>
The TradeChain community is used to keep track of transactions performed in the decentralized market.
<|file_name|>stif_tests.py<|end_file_name|><|fim▁begin|># Copyright (c) 2001-2016, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public transport: # a non ending quest to the responsive locomotion way of traveling! # # LICENCE: 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 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Stay tuned using # twitter @navitia # IRC #navitia on freenode # https://groups.google.com/d/forum/navitia # www.navitia.io from __future__ import absolute_import from .tests_mechanism import AbstractTestFixture, dataset from .check_utils import * @dataset({"main_stif_test": {}}) class TestStif(AbstractTestFixture): """ Test the stif scenario responses Possible journeys from A to B: 1/ 8h00 ====(line A)====> 10h00 2/ 9h00 ==(line B + C)==> 11h00 3/ 10h00 ====(line A)====> 12h00 """ def test_stif_simple(self): """ Test of simple request : * we want to make at least 2 journey calls (not only the best journey, but also try next) * we don't want 2 journeys using the same line and changing at same points So here we want journeys 1 and 2 """ query = "journeys?from={from_sp}&to={to_sp}&datetime={datetime}&_override_scenario=new_default" \ "&min_nb_journeys=1&_min_journeys_calls=2&_final_line_filter=true&_max_successive_physical_mode=3"\ .format(from_sp="stopA", to_sp="stopB", datetime="20140614T075500") response = self.query_region(query) assert len(response['journeys']) == 2 assert response['journeys'][0]['arrival_date_time'] == '20140614T100000' assert response['journeys'][1]['arrival_date_time'] == '20140614T110000' def test_stif_override_min_journeys_calls(self): """ Test of simple request : * we only want 1 journey calls (no next call) So here we only want journeys 1 """ query = "journeys?from={from_sp}&to={to_sp}&datetime={datetime}&_override_scenario=new_default" \ "&min_nb_journeys=1&_min_journeys_calls=1&_final_line_filter=true&_max_successive_physical_mode=3"\ .format(from_sp="stopA", to_sp="stopB", datetime="20140614T075500") response = self.query_region(query) assert len(response['journeys']) == 1 assert response['journeys'][0]['arrival_date_time'] == '20140614T100000' def test_stif_override_final_line_filter(self): """ Test of simple request : * we want to make at least 2 journey calls (not only the best journey, but also try next) * we deactivate the filter on journeys using the same line and changing at same points So here we want journeys 1, 2 and 3 """ query = "journeys?from={from_sp}&to={to_sp}&datetime={datetime}&_override_scenario=new_default" \ "&min_nb_journeys=1&_min_journeys_calls=2&_final_line_filter=false&_max_successive_physical_mode=3"\ .format(from_sp="stopA", to_sp="stopB", datetime="20140614T075500") response = self.query_region(query) assert len(response['journeys']) == 3 assert response['journeys'][0]['arrival_date_time'] == '20140614T100000' assert response['journeys'][1]['arrival_date_time'] == '20140614T110000' assert response['journeys'][2]['arrival_date_time'] == '20140614T120000' def test_stif_max_successive_buses(self): """ BUS Bus Bus Bus stopP ----> stopQ ----> stopR ----> stopS ----> stopT 15:00 16:00 17:00 18:00 19:00 Bus stopP ----------------------------------------> stopT 15:00 20:00 Test of request with parameter "_max_successive_physical_mode": * we want to make at least 2 journey calls (not only the best journey, but also try next) * we don't want the journey using more than 3 Buses So here we want journey1 """ query = "journeys?from={from_sp}&to={to_sp}&datetime={datetime}&_override_scenario=new_default" \ "&_max_successive_physical_mode=3&_max_additional_connections=10"\ .format(from_sp="stopP", to_sp="stopT", datetime="20140614T145500") <|fim▁hole|> assert len(response['journeys']) == 1 #As we modify the value of _max_successive_physical_mode to 5 we want two journeys query = "journeys?from={from_sp}&to={to_sp}&datetime={datetime}&_override_scenario=new_default" \ "&_max_successive_physical_mode=5&_max_additional_connections=10"\ .format(from_sp="stopP", to_sp="stopT", datetime="20140614T145500") response = self.query_region(query) assert len(response['journeys']) == 2 def test_stif_max_successive_buses_with_tram_in_between(self): """ BUS Bus Bus Bus Tram Bus Bus stopP ----> stopQ ----> stopR ----> stopS ----> stopT ----> stopU ----> stopV ----> stopW 15:00 16:00 17:00 18:00 19:00 19:30 20:00 20:30 Bus stopP ----------------------------------------------------------------------------> stopW 15:00 21:00 Test of request with parameter "_max_successive_physical_mode": * we want to make at least 2 journey calls (not only the best journey, but also try next) * we don't want the journey using more than 3 Buses successive * we have "Bus" and "Tram" as means of transport """ #As there are 4 buses successive to be used from stopP to stopW and _max_successive_physical_mode = 3 # we have 1 journey query = "journeys?from={from_sp}&to={to_sp}&datetime={datetime}&_override_scenario=new_default"\ "&_max_successive_physical_mode=3&_max_additional_connections=10"\ .format(from_sp="stopP", to_sp="stopW", datetime="20140614T145500") response = self.query_region(query) assert len(response['journeys']) == 1 #As we modify the value of _max_successive_physical_mode to 5 we want two journeys query = "journeys?from={from_sp}&to={to_sp}&datetime={datetime}&_override_scenario=new_default" \ "&_max_successive_physical_mode=5&_max_additional_connections=10"\ .format(from_sp="stopP", to_sp="stopW", datetime="20140614T145500") response = self.query_region(query) assert len(response['journeys']) == 2 # As we modify the value of _max_additional_connections to 2 we delete the second journey because # it contains more then nb_connections + 2 () query = "journeys?from={from_sp}&to={to_sp}&datetime={datetime}&_override_scenario=new_default" \ "&_max_successive_physical_mode=5&_max_additional_connections=2"\ .format(from_sp="stopP", to_sp="stopW", datetime="20140614T145500") response = self.query_region(query) assert len(response['journeys']) == 1<|fim▁end|>
response = self.query_region(query)
<|file_name|>issue-16452.rs<|end_file_name|><|fim▁begin|>// run-pass #![allow(dead_code)] // pretty-expanded FIXME #23616 <|fim▁hole|>fn main() { if true { return } match () { () => { static MAGIC: usize = 0; } } }<|fim▁end|>
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>#![cfg_attr(feature = "nightly-testing", feature(plugin))] #![cfg_attr(feature = "nightly-testing", plugin(clippy))] #[macro_use] extern crate clap; extern crate hoedown; extern crate rayon; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate toml; extern crate inflector; #[macro_use]<|fim▁hole|>extern crate lazy_static; extern crate regex; #[macro_use] extern crate log; extern crate env_logger; mod botocore; mod cargo; mod commands; mod config; mod service; mod util; mod doco; use std::path::Path; use clap::{Arg, App, SubCommand}; use service::Service; use config::ServiceConfig; use botocore::ServiceDefinition; fn main() { let matches = App::new("Rusoto Service Crate Generator") .version(crate_version!()) .author(crate_authors!()) .about(crate_description!()) .subcommand(SubCommand::with_name("check") .arg(Arg::with_name("services_config") .long("config") .short("c") .takes_value(true))) .subcommand(SubCommand::with_name("generate") .arg(Arg::with_name("services_config") .long("config") .short("c") .takes_value(true)) .arg(Arg::with_name("out_dir") .long("outdir") .short("o") .takes_value(true) .required(true))) .get_matches(); if let Some(matches) = matches.subcommand_matches("check") { let services_config_path = matches.value_of("services_config").unwrap(); let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file."); commands::check::check(service_configs); } if let Some(matches) = matches.subcommand_matches("generate") { let services_config_path = matches.value_of("services_config").unwrap(); let service_configs = ServiceConfig::load_all(services_config_path).expect("Unable to read services configuration file."); let out_dir = Path::new(matches.value_of("out_dir").unwrap()); commands::generate::generate_services(&service_configs, out_dir); } }<|fim▁end|>
<|file_name|>test_driver.py<|end_file_name|><|fim▁begin|>""" @package mi.instrument.nortek.aquadopp.ooicore.test.test_driver @author Rachel Manoni @brief Test cases for ooicore driver USAGE: Make tests verbose and provide stdout * From the IDK $ bin/test_driver $ bin/test_driver -u $ bin/test_driver -i $ bin/test_driver -q * From pyon $ bin/nosetests -s -v /Users/Bill/WorkSpace/marine-integrations/mi/instrument/nortek/aquadopp/ooicore $ bin/nosetests -s -v /Users/Bill/WorkSpace/marine-integrations/mi/instrument/nortek/aquadopp/ooicore -a UNIT $ bin/nosetests -s -v /Users/Bill/WorkSpace/marine-integrations/mi/instrument/nortek/aquadopp/ooicore -a INT $ bin/nosetests -s -v /Users/Bill/WorkSpace/marine-integrations/mi/instrument/nortek/aquadopp/ooicore -a QUAL """ __author__ = 'Rachel Manoni, Ronald Ronquillo' __license__ = 'Apache 2.0' import time from nose.plugins.attrib import attr from mi.core.log import get_logger log = get_logger() from mi.instrument.nortek.vector.ooicore.test.test_driver import bad_sample from mi.idk.unit_test import InstrumentDriverTestCase, ParameterTestConfigKey from mi.instrument.nortek.test.test_driver import DriverTestMixinSub from mi.core.instrument.instrument_driver import DriverConfigKey, ResourceAgentState from mi.core.instrument.data_particle import DataParticleKey, DataParticleValue from mi.core.instrument.chunker import StringChunker from mi.core.exceptions import SampleException from mi.instrument.nortek.aquadopp.ooicore.driver import NortekDataParticleType from mi.instrument.nortek.aquadopp.ooicore.driver import AquadoppDwVelocityDataParticle from mi.instrument.nortek.aquadopp.ooicore.driver import AquadoppDwVelocityDataParticleKey from mi.instrument.nortek.test.test_driver import NortekUnitTest, NortekIntTest, NortekQualTest, user_config2 from mi.instrument.nortek.driver import ProtocolState, ProtocolEvent, TIMEOUT, Parameter, NortekEngIdDataParticleKey, \ NortekInstrumentProtocol, NEWLINE, EngineeringParameter ### # Driver parameters for the tests ### InstrumentDriverTestCase.initialize( driver_module='mi.instrument.nortek.aquadopp.ooicore.driver', driver_class="InstrumentDriver", instrument_agent_resource_id='nortek_aquadopp_dw_ooicore', instrument_agent_name='nortek_aquadopp_dw_ooicore_agent', instrument_agent_packet_config=NortekDataParticleType(), driver_startup_config={ DriverConfigKey.PARAMETERS: { Parameter.DEPLOYMENT_NAME: 'test', Parameter.COMMENTS: 'this is a test', #update the following two parameters to allow for faster collecting of samples during testing Parameter.AVG_INTERVAL: 1, Parameter.MEASUREMENT_INTERVAL: 1}} ) def eng_id_sample(): sample_as_hex = "415144" return sample_as_hex.decode('hex') eng_id_particle = [{DataParticleKey.VALUE_ID: NortekEngIdDataParticleKey.ID, DataParticleKey.VALUE: "AQD 8493 "}] def velocity_sample(): sample_as_hex = "a5011500101926221211000000009300f83b810628017f01002d0000e3094c0122ff9afe1e1416006093" return sample_as_hex.decode('hex') velocity_particle = [{'value_id': AquadoppDwVelocityDataParticleKey.TIMESTAMP, 'value': '26/11/2012 22:10:19'}, {'value_id': AquadoppDwVelocityDataParticleKey.ERROR, 'value': 0}, {'value_id': AquadoppDwVelocityDataParticleKey.ANALOG1, 'value': 0}, {'value_id': AquadoppDwVelocityDataParticleKey.BATTERY_VOLTAGE, 'value': 147}, {'value_id': AquadoppDwVelocityDataParticleKey.SOUND_SPEED_ANALOG2, 'value': 15352}, {'value_id': AquadoppDwVelocityDataParticleKey.HEADING, 'value': 1665}, {'value_id': AquadoppDwVelocityDataParticleKey.PITCH, 'value': 296}, {'value_id': AquadoppDwVelocityDataParticleKey.ROLL, 'value': 383}, {'value_id': AquadoppDwVelocityDataParticleKey.STATUS, 'value': 45}, {'value_id': AquadoppDwVelocityDataParticleKey.PRESSURE, 'value': 0}, {'value_id': AquadoppDwVelocityDataParticleKey.TEMPERATURE, 'value': 2531}, {'value_id': AquadoppDwVelocityDataParticleKey.VELOCITY_BEAM1, 'value': 332}, {'value_id': AquadoppDwVelocityDataParticleKey.VELOCITY_BEAM2, 'value': -222}, {'value_id': AquadoppDwVelocityDataParticleKey.VELOCITY_BEAM3, 'value': -358}, {'value_id': AquadoppDwVelocityDataParticleKey.AMPLITUDE_BEAM1, 'value': 30}, {'value_id': AquadoppDwVelocityDataParticleKey.AMPLITUDE_BEAM2, 'value': 20}, {'value_id': AquadoppDwVelocityDataParticleKey.AMPLITUDE_BEAM3, 'value': 22}] ############################################################################### # DRIVER TEST MIXIN # # Defines a set of constants and assert methods used for data particle # # verification # # # # In python, mixin classes are classes designed such that they wouldn't be # # able to stand on their own, but are inherited by other classes generally # # using multiple inheritance. # # # # This class defines a configuration structure for testing and common assert # # methods for validating data particles. # ############################################################################### class AquadoppDriverTestMixinSub(DriverTestMixinSub): """ Mixin class used for storing data particle constance and common data assertion methods. """ #Create some short names for the parameter test config TYPE = ParameterTestConfigKey.TYPE READONLY = ParameterTestConfigKey.READONLY STARTUP = ParameterTestConfigKey.STARTUP DA = ParameterTestConfigKey.DIRECT_ACCESS VALUE = ParameterTestConfigKey.VALUE REQUIRED = ParameterTestConfigKey.REQUIRED DEFAULT = ParameterTestConfigKey.DEFAULT STATES = ParameterTestConfigKey.STATES #this particle can be used for both the velocity particle and the diagnostic particle _sample_velocity_diagnostic = { AquadoppDwVelocityDataParticleKey.TIMESTAMP: {TYPE: unicode, VALUE: '', REQUIRED: True}, AquadoppDwVelocityDataParticleKey.ERROR: {TYPE: int, VALUE: 0, REQUIRED: True}, AquadoppDwVelocityDataParticleKey.ANALOG1: {TYPE: int, VALUE: 0, REQUIRED: True}, AquadoppDwVelocityDataParticleKey.BATTERY_VOLTAGE: {TYPE: int, VALUE: 0, REQUIRED: True}, AquadoppDwVelocityDataParticleKey.SOUND_SPEED_ANALOG2: {TYPE: int, VALUE: 0, REQUIRED: True}, AquadoppDwVelocityDataParticleKey.HEADING: {TYPE: int, VALUE: 0, REQUIRED: True}, AquadoppDwVelocityDataParticleKey.PITCH: {TYPE: int, VALUE: 0, REQUIRED: True}, AquadoppDwVelocityDataParticleKey.ROLL: {TYPE: int, VALUE: 0, REQUIRED: True}, AquadoppDwVelocityDataParticleKey.PRESSURE: {TYPE: int, VALUE: 0, REQUIRED: True}, AquadoppDwVelocityDataParticleKey.STATUS: {TYPE: int, VALUE: 0, REQUIRED: True},<|fim▁hole|> AquadoppDwVelocityDataParticleKey.VELOCITY_BEAM2: {TYPE: int, VALUE: 0, REQUIRED: True}, AquadoppDwVelocityDataParticleKey.VELOCITY_BEAM3: {TYPE: int, VALUE: 0, REQUIRED: True}, AquadoppDwVelocityDataParticleKey.AMPLITUDE_BEAM1: {TYPE: int, VALUE: 0, REQUIRED: True}, AquadoppDwVelocityDataParticleKey.AMPLITUDE_BEAM2: {TYPE: int, VALUE: 0, REQUIRED: True}, AquadoppDwVelocityDataParticleKey.AMPLITUDE_BEAM3: {TYPE: int, VALUE: 0, REQUIRED: True} } def assert_particle_velocity(self, data_particle, verify_values=False): """ Verify velpt_velocity_data @param data_particle AquadoppDwVelocityDataParticleKey data particle @param verify_values bool, should we verify parameter values """ self.assert_data_particle_keys(AquadoppDwVelocityDataParticleKey, self._sample_velocity_diagnostic) self.assert_data_particle_header(data_particle, NortekDataParticleType.VELOCITY) self.assert_data_particle_parameters(data_particle, self._sample_velocity_diagnostic, verify_values) #################################### RULES #################################### # # # Common capabilities in the base class # # # # Instrument specific stuff in the derived class # # # # Generator spits out either stubs or comments describing test this here, # # test that there. # # # # Qualification tests are driven through the instrument_agent # # # ############################################################################### ############################################################################### # UNIT TESTS # # Unit tests test the method calls and parameters using Mock. # ############################################################################### @attr('UNIT', group='mi') class DriverUnitTest(NortekUnitTest): def setUp(self): NortekUnitTest.setUp(self) def test_driver_enums(self): """ Verify driver specific enums have no duplicates Base unit test driver will test enums specific for the base class. """ self.assert_enum_has_no_duplicates(NortekDataParticleType()) def test_velocity_sample_format(self): """ Verify driver can get velocity sample data out in a reasonable format. Parsed is all we care about...raw is tested in the base DataParticle tests """ port_timestamp = 3555423720.711772 driver_timestamp = 3555423722.711772 # construct the expected particle expected_particle = { DataParticleKey.PKT_FORMAT_ID: DataParticleValue.JSON_DATA, DataParticleKey.PKT_VERSION: 1, DataParticleKey.STREAM_NAME: NortekDataParticleType.VELOCITY, DataParticleKey.PORT_TIMESTAMP: port_timestamp, DataParticleKey.DRIVER_TIMESTAMP: driver_timestamp, DataParticleKey.PREFERRED_TIMESTAMP: DataParticleKey.PORT_TIMESTAMP, DataParticleKey.QUALITY_FLAG: DataParticleValue.OK, DataParticleKey.VALUES: velocity_particle} self.compare_parsed_data_particle(AquadoppDwVelocityDataParticle, velocity_sample(), expected_particle) def test_chunker(self): """ Verify the chunker can parse each sample type 1. complete data structure 2. fragmented data structure 3. combined data structure 4. data structure with noise """ chunker = StringChunker(NortekInstrumentProtocol.sieve_function) self.assert_chunker_sample(chunker, velocity_sample()) self.assert_chunker_fragmented_sample(chunker, velocity_sample()) self.assert_chunker_combined_sample(chunker, velocity_sample()) self.assert_chunker_sample_with_noise(chunker, velocity_sample()) def test_corrupt_data_structures(self): """ Verify when generating the particle, if the particle is corrupt, an exception is raised """ particle = AquadoppDwVelocityDataParticle(bad_sample(), port_timestamp=3558720820.531179) with self.assertRaises(SampleException): particle.generate() ############################################################################### # INTEGRATION TESTS # # Integration test test the direct driver / instrument interaction # # but making direct calls via zeromq. # # - Common Integration tests test the driver through the instrument agent # # and common for all drivers (minimum requirement for ION ingestion) # ############################################################################### @attr('INT', group='mi') class IntFromIDK(NortekIntTest, AquadoppDriverTestMixinSub): def setUp(self): NortekIntTest.setUp(self) def test_acquire_sample(self): """ Verify acquire sample command and events. 1. initialize the instrument to COMMAND state 2. command the driver to ACQUIRE SAMPLE 3. verify the particle coming in """ self.assert_initialize_driver(ProtocolState.COMMAND) self.assert_driver_command(ProtocolEvent.ACQUIRE_SAMPLE) self.assert_async_particle_generation(NortekDataParticleType.VELOCITY, self.assert_particle_velocity, timeout=TIMEOUT) def test_command_autosample(self): """ Verify autosample command and events. 1. initialize the instrument to COMMAND state 2. command the instrument to AUTOSAMPLE state 3. verify the particle coming in and the sampling is continuous (gather several samples) 4. stop AUTOSAMPLE """ self.assert_initialize_driver(ProtocolState.COMMAND) self.assert_driver_command(ProtocolEvent.START_AUTOSAMPLE, state=ProtocolState.AUTOSAMPLE, delay=1) self.assert_async_particle_generation(NortekDataParticleType.VELOCITY, self.assert_particle_velocity, particle_count=4, timeout=TIMEOUT) self.assert_driver_command(ProtocolEvent.STOP_AUTOSAMPLE, state=ProtocolState.COMMAND, delay=1) def test_parameters(self): """ Verify that we can set the parameters 1. Cannot set read only parameters 2. Can set read/write parameters """ self.assert_initialize_driver(ProtocolState.COMMAND) #test read/write parameter self.assert_set(Parameter.BLANKING_DISTANCE, 50) self.assert_set(Parameter.TIMING_CONTROL_REGISTER, 131) self.assert_set(Parameter.COMPASS_UPDATE_RATE, 2) self.assert_set(Parameter.COORDINATE_SYSTEM, 1) self.assert_set(Parameter.VELOCITY_ADJ_TABLE, 'bu0ePTk9Uz1uPYg9oj27PdQ97T0GPh4+Nj5OPmU+fT6TPqo+wD7WPuw+Aj8' 'XPyw/QT9VP2k/fT+RP6Q/uD/KP90/8D8CQBRAJkA3QElAWkBrQHxAjECcQK' 'xAvEDMQNtA6kD5QAhBF0ElQTNBQkFPQV1BakF4QYVBkkGeQatBt0HDQc9B20' 'HnQfJB/UEIQhNCHkIoQjNCPUJHQlFCW0JkQm5Cd0KAQolCkUKaQqJCqkKyQrpC',) #these need to update simultaneously #self.assert_set(Parameter.MEASUREMENT_INTERVAL, 61) #self.assert_set(Parameter.AVG_INTERVAL, 61) #test read only parameters (includes immutable, when not startup) self.assert_set_exception(EngineeringParameter.CLOCK_SYNC_INTERVAL, '12:00:00') self.assert_set_exception(EngineeringParameter.ACQUIRE_STATUS_INTERVAL, '12:00:00') self.assert_set_exception(Parameter.TRANSMIT_PULSE_LENGTH, 20) self.assert_set_exception(Parameter.TIME_BETWEEN_PINGS, 45) self.assert_set_exception(Parameter.NUMBER_PINGS, 1) self.assert_set_exception(Parameter.RECEIVE_LENGTH, 8) self.assert_set_exception(Parameter.TIME_BETWEEN_BURST_SEQUENCES, 1) self.assert_set_exception(Parameter.USER_NUMBER_BEAMS, 4) self.assert_set_exception(Parameter.POWER_CONTROL_REGISTER, 1) self.assert_set_exception(Parameter.A1_1_SPARE, 3) self.assert_set_exception(Parameter.B0_1_SPARE, 1) self.assert_set_exception(Parameter.B1_1_SPARE, 2) self.assert_set_exception(Parameter.NUMBER_BINS, 2) self.assert_set_exception(Parameter.BIN_LENGTH, 8) self.assert_set_exception(Parameter.ADJUSTMENT_SOUND_SPEED, 16658) self.assert_set_exception(Parameter.DEPLOYMENT_NAME, 'test') self.assert_set_exception(Parameter.WRAP_MODE, 0) self.assert_set_exception(Parameter.CLOCK_DEPLOY, 123) self.assert_set_exception(Parameter.DIAGNOSTIC_INTERVAL, 10801) self.assert_set_exception(Parameter.MODE, 49) self.assert_set_exception(Parameter.NUMBER_SAMPLES_DIAGNOSTIC, 2) self.assert_set_exception(Parameter.NUMBER_BEAMS_CELL_DIAGNOSTIC, 2) self.assert_set_exception(Parameter.NUMBER_PINGS_DIAGNOSTIC, 2) self.assert_set_exception(Parameter.MODE_TEST, 5) self.assert_set_exception(Parameter.ANALOG_INPUT_ADDR, '123') self.assert_set_exception(Parameter.SW_VERSION, 'blah') self.assert_set_exception(Parameter.USER_1_SPARE, 23) self.assert_set_exception(Parameter.COMMENTS, 'hello there') self.assert_set_exception(Parameter.WAVE_MEASUREMENT_MODE, 3) self.assert_set_exception(Parameter.DYN_PERCENTAGE_POSITION, 3) self.assert_set_exception(Parameter.WAVE_TRANSMIT_PULSE,3 ) self.assert_set_exception(Parameter.WAVE_BLANKING_DISTANCE, 3) self.assert_set_exception(Parameter.WAVE_CELL_SIZE, 3) self.assert_set_exception(Parameter.NUMBER_DIAG_SAMPLES, 1) self.assert_set_exception(Parameter.A1_2_SPARE, 6) self.assert_set_exception(Parameter.B0_2_SPARE, 4) self.assert_set_exception(Parameter.NUMBER_SAMPLES_PER_BURST, 4) self.assert_set_exception(Parameter.USER_2_SPARE, 1) self.assert_set_exception(Parameter.ANALOG_OUTPUT_SCALE, 234) self.assert_set_exception(Parameter.CORRELATION_THRESHOLD, 1234) self.assert_set_exception(Parameter.USER_3_SPARE, 1) self.assert_set_exception(Parameter.TRANSMIT_PULSE_LENGTH_SECOND_LAG, 1) self.assert_set_exception(Parameter.USER_4_SPARE, 1) self.assert_set_exception(Parameter.QUAL_CONSTANTS, 'consts') ############################################################################### # QUALIFICATION TESTS # # Device specific qualification tests are for # # testing device specific capabilities # ############################################################################### @attr('QUAL', group='mi') class QualFromIDK(NortekQualTest, AquadoppDriverTestMixinSub): def setUp(self): NortekQualTest.setUp(self) def test_direct_access_telnet_mode(self): """ Verify the Instrument Driver properly supports direct access to the physical instrument. (telnet mode) """ self.assert_direct_access_start_telnet() self.assertTrue(self.tcp_client) self.tcp_client.send_data("K1W%!Q") result = self.tcp_client.expect("AQUADOPP") self.assertTrue(result) log.debug("DA Server Started. Reading battery voltage") self.tcp_client.send_data("BV") self.tcp_client.expect("\x06\x06") self.tcp_client.send_data("CC" + user_config2()) self.tcp_client.expect("\x06\x06") self.assert_direct_access_stop_telnet() self.assert_state_change(ResourceAgentState.COMMAND, ProtocolState.COMMAND, 10) #verify the setting got restored. self.assert_get_parameter(Parameter.TRANSMIT_PULSE_LENGTH, 125) self.assert_get_parameter(Parameter.RECEIVE_LENGTH, 32) self.assert_get_parameter(Parameter.TIME_BETWEEN_BURST_SEQUENCES, 512) self.assert_get_parameter(Parameter.TIMING_CONTROL_REGISTER, 131) self.assert_get_parameter(Parameter.BIN_LENGTH, 7) self.assert_get_parameter(Parameter.ADJUSTMENT_SOUND_SPEED, 1525) self.assert_get_parameter(Parameter.VELOCITY_ADJ_TABLE, 'Aj0ePTk9Uz1uPYg9oj27PdQ97T0GPh4+Nj5OPmU+fT6TPqo+wD7WPuw+Aj8' 'XPyw/QT9VP2k/fT+RP6Q/uD/KP90/8D8CQBRAJkA3QElAWkBrQHxAjECcQK' 'xAvEDMQNtA6kD5QAhBF0ElQTNBQkFPQV1BakF4QYVBkkGeQatBt0HDQc9B20' 'HnQfJB/UEIQhNCHkIoQjNCPUJHQlFCW0JkQm5Cd0KAQolCkUKaQqJCqkKyQrpC',) self.assert_get_parameter(EngineeringParameter.CLOCK_SYNC_INTERVAL, '00:00:00') self.assert_get_parameter(EngineeringParameter.ACQUIRE_STATUS_INTERVAL, '00:00:00') self.assert_get_parameter(Parameter.BLANKING_DISTANCE, 49) self.assert_get_parameter(Parameter.TIME_BETWEEN_PINGS, 437) self.assert_get_parameter(Parameter.NUMBER_PINGS, 1) self.assert_get_parameter(Parameter.AVG_INTERVAL, 1) self.assert_get_parameter(Parameter.USER_NUMBER_BEAMS, 3) self.assert_get_parameter(Parameter.POWER_CONTROL_REGISTER, 0) self.assert_get_parameter(Parameter.COMPASS_UPDATE_RATE, 1) self.assert_get_parameter(Parameter.COORDINATE_SYSTEM, 2) self.assert_get_parameter(Parameter.NUMBER_BINS, 1) self.assert_get_parameter(Parameter.MEASUREMENT_INTERVAL, 1) self.assert_get_parameter(Parameter.WRAP_MODE, 0) self.assert_get_parameter(Parameter.CLOCK_DEPLOY, [0,0,0,0,0,0]) self.assert_get_parameter(Parameter.DIAGNOSTIC_INTERVAL, 11250) self.assert_get_parameter(Parameter.MODE, 48) self.assert_get_parameter(Parameter.NUMBER_SAMPLES_DIAGNOSTIC, 20) self.assert_get_parameter(Parameter.NUMBER_BEAMS_CELL_DIAGNOSTIC, 1) self.assert_get_parameter(Parameter.NUMBER_PINGS_DIAGNOSTIC, 1) self.assert_get_parameter(Parameter.MODE_TEST, 4) self.assert_get_parameter(Parameter.WAVE_MEASUREMENT_MODE, 0) self.assert_get_parameter(Parameter.DYN_PERCENTAGE_POSITION, 0) self.assert_get_parameter(Parameter.WAVE_TRANSMIT_PULSE, 0) self.assert_get_parameter(Parameter.WAVE_BLANKING_DISTANCE, 0) self.assert_get_parameter(Parameter.WAVE_CELL_SIZE, 0) self.assert_get_parameter(Parameter.NUMBER_DIAG_SAMPLES, 0) self.assert_get_parameter(Parameter.NUMBER_SAMPLES_PER_BURST, 0) self.assert_get_parameter(Parameter.ANALOG_OUTPUT_SCALE, 6711) self.assert_get_parameter(Parameter.CORRELATION_THRESHOLD, 0) self.assert_get_parameter(Parameter.TRANSMIT_PULSE_LENGTH_SECOND_LAG, 2) # Test direct access inactivity timeout self.assert_direct_access_start_telnet(inactivity_timeout=30, session_timeout=90) self.assert_state_change(ResourceAgentState.COMMAND, ProtocolState.COMMAND, 60) # Test session timeout without activity self.assert_direct_access_start_telnet(inactivity_timeout=120, session_timeout=30) self.assert_state_change(ResourceAgentState.COMMAND, ProtocolState.COMMAND, 60) # Test direct access session timeout with activity self.assert_direct_access_start_telnet(inactivity_timeout=30, session_timeout=60) # Send some activity every 30 seconds to keep DA alive. for i in range(1, 2, 3): self.tcp_client.send_data(NEWLINE) log.debug("Sending a little keep alive communication, sleeping for 15 seconds") time.sleep(15) self.assert_state_change(ResourceAgentState.COMMAND, ProtocolState.COMMAND, 45) def test_get_set_parameters(self): """ Verify that parameters can be get/set properly """ self.assert_enter_command_mode() #test read/write parameter self.assert_set_parameter(Parameter.BLANKING_DISTANCE, 50) self.assert_set_parameter(Parameter.TIMING_CONTROL_REGISTER, 131) self.assert_set_parameter(Parameter.COMPASS_UPDATE_RATE, 2) self.assert_set_parameter(Parameter.COORDINATE_SYSTEM, 1) self.assert_set_parameter(Parameter.VELOCITY_ADJ_TABLE, 'bu0ePTk9Uz1uPYg9oj27PdQ97T0GPh4+Nj5OPmU+fT6TPqo+wD7WPuw+Aj8' 'XPyw/QT9VP2k/fT+RP6Q/uD/KP90/8D8CQBRAJkA3QElAWkBrQHxAjECcQK' 'xAvEDMQNtA6kD5QAhBF0ElQTNBQkFPQV1BakF4QYVBkkGeQatBt0HDQc9B20' 'HnQfJB/UEIQhNCHkIoQjNCPUJHQlFCW0JkQm5Cd0KAQolCkUKaQqJCqkKyQrpC',) #test read only parameters (includes immutable, when not startup) self.assert_get_parameter(EngineeringParameter.CLOCK_SYNC_INTERVAL, '00:00:00') self.assert_get_parameter(EngineeringParameter.ACQUIRE_STATUS_INTERVAL, '00:00:00') self.assert_get_parameter(Parameter.TRANSMIT_PULSE_LENGTH, 125) self.assert_get_parameter(Parameter.TIME_BETWEEN_PINGS, 437) self.assert_get_parameter(Parameter.NUMBER_PINGS, 1) self.assert_get_parameter(Parameter.RECEIVE_LENGTH, 32) self.assert_get_parameter(Parameter.TIME_BETWEEN_BURST_SEQUENCES, 512) self.assert_get_parameter(Parameter.USER_NUMBER_BEAMS, 3) self.assert_get_parameter(Parameter.POWER_CONTROL_REGISTER, 0) self.assert_get_parameter(Parameter.NUMBER_BINS, 1) self.assert_get_parameter(Parameter.BIN_LENGTH, 7) self.assert_get_parameter(Parameter.ADJUSTMENT_SOUND_SPEED, 1525) self.assert_get_parameter(Parameter.WRAP_MODE, 0) self.assert_get_parameter(Parameter.CLOCK_DEPLOY, [0, 0, 0, 0, 0, 0]) self.assert_get_parameter(Parameter.DIAGNOSTIC_INTERVAL, 11250) self.assert_get_parameter(Parameter.MODE, 48) self.assert_get_parameter(Parameter.NUMBER_SAMPLES_DIAGNOSTIC, 20) self.assert_get_parameter(Parameter.NUMBER_BEAMS_CELL_DIAGNOSTIC, 1) self.assert_get_parameter(Parameter.ANALOG_INPUT_ADDR, 0) self.assert_get_parameter(Parameter.NUMBER_PINGS_DIAGNOSTIC, 1) self.assert_get_parameter(Parameter.MODE_TEST, 4) self.assert_get_parameter(Parameter.SW_VERSION, 13902) self.assert_get_parameter(Parameter.SW_VERSION, 13902) self.assert_get_parameter(Parameter.WAVE_MEASUREMENT_MODE, 0) self.assert_get_parameter(Parameter.DYN_PERCENTAGE_POSITION, 0) self.assert_get_parameter(Parameter.WAVE_TRANSMIT_PULSE, 0) self.assert_get_parameter(Parameter.WAVE_BLANKING_DISTANCE, 0) self.assert_get_parameter(Parameter.WAVE_CELL_SIZE, 0) self.assert_get_parameter(Parameter.NUMBER_DIAG_SAMPLES, 0) self.assert_get_parameter(Parameter.NUMBER_SAMPLES_PER_BURST, 0) self.assert_get_parameter(Parameter.ANALOG_OUTPUT_SCALE, 6711) self.assert_get_parameter(Parameter.CORRELATION_THRESHOLD, 0) self.assert_get_parameter(Parameter.TRANSMIT_PULSE_LENGTH_SECOND_LAG, 2) #NOTE: the following cannot be tested because there are no default values # 'spare' parameters are not used by the driver, only place holders for the config file sent to set params # other parameter values are dependent on the instrument being tested # self.assert_get_parameter(Parameter.A1_1_SPARE, 3) # self.assert_get_parameter(Parameter.B0_1_SPARE, 1) # self.assert_get_parameter(Parameter.B1_1_SPARE, 2) # self.assert_get_parameter(Parameter.DEPLOYMENT_NAME, 'test') # self.assert_get_parameter(Parameter.USER_1_SPARE, 23) # self.assert_get_parameter(Parameter.COMMENTS, 'hello there') # self.assert_get_parameter(Parameter.A1_2_SPARE, 6) # self.assert_get_parameter(Parameter.B0_2_SPARE, 4) # self.assert_get_parameter(Parameter.USER_2_SPARE, 1) # self.assert_get_parameter(Parameter.USER_3_SPARE, 1) # self.assert_get_parameter(Parameter.USER_4_SPARE, 1) # self.assert_get_parameter(Parameter.QUAL_CONSTANTS, 'consts') def test_poll(self): """ Verify the driver can poll the instrument for a single sample """ self.assert_sample_polled(self.assert_particle_velocity, NortekDataParticleType.VELOCITY, timeout=10) def test_autosample(self): """ Verify the driver can enter and exit autosample mode, while in autosample the driver will collect multiple samples. """ self.assert_sample_autosample(self.assert_particle_velocity, NortekDataParticleType.VELOCITY, timeout=20)<|fim▁end|>
AquadoppDwVelocityDataParticleKey.TEMPERATURE: {TYPE: int, VALUE: 0, REQUIRED: True}, AquadoppDwVelocityDataParticleKey.VELOCITY_BEAM1: {TYPE: int, VALUE: 0, REQUIRED: True},
<|file_name|>MessageTest.java<|end_file_name|><|fim▁begin|>/** * The MIT License * Copyright (c) 2012 Graylog, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.graylog2.plugin; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.graylog2.plugin.streams.Stream; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class MessageTest { private Message message; private DateTime originalTimestamp; @Before public void setUp() { originalTimestamp = Tools.iso8601(); message = new Message("foo", "bar", originalTimestamp); } @Test public void testAddFieldDoesOnlyAcceptAlphanumericKeys() throws Exception { Message m = new Message("foo", "bar", Tools.iso8601()); m.addField("some_thing", "bar"); assertEquals("bar", m.getField("some_thing")); m = new Message("foo", "bar", Tools.iso8601()); m.addField("some-thing", "bar"); assertEquals("bar", m.getField("some-thing")); m = new Message("foo", "bar", Tools.iso8601()); m.addField("somethin$g", "bar"); assertNull(m.getField("somethin$g")); m = new Message("foo", "bar", Tools.iso8601()); m.addField("someäthing", "bar"); assertNull(m.getField("someäthing")); } @Test public void testAddFieldTrimsValue() throws Exception { Message m = new Message("foo", "bar", Tools.iso8601()); m.addField("something", " bar "); assertEquals("bar", m.getField("something")); m.addField("something2", " bar"); assertEquals("bar", m.getField("something2")); m.addField("something3", "bar "); assertEquals("bar", m.getField("something3")); } @Test public void testAddFieldWorksWithIntegers() throws Exception { Message m = new Message("foo", "bar", Tools.iso8601()); m.addField("something", 3); assertEquals(3, m.getField("something")); } @Test public void testAddFields() throws Exception { final Map<String, Object> map = Maps.newHashMap(); map.put("field1", "Foo"); map.put("field2", 1); message.addFields(map); assertEquals("Foo", message.getField("field1")); assertEquals(1, message.getField("field2")); } @Test public void testAddStringFields() throws Exception { final Map<String, String> map = Maps.newHashMap(); map.put("field1", "Foo"); map.put("field2", "Bar"); message.addStringFields(map); assertEquals("Foo", message.getField("field1")); assertEquals("Bar", message.getField("field2")); } @Test public void testAddLongFields() throws Exception { final Map<String, Long> map = Maps.newHashMap(); map.put("field1", 10L); map.put("field2", 230L); message.addLongFields(map); assertEquals(10L, message.getField("field1")); assertEquals(230L, message.getField("field2")); } @Test public void testAddDoubleFields() throws Exception { final Map<String, Double> map = Maps.newHashMap(); map.put("field1", 10.0d); map.put("field2", 230.2d); message.addDoubleFields(map); assertEquals(10.0d, message.getField("field1")); assertEquals(230.2d, message.getField("field2")); } @Test public void testRemoveField() throws Exception { message.addField("foo", "bar"); message.removeField("foo"); assertNull(message.getField("foo")); } @Test public void testRemoveFieldNotDeletingReservedFields() throws Exception { message.removeField("message"); message.removeField("source"); message.removeField("timestamp"); assertNotNull(message.getField("message")); assertNotNull(message.getField("source")); assertNotNull(message.getField("timestamp")); } @Test public void testGetFieldAs() throws Exception { message.addField("fields", Lists.newArrayList("hello")); assertEquals(Lists.newArrayList("hello"), message.getFieldAs(List.class, "fields")); } @Test(expected = ClassCastException.class) public void testGetFieldAsWithIncompatibleCast() throws Exception { message.addField("fields", Lists.newArrayList("hello")); message.getFieldAs(Map.class, "fields"); } @Test public void testSetAndGetStreams() throws Exception { final Stream stream1 = mock(Stream.class); final Stream stream2 = mock(Stream.class); message.setStreams(Lists.newArrayList(stream1, stream2)); assertEquals(Lists.newArrayList(stream1, stream2), message.getStreams()); } @Test public void testGetStreamIds() throws Exception { message.addField("streams", Lists.newArrayList("stream-id")); assertEquals(Lists.newArrayList("stream-id"), message.getStreamIds()); } @Test public void testGetAndSetFilterOut() throws Exception { assertFalse(message.getFilterOut()); message.setFilterOut(true); assertTrue(message.getFilterOut()); message.setFilterOut(false); assertFalse(message.getFilterOut()); } @Test public void testGetId() throws Exception { final Pattern pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); assertTrue(pattern.matcher(message.getId()).matches()); } @Test public void testGetTimestamp() { try { final DateTime timestamp = message.getTimestamp(); assertNotNull(timestamp); assertEquals(originalTimestamp.getZone(), timestamp.getZone()); } catch (ClassCastException e) { fail("timestamp wasn't a DateTime " + e.getMessage()); } } @Test public void testTimestampAsDate() { final DateTime dateTime = new DateTime(2015, 9, 8, 0, 0, DateTimeZone.UTC); message.addField(Message.FIELD_TIMESTAMP, dateTime.toDate()); final Map<String, Object> elasticSearchObject = message.toElasticSearchObject(); final Object esTimestampFormatted = elasticSearchObject.get(Message.FIELD_TIMESTAMP); assertEquals("Setting message timestamp as java.util.Date results in correct format for elasticsearch", Tools.buildElasticSearchTimeFormat(dateTime), esTimestampFormatted); } @Test public void testGetMessage() throws Exception { assertEquals("foo", message.getMessage()); } @Test public void testGetSource() throws Exception { assertEquals("bar", message.getSource()); } @Test public void testValidKeys() throws Exception { assertTrue(Message.validKey("foo123")); assertTrue(Message.validKey("foo-bar123")); assertTrue(Message.validKey("foo_bar123")); assertTrue(Message.validKey("foo.bar123")); assertTrue(Message.validKey("123")); assertTrue(Message.validKey("")); assertFalse(Message.validKey("foo bar")); assertFalse(Message.validKey("foo+bar")); assertFalse(Message.validKey("foo$bar")); assertFalse(Message.validKey(" ")); } @Test public void testToElasticSearchObject() throws Exception { message.addField("field1", "wat"); message.addField("field2", "that"); final Map<String, Object> object = message.toElasticSearchObject(); assertEquals("foo", object.get("message")); assertEquals("bar", object.get("source")); assertEquals("wat", object.get("field1")); assertEquals("that", object.get("field2")); assertEquals(Tools.buildElasticSearchTimeFormat((DateTime) message.getField("timestamp")), object.get("timestamp")); assertEquals(Collections.EMPTY_LIST, object.get("streams")); } @Test public void testToElasticSearchObjectWithoutDateTimeTimestamp() throws Exception { message.addField("timestamp", "time!"); final Map<String, Object> object = message.toElasticSearchObject(); assertEquals("time!", object.get("timestamp")); }<|fim▁hole|> public void testToElasticSearchObjectWithStreams() throws Exception { final Stream stream = mock(Stream.class); when(stream.getId()).thenReturn("stream-id"); message.setStreams(Lists.newArrayList(stream)); final Map<String, Object> object = message.toElasticSearchObject(); assertEquals(Lists.newArrayList("stream-id"), object.get("streams")); } @Test public void testIsComplete() throws Exception { Message message = new Message("message", "source", Tools.iso8601()); assertTrue(message.isComplete()); message = new Message("message", "", Tools.iso8601()); assertTrue(message.isComplete()); message = new Message("message", null, Tools.iso8601()); assertTrue(message.isComplete()); message = new Message("", "source", Tools.iso8601()); assertFalse(message.isComplete()); message = new Message(null, "source", Tools.iso8601()); assertFalse(message.isComplete()); } @Test public void testGetValidationErrorsWithEmptyMessage() throws Exception { final Message message = new Message("", "source", Tools.iso8601()); assertEquals("message is empty, ", message.getValidationErrors()); } @Test public void testGetValidationErrorsWithNullMessage() throws Exception { final Message message = new Message(null, "source", Tools.iso8601()); assertEquals("message is missing, ", message.getValidationErrors()); } @Test public void testGetFields() throws Exception { final Map<String, Object> fields = message.getFields(); assertEquals(message.getId(), fields.get("_id")); assertEquals(message.getMessage(), fields.get("message")); assertEquals(message.getSource(), fields.get("source")); assertEquals(message.getField("timestamp"), fields.get("timestamp")); } @Test(expected = UnsupportedOperationException.class) public void testGetFieldsReturnsImmutableMap() throws Exception { final Map<String, Object> fields = message.getFields(); fields.put("foo", "bar"); } @Test public void testGetFieldNames() throws Exception { assertTrue("Missing fields in set!", Sets.symmetricDifference(message.getFieldNames(), Sets.newHashSet("_id", "timestamp", "source", "message")).isEmpty()); message.addField("testfield", "testvalue"); assertTrue("Missing fields in set!", Sets.symmetricDifference(message.getFieldNames(), Sets.newHashSet("_id", "timestamp", "source", "message", "testfield")).isEmpty()); } @Test(expected = UnsupportedOperationException.class) public void testGetFieldNamesReturnsUnmodifiableSet() throws Exception { final Set<String> fieldNames = message.getFieldNames(); fieldNames.remove("_id"); } @Test public void testHasField() throws Exception { assertFalse(message.hasField("__foo__")); message.addField("__foo__", "bar"); assertTrue(message.hasField("__foo__")); } }<|fim▁end|>
@Test
<|file_name|>style.js<|end_file_name|><|fim▁begin|>// ------------------------------------------------------------- // WARNING: this file is used by both the client and the server. // Do not use any browser or node-specific API! // ------------------------------------------------------------- /* eslint hammerhead/proto-methods: 2 */ import reEscape from '../utils/regexp-escape'; import INTERNAL_ATTRS from '../processing/dom/internal-attributes'; import { isSpecialPage } from '../utils/url'; const SOURCE_MAP_RE = /#\s*sourceMappingURL\s*=\s*[^\s]+(\s|\*\/)/i; const CSS_URL_PROPERTY_VALUE_PATTERN = /(url\s*\(\s*)(?:(')([^\s']*)(')|(")([^\s"]*)(")|([^\s\)]*))(\s*\))|(@import\s+)(?:(')([^\s']*)(')|(")([^\s"]*)("))/g; const STYLESHEET_PROCESSING_START_COMMENT = '/*hammerhead|stylesheet|start*/'; const STYLESHEET_PROCESSING_END_COMMENT = '/*hammerhead|stylesheet|end*/'; const HOVER_PSEUDO_CLASS_RE = /\s*:\s*hover(\W)/gi; const PSEUDO_CLASS_RE = new RegExp(`\\[${ INTERNAL_ATTRS.hoverPseudoClass }\\](\\W)`, 'ig'); const IS_STYLE_SHEET_PROCESSED_RE = new RegExp(`^\\s*${ reEscape(STYLESHEET_PROCESSING_START_COMMENT) }`, 'gi'); const STYLESHEET_PROCESSING_COMMENTS_RE = new RegExp(`^\\s*${ reEscape(STYLESHEET_PROCESSING_START_COMMENT) }\n?|` + `\n?${ reEscape(STYLESHEET_PROCESSING_END_COMMENT) }\\s*$`, 'gi'); class StyleProcessor { constructor () { this.STYLESHEET_PROCESSING_START_COMMENT = STYLESHEET_PROCESSING_START_COMMENT; this.STYLESHEET_PROCESSING_END_COMMENT = STYLESHEET_PROCESSING_END_COMMENT; } process (css, urlReplacer, isStylesheetTable) { if (!css || typeof css !== 'string' || IS_STYLE_SHEET_PROCESSED_RE.test(css)) return css; var prefix = isStylesheetTable ? STYLESHEET_PROCESSING_START_COMMENT + '\n' : ''; var postfix = isStylesheetTable ? '\n' + STYLESHEET_PROCESSING_END_COMMENT : ''; // NOTE: Replace the :hover pseudo-class. css = css.replace(HOVER_PSEUDO_CLASS_RE, '[' + INTERNAL_ATTRS.hoverPseudoClass + ']$1'); // NOTE: Remove the ‘source map’ directive. css = css.replace(SOURCE_MAP_RE, '$1'); // NOTE: Replace URLs in CSS rules with proxy URLs. return prefix + this._replaceStylsheetUrls(css, urlReplacer) + postfix; } cleanUp (css, parseProxyUrl) { if (typeof css !== 'string') return css; css = css .replace(PSEUDO_CLASS_RE, ':hover$1') .replace(STYLESHEET_PROCESSING_COMMENTS_RE, ''); return this._replaceStylsheetUrls(css, url => { var parsedProxyUrl = parseProxyUrl(url); return parsedProxyUrl ? parsedProxyUrl.destUrl : url; }); } _replaceStylsheetUrls (css, processor) { return css.replace( CSS_URL_PROPERTY_VALUE_PATTERN, (match, prefix1, openQuote1, url1, closeQuote1, openQuote2, url2, closeQuote2, url3, postfix, prefix2, openQuote3, url4, closeQuote3, openQuote4, url5, closeQuote4) => { var prefix = prefix1 || prefix2; var openQuote = openQuote1 || openQuote2 || openQuote3 || openQuote4 || '';<|fim▁hole|> postfix = postfix || ''; var processedUrl = isSpecialPage(url) ? url : processor(url); return url ? prefix + openQuote + processedUrl + closeQuote + postfix : match; } ); } } export default new StyleProcessor();<|fim▁end|>
var url = url1 || url2 || url3 || url4 || url5; var closeQuote = closeQuote1 || closeQuote2 || closeQuote3 || closeQuote4 || '';
<|file_name|>custom-admin.js<|end_file_name|><|fim▁begin|>jQuery(function($) { /////////////////////////////////////////////////////////////////// ///// META BOXES JS /////////////////////////////////////////////////////////////////// jQuery('.repeatable-add').live('click', function() { var field = jQuery(this).closest('td').find('.custom_repeatable li:last').clone(true); var fieldLocation = jQuery(this).closest('td').find('.custom_repeatable li:last'); field.find('input.regular-text, textarea, select').val(''); field.find('input, textarea, select').attr('name', function(index, name) { return name.replace(/(\d+)/, function(fullMatch, n) { return Number(n) + 1; }); }); field.insertAfter(fieldLocation, jQuery(this).closest('td')); var fieldsCount = jQuery('.repeatable-remove').length; if( fieldsCount > 1 ) { jQuery('.repeatable-remove').css('display','inline'); } return false; }); var fieldsCount = jQuery('.repeatable-remove').length; if( fieldsCount == 1 ) { jQuery('.repeatable-remove').css('display','none'); } jQuery('.repeatable-remove').live('click', function() { jQuery(this).parent().remove(); var fieldsCount = jQuery('.repeatable-remove').length; if( fieldsCount == 1 ) { jQuery('.repeatable-remove').css('display','none'); } return false; }); jQuery('.custom_repeatable').sortable({ opacity: 0.6, revert: true, cursor: 'move', handle: '.sort' }); // the upload image button, saves the id and outputs a preview of the image var imageFrame; $('.rg-bb_upload_image_button').live('click', function(event) { event.preventDefault(); var options, attachment; $self = $(event.target); $div = $self.closest('div.rg-bb_image'); // if the frame already exists, open it if ( imageFrame ) { imageFrame.open(); return; } // set our settings imageFrame = wp.media({ title: 'Choose Image', multiple: true, library: { type: 'image' }, button: { text: 'Use This Image' } }); // set up our select handler<|fim▁hole|> if ( ! selection ) return; // loop through the selected files selection.each( function( attachment ) { console.log(attachment); var src = attachment.attributes.sizes.full.url; var id = attachment.id; $div.find('.rg-bb_preview_image').attr('src', src); $div.find('.rg-bb_upload_image').val(id); } ); }); // open the frame imageFrame.open(); }); // the remove image link, removes the image id from the hidden field and replaces the image preview $('.rg-bb_clear_image_button').live('click', function() { var defaultImage = $(this).parent().siblings('.rg-bb_default_image').text(); $(this).parent().siblings('.rg-bb_upload_image').val(''); $(this).parent().siblings('.rg-bb_preview_image').attr('src', defaultImage); return false; }); // function to create an array of input values function ids(inputs) { var a = []; for (var i = 0; i < inputs.length; i++) { a.push(inputs[i].val); } //$("span").text(a.join(" ")); } // repeatable fields $('.toggle').on("click", function() { console.log($(this).parent().siblings().toggleClass('closed')); }); $('.meta_box_repeatable_add').live('click', function(e) { e.preventDefault(); // clone var row = $(this).closest('.meta_box_repeatable').find('tbody tr:last-child'); var clone = row.clone(); var defaultImage = clone.find('.meta_box_default_image').text(); clone.find('select.chosen').removeAttr('style', '').removeAttr('id', '').removeClass('chzn-done').data('chosen', null).next().remove(); // clone.find('input.regular-text, textarea, select').val(''); clone.find('.meta_box_preview_image').attr('src', defaultImage).removeClass('loaded'); clone.find('input[type=checkbox], input[type=radio]').attr('checked', false); row.after(clone); // increment name and id clone.find('input, textarea, select').attr('name', function(index, name) { return name.replace(/(\d+)/, function(fullMatch, n) { return Number(n) + 1; }); }); var arr = []; $('input.repeatable_id:text').each(function(){ arr.push($(this).val()); }); clone.find('input.repeatable_id') .val(Number(Math.max.apply( Math, arr )) + 1); if (!!$.prototype.chosen) { clone.find('select.chosen') .chosen({allow_single_deselect: true}); } }); $('.meta_box_repeatable_remove').live('click', function(e){ e.preventDefault(); $(this).closest('tr').remove(); }); $('.meta_box_repeatable tbody').sortable({ opacity: 0.6, revert: true, cursor: 'move', handle: '.hndle' }); // post_drop_sort $('.sort_list').sortable({ connectWith: '.sort_list', opacity: 0.6, revert: true, cursor: 'move', cancel: '.post_drop_sort_area_name', items: 'li:not(.post_drop_sort_area_name)', update: function(event, ui) { var result = $(this).sortable('toArray'); var thisID = $(this).attr('id'); $('.store-' + thisID).val(result) } }); $('.sort_list').disableSelection(); // turn select boxes into something magical if (!!$.prototype.chosen) $('.chosen').chosen({ allow_single_deselect: true }); });<|fim▁end|>
imageFrame.on( 'select', function() { selection = imageFrame.state().get('selection');
<|file_name|>paymentserver.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "paymentserver.h" #include "guiconstants.h" #include "ui_interface.h" #include "util.h" #include <QByteArray> #include <QDataStream> #include <QDebug> #include <QFileOpenEvent> #include <QHash> #include <QLocalServer> #include <QLocalSocket> #include <QStringList> #if QT_VERSION < 0x050000 #include <QUrl> #endif using namespace boost; const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds const QString BITCOIN_IPC_PREFIX("PAPAFRANCESCOCoin:"); // // Create a name that is unique for: // testnet / non-testnet // data directory // static QString ipcServerName() { QString name("BitcoinQt"); // Append a simple hash of the datadir // Note that GetDataDir(true) returns a different path // for -testnet versus main net QString ddir(GetDataDir(true).string().c_str()); name.append(QString::number(qHash(ddir))); return name; } // // This stores payment requests received before // the main GUI window is up and ready to ask the user // to send payment. // static QStringList savedPaymentRequests; // // Sending to the server is done synchronously, at startup. // If the server isn't already running, startup continues, // and the items in savedPaymentRequest will be handled // when uiReady() is called. // bool PaymentServer::ipcSendCommandLine() { bool fResult = false; const QStringList& args = qApp->arguments(); for (int i = 1; i < args.size(); i++) { if (!args[i].startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) continue; savedPaymentRequests.append(args[i]); } foreach (const QString& arg, savedPaymentRequests) { QLocalSocket* socket = new QLocalSocket(); socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) return false; QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << arg; out.device()->seek(0); socket->write(block); socket->flush(); socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT); socket->disconnectFromServer(); delete socket; fResult = true; } return fResult; } PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(true) { // Install global event filter to catch QFileOpenEvents on the mac (sent when you click bitcoin: links) parent->installEventFilter(this);<|fim▁hole|> QLocalServer::removeServer(name); uriServer = new QLocalServer(this); if (!uriServer->listen(name)) qDebug() << tr("Cannot start PAPAFRANCESCOCoin: click-to-pay handler"); else connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection())); } bool PaymentServer::eventFilter(QObject *object, QEvent *event) { // clicking on bitcoin: URLs creates FileOpen events on the Mac: if (event->type() == QEvent::FileOpen) { QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event); if (!fileEvent->url().isEmpty()) { if (saveURIs) // Before main window is ready: savedPaymentRequests.append(fileEvent->url().toString()); else emit receivedURI(fileEvent->url().toString()); return true; } } return false; } void PaymentServer::uiReady() { saveURIs = false; foreach (const QString& s, savedPaymentRequests) emit receivedURI(s); savedPaymentRequests.clear(); } void PaymentServer::handleURIConnection() { QLocalSocket *clientConnection = uriServer->nextPendingConnection(); while (clientConnection->bytesAvailable() < (int)sizeof(quint32)) clientConnection->waitForReadyRead(); connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); QDataStream in(clientConnection); in.setVersion(QDataStream::Qt_4_0); if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { return; } QString message; in >> message; if (saveURIs) savedPaymentRequests.append(message); else emit receivedURI(message); }<|fim▁end|>
QString name = ipcServerName(); // Clean up old socket leftover from a crash:
<|file_name|>EditorMouseMenu.java<|end_file_name|><|fim▁begin|>/* * EditorMouseMenu.java * * Created on March 21, 2007, 10:34 AM; Updated May 29, 2007 * * Copyright 2007 Grotto Networking */ package Samples.MouseMenu; import edu.uci.ics.jung.algorithms.layout.Layout; import edu.uci.ics.jung.algorithms.layout.StaticLayout; import edu.uci.ics.jung.graph.SparseMultigraph; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse; import edu.uci.ics.jung.visualization.control.ModalGraphMouse; import edu.uci.ics.jung.visualization.decorators.ToStringLabeller; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPopupMenu; /** * Illustrates the use of custom edge and vertex classes in a graph editing application. * Demonstrates a new graph mouse plugin for bringing up popup menus for vertices and * edges. * @author Dr. Greg M. Bernstein */ public class EditorMouseMenu { <|fim▁hole|> /** * @param args the command line arguments */ public static void main(String[] args) { JFrame frame = new JFrame("Editing and Mouse Menu Demo"); SparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge> g = new SparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge>(); // Layout<V, E>, VisualizationViewer<V,E> // Map<GraphElements.MyVertex,Point2D> vertexLocations = new HashMap<GraphElements.MyVertex, Point2D>(); Layout<GraphElements.MyVertex, GraphElements.MyEdge> layout = new StaticLayout(g); layout.setSize(new Dimension(300,300)); VisualizationViewer<GraphElements.MyVertex,GraphElements.MyEdge> vv = new VisualizationViewer<GraphElements.MyVertex,GraphElements.MyEdge>(layout); vv.setPreferredSize(new Dimension(350,350)); // Show vertex and edge labels vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller()); vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller()); // Create a graph mouse and add it to the visualization viewer EditingModalGraphMouse gm = new EditingModalGraphMouse(vv.getRenderContext(), GraphElements.MyVertexFactory.getInstance(), GraphElements.MyEdgeFactory.getInstance()); // Set some defaults for the Edges... GraphElements.MyEdgeFactory.setDefaultCapacity(192.0); GraphElements.MyEdgeFactory.setDefaultWeight(5.0); // Trying out our new popup menu mouse plugin... PopupVertexEdgeMenuMousePlugin myPlugin = new PopupVertexEdgeMenuMousePlugin(); // Add some popup menus for the edges and vertices to our mouse plugin. JPopupMenu edgeMenu = new MyMouseMenus.EdgeMenu(frame); JPopupMenu vertexMenu = new MyMouseMenus.VertexMenu(); myPlugin.setEdgePopup(edgeMenu); myPlugin.setVertexPopup(vertexMenu); gm.remove(gm.getPopupEditingPlugin()); // Removes the existing popup editing plugin gm.add(myPlugin); // Add our new plugin to the mouse vv.setGraphMouse(gm); //JFrame frame = new JFrame("Editing and Mouse Menu Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(vv); // Let's add a menu for changing mouse modes JMenuBar menuBar = new JMenuBar(); JMenu modeMenu = gm.getModeMenu(); modeMenu.setText("Mouse Mode"); modeMenu.setIcon(null); // I'm using this in a main menu modeMenu.setPreferredSize(new Dimension(80,20)); // Change the size so I can see the text menuBar.add(modeMenu); frame.setJMenuBar(menuBar); gm.setMode(ModalGraphMouse.Mode.EDITING); // Start off in editing mode frame.pack(); frame.setVisible(true); } }<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>__all__ = ["speedtest_exceptions", "speedtest"]<|fim▁hole|>from . import sendtest<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2020 CERN<|fim▁hole|># modify it under the terms of the MIT License; see the # LICENSE file for more details. from indico.util.mimetypes import register_custom_mimetypes __version__ = '2.3-dev' register_custom_mimetypes()<|fim▁end|>
# # Indico is free software; you can redistribute it and/or
<|file_name|>FeedEntryEditor.js.uncompressed.js<|end_file_name|><|fim▁begin|>define( "dojox/atom/widget/nls/ja/FeedEntryEditor", ({ doNew: "[新規]", edit: "[編集]", save: "[保存]", cancel: "[キャンセル]" })<|fim▁hole|><|fim▁end|>
);
<|file_name|>test.py<|end_file_name|><|fim▁begin|># Python - 3.6.0 <|fim▁hole|><|fim▁end|>
Test.expect(find_multiples(5, 25) == [5, 10, 15, 20, 25], f'{str(find_multiples(5, 25))} should equal [5, 10, 15, 20, 25]') Test.expect(find_multiples(1, 2) == [1, 2], f'{str(find_multiples(1, 2))} should equal [1, 2]')
<|file_name|>cloudpickle_wrapper.py<|end_file_name|><|fim▁begin|>import inspect from functools import partial try: from joblib.externals.cloudpickle import dumps, loads cloudpickle = True except ImportError: cloudpickle = False WRAP_CACHE = dict() class CloudpickledObjectWrapper(object): def __init__(self, obj, keep_wrapper=False): self._obj = obj self._keep_wrapper = keep_wrapper def __reduce__(self): _pickled_object = dumps(self._obj) if not self._keep_wrapper: return loads, (_pickled_object,) return _reconstruct_wrapper, (_pickled_object, self._keep_wrapper) def __getattr__(self, attr): # Ensure that the wrapped object can be used seemlessly as the # previous object. if attr not in ['_obj', '_keep_wrapper']: return getattr(self._obj, attr) return getattr(self, attr) # Make sure the wrapped object conserves the callable property class CallableObjectWrapper(CloudpickledObjectWrapper): def __call__(self, *args, **kwargs): return self._obj(*args, **kwargs) def _wrap_non_picklable_objects(obj, keep_wrapper): if callable(obj): return CallableObjectWrapper(obj, keep_wrapper=keep_wrapper) return CloudpickledObjectWrapper(obj, keep_wrapper=keep_wrapper) def _reconstruct_wrapper(_pickled_object, keep_wrapper): obj = loads(_pickled_object) return _wrap_non_picklable_objects(obj, keep_wrapper) def _wrap_objects_when_needed(obj): # Function to introspect an object and decide if it should be wrapped or # not. if not cloudpickle: return obj need_wrap = "__main__" in getattr(obj, "__module__", "") if isinstance(obj, partial): return partial( _wrap_objects_when_needed(obj.func), *[_wrap_objects_when_needed(a) for a in obj.args], **{k: _wrap_objects_when_needed(v) for k, v in obj.keywords.items()} ) if callable(obj): # Need wrap if the object is a function defined in a local scope of # another function. func_code = getattr(obj, "__code__", "") need_wrap |= getattr(func_code, "co_flags", 0) & inspect.CO_NESTED # Need wrap if the obj is a lambda expression func_name = getattr(obj, "__name__", "") need_wrap |= "<lambda>" in func_name if not need_wrap: return obj wrapped_obj = WRAP_CACHE.get(obj) if wrapped_obj is None: wrapped_obj = _wrap_non_picklable_objects(obj, keep_wrapper=False) WRAP_CACHE[obj] = wrapped_obj return wrapped_obj def wrap_non_picklable_objects(obj, keep_wrapper=True): """Wrapper for non-picklable object to use cloudpickle to serialize them. Note that this wrapper tends to slow down the serialization process as it is done with cloudpickle which is typically slower compared to pickle. The proper way to solve serialization issues is to avoid defining functions and objects in the main scripts and to implement __reduce__ functions for complex classes. """ if not cloudpickle: raise ImportError("could not from joblib.externals import cloudpickle. Please install " "cloudpickle to allow extended serialization. " "(`pip install cloudpickle`).") # If obj is a class, create a CloudpickledClassWrapper which instantiates # the object internally and wrap it directly in a CloudpickledObjectWrapper<|fim▁hole|> if inspect.isclass(obj): class CloudpickledClassWrapper(CloudpickledObjectWrapper): def __init__(self, *args, **kwargs): self._obj = obj(*args, **kwargs) self._keep_wrapper = keep_wrapper CloudpickledClassWrapper.__name__ = obj.__name__ return CloudpickledClassWrapper # If obj is an instance of a class, just wrap it in a regular # CloudpickledObjectWrapper return _wrap_non_picklable_objects(obj, keep_wrapper=keep_wrapper)<|fim▁end|>
<|file_name|>log_formatting.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import sys import string from datetime import datetime,timedelta import calendar import csv import re # ファイルオープン(fpは引数でログファイル,wfpは書き出すcsvファイルを指定) fp = open(sys.argv[1],'r') # logがローテートするタイミングが1日の間にある場合,/var/log/kern.logと/var/log/kern.log.1の両方を読み込む必要があるかもしれない wfp = open('/path/to/program/csv_data/formatted.csv', 'a') writer = csv.writer(wfp, lineterminator='\n') # 昨日の日付を計算 yesterday = datetime.now() + timedelta(days=-1) print "下記の日時のログ整形データをformatted.csvに書き出します" print yesterday.strftime('%Y %b %d %H:%M:%S') # idと書き出し用リストの変数を作成 i = 0 w = [0] * 7 # csvヘッダの作成 #w[0] = "id" #w[1] = "weekday" #w[2] = "hour" #w[3] = "smacaddr" #w[4] = "dipaddr" #w[5] = "proto" #w[6] = "spt" # ファイルに1行出力 #writer.writerow(w) # ログファイルのEOFまで for line in fp.readlines(): # フォワーディングパケットで,内部ネットから出るログを指定 if line.find("FORWARD_F IN=eth1") >= 0: # kernel:の数値の[の後に空白が入ると,後のsplitでうまくきれないため,[を削除する line = line.replace('[','') line = line.replace(' DF ',' ') # 0文字以上の文字をsplitで切り出し l = filter(lambda x: len(x)>0, re.split(r" ", line)) #昨日の日時と一致するログを出力 if l[0] == yesterday.strftime('%b') and int(l[1], 10) == int(yesterday.strftime('%d'), 10): # print l # id w[0] = i # 昨日の曜日(Mon:0,Tue;1,Wed:2,Thu:3,FRI:4,SAT:5,SUN:6) w[1] = yesterday.weekday() # 時刻(時のみ) w[2] = int(l[2][:2], 10) # 送信元MACアドレス w[3] = l[9][4:] # 送信先IPアドレス w[4] = l[11][4:] # プロトコル w[5] = l[17][6:] # 送信先ポート番号 # プロトコルがICMPなら,送信先ポート番号を0に if l[17][6:] == "ICMP":<|fim▁hole|> i += 1 # ファイルに1行出力 writer.writerow(w) # ファイルクローズ fp.close() wfp.close()<|fim▁end|>
l[19] = 0 w[6] = l[19] else: w[6] = l[19][4:]
<|file_name|>RegisterRulesTest.java<|end_file_name|><|fim▁begin|>/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.rule; import com.google.common.collect.Sets; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import org.sonar.core.persistence.AbstractDaoTestCase; import org.sonar.core.persistence.DbSession; import org.sonar.core.qualityprofile.db.QualityProfileDao; import org.sonar.core.rule.RuleDto; import org.sonar.core.rule.RuleParamDto; import org.sonar.core.technicaldebt.db.CharacteristicDao; import org.sonar.server.db.DbClient; import org.sonar.server.qualityprofile.RuleActivator; import org.sonar.server.qualityprofile.db.ActiveRuleDao; import org.sonar.server.rule.db.RuleDao; import java.util.Date; import java.util.List; import static org.fest.assertions.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RegisterRulesTest extends AbstractDaoTestCase { static final Date DATE1 = DateUtils.parseDateTime("2014-01-01T19:10:03+0100"); static final Date DATE2 = DateUtils.parseDateTime("2014-02-01T12:10:03+0100"); static final Date DATE3 = DateUtils.parseDateTime("2014-03-01T12:10:03+0100"); RuleActivator ruleActivator = mock(RuleActivator.class); System2 system; DbClient dbClient; DbSession dbSession; @Before public void before() { system = mock(System2.class); when(system.now()).thenReturn(DATE1.getTime()); RuleDao ruleDao = new RuleDao(system); ActiveRuleDao activeRuleDao = new ActiveRuleDao(new QualityProfileDao(getMyBatis(), system), ruleDao, system); dbClient = new DbClient(getDatabase(), getMyBatis(), ruleDao, activeRuleDao, new QualityProfileDao(getMyBatis(), system), new CharacteristicDao(getMyBatis())); dbSession = dbClient.openSession(false); } @After public void after() throws Exception { dbSession.close(); } @Test public void insert_new_rules() { execute(new FakeRepositoryV1()); // verify db assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(2); RuleKey ruleKey1 = RuleKey.of("fake", "rule1"); RuleDto rule1 = dbClient.ruleDao().getNullableByKey(dbSession, ruleKey1); assertThat(rule1.getName()).isEqualTo("One"); assertThat(rule1.getDescription()).isEqualTo("Description of One"); assertThat(rule1.getSeverityString()).isEqualTo(Severity.BLOCKER); assertThat(rule1.getTags()).isEmpty(); assertThat(rule1.getSystemTags()).containsOnly("tag1", "tag2", "tag3"); assertThat(rule1.getConfigKey()).isEqualTo("config1"); assertThat(rule1.getStatus()).isEqualTo(RuleStatus.BETA); assertThat(rule1.getCreatedAt()).isEqualTo(DATE1); assertThat(rule1.getUpdatedAt()).isEqualTo(DATE1); // TODO check characteristic and remediation function List<RuleParamDto> params = dbClient.ruleDao().findRuleParamsByRuleKey(dbSession, ruleKey1); assertThat(params).hasSize(2); RuleParamDto param = getParam(params, "param1"); assertThat(param.getDescription()).isEqualTo("parameter one"); assertThat(param.getDefaultValue()).isEqualTo("default1"); } @Test public void do_not_update_rules_when_no_changes() { execute(new FakeRepositoryV1()); assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(2); when(system.now()).thenReturn(DATE2.getTime()); execute(new FakeRepositoryV1()); RuleKey ruleKey1 = RuleKey.of("fake", "rule1"); RuleDto rule1 = dbClient.ruleDao().getNullableByKey(dbSession, ruleKey1); assertThat(rule1.getCreatedAt()).isEqualTo(DATE1); assertThat(rule1.getUpdatedAt()).isEqualTo(DATE1); } @Test public void update_and_remove_rules_on_changes() { execute(new FakeRepositoryV1()); assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(2); // user adds tags and sets markdown note RuleKey ruleKey1 = RuleKey.of("fake", "rule1"); RuleDto rule1 = dbClient.ruleDao().getNullableByKey(dbSession, ruleKey1); rule1.setTags(Sets.newHashSet("usertag1", "usertag2")); rule1.setNoteData("user *note*"); rule1.setNoteUserLogin("marius"); dbClient.ruleDao().update(dbSession, rule1); dbSession.commit(); when(system.now()).thenReturn(DATE2.getTime()); execute(new FakeRepositoryV2()); // rule1 has been updated rule1 = dbClient.ruleDao().getNullableByKey(dbSession, ruleKey1); assertThat(rule1.getName()).isEqualTo("One v2"); assertThat(rule1.getDescription()).isEqualTo("Description of One v2"); assertThat(rule1.getSeverityString()).isEqualTo(Severity.INFO); assertThat(rule1.getTags()).containsOnly("usertag1", "usertag2"); assertThat(rule1.getSystemTags()).containsOnly("tag1", "tag4"); assertThat(rule1.getConfigKey()).isEqualTo("config1 v2"); assertThat(rule1.getNoteData()).isEqualTo("user *note*"); assertThat(rule1.getNoteUserLogin()).isEqualTo("marius"); assertThat(rule1.getStatus()).isEqualTo(RuleStatus.READY); assertThat(rule1.getCreatedAt()).isEqualTo(DATE1); assertThat(rule1.getUpdatedAt()).isEqualTo(DATE2); // TODO check characteristic and remediation function List<RuleParamDto> params = dbClient.ruleDao().findRuleParamsByRuleKey(dbSession, ruleKey1); assertThat(params).hasSize(2); RuleParamDto param = getParam(params, "param1"); assertThat(param.getDescription()).isEqualTo("parameter one v2"); assertThat(param.getDefaultValue()).isEqualTo("default1 v2"); // rule2 has been removed -> status set to REMOVED but db row is not deleted RuleDto rule2 = dbClient.ruleDao().getNullableByKey(dbSession, RuleKey.of("fake", "rule2")); assertThat(rule2.getStatus()).isEqualTo(RuleStatus.REMOVED); assertThat(rule2.getUpdatedAt()).isEqualTo(DATE2); // rule3 has been created RuleDto rule3 = dbClient.ruleDao().getNullableByKey(dbSession, RuleKey.of("fake", "rule3")); assertThat(rule3).isNotNull(); assertThat(rule3.getStatus()).isEqualTo(RuleStatus.READY); } @Test public void do_not_update_already_removed_rules() { execute(new FakeRepositoryV1()); assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(2); RuleDto rule2 = dbClient.ruleDao().getByKey(dbSession, RuleKey.of("fake", "rule2")); assertThat(rule2.getStatus()).isEqualTo(RuleStatus.READY); when(system.now()).thenReturn(DATE2.getTime()); execute(new FakeRepositoryV2()); // On MySQL, need to update a rule otherwise rule2 will be seen as READY, but why ??? dbClient.ruleDao().update(dbSession, dbClient.ruleDao().getByKey(dbSession, RuleKey.of("fake", "rule1"))); dbSession.commit(); // rule2 is removed rule2 = dbClient.ruleDao().getNullableByKey(dbSession, RuleKey.of("fake", "rule2")); assertThat(rule2.getStatus()).isEqualTo(RuleStatus.REMOVED); when(system.now()).thenReturn(DATE3.getTime()); execute(new FakeRepositoryV2()); dbSession.commit(); // -> rule2 is still removed, but not update at DATE3 rule2 = dbClient.ruleDao().getNullableByKey(dbSession, RuleKey.of("fake", "rule2")); assertThat(rule2.getStatus()).isEqualTo(RuleStatus.REMOVED); assertThat(rule2.getUpdatedAt()).isEqualTo(DATE2); } @Test public void mass_insert() { execute(new BigRepository()); assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(BigRepository.SIZE); assertThat(dbClient.ruleDao().findAllRuleParams(dbSession)).hasSize(BigRepository.SIZE * 20); } @Test public void manage_repository_extensions() { execute(new FindbugsRepository(), new FbContribRepository()); List<RuleDto> rules = dbClient.ruleDao().findAll(dbSession); assertThat(rules).hasSize(2); for (RuleDto rule : rules) { assertThat(rule.getRepositoryKey()).isEqualTo("findbugs"); } } private void execute(RulesDefinition... defs) { RuleDefinitionsLoader loader = new RuleDefinitionsLoader(mock(RuleRepositories.class), defs); Languages languages = mock(Languages.class); when(languages.get("java")).thenReturn(mock(Language.class)); RegisterRules task = new RegisterRules(loader, ruleActivator, dbClient, languages, system); task.start(); } private RuleParamDto getParam(List<RuleParamDto> params, String key) { for (RuleParamDto param : params) { if (param.getName().equals(key)) { return param; } } return null; } static class FakeRepositoryV1 implements RulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository("fake", "java"); NewRule rule1 = repo.createRule("rule1") .setName("One") .setHtmlDescription("Description of One") .setSeverity(Severity.BLOCKER) .setInternalKey("config1") .setTags("tag1", "tag2", "tag3") .setStatus(RuleStatus.BETA) .setDebtSubCharacteristic("MEMORY_EFFICIENCY") .setEffortToFixDescription("squid.S115.effortToFix"); rule1.setDebtRemediationFunction(rule1.debtRemediationFunctions().linearWithOffset("5d", "10h")); rule1.createParam("param1").setDescription("parameter one").setDefaultValue("default1"); rule1.createParam("param2").setDescription("parameter two").setDefaultValue("default2"); repo.createRule("rule2") .setName("Two") .setHtmlDescription("Minimal rule"); repo.done(); } } /** * FakeRepositoryV1 with some changes */ static class FakeRepositoryV2 implements RulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository("fake", "java"); // almost all the attributes of rule1 are changed NewRule rule1 = repo.createRule("rule1") .setName("One v2") .setHtmlDescription("Description of One v2") .setSeverity(Severity.INFO) .setInternalKey("config1 v2") // tag2 and tag3 removed, tag4 added .setTags("tag1", "tag4") .setStatus(RuleStatus.READY) .setDebtSubCharacteristic("MEMORY_EFFICIENCY") .setEffortToFixDescription("squid.S115.effortToFix.v2"); rule1.setDebtRemediationFunction(rule1.debtRemediationFunctions().linearWithOffset("6d", "2h")); rule1.createParam("param1").setDescription("parameter one v2").setDefaultValue("default1 v2"); rule1.createParam("param2").setDescription("parameter two v2").setDefaultValue("default2 v2"); // rule2 is dropped, rule3 is new repo.createRule("rule3") .setName("Three") .setHtmlDescription("Rule Three"); repo.done(); } } static class BigRepository implements RulesDefinition { static final int SIZE = 500; @Override public void define(Context context) { NewRepository repo = context.createRepository("big", "java"); for (int i = 0; i < SIZE; i++) { NewRule rule = repo.createRule("rule" + i) .setName("name of " + i) .setHtmlDescription("description of " + i); for (int j = 0; j < 20; j++) { rule.createParam("param" + j); } } repo.done(); } } static class FindbugsRepository implements RulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository("findbugs", "java"); repo.createRule("rule1") .setName("Rule One") .setHtmlDescription("Description of Rule One"); repo.done(); } } static class FbContribRepository implements RulesDefinition { @Override public void define(Context context) { NewExtendedRepository repo = context.extendRepository("findbugs", "java"); repo.createRule("rule2") .setName("Rule Two") .setHtmlDescription("Description of Rule Two"); repo.done();<|fim▁hole|><|fim▁end|>
} } }
<|file_name|>json_format.js<|end_file_name|><|fim▁begin|>// Эти данные получаются с помощью метода cars_by_order var result = { // Базовые данные carModel: "INFINITI FX5 PREMIUM", num: "т607ау190", vin: "JN1TANS50U0005180", body: "", // Номер кузова year: "2007", engineDisp: "3498", // Объем двигателя engineHp: "280", // Мощность (л.с.) // Пробег автомобиля // Максимальный пробег в КМ milleage: "106000", // Массив пробегов milleageArr: [ { year: "07-09-2012", milleage: "106000"<|fim▁hole|> } ], // Проверка контрольного символа VIN isVinOk: true, // Документы об участии в ДТП docs: [ { link: "http://cdn.adaperio.ru/data%2F%D0%BE100%D1%80%D1%81197.pdf", link_thumbnail: "" } ], // Данные об участии в ДТП dtps: [ { date: "17.04.2014", type: "Наезд на препятствие", damage: "" } ], // История регистрационных действий за последние 5 лет regData: { Category: "В", Displacement: "3498", // Приоритет отдаётся полю engineDisp EngineNumber: "129547С", MarkaRus: "ИНФИНИТИ FХ35 РRЕМIUМ", MaxWeight: "2530", NettoWeight: "2080", Power: "280", // Приоритет отдаётся полю engineHp // 1 - левый руль // 2 - правый руль SteeringWheelPlacement: "1", Year: "2007" // Приоритет отдаётся полю year codeOfTechOperation: "", arr: [ { // Недокументированное поле area: "142960", // 1 - Юридическое лицо // 2 - Физическое лицо categoryOfOwner: "2", city: "УЗУНОВО С.", // 11 - 'Первичная регистрация'; // 12 - 'Регистрация снятого с учета ТС'; // 41 - 'Замена государственного регистрационного знака'; // 42 - 'Выдача дубликата регистрационного документа'; // 43 - 'Выдача (замена) паспорта ТС'; // 44 - 'Замена номерного агрегата, цвета, изменение конструкции ТС'; // 45 - 'Изменение Ф.И.О. (наименования) владельца'; // 46 - 'Изменение места жительства (юридического адреса) владельца в пределах территории обслуживания регистрационным пунктом'; // 47 - 'Наличие запретов и ограничений'; // 48 - 'Снятие запретов и ограничений'; // 51 - 'Коррекция иных реквизитов'; // 52 - 'Выдача акта технического осмотра'; // 53 - 'Проведение ГТО'; // 54 - 'Постоянная регистрация ТС по окончанию временной'; // 91 - 'Изменение собственника по наследству с заменой государственных регистрационных знаков'; // 92 - 'Изменение собственника по наследству с сохранением государственных регистрационных знаков за новым собственником (наследником)'; // 93 - 'Изменение собственника по сделкам, произведенным в любой форме (купля-продажа, дарение, др.) с заменой государственных регистрационных знаков'; // 94 - 'Изменение собственника по сделкам, произведенным в любой форме с сохранением государственных регистрационных знаков'; codeOfTechOperation: "16", dateOfFirstRegistration: "01.01.0001", dateOfLastOperation: "15.12.2009", oblast: "Московская область", okrug: "Центральный", region: "СЕРЕБРЯНО-ПРУДСКИЙ", street: "-" } ] }, // Использование автомобиля в качестве такси taxiData: [ { name: "Инфинити", owner: "Проташков Александр Владимирович", started: "14.01.2011", end: "14.01.2012" } ], // Информация о розыске транспортного средства, в федеральной информационной системе МВД России gibddWanted: false, // Информация о наложении ограничений в федеральной информационной системе МВД России gibddRestricted: true, restrictedArr: [ { dateadd: "08.08.2014", dateogr: "08.08.2014", divid: "040", //1 - 'Судебные органы'; //2 - 'Судебный пристав'; //3 - 'Таможенные органы'; //4 - 'Органы социальной защиты'; //5 - 'Нотарус'; //6 - 'Органы внутренних дел или иные правоохранительные органы'; //7 - 'Органы внутренних дел или иные правоохранительные органы (прочие)'; divtype: "6", gid: "43#000075178", ogrkod: "1", regid: "1133", regname: "Кировская область", tsmodel: "INFINIТI FХ-35 РRЕМIUМ", tsyear: "2007" } ], // Информация о нахождении в залоге у банков // Завершилась ли проверка залогов успешно reestrGotResult: true, reestrResult: [ { // Дата регистрации уведомления о залоге RegDate: '', // Залогодержатели Mortgagees: '', // Дата договора date: '', // Срок исполнения обязательства end: '' } ], // Проверка истории CARFAX carfax: { fullLink: "http://cdn.adaperio.ru/some_link", history: { accident: false, totalLoss: false, structuralDamage: false, airbagDeployment: false, odometrCheck: false, manufacturerRecall: false, warantyVoid: true }, owners: [ { lastMilleage: 137680, // Км. ownership: "43 мес.", state: "Louisiana", yearPurchased: "2001" } ] }, // Проверка истории на аукционах auctions: [ { damage: [ "Передняя часть" ], date: "", odometr: "12298", photos: [ "http://img.copartimages.com//website/data/pix/20110517/17605611_1X.JPG" ], } ], // Данные таможни customs: { country: "ЯПОНИЯ", date: "15.09.2008", model: "Infiniti FX5", odometer: "", price: "574719" // таможенная стоимость в рублях }, // Комплектация equip: { make: "Nissan", model: "[S50] INFINITIFX45/35 ", series: "", year: "07/2007", engine: "[VQ35DE] VQ35DE TYPE ENGINE", bodyType: "[W] WAGON ", color: "[KH3] BLACK ", interiorColor: "[G] BLACK ", transmission: "[AT] AUTOMATIC TRANSMISSION ", year: "07/2007", manufacturedAt: "", // Произведено month: "", // Месяц engineCode: "", // Код двигателя transmissionCode: "", // Код трансммиссии transmission2: "", // Трансммиссия (дополнительно) internalsCode: "", // Код отделки roofColor: "", // Цвет крыши typeCode: "", // Код catalysis: "", // Катализатор panzer: "", // Бронирование steeringWheel: "", // Руль gearbox: "", // Коробка передач made: "", // Изготовление marking: "", // Обозначение manuf: "", // Сборка factory: "", // Завод изготовитель trim: "", // Комплектация trimCode: "", // Комплектация (код) drive: "", // Привод region: "", // Регион modelCode: "", // Код модели manufPeriod: "", // Период производства engineDisp: "", // Объем fuelType: "", // Вид топлива country: "", // Страна происхождения modelYear: "", // Модельный год seats: "", // Тип сидений doorStyle: "", // Стиль дверей classification: "", // Класификация susp: "", // Подвеска options: "", // Опции optionsArr: [ { code: "", desc: "" } ] }, // Ремонтные работы (по расчетам страховой компании) repairs: { vin: "JN1TANS50U0005180", make: "INFINITI [R] [47]", year: "", engine: "", color: "", engineDisp: "" hp: "", repairs: [ { date: "02.08.2011", items: [ { changed: true, paint: false, partlyChanged: false, partlyRepaired: false, repaired: false, title: "КРЕПЛ БАМПЕРА П62030-1CA0A" } ] } ] } };<|fim▁end|>
<|file_name|>clean.js<|end_file_name|><|fim▁begin|><|fim▁hole|> { all: '<%= settings.build.dst %>' }); }<|fim▁end|>
'use strict'; module.exports = function(grunt) { grunt.config('clean',
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>default_app_config = 'workflow.apps.WorkflowAppConfig'<|fim▁end|>
<|file_name|>dns.py<|end_file_name|><|fim▁begin|>import sqlalchemy as sa from oslo_db.sqlalchemy import types as db_types from nca47.db.sqlalchemy.models import base as model_base from nca47.objects import attributes as attr HasTenant = model_base.HasTenant HasId = model_base.HasId HasStatus = model_base.HasStatus HasOperationMode = model_base.HasOperationMode class DnsServer(model_base.BASE, HasId, HasOperationMode): """Represents a dns server.""" name = sa.Column(sa.String(attr.NAME_MAX_LEN)) class Zone(model_base.BASE, HasId, HasOperationMode): """Represents a dns zone.""" __tablename__ = 'dns_zone_info' zone_name = sa.Column(sa.String(attr.NAME_MAX_LEN)) tenant_id = sa.Column(sa.String(attr.NAME_MAX_LEN)) zone_id = sa.Column(sa.String(attr.NAME_MAX_LEN)) vres_id = sa.Column(sa.String(attr.NAME_MAX_LEN))<|fim▁hole|> renewal = sa.Column(sa.String(attr.NAME_MAX_LEN)) default_ttl = sa.Column(sa.String(attr.NAME_MAX_LEN)) owners = sa.Column(db_types.JsonEncodedList) ad_controller = sa.Column(sa.String(attr.NAME_MAX_LEN)) comment = sa.Column(sa.String(attr.NAME_MAX_LEN)) class ZoneRecord(model_base.BASE, HasId, HasOperationMode): """Represents a dns zone.""" __tablename__ = 'dns_rrs_info' zone_id = sa.Column(sa.String(attr.UUID_LEN)) rrs_id = sa.Column(sa.String(attr.NAME_MAX_LEN)) rrs_name = sa.Column(sa.String(attr.NAME_MAX_LEN)) type = sa.Column(sa.String(attr.NAME_MAX_LEN)) klass = sa.Column(sa.String(attr.NAME_MAX_LEN)) ttl = sa.Column(sa.String(attr.NAME_MAX_LEN)) rdata = sa.Column(sa.String(attr.NAME_MAX_LEN))<|fim▁end|>
masters = sa.Column(db_types.JsonEncodedList) slaves = sa.Column(db_types.JsonEncodedList)
<|file_name|>named_test.go<|end_file_name|><|fim▁begin|>package named import ( "testing" ) func TestNamedSelector(t *testing.T) { data := []string{"foo", "bar", "baz"} s := NewSelector() for _, name := range data { next, err := s.Select(name) if err != nil { t.Fatal(err) } for i := 0; i < 3; i++ { node, err := next() if err != nil {<|fim▁hole|> t.Fatal(err) } if node.Address != name { t.Fatalf("got %s expected %s", node.Address, name) } } } }<|fim▁end|>
<|file_name|>test_connect_all_to_all.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # test_connect_all_to_all.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 version. # # NEST 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 License # along with NEST. If not, see <http://www.gnu.org/licenses/>. import unittest import numpy as np import scipy.stats import test_connect_helpers as hf from test_connect_parameters import TestParams @hf.nest.ll_api.check_stack class TestAllToAll(TestParams): # specify connection pattern rule = 'all_to_all' conn_dict = {'rule': rule} # sizes of populations N1 = 6 N2 = 7 N1_array = 500 N2_array = 10 def testConnectivity(self): self.setUpNetwork(self.conn_dict) # make sure all connections do exist M = hf.get_connectivity_matrix(self.pop1, self.pop2) M_all = np.ones((len(self.pop2), len(self.pop1))) hf.mpi_assert(M, M_all, self) # make sure no connections were drawn from the target to the source # population M = hf.get_connectivity_matrix(self.pop2, self.pop1) M_none = np.zeros((len(self.pop1), len(self.pop2))) hf.mpi_assert(M, M_none, self) def testInputArray(self): for label in ['weight', 'delay']: syn_params = {} if label == 'weight': self.param_array = np.arange( self.N1_array * self.N2_array, dtype=float ).reshape(self.N2_array, self.N1_array) elif label == 'delay': self.param_array = np.arange( 1, self.N1_array * self.N2_array + 1 ).reshape(self.N2_array, self.N1_array) * 0.1 syn_params[label] = self.param_array hf.nest.ResetKernel() self.setUpNetwork(self.conn_dict, syn_params, N1=self.N1_array, N2=self.N2_array) M_nest = hf.get_weighted_connectivity_matrix( self.pop1, self.pop2, label) hf.mpi_assert(M_nest, self.param_array, self) def testInputArrayWithoutAutapses(self): self.conn_dict['allow_autapses'] = False for label in ['weight', 'delay']: syn_params = {} if label == 'weight': self.param_array = np.arange( self.N1 * self.N1, dtype=float).reshape(self.N1, self.N1) elif label == 'delay': self.param_array = np.arange( 1, self.N1 * self.N1 + 1).reshape(self.N1, self.N1) * 0.1 syn_params[label] = self.param_array self.setUpNetworkOnePop(self.conn_dict, syn_params) M_nest = hf.get_weighted_connectivity_matrix( self.pop, self.pop, label) np.fill_diagonal(self.param_array, 0) hf.mpi_assert(M_nest, self.param_array, self) def testInputArrayRPort(self): syn_params = {} neuron_model = 'iaf_psc_exp_multisynapse' neuron_dict = {'tau_syn': [0.1 + i for i in range(self.N2)]} self.pop1 = hf.nest.Create(neuron_model, self.N1) self.pop2 = hf.nest.Create(neuron_model, self.N2, neuron_dict) self.param_array = np.transpose(np.asarray( [np.arange(1, self.N2 + 1) for i in range(self.N1)])) syn_params['receptor_type'] = self.param_array hf.nest.Connect(self.pop1, self.pop2, self.conn_dict, syn_params) M = hf.get_weighted_connectivity_matrix( self.pop1, self.pop2, 'receptor') hf.mpi_assert(M, self.param_array, self) def testInputArrayToStdpSynapse(self): params = ['Wmax', 'alpha', 'lambda', 'mu_minus', 'mu_plus', 'tau_plus'] syn_params = {'synapse_model': 'stdp_synapse'} values = [ np.arange(self.N1 * self.N2, dtype=float).reshape(self.N2, self.N1) for i in range(6) ] for i, param in enumerate(params): syn_params[param] = values[i] self.setUpNetwork(self.conn_dict, syn_params) for i, param in enumerate(params): a = hf.get_weighted_connectivity_matrix( self.pop1, self.pop2, param) hf.mpi_assert(a, values[i], self) # test single threaded for now def testRPortDistribution(self): n_rport = 10 nr_neurons = 100 hf.nest.ResetKernel() # To reset local_num_threads neuron_model = 'iaf_psc_exp_multisynapse' neuron_dict = {'tau_syn': [0.1 + i for i in range(n_rport)]}<|fim▁hole|> self.pop1 = hf.nest.Create(neuron_model, nr_neurons, neuron_dict) self.pop2 = hf.nest.Create(neuron_model, nr_neurons, neuron_dict) syn_params = {'synapse_model': 'static_synapse'} syn_params['receptor_type'] = 1 + hf.nest.random.uniform_int(n_rport) hf.nest.Connect(self.pop1, self.pop2, self.conn_dict, syn_params) M = hf.get_weighted_connectivity_matrix( self.pop1, self.pop2, 'receptor') M = hf.gather_data(M) if M is not None: M = M.flatten() frequencies = scipy.stats.itemfreq(M) self.assertTrue(np.array_equal(frequencies[:, 0], np.arange( 1, n_rport + 1)), 'Missing or invalid rports') chi, p = scipy.stats.chisquare(frequencies[:, 1]) self.assertGreater(p, self.pval) def suite(): suite = unittest.TestLoader().loadTestsFromTestCase(TestAllToAll) return suite def run(): runner = unittest.TextTestRunner(verbosity=2) runner.run(suite()) if __name__ == '__main__': run()<|fim▁end|>
<|file_name|>AnimatedButton.js<|end_file_name|><|fim▁begin|>/******************************************************************************* * Copyright 2012, 2013 CNES - CENTRE NATIONAL d'ETUDES SPATIALES * * This file is part of SITools2. * * SITools2 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. * * SITools2 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 License * along with SITools2. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ /*global define: false */ /** * Animated button */ define( [ "jquery", "jquery.ui"], function($) { var AnimatedButton = function(element, options) { this.$element = $(element).button(); this.stopped = true; if ( options ) { this.$element.on('click', $.proxy( options.onclick, this )); } }; /**************************************************************************************************************/ /** * Start animation */ AnimatedButton.prototype.startAnimation = function() { this.stopped = false; this.iterateAnimation(); }; /**************************************************************************************************************/ /** * Stop animation */<|fim▁hole|>}; /**************************************************************************************************************/ /** * Loading animation */ AnimatedButton.prototype.iterateAnimation = function() { var self = this; this.$element.children('span').animate({ backgroundColor: "rgb(255, 165, 0);" }, 300, function(){ $(this).animate({ backgroundColor: "transparent" }, 300, function(){ if ( !self.stopped ) { self.iterateAnimation(); } }); }); }; /**************************************************************************************************************/ return AnimatedButton; });<|fim▁end|>
AnimatedButton.prototype.stopAnimation = function() { this.stopped = true;
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>#![feature(iter_max_by, iter_min_by)] use std::collections::HashMap; use std::io; use std::io::prelude::*; enum DecodingMethod { MostLikely, LeastLikely, } fn decode_message(input: &str, method: DecodingMethod) -> String { let len = input.lines().map(|line| line.chars().count()).max().unwrap(); let mut histograms = vec![HashMap::new(); len]; for line in input.lines() { for (pos, ch) in line.chars().enumerate() { let cnt = histograms[pos].entry(ch).or_insert(0); *cnt += 1; } } histograms.into_iter() .map(|h| { match method { DecodingMethod::MostLikely => { h.into_iter().max_by(|&(_, cnt_a), &(_, cnt_b)| cnt_a.cmp(&cnt_b)) } DecodingMethod::LeastLikely => { h.into_iter().min_by(|&(_, cnt_a), &(_, cnt_b)| cnt_a.cmp(&cnt_b)) } } .unwrap() .0 }) .collect() } fn main() { let mut message_str = String::new(); io::stdin().read_to_string(&mut message_str).expect("Invalid input string!"); println!("The initial decoded message is: {}", decode_message(&message_str, DecodingMethod::MostLikely)); println!("The actual decoded message is: {}", decode_message(&message_str, DecodingMethod::LeastLikely)); } #[cfg(test)] mod tests { use super::decode_message; use super::DecodingMethod; const TEST_INPUT: &'static str = "eedadn\n\ drvtee\n\ eandsr\n\ raavrd\n\ atevrs\n\ tsrnev\n\ sdttsa\n\ rasrtv\n\ nssdts\n\ ntnada\n\<|fim▁hole|> vntsnd\n\ vrdear\n\ dvrsen\n\ enarar"; #[test] fn decode_message_test() { assert_eq!(decode_message(TEST_INPUT, DecodingMethod::MostLikely), "easter"); } #[test] fn decode_message_b_test() { assert_eq!(decode_message(TEST_INPUT, DecodingMethod::LeastLikely), "advent"); } }<|fim▁end|>
svetve\n\ tesnvt\n\
<|file_name|>api_protocol_base.cpp<|end_file_name|><|fim▁begin|>#include "api_protocol_base.h" /// /// \brief TestProtocol::TestProtocol /// Constructor /// TestProtocol::TestProtocol() { nam = new QNetworkAccessManager(this); // nam = NAM_INSTANCE; connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(onNamResponce(QNetworkReply*))); reply = nullptr; parser = new TestProtocolParser(); } void TestProtocol::setupProtocol() { parser->reinitParser(); connect(this, SIGNAL(newData()), parser,SLOT(onNewData()), Qt::QueuedConnection); } /// /// \brief TestProtocol::setupProtocol /// void TestProtocol::setupProtocol(TestApiClient *tester) { parser->reinitParser(); parser->setupSignalsSlots(this, tester); connect(this, SIGNAL(newData()), parser,SLOT(onNewData()), Qt::QueuedConnection); } /// /// \brief TestProtocol::runProtocol /// runProtocol /// void TestProtocol::invoke() { } /// /// \brief TestProtocol::onTimer /// Сначала проверить, завершился ли запрос в QFuture /// Запрос делается через сигнал /// void TestProtocol::onTimer() { qDebug() << "On timer"; if(reply == nullptr) { reply =nam->get(QNetworkRequest(QUrl("http://127.0.0.1:8080/quote"))); qInfo() << "Reply works" << reply->isRunning(); } if (reply->isRunning() == false) { reply =nam->get(QNetworkRequest(QUrl("http://127.0.0.1:8080/quote"))); qInfo() << "Reply works" << reply->isRunning(); } qInfo() << "ok"; } /// /// \brief TestProtocol::onResponce /// \param Reply /// void TestProtocol::onNamResponce(QNetworkReply* reply) { QTimer::singleShot(1000, this, SLOT(onTimer())); QUrl url = reply->url(); QJsonDocument itemDoc = QJsonDocument::fromJson(reply->readAll()); qInfo() << "OnNamResponce, thread id " << QThread::currentThreadId() << "Itemdoc "<|fim▁hole|>} /// /// \brief TestProtocolParser::resetParser /// void TestProtocolParser::setupSignalsSlots(TestProtocol *prot, TestApiClient *tester) { int i = 1; } /// /// \brief TestProtocolParser::reinitParser /// void TestProtocolParser::reinitParser() { if(thr != nullptr) if(thr->isRunning()) delete (thr); thr = new QThread(0); } /// /// \brief TestProtocolParser::reinitThread /// void TestProtocolParser::reinitThread() { this->moveToThread(thr); thr->start(); } /// /// \brief TestProtocolParser::onNewVoidCall /// void TestProtocolParser::dataToParseReady() { qInfo() << "TestProtocolParser::onNewVoidCall, Thread id " << QThread::currentThreadId(); emit voidCall(); }<|fim▁end|>
<< itemDoc; emit newData();
<|file_name|>EPAAlgorithm.java<|end_file_name|><|fim▁begin|>/* * This file is part of React, licensed under the MIT License (MIT). * * Copyright (c) 2013 Flow Powered <https://flowpowered.com/> * Original ReactPhysics3D C++ library by Daniel Chappuis <http://danielchappuis.ch> * React is re-licensed with permission from ReactPhysics3D author. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.flowpowered.react.collision.narrowphase.EPA; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Queue; import com.flowpowered.react.ReactDefaults; import com.flowpowered.react.collision.narrowphase.GJK.GJKAlgorithm; import com.flowpowered.react.collision.narrowphase.GJK.Simplex; import com.flowpowered.react.collision.shape.CollisionShape; import com.flowpowered.react.constraint.ContactPoint.ContactPointInfo; import com.flowpowered.react.math.Matrix3x3; import com.flowpowered.react.math.Quaternion; import com.flowpowered.react.math.Transform; import com.flowpowered.react.math.Vector3; /** * This class is the implementation of the Expanding Polytope Algorithm (EPA). The EPA algorithm computes the penetration depth and contact points between two enlarged objects (with margin) where the * original objects (without margin) intersect. The penetration depth of a pair of intersecting objects A and B is the length of a point on the boundary of the Minkowski sum (A-B) closest to the * origin. The goal of the EPA algorithm is to start with an initial simplex polytope that contains the origin and expend it in order to find the point on the boundary of (A-B) that is closest to the * origin. An initial simplex that contains the origin has been computed with the GJK algorithm. The EPA Algorithm will extend this simplex polytope to find the correct penetration depth. The * implementation of the EPA algorithm is based on the book "Collision Detection in 3D Environments". */ public class EPAAlgorithm { private static final int MAX_SUPPORT_POINTS = 100; private static final int MAX_FACETS = 200; /** * Computes the penetration depth with the EPA algorithm. This method computes the penetration depth and contact points between two enlarged objects (with margin) where the original objects * (without margin) intersect. An initial simplex that contains the origin has been computed with GJK algorithm. The EPA Algorithm will extend this simplex polytope to find the correct penetration * depth. Returns true if the computation was successful, false if not. * * @param simplex The initial simplex * @param collisionShape1 The first collision shape * @param transform1 The transform of the first collision shape<|fim▁hole|> * @param v The vector in which to store the closest point * @param contactInfo The contact info in which to store the contact info of the collision * @return Whether or not the computation was successful */ public boolean computePenetrationDepthAndContactPoints(Simplex simplex, CollisionShape collisionShape1, Transform transform1, CollisionShape collisionShape2, Transform transform2, Vector3 v, ContactPointInfo contactInfo) { final Vector3[] suppPointsA = new Vector3[MAX_SUPPORT_POINTS]; final Vector3[] suppPointsB = new Vector3[MAX_SUPPORT_POINTS]; final Vector3[] points = new Vector3[MAX_SUPPORT_POINTS]; final TrianglesStore triangleStore = new TrianglesStore(); final Queue<TriangleEPA> triangleHeap = new PriorityQueue<>(MAX_FACETS, new TriangleComparison()); final Transform body2Tobody1 = Transform.multiply(transform1.getInverse(), transform2); final Matrix3x3 rotateToBody2 = Matrix3x3.multiply(transform2.getOrientation().getMatrix().getTranspose(), transform1.getOrientation().getMatrix()); int nbVertices = simplex.getSimplex(suppPointsA, suppPointsB, points); final float tolerance = ReactDefaults.MACHINE_EPSILON * simplex.getMaxLengthSquareOfAPoint(); int nbTriangles = 0; triangleStore.clear(); switch (nbVertices) { case 1: return false; case 2: { final Vector3 d = Vector3.subtract(points[1], points[0]).getUnit(); final int minAxis = d.getAbsoluteVector().getMinAxis(); final float sin60 = (float) Math.sqrt(3) * 0.5f; final Quaternion rotationQuat = new Quaternion(d.getX() * sin60, d.getY() * sin60, d.getZ() * sin60, 0.5f); final Matrix3x3 rotationMat = rotationQuat.getMatrix(); final Vector3 v1 = d.cross(new Vector3(minAxis == 0 ? 1 : 0, minAxis == 1 ? 1 : 0, minAxis == 2 ? 1 : 0)); final Vector3 v2 = Matrix3x3.multiply(rotationMat, v1); final Vector3 v3 = Matrix3x3.multiply(rotationMat, v2); suppPointsA[2] = collisionShape1.getLocalSupportPointWithMargin(v1); suppPointsB[2] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(v1)))); points[2] = Vector3.subtract(suppPointsA[2], suppPointsB[2]); suppPointsA[3] = collisionShape1.getLocalSupportPointWithMargin(v2); suppPointsB[3] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(v2)))); points[3] = Vector3.subtract(suppPointsA[3], suppPointsB[3]); suppPointsA[4] = collisionShape1.getLocalSupportPointWithMargin(v3); suppPointsB[4] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(v3)))); points[4] = Vector3.subtract(suppPointsA[4], suppPointsB[4]); if (isOriginInTetrahedron(points[0], points[2], points[3], points[4]) == 0) { suppPointsA[1].set(suppPointsA[4]); suppPointsB[1].set(suppPointsB[4]); points[1].set(points[4]); } else if (isOriginInTetrahedron(points[1], points[2], points[3], points[4]) == 0) { suppPointsA[0].set(suppPointsA[4]); suppPointsB[0].set(suppPointsB[4]); points[0].set(points[4]); } else { return false; } nbVertices = 4; } case 4: { final int badVertex = isOriginInTetrahedron(points[0], points[1], points[2], points[3]); if (badVertex == 0) { final TriangleEPA face0 = triangleStore.newTriangle(points, 0, 1, 2); final TriangleEPA face1 = triangleStore.newTriangle(points, 0, 3, 1); final TriangleEPA face2 = triangleStore.newTriangle(points, 0, 2, 3); final TriangleEPA face3 = triangleStore.newTriangle(points, 1, 3, 2); if (!(face0 != null && face1 != null && face2 != null && face3 != null && face0.getDistSquare() > 0 && face1.getDistSquare() > 0 && face2.getDistSquare() > 0 && face3.getDistSquare() > 0)) { return false; } TriangleEPA.link(new EdgeEPA(face0, 0), new EdgeEPA(face1, 2)); TriangleEPA.link(new EdgeEPA(face0, 1), new EdgeEPA(face3, 2)); TriangleEPA.link(new EdgeEPA(face0, 2), new EdgeEPA(face2, 0)); TriangleEPA.link(new EdgeEPA(face1, 0), new EdgeEPA(face2, 2)); TriangleEPA.link(new EdgeEPA(face1, 1), new EdgeEPA(face3, 0)); TriangleEPA.link(new EdgeEPA(face2, 1), new EdgeEPA(face3, 1)); nbTriangles = addFaceCandidate(face0, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face1, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face2, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face3, triangleHeap, nbTriangles, Float.MAX_VALUE); break; } if (badVertex < 4) { suppPointsA[badVertex - 1].set(suppPointsA[4]); suppPointsB[badVertex - 1].set(suppPointsB[4]); points[badVertex - 1].set(points[4]); } nbVertices = 3; } case 3: { final Vector3 v1 = Vector3.subtract(points[1], points[0]); final Vector3 v2 = Vector3.subtract(points[2], points[0]); final Vector3 n = v1.cross(v2); suppPointsA[3] = collisionShape1.getLocalSupportPointWithMargin(n); suppPointsB[3] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(n)))); points[3] = Vector3.subtract(suppPointsA[3], suppPointsB[3]); suppPointsA[4] = collisionShape1.getLocalSupportPointWithMargin(Vector3.negate(n)); suppPointsB[4] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, n))); points[4] = Vector3.subtract(suppPointsA[4], suppPointsB[4]); final TriangleEPA face0 = triangleStore.newTriangle(points, 0, 1, 3); final TriangleEPA face1 = triangleStore.newTriangle(points, 1, 2, 3); final TriangleEPA face2 = triangleStore.newTriangle(points, 2, 0, 3); final TriangleEPA face3 = triangleStore.newTriangle(points, 0, 2, 4); final TriangleEPA face4 = triangleStore.newTriangle(points, 2, 1, 4); final TriangleEPA face5 = triangleStore.newTriangle(points, 1, 0, 4); if (!(face0 != null && face1 != null && face2 != null && face3 != null && face4 != null && face5 != null && face0.getDistSquare() > 0 && face1.getDistSquare() > 0 && face2.getDistSquare() > 0 && face3.getDistSquare() > 0 && face4.getDistSquare() > 0 && face5.getDistSquare() > 0)) { return false; } TriangleEPA.link(new EdgeEPA(face0, 1), new EdgeEPA(face1, 2)); TriangleEPA.link(new EdgeEPA(face1, 1), new EdgeEPA(face2, 2)); TriangleEPA.link(new EdgeEPA(face2, 1), new EdgeEPA(face0, 2)); TriangleEPA.link(new EdgeEPA(face0, 0), new EdgeEPA(face5, 0)); TriangleEPA.link(new EdgeEPA(face1, 0), new EdgeEPA(face4, 0)); TriangleEPA.link(new EdgeEPA(face2, 0), new EdgeEPA(face3, 0)); TriangleEPA.link(new EdgeEPA(face3, 1), new EdgeEPA(face4, 2)); TriangleEPA.link(new EdgeEPA(face4, 1), new EdgeEPA(face5, 2)); TriangleEPA.link(new EdgeEPA(face5, 1), new EdgeEPA(face3, 2)); nbTriangles = addFaceCandidate(face0, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face1, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face2, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face3, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face4, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face5, triangleHeap, nbTriangles, Float.MAX_VALUE); nbVertices = 5; } break; } if (nbTriangles == 0) { return false; } TriangleEPA triangle; float upperBoundSquarePenDepth = Float.MAX_VALUE; do { triangle = triangleHeap.remove(); nbTriangles--; if (!triangle.isObsolete()) { if (nbVertices == MAX_SUPPORT_POINTS) { break; } suppPointsA[nbVertices] = collisionShape1.getLocalSupportPointWithMargin(triangle.getClosestPoint()); suppPointsB[nbVertices] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(triangle.getClosestPoint())))); points[nbVertices] = Vector3.subtract(suppPointsA[nbVertices], suppPointsB[nbVertices]); final int indexNewVertex = nbVertices; nbVertices++; final float wDotv = points[indexNewVertex].dot(triangle.getClosestPoint()); if (wDotv <= 0) { throw new IllegalStateException("wDotv must be greater than zero"); } final float wDotVSquare = wDotv * wDotv / triangle.getDistSquare(); if (wDotVSquare < upperBoundSquarePenDepth) { upperBoundSquarePenDepth = wDotVSquare; } final float error = wDotv - triangle.getDistSquare(); if (error <= Math.max(tolerance, GJKAlgorithm.REL_ERROR_SQUARE * wDotv) || points[indexNewVertex].equals(points[triangle.get(0)]) || points[indexNewVertex].equals(points[triangle.get(1)]) || points[indexNewVertex].equals(points[triangle.get(2)])) { break; } int i = triangleStore.getNbTriangles(); if (!triangle.computeSilhouette(points, indexNewVertex, triangleStore)) { break; } while (i != triangleStore.getNbTriangles()) { final TriangleEPA newTriangle = triangleStore.get(i); nbTriangles = addFaceCandidate(newTriangle, triangleHeap, nbTriangles, upperBoundSquarePenDepth); i++; } } } while (nbTriangles > 0 && triangleHeap.element().getDistSquare() <= upperBoundSquarePenDepth); v.set(Matrix3x3.multiply(transform1.getOrientation().getMatrix(), triangle.getClosestPoint())); final Vector3 pALocal = triangle.computeClosestPointOfObject(suppPointsA); final Vector3 pBLocal = Transform.multiply(body2Tobody1.getInverse(), triangle.computeClosestPointOfObject(suppPointsB)); final Vector3 normal = v.getUnit(); final float penetrationDepth = v.length(); if (penetrationDepth <= 0) { throw new IllegalStateException("penetration depth must be greater that zero"); } contactInfo.set(normal, penetrationDepth, pALocal, pBLocal); return true; } // Decides if the origin is in the tetrahedron. // Returns 0 if the origin is in the tetrahedron or returns the index (1,2,3 or 4) of the bad // vertex if the origin is not in the tetrahedron. private static int isOriginInTetrahedron(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4) { final Vector3 normal1 = Vector3.subtract(p2, p1).cross(Vector3.subtract(p3, p1)); if (normal1.dot(p1) > 0 == normal1.dot(p4) > 0) { return 4; } final Vector3 normal2 = Vector3.subtract(p4, p2).cross(Vector3.subtract(p3, p2)); if (normal2.dot(p2) > 0 == normal2.dot(p1) > 0) { return 1; } final Vector3 normal3 = Vector3.subtract(p4, p3).cross(Vector3.subtract(p1, p3)); if (normal3.dot(p3) > 0 == normal3.dot(p2) > 0) { return 2; } final Vector3 normal4 = Vector3.subtract(p2, p4).cross(Vector3.subtract(p1, p4)); if (normal4.dot(p4) > 0 == normal4.dot(p3) > 0) { return 3; } return 0; } // Adds a triangle face in the candidate triangle heap in the EPA algorithm. private static int addFaceCandidate(TriangleEPA triangle, Queue<TriangleEPA> heap, int nbTriangles, float upperBoundSquarePenDepth) { if (triangle.isClosestPointInternalToTriangle() && triangle.getDistSquare() <= upperBoundSquarePenDepth) { heap.add(triangle); nbTriangles++; } return nbTriangles; } // Compares the EPA triangles in the queue. private static class TriangleComparison implements Comparator<TriangleEPA> { @Override public int compare(TriangleEPA face1, TriangleEPA face2) { final float dist1 = face1.getDistSquare(); final float dist2 = face2.getDistSquare(); if (dist1 == dist2) { return 0; } return dist1 > dist2 ? 1 : -1; } } }<|fim▁end|>
* @param collisionShape2 The second collision shape * @param transform2 The transform of the second collision shape
<|file_name|>torchir_passes.py<|end_file_name|><|fim▁begin|># Copyright (c) 2021, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause from collections import defaultdict, OrderedDict import logging as _logging from .internal_graph import InternalTorchIRNode, InternalTorchIRGraph def generate_tensor_assignment_ops(graph): """ This graph pass handles inplace tensor assignements, specifically it handles: `torch.Tensor.copy_` and `torch.Tensor.fill_`. There are many other inplace tensor assignments which are currently not handled. for instance: def forward(self, x): # x a tensor with shape [4,10] x[:2, 4] = [[1],[3]] return x In Pytorch, this is represented by a sequence of slice / select ops followed by a copy op: input -> %x %1 = slice(%x, dim=0, begin=0, end=2) # the slice for dimension 0 %2 = select(%1, dim=1, index=4) # the select for dimension 1 %3 = copy_(%2, value=[[1], [3]]) output -> %x This graph pass fuses the sequences into a single InternalTorchIRNode of a new kind, which is defined as `_internal_op_tensor_inplace_copy`. input -> %x %nodes_to_fuse = [slice(%x, begin=0, end=2), select(%1, dim=1, index=4)] %x_internal_tensor_assign_1 = _internal_op_tensor_inplace_copy(%x, value=[[1],[3]], nodes_to_fuse=nodes_to_fuse) output -> x_internal_tensor_assign_1 The _internal_tensor_value_assign op takes an additional internal data member nodes_to_fuse, which is a list of select / slice InternalTorchIRNodes that need to be fused. Here is a more complicated example: def forward(self, x): # x a tensor with shape [4,10] x[0, 0] = 1 x[1:2, 1:2] = [[0]] return x Input graph: input -> %x %1 = select(%x, dim=0, index=0) %2 = select(%1, dim=0, index=0) %3 = copy_(%2, value=1) %4 = slice(%x, dim=0, begin=1, end=2) %5 = slice(%4, dim=1, begin=1, end=2) %6 = copy_(%5, value=[[0]]) output -> %x Output graph: input -> %x %nodes_to_fuse_1 = [select(%x, dim=0, index=0), select(%1, dim=0, index=0)] %x_internal_tensor_assign_1 = _internal_op_tensor_inplace_copy(%x, value=1, nodes_to_fuse=nodes_to_fuse_1) %nodes_to_fuse_2 = [slice(%x, dim=0, begin=1, end=2), slice(%4, dim=1, begin=1, end=2)] %x_internal_tensor_assign_2 = _internal_op_tensor_inplace_copy(%x_internal_tensor_assign_1, value=[[0]], nodes_to_fuse=nodes_to_fuse_2)<|fim▁hole|> torch.Tensor.fill_ works in a similar way, except the InternalTorchIRNodes is defined by `_internal_op_tensor_inplace_fill`. A fill_ operator is generated from the following forward pass: def forward(self, x): # x a tensor with shape [5, 4] x[2] = 9 return x """ TENSOR_ASSIGMENT_PREFIX = "_internal_tensor_assign_" def _get_updated_name(name, updated_tensor_count): if name in updated_tensor_count: return name + TENSOR_ASSIGMENT_PREFIX + str(updated_tensor_count[name]) return name def _construct_nodes_to_fuse_inputs(nodes_to_fuse): inputs = [] for node in nodes_to_fuse: if node.kind == "select": inputs += [node.inputs[2], None] if node.kind == "slice": inputs += [node.inputs[2], node.inputs[3]] return inputs tensor_to_node_sequence_mapping = {} updated_tensor_count = defaultdict(lambda : 0) for i in range(len(graph.nodes)): node = graph.nodes[i] for idx in range(len(node.inputs)): input_name = node.inputs[idx] node.inputs[idx] = _get_updated_name(input_name, updated_tensor_count) if node.kind in ("select", "slice"): node_input = node.inputs[0] node_output = node.outputs[0] node_sequence = tensor_to_node_sequence_mapping.get(node_input, []) if len(node_sequence) > 0: tensor_to_node_sequence_mapping.pop(node_input) node_sequence.append(node) tensor_to_node_sequence_mapping[node_output] = node_sequence if node.kind in ("copy_", "fill_"): node_input = node.inputs[0] if node_input not in tensor_to_node_sequence_mapping: raise ValueError("No matching select or slice.") if node.kind == "copy_": kind = "_internal_op_tensor_inplace_copy" else: kind = "_internal_op_tensor_inplace_fill" nodes_to_fuse = tensor_to_node_sequence_mapping[node_input] source_tensor = nodes_to_fuse[0].inputs[0] origin_name = source_tensor.split(TENSOR_ASSIGMENT_PREFIX)[0] updated_tensor_count[origin_name] += 1 outputs = [_get_updated_name(origin_name, updated_tensor_count)] update_value = node.inputs[1] nodes_to_fuse_inputs = _construct_nodes_to_fuse_inputs(nodes_to_fuse) tensor_assign_node = InternalTorchIRNode( node=None, inputs=[source_tensor, update_value] + nodes_to_fuse_inputs, outputs=outputs, kind=kind, blocks=[], ) graph.nodes[i] = tensor_assign_node # modify the graph outputs if it is effected by this graph pass for idx in range(len(graph.outputs)): output = graph.outputs[idx] if output in updated_tensor_count: graph.outputs[idx] = _get_updated_name(output, updated_tensor_count) def remove_getattr_nodes(graph): """ Remove the getattr nodes in the graph """ getattr_nodes = [] new_nodes = [] for node in graph.nodes: for block in node.blocks: remove_getattr_nodes(block) if node.kind == "getattr": getattr_nodes.append(node) else: new_nodes.append(node) # check the getattr nodes not in the outputs for node in getattr_nodes: if node.name in graph.outputs: raise RuntimeError("{} should not be in the graph outputs.".format(node.name)) # remove the getattr nodes graph.nodes = new_nodes def transform_inplace_ops(graph, name_remap_dict=None): # As we modify ops, we'll need to remap symbols. if name_remap_dict is None: name_remap_dict = {} for node in graph.nodes: for k, v in name_remap_dict.items(): node.replace_name(k, v) if node.kind == "append": if isinstance(node.parent, InternalTorchIRGraph): # If append appears in a graph (outer block), replace # subsequent uses of its input symbol with its output symbol. name_remap_dict[node.inputs[0]] = node.outputs[0] elif node.parent.parent.kind == "loop": # If append appears in a loop block, add its inputs to the block # inputs and loop inputs, and its outputs to the block outputs # and loop outputs. # This is the global input to append. We need to add it to the # loop's input list, and replace any uses after the node with # @global_output below. global_input = node.inputs[0] # This will be the name of the input to append within the # block. We need to add it to the block inputs. local_input = node.parent.parent.name + ".0" # This is the output of append. We need to add it to the list # of block outputs. local_output = node.outputs[0] # This is the name of the new output from the loop. It should # replace any uses of @global_input after the loop op. global_output = local_output + ".out" name_remap_dict[global_input] = global_output node.parent.parent.inputs.append(global_input) node.parent.inputs.append(local_input) node.replace_name(global_input, local_input) node.parent.outputs.append(local_output) node.parent.parent.outputs.append(global_output) node.parent.parent.name = node.parent.parent.outputs[0] elif node.parent.parent.kind == "if": # If append appears in an if/else block, add its outputs to the # block outputs and loop outputs. # Note that we can't assume the append appears in both blocks. raise NotImplementedError( "inplace_ops pass doesn't yet support append op inside conditional" ) for block in node.blocks: transform_inplace_ops(block, name_remap_dict) # Replace names in graph outputs for k, v in name_remap_dict.items(): try: idx = graph.outputs.index(k) except ValueError: pass else: graph.outputs[idx] = v def flatten_graph_input_values(graph): """ CoreML can't handle nested iterables of tensors, so we flatten the inputs of any graph that expects them. """ new_graph_inputs = graph.inputs all_new_nodes = [] changed = True notified = False while changed: old_graph_inputs = new_graph_inputs new_graph_inputs = OrderedDict() new_nodes = [] changed = False for _input_name, _input_val in old_graph_inputs.items(): if isinstance(_input_val, (tuple, list)): changed = True if not notified: notified = True _logging.warning( "Tuple detected at graph input. This will be flattened in the converted model." ) # If this input to the graph is a tuple, we want to replace it # with a flattened version and add an op to construct the tuple. node_inputs = [] for idx, item in enumerate(_input_val): name = _input_name + "_{}".format(idx) new_graph_inputs[name] = item node_inputs.append(name) new_nodes.append( InternalTorchIRNode( inputs=node_inputs, outputs=[_input_name], kind="tupleconstruct", ) ) else: # This input isn't a tuple, keep it as is. new_graph_inputs[_input_name] = _input_val all_new_nodes = new_nodes + all_new_nodes graph.inputs = new_graph_inputs graph.nodes = all_new_nodes + graph.nodes def flatten_graph_output_values(graph): """ CoreML can't handle nested iterables of tensors, so we flatten the outputs of any graph that produces them. """ node_names = [node.name for node in graph.nodes] new_graph_outputs = graph.outputs changed = True notified = False while changed: old_graph_outputs = new_graph_outputs new_graph_outputs = [] changed = False for outp in old_graph_outputs: # Find the node that generates this output var. # It is possible to not find the output var in the list of node # names since nodes are named after their first output. In that # case, it means the output var comes from a node that returns # multiple outputs, which means that node cannot be a construct op. try: node_idx = node_names.index(outp) except: # @outp doesn't come from a construct op new_graph_outputs.append(outp) continue if graph.nodes[node_idx].kind in [ "tupleconstruct", "listconstruct", ]: # Since this output came from a construct op, we can replace it # with the inputs to the op. new_graph_outputs.extend(graph.nodes[node_idx].inputs) changed = True if not notified: notified = True _logging.warning( "Tuple detected at graph output. This will be flattened in the converted model." ) else: new_graph_outputs.append(outp) # Note: if we flattened outputs, there are likely to be construct ops # that are no longer needed. These will be removed in a later DCE pass. graph.outputs = new_graph_outputs<|fim▁end|>
output -> x_internal_tensor_assign_2
<|file_name|>np_mask_ops.py<|end_file_name|><|fim▁begin|># 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 applicable law or agreed to in writing, software # distributed under 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. # ============================================================================== """Operations for [N, height, width] numpy arrays representing masks. Example mask operations that are supported: * Areas: compute mask areas * IOU: pairwise intersection-over-union scores """ import numpy as np EPSILON = 1e-7 def area(masks): """Computes area of masks. Args: masks: Numpy array with shape [N, height, width] holding N masks. Masks values are of type np.uint8 and values are in {0,1}. Returns: a numpy array with shape [N*1] representing mask areas. Raises: ValueError: If masks.dtype is not np.uint8 """ if masks.dtype != np.uint8: raise ValueError('Masks type should be np.uint8') return np.sum(masks, axis=(1, 2), dtype=np.float32) def intersection(masks1, masks2): """Compute pairwise intersection areas between masks. Args: masks1: a numpy array with shape [N, height, width] holding N masks. Masks values are of type np.uint8 and values are in {0,1}. masks2: a numpy array with shape [M, height, width] holding M masks. Masks values are of type np.uint8 and values are in {0,1}. Returns: a numpy array with shape [N*M] representing pairwise intersection area. Raises: ValueError: If masks1 and masks2 are not of type np.uint8. """ if masks1.dtype != np.uint8 or masks2.dtype != np.uint8: raise ValueError('masks1 and masks2 should be of type np.uint8') n = masks1.shape[0] m = masks2.shape[0] answer = np.zeros([n, m], dtype=np.float32) for i in np.arange(n): for j in np.arange(m): answer[i, j] = np.sum(np.minimum(masks1[i], masks2[j]), dtype=np.float32) return answer def iou(masks1, masks2): """Computes pairwise intersection-over-union between mask collections. Args: masks1: a numpy array with shape [N, height, width] holding N masks. Masks values are of type np.uint8 and values are in {0,1}. masks2: a numpy array with shape [M, height, width] holding N masks. Masks values are of type np.uint8 and values are in {0,1}. Returns: a numpy array with shape [N, M] representing pairwise iou scores. Raises: ValueError: If masks1 and masks2 are not of type np.uint8. """ if masks1.dtype != np.uint8 or masks2.dtype != np.uint8: raise ValueError('masks1 and masks2 should be of type np.uint8') intersect = intersection(masks1, masks2) area1 = area(masks1) area2 = area(masks2) union = np.expand_dims(area1, axis=1) + np.expand_dims( area2, axis=0) - intersect return intersect / np.maximum(union, EPSILON) def ioa(masks1, masks2):<|fim▁hole|> their intersection area over mask2's area. Note that ioa is not symmetric, that is, IOA(mask1, mask2) != IOA(mask2, mask1). Args: masks1: a numpy array with shape [N, height, width] holding N masks. Masks values are of type np.uint8 and values are in {0,1}. masks2: a numpy array with shape [M, height, width] holding N masks. Masks values are of type np.uint8 and values are in {0,1}. Returns: a numpy array with shape [N, M] representing pairwise ioa scores. Raises: ValueError: If masks1 and masks2 are not of type np.uint8. """ if masks1.dtype != np.uint8 or masks2.dtype != np.uint8: raise ValueError('masks1 and masks2 should be of type np.uint8') intersect = intersection(masks1, masks2) areas = np.expand_dims(area(masks2), axis=0) return intersect / (areas + EPSILON)<|fim▁end|>
"""Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two masks, mask1 and mask2 is defined as
<|file_name|>apt_retry.go<|end_file_name|><|fim▁begin|>package main import ( "encoding/json" "flag" "fmt" "github.com/APTrust/bagman/bagman" "github.com/APTrust/bagman/workers" "io/ioutil" "os" ) /* apt_retry retries the record step of a failed item. This only works on items that have passed the prepare and store steps, and then have wound up in the trouble queue. */ func main() {<|fim▁hole|> jsonFile := flag.String("file", "", "JSON file to load") procUtil := workers.CreateProcUtil("aptrust") procUtil.MessageLog.Info("apt_retry started") bagRecorder := workers.NewBagRecorder(procUtil) if jsonFile == nil { fmt.Println("apt_retry tries to re-send metadata to Fluctus") fmt.Println("Usage: apt_retry -file=path/to/file.json -config=some_config") os.Exit(0) } fmt.Println(*jsonFile) result := loadJsonFile(*jsonFile) result.ErrorMessage = "" bagRecorder.RunWithoutNsq(result) } func loadJsonFile(jsonFile string) (*bagman.ProcessResult) { bytes, err := ioutil.ReadFile(jsonFile) if err != nil { fmt.Fprintf(os.Stderr, "Cannot read file '%s': %v\n", jsonFile, err) os.Exit(1) } var result bagman.ProcessResult err = json.Unmarshal(bytes, &result) if err != nil { fmt.Fprintf(os.Stderr, "Cannot convert JSON to object: %v\n", err) os.Exit(1) } return &result }<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Core XML support for Python. This package contains four sub-packages: dom -- The W3C Document Object Model. This supports DOM Level 1 + Namespaces. parsers -- Python wrappers for XML parsers (currently only supports Expat). sax -- The Simple API for XML, developed by XML-Dev, led by David Megginson and ported to Python by Lars Marius Garshol. This supports the SAX 2 API. etree -- The ElementTree XML library. This is a subset of the full ElementTree XML release. """ __all__ = ["dom", "parsers", "sax", "etree"] # When being checked-out without options, this has the form # "<dollar>Revision: x.y </dollar>" # When exported using -kv, it is "x.y". __version__ = "$Revision: 41660 $".split()[-2:][0] _MINIMUM_XMLPLUS_VERSION = (0, 8, 4) import os # only prefer _xmlplus if the environment variable PY_USE_XMLPLUS is defined<|fim▁hole|> try: import _xmlplus except ImportError: pass else: try: v = _xmlplus.version_info except AttributeError: # _xmlplus is too old; ignore it pass else: if v >= _MINIMUM_XMLPLUS_VERSION: import sys _xmlplus.__path__.extend(__path__) sys.modules[__name__] = _xmlplus else: del v<|fim▁end|>
if 'PY_USE_XMLPLUS' in os.environ:
<|file_name|>loader.go<|end_file_name|><|fim▁begin|>package loader import ( "errors" "fmt" "go/ast" "go/parser" "go/scanner" "go/token" "go/types" "log" "os" "golang.org/x/tools/go/gcexportdata" "golang.org/x/tools/go/packages" ) // Graph resolves patterns and returns packages with all the // information required to later load type information, and optionally // syntax trees. // // The provided config can set any setting with the exception of Mode. func Graph(cfg packages.Config, patterns ...string) ([]*packages.Package, error) { cfg.Mode = packages.NeedName | packages.NeedImports | packages.NeedDeps | packages.NeedExportsFile | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedTypesSizes pkgs, err := packages.Load(&cfg, patterns...) if err != nil { return nil, err } fset := token.NewFileSet() packages.Visit(pkgs, nil, func(pkg *packages.Package) { pkg.Fset = fset }) n := 0 for _, pkg := range pkgs { if len(pkg.CompiledGoFiles) == 0 && len(pkg.Errors) == 0 && pkg.PkgPath != "unsafe" { // If a package consists only of test files, then // go/packages incorrectly(?) returns an empty package for // the non-test variant. Get rid of those packages. See // #646. // // Do not, however, skip packages that have errors. Those, // too, may have no files, but we want to print the // errors. continue } pkgs[n] = pkg n++ } return pkgs[:n], nil } // LoadFromExport loads a package from export data. All of its // dependencies must have been loaded already. func LoadFromExport(pkg *packages.Package) error { pkg.IllTyped = true for path, pkg := range pkg.Imports { if pkg.Types == nil {<|fim▁hole|> return fmt.Errorf("no export data for %q", pkg.ID) } f, err := os.Open(pkg.ExportFile) if err != nil { return err } defer f.Close() r, err := gcexportdata.NewReader(f) if err != nil { return err } view := make(map[string]*types.Package) // view seen by gcexportdata seen := make(map[*packages.Package]bool) // all visited packages var visit func(pkgs map[string]*packages.Package) visit = func(pkgs map[string]*packages.Package) { for _, pkg := range pkgs { if !seen[pkg] { seen[pkg] = true view[pkg.PkgPath] = pkg.Types visit(pkg.Imports) } } } visit(pkg.Imports) tpkg, err := gcexportdata.Read(r, pkg.Fset, view, pkg.PkgPath) if err != nil { return err } pkg.Types = tpkg pkg.IllTyped = false return nil } // LoadFromSource loads a package from source. All of its dependencies // must have been loaded already. func LoadFromSource(pkg *packages.Package) error { pkg.IllTyped = true pkg.Types = types.NewPackage(pkg.PkgPath, pkg.Name) // OPT(dh): many packages have few files, much fewer than there // are CPU cores. Additionally, parsing each individual file is // very fast. A naive parallel implementation of this loop won't // be faster, and tends to be slower due to extra scheduling, // bookkeeping and potentially false sharing of cache lines. pkg.Syntax = make([]*ast.File, len(pkg.CompiledGoFiles)) for i, file := range pkg.CompiledGoFiles { f, err := parser.ParseFile(pkg.Fset, file, nil, parser.ParseComments) if err != nil { pkg.Errors = append(pkg.Errors, convertError(err)...) return err } pkg.Syntax[i] = f } pkg.TypesInfo = &types.Info{ Types: make(map[ast.Expr]types.TypeAndValue), Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Implicits: make(map[ast.Node]types.Object), Scopes: make(map[ast.Node]*types.Scope), Selections: make(map[*ast.SelectorExpr]*types.Selection), } importer := func(path string) (*types.Package, error) { if path == "unsafe" { return types.Unsafe, nil } if path == "C" { // go/packages doesn't tell us that cgo preprocessing // failed. When we subsequently try to parse the package, // we'll encounter the raw C import. return nil, errors.New("cgo preprocessing failed") } imp := pkg.Imports[path] if imp == nil { return nil, nil } if len(imp.Errors) > 0 { return nil, imp.Errors[0] } return imp.Types, nil } tc := &types.Config{ Importer: importerFunc(importer), Error: func(err error) { pkg.Errors = append(pkg.Errors, convertError(err)...) }, } err := types.NewChecker(tc, pkg.Fset, pkg.Types, pkg.TypesInfo).Files(pkg.Syntax) if err != nil { return err } pkg.IllTyped = false return nil } func convertError(err error) []packages.Error { var errs []packages.Error // taken from go/packages switch err := err.(type) { case packages.Error: // from driver errs = append(errs, err) case *os.PathError: // from parser errs = append(errs, packages.Error{ Pos: err.Path + ":1", Msg: err.Err.Error(), Kind: packages.ParseError, }) case scanner.ErrorList: // from parser for _, err := range err { errs = append(errs, packages.Error{ Pos: err.Pos.String(), Msg: err.Msg, Kind: packages.ParseError, }) } case types.Error: // from type checker errs = append(errs, packages.Error{ Pos: err.Fset.Position(err.Pos).String(), Msg: err.Msg, Kind: packages.TypeError, }) default: // unexpected impoverished error from parser? errs = append(errs, packages.Error{ Pos: "-", Msg: err.Error(), Kind: packages.UnknownError, }) // If you see this error message, please file a bug. log.Printf("internal error: error %q (%T) without position", err, err) } return errs } type importerFunc func(path string) (*types.Package, error) func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }<|fim▁end|>
return fmt.Errorf("dependency %q hasn't been loaded yet", path) } } if pkg.ExportFile == "" {
<|file_name|>AuctionController.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package test.auctionportal; import static com.sun.org.apache.xerces.internal.jaxp.JAXPConstants.JAXP_SCHEMA_LANGUAGE; import static com.sun.org.apache.xerces.internal.jaxp.JAXPConstants.JAXP_SCHEMA_SOURCE; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.math.BigInteger; import java.nio.file.Paths; import java.util.GregorianCalendar; import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.Duration; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import jaxp.library.JAXPFileReadOnlyBaseTest; import static jaxp.library.JAXPTestUtilities.bomStream; import org.testng.annotations.Test; import org.w3c.dom.Attr; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.TypeInfo; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; import static test.auctionportal.HiBidConstants.PORTAL_ACCOUNT_NS; import static test.auctionportal.HiBidConstants.XML_DIR; /** * This is the user controller class for the Auction portal HiBid.com. */ public class AuctionController extends JAXPFileReadOnlyBaseTest { /** * Check for DOMErrorHandler handling DOMError. Before fix of bug 4890927 * DOMConfiguration.setParameter("well-formed",true) throws an exception. * * @throws Exception If any errors occur. */ @Test(groups = {"readLocalFiles"}) public void testCreateNewItem2Sell() throws Exception { String xmlFile = XML_DIR + "novelsInvalid.xml"; Document document = DocumentBuilderFactory.newInstance() .newDocumentBuilder().parse(xmlFile); document.getDomConfig().setParameter("well-formed", true); DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); MyDOMOutput domOutput = new MyDOMOutput(); domOutput.setByteStream(System.out); LSSerializer writer = impl.createLSSerializer(); writer.write(document, domOutput); } /** * Check for DOMErrorHandler handling DOMError. Before fix of bug 4896132 * test throws DOM Level 1 node error. * * @throws Exception If any errors occur. */ @Test(groups = {"readLocalFiles"}) public void testCreateNewItem2SellRetry() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document document = dbf.newDocumentBuilder().parse(xmlFile); DOMConfiguration domConfig = document.getDomConfig(); MyDOMErrorHandler errHandler = new MyDOMErrorHandler(); domConfig.setParameter("error-handler", errHandler); DOMImplementationLS impl = (DOMImplementationLS) DOMImplementationRegistry.newInstance() .getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); MyDOMOutput domoutput = new MyDOMOutput(); domoutput.setByteStream(System.out); writer.write(document, domoutput); document.normalizeDocument(); writer.write(document, domoutput); assertFalse(errHandler.isError()); } /** * Check if setting the attribute to be of type ID works. This will affect * the Attr.isID method according to the spec. * * @throws Exception If any errors occur. */ @Test(groups = {"readLocalFiles"}) public void testCreateID() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document document = dbf.newDocumentBuilder().parse(xmlFile); Element account = (Element)document .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); account.setIdAttributeNS(PORTAL_ACCOUNT_NS, "accountID", true); Attr aID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID"); assertTrue(aID.isId()); } /** * Check the user data on the node. * * @throws Exception If any errors occur. */ @Test(groups = {"readLocalFiles"}) public void testCheckingUserData() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); Document document = docBuilder.parse(xmlFile); Element account = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); assertEquals(account.getNodeName(), "acc:Account"); Element firstName = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0); assertEquals(firstName.getNodeName(), "FirstName"); Document doc1 = docBuilder.newDocument(); Element someName = doc1.createElement("newelem"); someName.setUserData("mykey", "dd", (operation, key, data, src, dst) -> { System.err.println("In UserDataHandler" + key); System.out.println("In UserDataHandler"); }); Element impAccount = (Element)document.importNode(someName, true); assertEquals(impAccount.getNodeName(), "newelem"); document.normalizeDocument(); String data = (someName.getUserData("mykey")).toString(); assertEquals(data, "dd"); } /** * Check the UTF-16 XMLEncoding xml file. * * @throws Exception If any errors occur. * @see <a href="content/movies.xml">movies.xml</a> */ @Test(groups = {"readLocalFiles"}) public void testCheckingEncoding() throws Exception { // Note since movies.xml is UTF-16 encoding. We're not using stanard XML // file suffix. String xmlFile = XML_DIR + "movies.xml.data"; <|fim▁hole|> Document document = dbf.newDocumentBuilder().parse(source); assertEquals(document.getXmlEncoding(), "UTF-16"); assertEquals(document.getXmlStandalone(), true); } } /** * Check validation API features. A schema which is including in Bug 4909119 * used to be testing for the functionalities. * * @throws Exception If any errors occur. * @see <a href="content/userDetails.xsd">userDetails.xsd</a> */ @Test(groups = {"readLocalFiles"}) public void testGetOwnerInfo() throws Exception { String schemaFile = XML_DIR + "userDetails.xsd"; String xmlFile = XML_DIR + "userDetails.xml"; try(FileInputStream fis = new FileInputStream(xmlFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(Paths.get(schemaFile).toFile()); Validator validator = schema.newValidator(); MyErrorHandler eh = new MyErrorHandler(); validator.setErrorHandler(eh); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); docBuilder.setErrorHandler(eh); Document document = docBuilder.parse(fis); DOMResult dResult = new DOMResult(); DOMSource domSource = new DOMSource(document); validator.validate(domSource, dResult); assertFalse(eh.isAnyError()); } } /** * Check grammar caching with imported schemas. * * @throws Exception If any errors occur. * @see <a href="content/coins.xsd">coins.xsd</a> * @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a> */ @Test(groups = {"readLocalFiles"}) public void testGetOwnerItemList() throws Exception { String xsdFile = XML_DIR + "coins.xsd"; String xmlFile = XML_DIR + "coins.xml"; try(FileInputStream fis = new FileInputStream(xmlFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); dbf.setValidating(false); SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new File(((xsdFile)))); MyErrorHandler eh = new MyErrorHandler(); Validator validator = schema.newValidator(); validator.setErrorHandler(eh); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); Document document = docBuilder.parse(fis); validator.validate(new DOMSource(document), new DOMResult()); assertFalse(eh.isAnyError()); } } /** * Check for the same imported schemas but will use SAXParserFactory and try * parsing using the SAXParser. SCHEMA_SOURCE attribute is using for this * test. * * @throws Exception If any errors occur. * @see <a href="content/coins.xsd">coins.xsd</a> * @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a> */ @Test(groups = {"readLocalFiles"}) public void testGetOwnerItemList1() throws Exception { String xsdFile = XML_DIR + "coins.xsd"; String xmlFile = XML_DIR + "coins.xml"; SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(true); SAXParser sp = spf.newSAXParser(); sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); sp.setProperty(JAXP_SCHEMA_SOURCE, xsdFile); MyErrorHandler eh = new MyErrorHandler(); sp.parse(new File(xmlFile), eh); assertFalse(eh.isAnyError()); } /** * Check usage of javax.xml.datatype.Duration class. * * @throws Exception If any errors occur. */ @Test(groups = {"readLocalFiles"}) public void testGetItemDuration() throws Exception { String xmlFile = XML_DIR + "itemsDuration.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document document = dbf.newDocumentBuilder().parse(xmlFile); Element durationElement = (Element) document.getElementsByTagName("sellDuration").item(0); NodeList childList = durationElement.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { System.out.println("child " + i + childList.item(i)); } Duration duration = DatatypeFactory.newInstance().newDuration("P365D"); Duration sellDuration = DatatypeFactory.newInstance().newDuration(childList.item(0).getNodeValue()); assertFalse(sellDuration.isShorterThan(duration)); assertFalse(sellDuration.isLongerThan(duration)); assertEquals(sellDuration.getField(DatatypeConstants.DAYS), BigInteger.valueOf(365)); assertEquals(sellDuration.normalizeWith(new GregorianCalendar(1999, 2, 22)), duration); Duration myDuration = sellDuration.add(duration); assertEquals(myDuration.normalizeWith(new GregorianCalendar(2003, 2, 22)), DatatypeFactory.newInstance().newDuration("P730D")); } /** * Check usage of TypeInfo interface introduced in DOM L3. * * @throws Exception If any errors occur. */ @Test(groups = {"readLocalFiles"}) public void testGetTypeInfo() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); docBuilder.setErrorHandler(new MyErrorHandler()); Document document = docBuilder.parse(xmlFile); Element userId = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0); TypeInfo typeInfo = userId.getSchemaTypeInfo(); assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger")); assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI)); Element role = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0); TypeInfo roletypeInfo = role.getSchemaTypeInfo(); assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell")); assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS)); } }<|fim▁end|>
try (InputStream source = bomStream("UTF-16", xmlFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);
<|file_name|>ckan_engine_e2e_tests.py<|end_file_name|><|fim▁begin|>import os import random import string import unittest import requests from tethys_dataset_services.engines import CkanDatasetEngine try: from tethys_dataset_services.tests.test_config import TEST_CKAN_DATASET_SERVICE except ImportError: print('ERROR: To perform tests, you must create a file in the "tests" package called "test_config.py". In this file' 'provide a dictionary called "TEST_CKAN_DATASET_SERVICE" with keys "API_ENDPOINT" and "APIKEY".') exit(1) def random_string_generator(size): chars = string.ascii_lowercase + string.digits return ''.join(random.choice(chars) for _ in range(size)) class TestCkanDatasetEngine(unittest.TestCase): def setUp(self): # Auth self.endpoint = TEST_CKAN_DATASET_SERVICE['ENDPOINT'] self.apikey = TEST_CKAN_DATASET_SERVICE['APIKEY'] self.username = TEST_CKAN_DATASET_SERVICE['USERNAME'] # Files self.tests_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) self.files_root = os.path.join(self.tests_root, 'files') self.support_root = os.path.join(self.tests_root, 'support') # Create Test Engine self.engine = CkanDatasetEngine(endpoint=self.endpoint, apikey=self.apikey) # Create Test Organization self.test_org = random_string_generator(10) data_dict = { 'name': self.test_org, 'users': [{'name': self.username}] } url, data, headers = self.engine._prepare_request( 'organization_create', data_dict=data_dict, apikey=self.apikey ) status_code, response_text = self.engine._execute_request(url, data, headers) if status_code != 200: raise requests.RequestException('Unable to create group: {}'.format(response_text)) # Create Test Dataset self.test_dataset_name = random_string_generator(10) dataset_result = self.engine.create_dataset(name=self.test_dataset_name, version='1.0', owner_org=self.test_org) if not dataset_result['success']: raise requests.RequestException('Unable to create test dataset: {}'.format(dataset_result['error'])) self.test_dataset = dataset_result['result'] # Create Test Resource self.test_resource_name = random_string_generator(10) self.test_resource_url = 'http://home.byu.edu' resource_result = self.engine.create_resource(self.test_dataset_name, url=self.test_resource_url, format='zip') if not resource_result['success']: raise requests.RequestException('Unable to create test resource: {}'.format(resource_result['error'])) self.test_resource = resource_result['result'] def tearDown(self): pass # Delete test resource and dataset self.engine.delete_dataset(dataset_id=self.test_dataset_name) def test_create_dataset(self): # Setup new_dataset_name = random_string_generator(10) # Execute result = self.engine.create_dataset(name=new_dataset_name, owner_org=self.test_org) # Verify Success self.assertTrue(result['success']) # Should return the new one self.assertEqual(new_dataset_name, result['result']['name']) # TEST search_datasets result = self.engine.search_datasets(query={'name': new_dataset_name}, console=False) # Verify Success self.assertTrue(result['success']) # Check search results search_results = result['result']['results'] self.assertIn(new_dataset_name, search_results[0]['name']) self.assertIn(self.test_org, search_results[0]['organization']['name']) # TEST list_datasets # Execute result = self.engine.list_datasets() # Verify Success self.assertTrue(result['success']) self.assertIn(new_dataset_name, result['result']) # Delete result = self.engine.delete_dataset(dataset_id=new_dataset_name) # Check if success self.assertTrue(result['success']) def test_create_resource_file(self): # Prepare file_name = 'upload_test.txt' save_name = random_string_generator(10) file_to_upload = os.path.join(self.support_root, file_name) # Execute result = self.engine.create_resource(dataset_id=self.test_dataset_name, name=save_name, file=file_to_upload) # Verify Success self.assertTrue(result['success']) # Verify name and url_type (which should be upload if file upload) self.assertIn(save_name, result['result']['name']) self.assertEqual(result['result']['url_type'], 'upload') # TEST search resource # Execute result = self.engine.search_resources(query={'name': save_name}) # Verify Success self.assertTrue(result['success']) self.assertIn(save_name, result['result']['results'][-1]['name']) # Delete result = self.engine.delete_resource(resource_id=result['result']['results'][-1]['id']) self.assertTrue(result['success']) def test_create_resource_url(self): # Prepare new_resource_name = random_string_generator(10) new_resource_url = 'http://home.byu.edu/' # Execute result = self.engine.create_resource(dataset_id=self.test_dataset_name, url=new_resource_url, name=new_resource_name) # Verify Success self.assertTrue(result['success']) # Verify name and url_type (which should be upload if file upload) self.assertIn(new_resource_name, result['result']['name']) self.assertEqual(result['result']['url'], new_resource_url) # TEST search resource # Execute result = self.engine.search_resources(query={'name': new_resource_name}) <|fim▁hole|> self.assertTrue(result['success']) self.assertIn(new_resource_name, result['result']['results'][-1]['name']) self.assertIn(new_resource_url, result['result']['results'][-1]['url']) # Delete result = self.engine.delete_resource(resource_id=result['result']['results'][-1]['id']) self.assertTrue(result['success']) def test_update_dataset(self): # Setup notes = random_string_generator(10) author = random_string_generator(5) # Execute result = self.engine.update_dataset(dataset_id=self.test_dataset_name, author=author, notes=notes) # Verify Success self.assertTrue(result['success']) # Verify new property self.assertEqual(result['result']['author'], author) self.assertEqual(result['result']['notes'], notes) # TEST get_dataset # Execute result = self.engine.get_dataset(dataset_id=self.test_dataset_name) # Verify Success self.assertTrue(result['success']) # Verify Name self.assertEqual(result['result']['name'], self.test_dataset_name) self.assertEqual(result['result']['author'], author) self.assertEqual(result['result']['notes'], notes) # TEST download_dataset location = self.files_root result = self.engine.download_dataset(self.test_dataset_name, location=location) # Result will return list of the file with .zip at the end. Check here self.assertIn('.zip', result[0][-4:].lower()) download_file = os.path.basename(result[0]) location_final = os.path.join(self.files_root, download_file) # Delete the file if os.path.isfile(location_final): os.remove(location_final) else: raise AssertionError('No file has been downloaded') # TEST delete_dataset # Execute result = self.engine.delete_dataset(dataset_id=self.test_dataset_name) # Confirm Success self.assertTrue(result['success']) # Delete requests should return nothing self.assertEqual(result['result'], None) def test_update_resource(self): # Get Resource ID result = self.engine.get_dataset(dataset_id=self.test_dataset_name) resource_id = result['result']['resources'][0]['id'] # Setup file_name = 'upload_test.txt' file_to_upload = os.path.join(self.support_root, file_name) description_new = random_string_generator(10) # Execute result = self.engine.update_resource(resource_id=resource_id, file=file_to_upload, description=description_new) # Verify Success self.assertTrue(result['success']) # Verify Name (should be the same as the file uploaded by default) self.assertEqual(result['result']['name'], file_name) self.assertEqual(result['result']['description'], description_new) # TEST get_resource # Execute result = self.engine.get_resource(resource_id=resource_id) # Verify Success self.assertTrue(result['success']) # Verify Properties self.assertEqual(result['result']['name'], file_name) self.assertEqual(result['result']['description'], description_new) # TEST download_resource location = self.files_root result = self.engine.download_resource(resource_id=resource_id, location=location) # Result will return list of the file with .zip at the end. Check here self.assertIn('.zip', result[-4:].lower()) download_file = os.path.basename(result) location_final = os.path.join(self.files_root, download_file) # Delete the file if os.path.isfile(location_final): os.remove(location_final) else: raise AssertionError('No file has been downloaded') # TEST delete_resource # Execute result = self.engine.delete_resource(resource_id=resource_id) # Verify Success self.assertTrue(result['success']) # Delete requests should return nothing self.assertEqual(result['result'], None) def test_validate(self): self.engine.validate() def test_validate_status_code(self): self.engine2 = CkanDatasetEngine(endpoint="http://localhost:5000/api/a/action/", apikey=TEST_CKAN_DATASET_SERVICE['APIKEY']) self.assertRaises(AssertionError, self.engine2.validate)<|fim▁end|>
# Verify Success
<|file_name|>rpsystem.py<|end_file_name|><|fim▁begin|>""" Roleplaying base system for Evennia Contribution - Griatch, 2015 This module contains the ContribRPObject, ContribRPRoom and ContribRPCharacter typeclasses. If you inherit your objects/rooms/character from these (or make them the defaults) from these you will get the following features: - Objects/Rooms will get the ability to have poses and will report the poses of items inside them (the latter most useful for Rooms). - Characters will get poses and also sdescs (short descriptions) that will be used instead of their keys. They will gain commands for managing recognition (custom sdesc-replacement), masking themselves as well as an advanced free-form emote command. To use, simply import the typclasses you want from this module and use them to create your objects, or set them to default. In more detail, This RP base system introduces the following features to a game, common to many RP-centric games: - emote system using director stance emoting (names/sdescs). This uses a customizable replacement noun (/me, @ etc) to represent you in the emote. You can use /sdesc, /nick, /key or /alias to reference objects in the room. You can use any number of sdesc sub-parts to differentiate a local sdesc, or use /1-sdesc etc to differentiate them. The emote also identifies nested says. - sdesc obscuration of real character names for use in emotes and in any referencing such as object.search(). This relies on an SdescHandler `sdesc` being set on the Character and makes use of a custom Character.get_display_name hook. If sdesc is not set, the character's `key` is used instead. This is particularly used in the emoting system. - recog system to assign your own nicknames to characters, can then be used for referencing. The user may recog a user and assign any personal nick to them. This will be shown in descriptions and used to reference them. This is making use of the nick functionality of Evennia. - masks to hide your identity (using a simple lock). - pose system to set room-persistent poses, visible in room descriptions and when looking at the person/object. This is a simple Attribute that modifies how the characters is viewed when in a room as sdesc + pose. - in-emote says, including seamless integration with language obscuration routine (such as contrib/rplanguage.py) Examples: > look Tavern The tavern is full of nice people *A tall man* is standing by the bar. Above is an example of a player with an sdesc "a tall man". It is also an example of a static *pose*: The "standing by the bar" has been set by the player of the tall man, so that people looking at him can tell at a glance what is going on. > emote /me looks at /tall and says "Hello!" I see: Griatch looks at Tall man and says "Hello". Tall man (assuming his name is Tom) sees: The godlike figure looks at Tom and says "Hello". """ from builtins import object import re from re import escape as re_escape import itertools from evennia import DefaultObject, DefaultCharacter from evennia import Command, CmdSet from evennia import ansi from evennia.utils.utils import lazy_property #------------------------------------------------------------ # Emote parser #------------------------------------------------------------ # Settings # The prefix is the (single-character) symbol used to find the start # of a object reference, such as /tall (note that # the system will understand multi-word references like '/a tall man' too). _PREFIX = "/" # The num_sep is the (single-character) symbol used to separate the # sdesc from the number when trying to separate identical sdescs from # one another. This is the same syntax used in the rest of Evennia, so # by default, multiple "tall" can be separated by entering 1-tall, # 2-tall etc. _NUM_SEP = "-" # Texts _EMOTE_NOMATCH_ERROR = \ """{{RNo match for {{r{ref}{{R.{{n""" _EMOTE_MULTIMATCH_ERROR = \ """{{RMultiple possibilities for {ref}: {{r{reflist}{{n""" _RE_FLAGS = re.MULTILINE + re.IGNORECASE + re.UNICODE _RE_PREFIX = re.compile(r"^%s" % _PREFIX, re.UNICODE) # The num_sep is the (single-character) symbol used to separate the # sdesc from the number when trying to separate identical sdescs from # one another. This is the same syntax used in the rest of Evennia, so # by default, multiple "tall" can be separated by entering 1-tall, # 2-tall etc. _NUM_SEP = "-" # This regex will return groups (num, word), where num is an optional counter to # separate multimatches from one another and word is the first word in the # marker. So entering "/tall man" will return groups ("", "tall") # and "/2-tall man" will return groups ("2", "tall"). _RE_OBJ_REF_START = re.compile(r"%s(?:([0-9]+)%s)*(\w+)" % (_PREFIX, _NUM_SEP), _RE_FLAGS) # Reference markers are used internally when distributing the emote to # all that can see it. They are never seen by players and are on the form {#dbref}. _RE_REF = re.compile(r"\{+\#([0-9]+)\}+") # This regex is used to quickly reference one self in an emote. _RE_SELF_REF = re.compile(r"/me|@", _RE_FLAGS) # regex for non-alphanumberic end of a string _RE_CHAREND = re.compile(r"\W+$", _RE_FLAGS) # reference markers for language _RE_REF_LANG = re.compile(r"\{+\##([0-9]+)\}+") # language says in the emote are on the form "..." or langname"..." (no spaces). # this regex returns in groups (langname, say), where langname can be empty. _RE_LANGUAGE = re.compile(r"(?:\((\w+)\))*(\".+?\")") # the emote parser works in two steps: # 1) convert the incoming emote into an intermediary # form with all object references mapped to ids. # 2) for every person seeing the emote, parse this # intermediary form into the one valid for that char. class EmoteError(Exception): pass class SdescError(Exception): pass class RecogError(Exception): pass class LanguageError(Exception): pass def _dummy_process(text, *args, **kwargs): "Pass-through processor" return text # emoting mechanisms def ordered_permutation_regex(sentence): """ Builds a regex that matches 'ordered permutations' of a sentence's words. Args: sentence (str): The sentence to build a match pattern to Returns: regex (re object): Compiled regex object represented the possible ordered permutations of the sentence, from longest to shortest. Example: The sdesc_regex for an sdesc of " very tall man" will result in the following allowed permutations, regex-matched in inverse order of length (case-insensitive): "the very tall man", "the very tall", "very tall man", "very tall", "the very", "tall man", "the", "very", "tall", and "man". We also add regex to make sure it also accepts num-specifiers, like /2-tall. """ # escape {#nnn} markers from sentence, replace with nnn sentence = _RE_REF.sub(r"\1", sentence) # escape {##nnn} markers, replace with nnn sentence = _RE_REF_LANG.sub(r"\1", sentence) # escape self-ref marker from sentence sentence = _RE_SELF_REF.sub(r"", sentence) # ordered permutation algorithm words = sentence.split() combinations = itertools.product((True, False), repeat=len(words)) solution = [] for combination in combinations: comb = [] for iword, word in enumerate(words): if combination[iword]: comb.append(word) elif comb: break if comb: solution.append(_PREFIX + r"[0-9]*%s*%s(?=\W|$)+" % (_NUM_SEP, re_escape(" ".join(comb)).rstrip("\\"))) # combine into a match regex, first matching the longest down to the shortest components regex = r"|".join(sorted(set(solution), key=lambda o:len(o), reverse=True)) return regex def parse_language(speaker, emote): """ Parse the emote for language. This is used with a plugin for handling languages. Args: speaker (Object): The object speaking. emote (str): An emote possibly containing language references. Returns: (emote, mapping) (tuple): A tuple where the `emote` is the emote string with all says (including quotes) replaced with reference markers on the form {##n} where n is a running number. The `mapping` is a dictionary between the markers and a tuple (langname, saytext), where langname can be None. Raises: LanguageError: If an invalid language was specified. Notes: Note that no errors are raised if the wrong language identifier is given. This data, together with the identity of the speaker, is intended to be used by the "listener" later, since with this information the language skill of the speaker can be offset to the language skill of the listener to determine how much information is actually conveyed. """ # escape mapping syntax on the form {##id} if it exists already in emote, # if so it is replaced with just "id". emote = _RE_REF_LANG.sub(r"\1", emote) errors = [] mapping = {} for imatch, say_match in enumerate(reversed(list(_RE_LANGUAGE.finditer(emote)))): # process matches backwards to be able to replace # in-place without messing up indexes for future matches # note that saytext includes surrounding "...". langname, saytext = say_match.groups() istart, iend = say_match.start(), say_match.end() # the key is simply the running match in the emote key = "##%i" % imatch # replace say with ref markers in emote emote = emote[:istart] + "{%s}" % key + emote[iend:] mapping[key] = (langname, saytext) if errors: # catch errors and report raise LanguageError("\n".join(errors)) # at this point all says have been replaced with {##nn} markers # and mapping maps 1:1 to this. return emote, mapping def parse_sdescs_and_recogs(sender, candidates, string, search_mode=False): """ Read a textraw emote and parse it into an intermediary format for distributing to all observers. Args: sender (Object): The object sending the emote. This object's recog data will be considered in the parsing. candidates (iterable): A list of objects valid for referencing in the emote. string (str): The string (like an emote) we want to analyze for keywords. search_mode (bool, optional): If `True`, the "emote" is a query string we want to analyze. If so, the return value is changed. Returns: (emote, mapping) (tuple): If `search_mode` is `False` (default), a tuple where the emote is the emote string, with all references replaced with internal-representation {#dbref} markers and mapping is a dictionary `{"#dbref":obj, ...}`. result (list): If `search_mode` is `True` we are performing a search query on `string`, looking for a specific object. A list with zero, one or more matches. Raises: EmoteException: For various ref-matching errors. Notes: The parser analyzes and should understand the following _PREFIX-tagged structures in the emote: - self-reference (/me) - recogs (any part of it) stored on emoter, matching obj in `candidates`. - sdesc (any part of it) from any obj in `candidates`. - N-sdesc, N-recog separating multi-matches (1-tall, 2-tall) - says, "..." are """ # Load all candidate regex tuples [(regex, obj, sdesc/recog),...] candidate_regexes = \ [(_RE_SELF_REF, sender, sender.sdesc.get())] + \ [sender.recog.get_regex_tuple(obj) for obj in candidates if hasattr(obj, "recog")] + \ [obj.sdesc.get_regex_tuple() for obj in candidates if hasattr(obj, "sdesc")] # filter out non-found data candidate_regexes = [tup for tup in candidate_regexes if tup] # escape mapping syntax on the form {#id} if it exists already in emote, # if so it is replaced with just "id". string = _RE_REF.sub(r"\1", string) # we now loop over all references and analyze them mapping = {} errors = [] obj = None nmatches = 0 for marker_match in reversed(list(_RE_OBJ_REF_START.finditer(string))): # we scan backwards so we can replace in-situ without messing # up later occurrences. Given a marker match, query from # start index forward for all candidates. # first see if there is a number given (e.g. 1-tall) num_identifier, _ = marker_match.groups("") # return "" if no match, rather than None istart0 = marker_match.start() istart = istart0 # loop over all candidate regexes and match against the string following the match matches = ((reg.match(string[istart:]), obj, text) for reg, obj, text in candidate_regexes) # score matches by how long part of the string was matched matches = [(match.end() if match else -1, obj, text) for match, obj, text in matches] maxscore = max(score for score, obj, text in matches) # we have a valid maxscore, extract all matches with this value bestmatches = [(obj, text) for score, obj, text in matches if maxscore == score != -1] nmatches = len(bestmatches) if not nmatches: # no matches obj = None nmatches = 0 elif nmatches == 1: # an exact match. obj = bestmatches[0][0] nmatches = 1 elif all(bestmatches[0][0].id == obj.id for obj, text in bestmatches): # multi-match but all matches actually reference the same # obj (could happen with clashing recogs + sdescs) obj = bestmatches[0][0] nmatches = 1 else: # multi-match. # was a numerical identifier given to help us separate the multi-match? inum = min(max(0, int(num_identifier) - 1), nmatches-1) if num_identifier else None if inum is not None: # A valid inum is given. Use this to separate data. obj = bestmatches[inum][0] nmatches = 1 else: # no identifier given - a real multimatch. obj = bestmatches if search_mode: # single-object search mode. Don't continue loop. break elif nmatches == 0: errors.append(_EMOTE_NOMATCH_ERROR.format(ref=marker_match.group())) elif nmatches == 1: key = "#%i" % obj.id string = string[:istart0] + "{%s}" % key + string[istart + maxscore:] mapping[key] = obj else: refname = marker_match.group() reflist = ["%s%s%s (%s%s)" % (inum+1, _NUM_SEP, _RE_PREFIX.sub("", refname), text, " (%s)" % sender.key if sender == obj else "") for inum, (obj, text) in enumerate(bestmatches) if score == maxscore] errors.append(_EMOTE_MULTIMATCH_ERROR.format( ref=marker_match.group(), reflist="\n ".join(reflist))) if search_mode: # return list of object(s) matching if nmatches == 0: return [] elif nmatches == 1: return [obj] else: return [tup[0] for tup in obj] if errors: # make sure to not let errors through. raise EmoteError("\n".join(errors)) # at this point all references have been replaced with {#xxx} markers and the mapping contains # a 1:1 mapping between those inline markers and objects. return string, mapping def send_emote(sender, receivers, emote, anonymous_add="first"): """ Main access function for distribute an emote. Args: sender (Object): The one sending the emote. receivers (iterable): Receivers of the emote. These will also form the basis for which sdescs are 'valid' to use in the emote. emote (str): The raw emote string as input by emoter. anonymous_add (str or None, optional): If `sender` is not self-referencing in the emote, this will auto-add `sender`'s data to the emote. Possible values are - None: No auto-add at anonymous emote - 'last': Add sender to the end of emote as [sender] - 'first': Prepend sender to start of emote. """ try: emote, obj_mapping = parse_sdescs_and_recogs(sender, receivers, emote) emote, language_mapping = parse_language(sender, emote) except (EmoteError, LanguageError) as err: # handle all error messages, don't hide actual coding errors sender.msg(err.message) return if anonymous_add and not "#%i" % sender.id in obj_mapping: # no self-reference in the emote - add to the end key = "#%i" % sender.id obj_mapping[key] = sender if anonymous_add == 'first': possessive = "" if emote.startswith('\'') else " " emote = "%s%s%s" % ("{%s}" % key, possessive, emote) else: emote = "%s [%s]" % (emote, "{%s}" % key) # broadcast emote to everyone for receiver in receivers: # we make a temporary copy that we can modify try: recog_get = receiver.recog.get mapping = dict((ref, recog_get(obj)) for ref, obj in obj_mapping.items()) except AttributeError: mapping = dict((ref, obj.sdesc.get() if hasattr(obj, "sdesc") else obj.key) for ref, obj in obj_mapping.items()) # handle the language mapping, which always produce different keys ##nn try: process_language = receiver.process_language except AttributeError: process_language = _dummy_process for key, (langname, saytext) in language_mapping.iteritems(): # color says mapping[key] = process_language(saytext, sender, langname) # make sure receiver always sees their real name rkey = "#%i" % receiver.id if rkey in mapping: mapping[rkey] = receiver.key # add color to sdesc strings try: process_sdesc = receiver.process_sdesc except AttributeError: process_sdesc = _dummy_process mapping = dict((key, process_sdesc(val, receiver)) for key, val in mapping.iteritems()) # do the template replacement receiver.msg(emote.format(**mapping)) #------------------------------------------------------------ # Handlers for sdesc and recog #------------------------------------------------------------ class SdescHandler(object): """ This Handler wraps all operations with sdescs. We need to use this since we do a lot preparations on sdescs when updating them, in order for them to be efficient to search for and query. """ def __init__(self, obj): """ Initialize the handler Args: obj (Object): The entity on which this handler is stored. """ self.obj = obj self.sdesc = "" self.sdesc_regex = "" self._cache() def _cache(self): """ Cache data from storage """ self.sdesc = self.obj.attributes.get("_sdesc", default="") sdesc_regex = self.obj.attributes.get("_sdesc_regex", default="") self.sdesc_regex = re.compile(sdesc_regex, _RE_FLAGS) def add(self, sdesc, max_length=60): """ Add a new sdesc to object, replacing the old one. Args: sdesc (str): The sdesc to set. This may be stripped of control sequences before setting. max_length (int, optional): The max limit of the sdesc. Returns: sdesc (str): The actually set sdesc. Raises: SdescError: If the sdesc can not be set or is longer than `max_length`. """ # strip emote components from sdesc sdesc = _RE_REF.sub(r"\1", _RE_REF_LANG.sub(r"\1", _RE_SELF_REF.sub(r"", _RE_LANGUAGE.sub(r"", _RE_OBJ_REF_START.sub(r"", sdesc))))) # make an sdesc clean of ANSI codes cleaned_sdesc = ansi.strip_ansi(sdesc) if len(cleaned_sdesc) > max_length: raise SdescError("Too long sdesc") # store to attributes sdesc_regex = ordered_permutation_regex(cleaned_sdesc) self.obj.attributes.add("_sdesc", sdesc) self.obj.attributes.add("_sdesc_regex", sdesc_regex) # local caching self.sdesc = sdesc self.sdesc_regex = re.compile(sdesc_regex, _RE_FLAGS) return sdesc def get(self): """ Simple getter. """ return self.sdesc def get_regex_tuple(self): """ Return data for sdesc/recog handling Returns: tup (tuple): tuple (sdesc_regex, obj, sdesc) """ return self.sdesc_regex, self.obj, self.sdesc class RecogHandler(object): """ This handler manages the recognition mapping of an Object. """ def __init__(self, obj): """ Initialize the handler Args: obj (Object): The entity on which this handler is stored. """ self.obj = obj # mappings self.ref2recog = {} self.obj2regex = {} self.obj2recog = {} self._cache() def _cache(self): """ Load data to handler cache """ self.ref2recog = self.obj.attributes.get("_recog_ref2recog", default={}) obj2regex = self.obj.attributes.get("_recog_obj2regex", default={}) obj2recog = self.obj.attributes.get("_recog_obj2recog", default={}) self.obj2regex = dict((obj, re.compile(regex, _RE_FLAGS)) for obj, regex in obj2regex.items() if obj) self.obj2recog = dict((obj, recog) for obj, recog in obj2recog.items() if obj) def add(self, obj, recog, max_length=60): """ Assign a custom recog (nick) to the given object. Args: obj (Object): The object ot associate with the recog string. This is usually determined from the sdesc in the room by a call to parse_sdescs_and_recogs, but can also be given. recog (str): The replacement string to use with this object. max_length (int, optional): The max length of the recog string. Returns: recog (str): The (possibly cleaned up) recog string actually set. Raises: SdescError: When recog could not be set or sdesc longer than `max_length`. """ # strip emote components from recog recog = _RE_REF.sub(r"\1", _RE_REF_LANG.sub(r"\1", _RE_SELF_REF.sub(r"", _RE_LANGUAGE.sub(r"", _RE_OBJ_REF_START.sub(r"", recog))))) # make an recog clean of ANSI codes cleaned_recog = ansi.strip_ansi(recog) if len(cleaned_recog) > max_length: raise RecogError("Too long recog") # mapping #dbref:obj key = "#%i" % obj.id self.obj.db._recog_ref2recog[key] = recog self.obj.db._recog_obj2recog[obj] = recog regex = ordered_permutation_regex(cleaned_recog) self.obj.db._recog_obj2regex[obj] = regex # local caching self.ref2recog[key] = recog self.obj2recog[obj] = recog self.obj2regex[obj] = re.compile(regex, _RE_FLAGS) return recog def get(self, obj): """ Get recog replacement string, if one exists, otherwise get sdesc and as a last resort, the object's key. Args: obj (Object): The object, whose sdesc to replace Returns: recog (str): The replacement string to use. Notes: This method will respect a "enable_recog" lock set on `obj` (True by default) in order to turn off recog mechanism. This is useful for adding masks/hoods etc. """ if obj.access(self.obj, "enable_recog", default=True): # check an eventual recog_masked lock on the object # to avoid revealing masked characters. If lock # does not exist, pass automatically. return self.obj2recog.get(obj, obj.sdesc.get() if hasattr(obj, "sdesc") else obj.key) else: # recog_mask log not passed, disable recog return obj.sdesc.get() if hasattr(obj, "sdesc") else obj.key def remove(self, obj): """ Clear recog for a given object. Args: obj (Object): The object for which to remove recog. """ if obj in self.obj2recog: del self.obj.db._recog_obj2recog[obj] del self.obj.db._recog_obj2regex[obj] del self.obj.db._recog_ref2recog["#%i" % obj.id] self._cache() def get_regex_tuple(self, obj): """ Returns: rec (tuple): Tuple (recog_regex, obj, recog) """ if obj in self.obj2recog and obj.access(self.obj, "enable_recog", default=True): return self.obj2regex[obj], obj, self.obj2regex[obj] return None #------------------------------------------------------------ # RP Commands #------------------------------------------------------------ class RPCommand(Command): "simple parent" def parse(self): "strip extra whitespace" self.args = self.args.strip() class CmdEmote(RPCommand): # replaces the main emote """ Emote an action, allowing dynamic replacement of text in the emote. Usage: emote text Example: emote /me looks around. emote With a flurry /me attacks /tall man with his sword. emote "Hello", /me says. Describes an event in the world. This allows the use of /ref markers to replace with the short descriptions or recognized strings of objects in the same room. These will be translated to emotes to match each person seeing it. Use "..." for saying things and langcode"..." without spaces to say something in a different language. """ key = "emote" aliases = [":"] locks = "cmd:all()" def func(self): "Perform the emote." if not self.args: self.caller.msg("What do you want to do?") else: # we also include ourselves here. emote = self.args targets = self.caller.location.contents if not emote.endswith((".", "!")): emote = "%s." % emote send_emote(self.caller, targets, emote, anonymous_add='first') class CmdSdesc(RPCommand): # set/look at own sdesc """ Assign yourself a short description (sdesc). Usage: sdesc <short description> Assigns a short description to yourself. """ key = "sdesc" locks = "cmd:all()" def func(self): "Assign the sdesc" caller = self.caller if not self.args: caller.msg("Usage: sdesc <sdesc-text>") return else: # strip non-alfanum chars from end of sdesc sdesc = _RE_CHAREND.sub("", self.args) sdesc = caller.sdesc.add(sdesc) caller.msg("%s's sdesc was set to '%s'." % (caller.key, sdesc)) class CmdPose(RPCommand): # set current pose and default pose """ Set a static pose Usage: pose <pose> pose default <pose> pose reset pose obj = <pose> pose default obj = <pose> pose reset obj = Examples: pose leans against the tree pose is talking to the barkeep. pose box = is sitting on the floor. Set a static pose. This is the end of a full sentence that starts with your sdesc. If no full stop is given, it will be added automatically. The default pose is the pose you get when using pose reset. Note that you can use sdescs/recogs to reference people in your pose, but these always appear as that person's sdesc in the emote, regardless of who is seeing it. """ key = "pose" def parse(self): """ Extract the "default" alternative to the pose. """ args = self.args.strip() default = args.startswith("default") reset = args.startswith("reset") if default: args = re.sub(r"^default", "", args) if reset: args = re.sub(r"^reset", "", args) target = None if "=" in args: target, args = [part.strip() for part in args.split("=", 1)] self.target = target self.reset = reset self.default = default self.args = args.strip() def func(self): "Create the pose" caller = self.caller pose = self.args target = self.target if not pose and not self.reset: caller.msg("Usage: pose <pose-text> OR pose obj = <pose-text>") return if not pose.endswith("."): pose = "%s." % pose if target: # affect something else target = caller.search(target) if not target: return if not target.access(caller, "edit"): caller.msg("You can't pose that.") return else: target = caller if not target.attributes.has("pose"): caller.msg("%s cannot be posed." % target.key) return target_name = target.sdesc.get() if hasattr(target, "sdesc") else target.key # set the pose if self.reset: pose = target.db.pose_default target.db.pose = pose elif self.default: target.db.pose_default = pose caller.msg("Default pose is now '%s %s'." % (target_name, pose)) return else: # set the pose. We do one-time ref->sdesc mapping here. parsed, mapping = parse_sdescs_and_recogs(caller, caller.location.contents, pose) mapping = dict((ref, obj.sdesc.get() if hasattr(obj, "sdesc") else obj.key) for ref, obj in mapping.iteritems()) pose = parsed.format(**mapping) if len(target_name) + len(pose) > 60: caller.msg("Your pose '%s' is too long." % pose) return target.db.pose = pose caller.msg("Pose will read '%s %s'." % (target_name, pose)) class CmdRecog(RPCommand): # assign personal alias to object in room """ Recognize another person in the same room. Usage: recog sdesc as alias Example: recog tall man as Griatch forget griatch This will assign a personal alias for a person, or forget said alias. """ key = "recog" aliases = ["recognize", "forget"] def parse(self): "Parse for the sdesc as alias structure" if "as" in self.args: self.sdesc, self.alias = [part.strip() for part in self.args.split(" as ", 2)] elif self.args: self.sdesc = self.args.strip() self.alias = "" def func(self): "Assign the recog" caller = self.caller if not self.args: caller.msg("Usage: recog <sdesc> as <alias> or forget <alias>") return sdesc = self.sdesc alias = self.alias.rstrip(".?!") prefixed_sdesc = sdesc if sdesc.startswith(_PREFIX) else _PREFIX + sdesc candidates = caller.location.contents matches = parse_sdescs_and_recogs(caller, candidates, prefixed_sdesc, search_mode=True) nmatches = len(matches) # handle 0, 1 and >1 matches if nmatches == 0: caller.msg(_EMOTE_NOMATCH_ERROR.format(ref=sdesc)) elif nmatches > 1: reflist = ["%s%s%s (%s%s)" % (inum+1, _NUM_SEP, _RE_PREFIX.sub("", sdesc), caller.recog.get(obj), " (%s)" % caller.key if caller == obj else "") for inum, obj in enumerate(matches)] caller.msg(_EMOTE_MULTIMATCH_ERROR.format(ref=sdesc,reflist="\n ".join(reflist))) else: obj = matches[0] if not obj.access(self.obj, "enable_recog", default=True): # don't apply recog if object doesn't allow it (e.g. by being masked). caller.msg("Can't recognize someone who is masked.") return if self.cmdstring == "forget": # remove existing recog caller.recog.remove(obj) caller.msg("%s will know only '%s'." % (caller.key, obj.recog.get(obj))) else: sdesc = obj.sdesc.get() if hasattr(obj, "sdesc") else obj.key alias = caller.recog.add(obj, alias) caller.msg("%s will now remember {w%s{n as {w%s{n." % (caller.key, sdesc, alias)) class CmdMask(RPCommand): """ Wear a mask Usage: mask <new sdesc> unmask This will put on a mask to hide your identity. When wearing a mask, your sdesc will be replaced by the sdesc you pick and people's recognitions of you will be disabled. """ key = "mask" aliases = ["unmask"] def func(self): caller = self.caller if self.cmdstring == "mask": # wear a mask if not self.args: caller.msg("Usage: (un)wearmask sdesc") return if caller.db.unmasked_sdesc: caller.msg("You are already wearing a mask.") return sdesc = _RE_CHAREND.sub("", self.args) sdesc = "%s {H[masked]{n" % sdesc if len(sdesc) > 60: caller.msg("Your masked sdesc is too long.") return caller.db.unmasked_sdesc = caller.sdesc.get() caller.locks.add("enable_recog:false()") caller.sdesc.add(sdesc) caller.msg("You wear a mask as '%s'." % sdesc) else: #unmask old_sdesc = caller.db.unmasked_sdesc if not old_sdesc: caller.msg("You are not wearing a mask.") return del caller.db.unmasked_sdesc caller.locks.remove("enable_recog") caller.sdesc.add(old_sdesc) caller.msg("You remove your mask and is again '%s'." % old_sdesc) class RPSystemCmdSet(CmdSet): """ Mix-in for adding rp-commands to default cmdset. """ def at_cmdset_creation(self): self.add(CmdEmote()) self.add(CmdSdesc()) self.add(CmdPose()) self.add(CmdRecog()) self.add(CmdMask()) #------------------------------------------------------------ # RP typeclasses #------------------------------------------------------------ class ContribRPObject(DefaultObject): """ This class is meant as a mix-in or parent for objects in an rp-heavy game. It implements the base functionality for poses. """ def at_object_creation(self): """ Called at initial creation. """ super(ContribRPObject, self).at_object_creation # emoting/recog data self.db.pose = "" self.db.pose_default = "is here." def search(self, searchdata, **kwargs): """ This version of search will pre-parse searchdata for eventual matches against recogs and sdescs of candidates in the same location. Args: searchdata (str): Search string. Notes: Recog/sdesc matching is always turned off if the keyword `global_search` is set or `candidates` are given. """ if (isinstance(searchdata, basestring) and not (kwargs.get("global_search") or kwargs.get("candidates"))): # searchdata is a string; common self-references if searchdata.lower() in ("here", ): return [self.location] if "quiet" in kwargs else self.location if searchdata.lower() in ("me", "self",): return [self] if "quiet" in kwargs else self if searchdata.lower() == self.key.lower(): return [self] if "quiet" in kwargs else self # sdesc/recog matching candidates = self.location.contents matches = parse_sdescs_and_recogs(self, candidates, _PREFIX + searchdata, search_mode=True) nmatches = len(matches) if nmatches == 1: return matches[0] elif nmatches > 1: # multimatch reflist = ["%s%s%s (%s%s)" % (inum+1, _NUM_SEP, searchdata, self.recog.get(obj), " (%s)" % self.key if self == obj else "") for inum, obj in enumerate(matches)] self.msg(_EMOTE_MULTIMATCH_ERROR.format(ref=searchdata,reflist="\n ".join(reflist))) return if not self.locks.check_lockstring(self, "perm(Builders)"): # we block lookup unless we have access to continue if "nofound_string" in kwargs: self.msg(kwargs["nofound_string"]) else: self.msg("There is no '%s' here." % searchdata) return # fall back to normal search return super(ContribRPObject, self).search(searchdata, **kwargs) def get_display_name(self, looker, **kwargs): """ Displays the name of the object in a viewer-aware manner. Args: looker (TypedObject): The object or player that is looking at/getting inforamtion for this object. Kwargs: pose (bool): Include the pose (if available) in the return. Returns: name (str): A string of the sdesc containing the name of the object, if this is defined. including the DBREF if this user is privileged to control said object. <|fim▁hole|> """ idstr = "(#%s)" % self.id if self.access(looker, access_type='control') else "" try: recog = looker.recog.get(self) except AttributeError: recog = None sdesc = recog or (hasattr(self, "sdesc") and self.sdesc.get()) or self.key pose = " %s" % ((self.db.pose or "") if kwargs.get("pose", False) else "") return "%s%s%s" % (sdesc, idstr, pose) def return_appearance(self, looker): """ This formats a description. It is the hook a 'look' command should call. Args: looker (Object): Object doing the looking. """ if not looker: return # get and identify all objects visible = (con for con in self.contents if con != looker and con.access(looker, "view")) exits, users, things = [], [], [] for con in visible: key = con.get_display_name(looker, pose=True) if con.destination: exits.append(key) elif con.has_player: users.append(key) else: things.append(key) # get description, build string string = "{c%s{n\n" % self.get_display_name(looker, pose=True) desc = self.db.desc if desc: string += "%s" % desc if exits: string += "\n{wExits:{n " + ", ".join(exits) if users or things: string += "\n " + "\n ".join(users + things) return string class ContribRPRoom(ContribRPObject): """ Dummy inheritance for rooms. """ pass class ContribRPCharacter(DefaultCharacter, ContribRPObject): """ This is a character class that has poses, sdesc and recog. """ # Handlers @lazy_property def sdesc(self): return SdescHandler(self) @lazy_property def recog(self): return RecogHandler(self) def get_display_name(self, looker, **kwargs): """ Displays the name of the object in a viewer-aware manner. Args: looker (TypedObject): The object or player that is looking at/getting inforamtion for this object. Kwargs: pose (bool): Include the pose (if available) in the return. Returns: name (str): A string of the sdesc containing the name of the object, if this is defined. including the DBREF if this user is privileged to control said object. Notes: The RPCharacter version of this method colors its display to make characters stand out from other objects. """ idstr = "(#%s)" % self.id if self.access(looker, access_type='control') else "" try: recog = looker.recog.get(self) except AttributeError: recog = None sdesc = recog or (hasattr(self, "sdesc") and self.sdesc.get()) or self.key pose = " %s" % self.db.pose or "" if kwargs.get("pose", False) else "" return "{c%s{n%s%s" % (sdesc, idstr, pose) def at_object_creation(self): """ Called at initial creation. """ super(ContribRPCharacter, self).at_object_creation() self.db._sdesc = "" self.db._sdesc_regex = "" self.db._recog_ref2recog = {} self.db._recog_obj2regex = {} self.db._recog_obj2recog = {} self.cmdset.add(RPSystemCmdSet, permanent=True) # initializing sdesc self.sdesc.add("A normal person") def process_sdesc(self, sdesc, obj, **kwargs): """ Allows to customize how your sdesc is displayed (primarily by changing colors). Args: sdesc (str): The sdesc to display. obj (Object): The object to which the adjoining sdesc belongs (can be yourself). Returns: sdesc (str): The processed sdesc ready for display. """ return "{b%s{n" % sdesc def process_language(self, text, speaker, language, **kwargs): """ Allows to process the spoken text, for example by obfuscating language based on your and the speaker's language skills. Also a good place to put coloring. Args: text (str): The text to process. speaker (Object): The object delivering the text. language (str): An identifier string for the language. Return: text (str): The optionally processed text. Notes: This is designed to work together with a string obfuscator such as the `obfuscate_language` or `obfuscate_whisper` in the evennia.contrib.rplanguage module. """ return "%s{w%s{n" % ("{W(%s)" % language if language else "", text) #from evennia.contrib import rplanguage #return "{w%s{n" % rplanguage.obfuscate_language(text, level=1.0)<|fim▁end|>
Notes: The RPObject version doesn't add color to its display.
<|file_name|>video_input_generator.py<|end_file_name|><|fim▁begin|># Copyright 2018 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under 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. # ============================================================================== """Wrapper for providing semantic segmentation video data.""" import tensorflow as tf from feelvos import input_preprocess from feelvos import model from feelvos.utils import mask_damaging from feelvos.utils import train_utils slim = tf.contrib.slim dataset_data_provider = slim.dataset_data_provider MIN_LABEL_COUNT = 10 def decode_image_sequence(tensor, image_format='jpeg', shape=None, channels=3, raw_dtype=tf.uint8): """Decodes a sequence of images. Args: tensor: the tensor of strings to decode, shape: [num_images] image_format: a string (possibly tensor) with the format of the image. Options include 'jpeg', 'png', and 'raw'. shape: a list or tensor of the decoded image shape for a single image. channels: if 'shape' is None, the third dimension of the image is set to this value. raw_dtype: if the image is encoded as raw bytes, this is the method of decoding the bytes into values. Returns: The decoded images with shape [time, height, width, channels]. """ handler = slim.tfexample_decoder.Image( shape=shape, channels=channels, dtype=raw_dtype, repeated=True) return handler.tensors_to_item({'image/encoded': tensor, 'image/format': image_format}) def _get_data(data_provider, dataset_split, video_frames_are_decoded): """Gets data from data provider. Args: data_provider: An object of slim.data_provider. dataset_split: Dataset split. video_frames_are_decoded: Boolean, whether the video frames are already decoded Returns: image: Image Tensor. label: Label Tensor storing segmentation annotations. object_label: An integer refers to object_label according to labelmap. If the example has more than one object_label, take the first one. image_name: Image name. height: Image height. width: Image width. video_id: String tensor representing the name of the video. Raises: ValueError: Failed to find label. """ if video_frames_are_decoded: image, = data_provider.get(['image']) else: image, = data_provider.get(['image/encoded']) # Some datasets do not contain image_name. if 'image_name' in data_provider.list_items(): image_name, = data_provider.get(['image_name']) else: image_name = tf.constant('') height, width = data_provider.get(['height', 'width']) label = None if dataset_split != 'test': if video_frames_are_decoded: if 'labels_class' not in data_provider.list_items(): raise ValueError('Failed to find labels.') label, = data_provider.get(['labels_class']) else: key = 'segmentation/object/encoded' if key not in data_provider.list_items(): raise ValueError('Failed to find labels.') label, = data_provider.get([key]) object_label = None video_id, = data_provider.get(['video_id']) return image, label, object_label, image_name, height, width, video_id def _has_foreground_and_background_in_first_frame(label, subsampling_factor): """Checks if the labels have foreground and background in the first frame. Args: label: Label tensor of shape [num_frames, height, width, 1]. subsampling_factor: Integer, the subsampling factor. Returns: Boolean, whether the labels have foreground and background in the first frame. """ h, w = train_utils.resolve_shape(label)[1:3] label_downscaled = tf.squeeze( tf.image.resize_nearest_neighbor(label[0, tf.newaxis], [h // subsampling_factor, w // subsampling_factor], align_corners=True), axis=0) is_bg = tf.equal(label_downscaled, 0) is_fg = tf.logical_not(is_bg) # Just using reduce_any was not robust enough, so lets make sure the count # is above MIN_LABEL_COUNT. fg_count = tf.reduce_sum(tf.cast(is_fg, tf.int32)) bg_count = tf.reduce_sum(tf.cast(is_bg, tf.int32)) has_bg = tf.greater_equal(fg_count, MIN_LABEL_COUNT) has_fg = tf.greater_equal(bg_count, MIN_LABEL_COUNT) return tf.logical_and(has_bg, has_fg) def _has_foreground_and_background_in_first_frame_2(label, decoder_output_stride): """Checks if the labels have foreground and background in the first frame. Second attempt, this time we use the actual output dimension for resizing. Args: label: Label tensor of shape [num_frames, height, width, 1]. decoder_output_stride: Integer, the stride of the decoder output. Returns: Boolean, whether the labels have foreground and background in the first frame. """ h, w = train_utils.resolve_shape(label)[1:3] h_sub = model.scale_dimension(h, 1.0 / decoder_output_stride) w_sub = model.scale_dimension(w, 1.0 / decoder_output_stride) label_downscaled = tf.squeeze( tf.image.resize_nearest_neighbor(label[0, tf.newaxis], [h_sub, w_sub], align_corners=True), axis=0) is_bg = tf.equal(label_downscaled, 0) is_fg = tf.logical_not(is_bg) # Just using reduce_any was not robust enough, so lets make sure the count # is above MIN_LABEL_COUNT. fg_count = tf.reduce_sum(tf.cast(is_fg, tf.int32)) bg_count = tf.reduce_sum(tf.cast(is_bg, tf.int32)) has_bg = tf.greater_equal(fg_count, MIN_LABEL_COUNT) has_fg = tf.greater_equal(bg_count, MIN_LABEL_COUNT) return tf.logical_and(has_bg, has_fg) def _has_enough_pixels_of_each_object_in_first_frame( label, decoder_output_stride): """Checks if for each object (incl. background) enough pixels are visible. During test time, we will usually not see a reference frame in which only very few pixels of one object are visible. These cases can be problematic during training, especially if more than the 1-nearest neighbor is used. That's why this function can be used to detect and filter these cases. Args: label: Label tensor of shape [num_frames, height, width, 1]. decoder_output_stride: Integer, the stride of the decoder output. Returns: Boolean, whether the labels have enough pixels of each object in the first frame. """ h, w = train_utils.resolve_shape(label)[1:3] h_sub = model.scale_dimension(h, 1.0 / decoder_output_stride) w_sub = model.scale_dimension(w, 1.0 / decoder_output_stride) label_downscaled = tf.squeeze( tf.image.resize_nearest_neighbor(label[0, tf.newaxis], [h_sub, w_sub], align_corners=True), axis=0) _, _, counts = tf.unique_with_counts( tf.reshape(label_downscaled, [-1])) has_enough_pixels_per_object = tf.reduce_all( tf.greater_equal(counts, MIN_LABEL_COUNT)) return has_enough_pixels_per_object def get(dataset, num_frames_per_video, crop_size, batch_size, min_resize_value=None, max_resize_value=None, resize_factor=None, min_scale_factor=1., max_scale_factor=1., scale_factor_step_size=0, preprocess_image_and_label=True, num_readers=1, num_threads=1, dataset_split=None, is_training=True, model_variant=None, batch_capacity_factor=32, video_frames_are_decoded=False, decoder_output_stride=None, first_frame_finetuning=False, sample_only_first_frame_for_finetuning=False, sample_adjacent_and_consistent_query_frames=False, remap_labels_to_reference_frame=True, generate_prev_frame_mask_by_mask_damaging=False, three_frame_dataset=False, add_prev_frame_label=True): """Gets the dataset split for semantic segmentation. This functions gets the dataset split for semantic segmentation. In particular, it is a wrapper of (1) dataset_data_provider which returns the raw dataset split, (2) input_preprcess which preprocess the raw data, and (3) the Tensorflow operation of batching the preprocessed data. Then, the output could be directly used by training, evaluation or visualization. Args: dataset: An instance of slim Dataset. num_frames_per_video: The number of frames used per video crop_size: Image crop size [height, width]. batch_size: Batch size. min_resize_value: Desired size of the smaller image side. max_resize_value: Maximum allowed size of the larger image side. resize_factor: Resized dimensions are multiple of factor plus one. min_scale_factor: Minimum scale factor value. max_scale_factor: Maximum scale factor value. scale_factor_step_size: The step size from min scale factor to max scale factor. The input is randomly scaled based on the value of (min_scale_factor, max_scale_factor, scale_factor_step_size). preprocess_image_and_label: Boolean variable specifies if preprocessing of image and label will be performed or not. num_readers: Number of readers for data provider. num_threads: Number of threads for batching data. dataset_split: Dataset split. is_training: Is training or not. model_variant: Model variant (string) for choosing how to mean-subtract the images. See feature_extractor.network_map for supported model variants. batch_capacity_factor: Batch capacity factor affecting the training queue batch capacity. video_frames_are_decoded: Boolean, whether the video frames are already decoded decoder_output_stride: Integer, the stride of the decoder output. first_frame_finetuning: Boolean, whether to only sample the first frame for fine-tuning. sample_only_first_frame_for_finetuning: Boolean, whether to only sample the first frame during fine-tuning. This should be False when using lucid or wonderland data, but true when fine-tuning on the first frame only. Only has an effect if first_frame_finetuning is True. sample_adjacent_and_consistent_query_frames: Boolean, if true, the query frames (all but the first frame which is the reference frame) will be sampled such that they are adjacent video frames and have the same crop coordinates and flip augmentation. remap_labels_to_reference_frame: Boolean, whether to remap the labels of the query frames to match the labels of the (downscaled) reference frame. If a query frame contains a label which is not present in the reference, it will be mapped to background. generate_prev_frame_mask_by_mask_damaging: Boolean, whether to generate the masks used as guidance from the previous frame by damaging the ground truth mask. three_frame_dataset: Boolean, whether the dataset has exactly three frames per video of which the first is to be used as reference and the two others are consecutive frames to be used as query frames. add_prev_frame_label: Boolean, whether to sample one more frame before the first query frame to obtain a previous frame label. Only has an effect, if sample_adjacent_and_consistent_query_frames is True and generate_prev_frame_mask_by_mask_damaging is False. Returns: A dictionary of batched Tensors for semantic segmentation. Raises: ValueError: dataset_split is None, or Failed to find labels. """ if dataset_split is None: raise ValueError('Unknown dataset split.') if model_variant is None: tf.logging.warning('Please specify a model_variant. See ' 'feature_extractor.network_map for supported model ' 'variants.') data_provider = dataset_data_provider.DatasetDataProvider( dataset, num_readers=num_readers, num_epochs=None if is_training else 1, shuffle=is_training) image, label, object_label, image_name, height, width, video_id = _get_data( data_provider, dataset_split, video_frames_are_decoded) sampling_is_valid = tf.constant(True) if num_frames_per_video is not None: total_num_frames = tf.shape(image)[0] if first_frame_finetuning or three_frame_dataset: if sample_only_first_frame_for_finetuning: assert not sample_adjacent_and_consistent_query_frames, ( 'this option does not make sense for sampling only first frame.') # Sample the first frame num_frames_per_video times. sel_indices = tf.tile(tf.constant(0, dtype=tf.int32)[tf.newaxis], multiples=[num_frames_per_video]) else: if sample_adjacent_and_consistent_query_frames: if add_prev_frame_label: num_frames_per_video += 1 # Since this is first frame fine-tuning, we'll for now assume that # each sequence has exactly 3 images: the ref frame and 2 adjacent # query frames. assert num_frames_per_video == 3 with tf.control_dependencies([tf.assert_equal(total_num_frames, 3)]): sel_indices = tf.constant([1, 2], dtype=tf.int32) else: # Sample num_frames_per_video - 1 query frames which are not the # first frame. sel_indices = tf.random_shuffle( tf.range(1, total_num_frames))[:(num_frames_per_video - 1)] # Concat first frame as reference frame to the front. sel_indices = tf.concat([tf.constant(0, dtype=tf.int32)[tf.newaxis], sel_indices], axis=0) else: if sample_adjacent_and_consistent_query_frames: if add_prev_frame_label: # Sample one more frame which we can use to provide initial softmax # feedback. num_frames_per_video += 1 ref_idx = tf.random_shuffle(tf.range(total_num_frames))[0] sampling_is_valid = tf.greater_equal(total_num_frames, num_frames_per_video) def sample_query_start_idx(): return tf.random_shuffle( tf.range(total_num_frames - num_frames_per_video + 1))[0] query_start_idx = tf.cond(sampling_is_valid, sample_query_start_idx, lambda: tf.constant(0, dtype=tf.int32)) def sample_sel_indices(): return tf.concat( [ref_idx[tf.newaxis], tf.range( query_start_idx, query_start_idx + (num_frames_per_video - 1))], axis=0) sel_indices = tf.cond( sampling_is_valid, sample_sel_indices, lambda: tf.zeros((num_frames_per_video,), dtype=tf.int32)) else: # Randomly sample some frames from the video. sel_indices = tf.random_shuffle( tf.range(total_num_frames))[:num_frames_per_video] image = tf.gather(image, sel_indices, axis=0) if not video_frames_are_decoded: image = decode_image_sequence(image) if label is not None: if num_frames_per_video is not None: label = tf.gather(label, sel_indices, axis=0) if not video_frames_are_decoded: label = decode_image_sequence(label, image_format='png', channels=1) # Sometimes, label is saved as [num_frames_per_video, height, width] or # [num_frames_per_video, height, width, 1]. We change it to be<|fim▁hole|> # [num_frames_per_video, height, width, 1]. if label.shape.ndims == 3: label = tf.expand_dims(label, 3) elif label.shape.ndims == 4 and label.shape.dims[3] == 1: pass else: raise ValueError('Input label shape must be ' '[num_frames_per_video, height, width],' ' or [num_frames, height, width, 1]. ' 'Got {}'.format(label.shape.ndims)) label.set_shape([None, None, None, 1]) # Add size of first dimension since tf can't figure it out automatically. image.set_shape((num_frames_per_video, None, None, None)) if label is not None: label.set_shape((num_frames_per_video, None, None, None)) preceding_frame_label = None if preprocess_image_and_label: if num_frames_per_video is None: raise ValueError('num_frame_per_video must be specified for preproc.') original_images = [] images = [] labels = [] if sample_adjacent_and_consistent_query_frames: num_frames_individual_preproc = 1 else: num_frames_individual_preproc = num_frames_per_video for frame_idx in range(num_frames_individual_preproc): original_image_t, image_t, label_t = ( input_preprocess.preprocess_image_and_label( image[frame_idx], label[frame_idx], crop_height=crop_size[0] if crop_size is not None else None, crop_width=crop_size[1] if crop_size is not None else None, min_resize_value=min_resize_value, max_resize_value=max_resize_value, resize_factor=resize_factor, min_scale_factor=min_scale_factor, max_scale_factor=max_scale_factor, scale_factor_step_size=scale_factor_step_size, ignore_label=dataset.ignore_label, is_training=is_training, model_variant=model_variant)) original_images.append(original_image_t) images.append(image_t) labels.append(label_t) if sample_adjacent_and_consistent_query_frames: imgs_for_preproc = [image[frame_idx] for frame_idx in range(1, num_frames_per_video)] labels_for_preproc = [label[frame_idx] for frame_idx in range(1, num_frames_per_video)] original_image_rest, image_rest, label_rest = ( input_preprocess.preprocess_images_and_labels_consistently( imgs_for_preproc, labels_for_preproc, crop_height=crop_size[0] if crop_size is not None else None, crop_width=crop_size[1] if crop_size is not None else None, min_resize_value=min_resize_value, max_resize_value=max_resize_value, resize_factor=resize_factor, min_scale_factor=min_scale_factor, max_scale_factor=max_scale_factor, scale_factor_step_size=scale_factor_step_size, ignore_label=dataset.ignore_label, is_training=is_training, model_variant=model_variant)) original_images.extend(original_image_rest) images.extend(image_rest) labels.extend(label_rest) assert len(original_images) == num_frames_per_video assert len(images) == num_frames_per_video assert len(labels) == num_frames_per_video if remap_labels_to_reference_frame: # Remap labels to indices into the labels of the (downscaled) reference # frame, or 0, i.e. background, for labels which are not present # in the reference. reference_labels = labels[0][tf.newaxis] h, w = train_utils.resolve_shape(reference_labels)[1:3] embedding_height = model.scale_dimension( h, 1.0 / decoder_output_stride) embedding_width = model.scale_dimension( w, 1.0 / decoder_output_stride) reference_labels_embedding_size = tf.squeeze( tf.image.resize_nearest_neighbor( reference_labels, tf.stack([embedding_height, embedding_width]), align_corners=True), axis=0) # Get sorted unique labels in the reference frame. labels_in_ref_frame, _ = tf.unique( tf.reshape(reference_labels_embedding_size, [-1])) labels_in_ref_frame = tf.contrib.framework.sort(labels_in_ref_frame) for idx in range(1, len(labels)): ref_label_mask = tf.equal( labels[idx], labels_in_ref_frame[tf.newaxis, tf.newaxis, :]) remapped = tf.argmax(tf.cast(ref_label_mask, tf.uint8), axis=-1, output_type=tf.int32) # Set to 0 if label is not present is_in_ref = tf.reduce_any(ref_label_mask, axis=-1) remapped *= tf.cast(is_in_ref, tf.int32) labels[idx] = remapped[..., tf.newaxis] if sample_adjacent_and_consistent_query_frames: if first_frame_finetuning and generate_prev_frame_mask_by_mask_damaging: preceding_frame_label = mask_damaging.damage_masks(labels[1]) elif add_prev_frame_label: # Discard the image of the additional frame and take the label as # initialization for softmax feedback. original_images = [original_images[0]] + original_images[2:] preceding_frame_label = labels[1] images = [images[0]] + images[2:] labels = [labels[0]] + labels[2:] num_frames_per_video -= 1 original_image = tf.stack(original_images, axis=0) image = tf.stack(images, axis=0) label = tf.stack(labels, axis=0) else: if label is not None: # Need to set label shape due to batching. label.set_shape([num_frames_per_video, None if crop_size is None else crop_size[0], None if crop_size is None else crop_size[1], 1]) original_image = tf.to_float(tf.zeros_like(label)) if crop_size is None: height = tf.shape(image)[1] width = tf.shape(image)[2] else: height = crop_size[0] width = crop_size[1] sample = {'image': image, 'image_name': image_name, 'height': height, 'width': width, 'video_id': video_id} if label is not None: sample['label'] = label if object_label is not None: sample['object_label'] = object_label if preceding_frame_label is not None: sample['preceding_frame_label'] = preceding_frame_label if not is_training: # Original image is only used during visualization. sample['original_image'] = original_image if is_training: if first_frame_finetuning: keep_input = tf.constant(True) else: keep_input = tf.logical_and(sampling_is_valid, tf.logical_and( _has_enough_pixels_of_each_object_in_first_frame( label, decoder_output_stride), _has_foreground_and_background_in_first_frame_2( label, decoder_output_stride))) batched = tf.train.maybe_batch(sample, keep_input=keep_input, batch_size=batch_size, num_threads=num_threads, capacity=batch_capacity_factor * batch_size, dynamic_pad=True) else: batched = tf.train.batch(sample, batch_size=batch_size, num_threads=num_threads, capacity=batch_capacity_factor * batch_size, dynamic_pad=True) # Flatten from [batch, num_frames_per_video, ...] to # batch * num_frames_per_video, ...]. cropped_height = train_utils.resolve_shape(batched['image'])[2] cropped_width = train_utils.resolve_shape(batched['image'])[3] if num_frames_per_video is None: first_dim = -1 else: first_dim = batch_size * num_frames_per_video batched['image'] = tf.reshape(batched['image'], [first_dim, cropped_height, cropped_width, 3]) if label is not None: batched['label'] = tf.reshape(batched['label'], [first_dim, cropped_height, cropped_width, 1]) return batched<|fim▁end|>
<|file_name|>unauthenticated.exception.ts<|end_file_name|><|fim▁begin|>import { HttpException, HttpStatus } from '@nestjs/common'; import { WsException } from '@nestjs/websockets'; import { createExceptionBody } from '../../exceptions/exceptionBody.util'; export const ERROR_CODE = 'CHARACTER_NOT_AUTHENTICATED'; export const ERROR_MESSAGE = 'You aren\'t authenticated!'; export class HttpUnauthenticatedException extends HttpException { constructor() { super( createExceptionBody(ERROR_MESSAGE, ERROR_CODE, HttpStatus.UNAUTHORIZED), HttpStatus.UNAUTHORIZED, ); }<|fim▁hole|> export class WsUnauthenticatedException extends WsException { constructor() { super( createExceptionBody(ERROR_MESSAGE, ERROR_CODE, HttpStatus.UNAUTHORIZED), ); } }<|fim▁end|>
}
<|file_name|>rules.js<|end_file_name|><|fim▁begin|><|fim▁hole|>// Generated by CoffeeScript 1.7.1 (function() { var ERROR, IGNORE, WARN; ERROR = 'error'; WARN = 'warn'; IGNORE = 'ignore'; module.exports = { coffeescript_error: { level: ERROR, message: '' } }; }).call(this);<|fim▁end|>
<|file_name|>services.py<|end_file_name|><|fim▁begin|>from .models import * from django.db.models import Count, F, Max, Sum # Game info services def get_median_points(game_id): return median_value(Team.objects.filter(play__game__id=game_id) \ .exclude(play__team__points__isnull=True), 'play__team__points') def get_play_count(game_id): return Play.objects.filter(game__id=game_id).count() def get_game_list(): games = Game.objects.all() \ .annotate(plays=Count('play__id')) \ .annotate(last_played=Max('play__date')) \ .order_by('-plays') return games def get_game_players(game_id): play_players = Play.objects.filter(game__id=game_id) \ .annotate(name=F('team__players__name')) \ .annotate(winner=F('team__winner')) \ .annotate(pid=F('team__players__id')) \ .values('id', 'name', 'pid', 'winner').distinct() return Player.objects.raw( '''SELECT pid, name, COUNT(DISTINCT id) AS 'count', SUM(winner) AS 'wins' FROM ( %s ) GROUP BY pid ORDER BY COUNT(id) DESC, SUM(winner) DESC''' % str(play_players.query), translations={'pid': 'id'}) def get_faction_plays(game_id): return Faction.objects.filter(game__id=game_id) \ .values('name') \ .annotate(wins=Sum('team__winner')) \ .annotate(count=Count('name')) \ .order_by('-count', '-wins') # Player info services def get_player_games(player_id): plays_ids = get_play_ids(player_id) return Game.objects.filter(play__id__in=plays_ids) \ .extra(select={ 'wins': 'SELECT COUNT(DISTINCT bgplays_team.play_id) FROM bgplays_team ' 'INNER JOIN bgplays_team_players ON bgplays_team.id = bgplays_team_players.team_id ' 'INNER JOIN bgplays_play ON bgplays_play.id = bgplays_team.play_id ' 'WHERE winner = 1 ' 'AND bgplays_play.game_id = bgplays_game.id ' 'AND bgplays_team_players.player_id = % s' % player_id}, ) \ .values('name', 'id', 'wins') \ .annotate(count=Count('name')) \ .order_by('-count') def get_player_list(): # The plays calculation takes a lot. # TODO: We should find another way to fetch them. players = Player.objects.all() \ .annotate(last_played=Max('team__play__date')) \ .extra(select={ 'plays': 'SELECT COUNT(DISTINCT bgplays_team.play_id) FROM bgplays_team ' 'INNER JOIN bgplays_team_players ON bgplays_team.id = bgplays_team_players.team_id ' 'WHERE bgplays_team_players.player_id = bgplays_player.id'}, ) \<|fim▁hole|> .order_by('-plays', '-last_played') return players def get_player_mates(player_id): # XXX: That distinct() is probably not working as expected # But there are not counterexamples in the current data set plays_ids = get_play_ids(player_id) return Player.objects.filter(team__play__id__in=plays_ids) \ .exclude(id=player_id) \ .values('name', 'team__play__id') \ .distinct() \ .values('name') \ .annotate(count=Count('name')) \ .order_by('-count') # Helper methods def get_play_ids(player_id): return Play.objects.filter(team__players__id=player_id).values('id').distinct() def median_value(queryset, term): count = queryset.count() values = queryset.values_list(term, flat=True).order_by(term) if count % 2 == 1: return values[int(round(count / 2))] elif count > 0: return sum(values[count / 2 - 1:count / 2 + 1]) / 2.0 else: return 0<|fim▁end|>
<|file_name|>promoted-function-2.rs<|end_file_name|><|fim▁begin|>// build-fail // compile-flags:-Zpolymorphize=on #![crate_type = "lib"] #![feature(generic_const_exprs, rustc_attrs)] //~^ WARN the feature `generic_const_exprs` is incomplete #[rustc_polymorphize_error] fn test<T>() { //~^ ERROR item has unused generic parameters let x = [0; 3 + 4];<|fim▁hole|> test::<String>(); test::<Vec<String>>(); }<|fim▁end|>
} pub fn caller() {
<|file_name|>environment.rs<|end_file_name|><|fim▁begin|>use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use lox_object::LoxObject; use scanner::Token; use interpreter::{RuntimeError, RuntimeResult}; pub struct Environment { enclosing: Option<Rc<Environment>>, values: RefCell<HashMap<String, LoxObject>>, } impl Environment { pub fn new() -> Self { Self {<|fim▁hole|> values: RefCell::new(HashMap::new()), } } pub fn new_enclosed(enclosing: Rc<Self>) -> Self { Self { enclosing: Some(enclosing), values: RefCell::new(HashMap::new()), } } pub fn define(&self, name: &str, value: &LoxObject) { self.values.borrow_mut().insert(name.to_owned(), value.clone()); } pub fn assign(&self, name: &Token, value: &LoxObject) -> RuntimeResult<()> { let mut values = self.values.borrow_mut(); if values.contains_key(&name.lexeme) { values.insert(name.lexeme.to_owned(), value.clone()); Ok(()) } else { if let Some(ref enclosing_env) = self.enclosing { enclosing_env.assign(name, value) } else { Err(RuntimeError::new( name, &format!("Undefined variable '{}'.", name.lexeme), )) } } } pub fn get(&self, name: &Token) -> RuntimeResult<LoxObject> { match self.values.borrow().get(&name.lexeme) { Some(object) => Ok(object.clone()), None => { if let Some(ref env) = self.enclosing { env.get(name) } else { Err(RuntimeError::new( name, &format!("Undefined variable '{}'.", name.lexeme), )) } } } } }<|fim▁end|>
enclosing: None,
<|file_name|>diff_test.go<|end_file_name|><|fim▁begin|>// Copyright 2015 The etcd Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under 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. package raft import ( "fmt" "io" "os" "os/exec" "strings" ) func diffu(a, b string) string { if a == b { return "" } aname, bname := mustTemp("base", a), mustTemp("other", b) defer os.Remove(aname) defer os.Remove(bname) cmd := exec.Command("diff", "-u", aname, bname) buf, err := cmd.CombinedOutput() if err != nil { if _, ok := err.(*exec.ExitError); ok { // do nothing return string(buf) } panic(err) } return string(buf)<|fim▁hole|> f, err := os.CreateTemp("", pre) if err != nil { panic(err) } _, err = io.Copy(f, strings.NewReader(body)) if err != nil { panic(err) } f.Close() return f.Name() } func ltoa(l *raftLog) string { s := fmt.Sprintf("committed: %d\n", l.committed) s += fmt.Sprintf("applied: %d\n", l.applied) for i, e := range l.allEntries() { s += fmt.Sprintf("#%d: %+v\n", i, e) } return s }<|fim▁end|>
} func mustTemp(pre, body string) string {
<|file_name|>test_hfl_logistic_regression.py<|end_file_name|><|fim▁begin|># # Copyright 2016 The BigDL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under 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 unittest import numpy as np from bigdl.ppml import FLServer from bigdl.ppml.algorithms.fgboost_regression import FGBoostRegression from bigdl.ppml.utils import init_fl_context class TestHflLogisticRegression(unittest.TestCase):<|fim▁hole|> self.fl_server.start() init_fl_context() def tearDown(self) -> None: self.fl_server.stop() def test_dummy_data(self): x, y = np.ones([2, 3]), np.ones([2]) if __name__ == '__main__': unittest.main()<|fim▁end|>
def setUp(self) -> None: self.fl_server = FLServer() self.fl_server.build()
<|file_name|>start_controllers.go<|end_file_name|><|fim▁begin|>package start import ( "fmt" "io" "os" "github.com/golang/glog" "github.com/spf13/cobra" kerrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/kubernetes/pkg/kubectl/cmd/templates" kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "github.com/openshift/origin/pkg/cmd/flagtypes" configapi "github.com/openshift/origin/pkg/cmd/server/apis/config" ) var controllersLong = templates.LongDesc(` Start the master controllers This command starts the controllers for the master. Running %[1]s start master %[2]s will start the controllers that manage the master state, including the scheduler. The controllers will run in the foreground until you terminate the process.`) // NewCommandStartMasterControllers starts only the controllers func NewCommandStartMasterControllers(name, basename string, out, errout io.Writer) (*cobra.Command, *MasterOptions) { options := &MasterOptions{Output: out} options.DefaultsFromName(basename) cmd := &cobra.Command{ Use: "controllers", Short: "Launch master controllers", Long: fmt.Sprintf(controllersLong, basename, name), Run: func(c *cobra.Command, args []string) { if err := options.Complete(); err != nil { fmt.Fprintln(errout, kcmdutil.UsageErrorf(c, err.Error())) return } if len(options.ConfigFile) == 0 { fmt.Fprintln(errout, kcmdutil.UsageErrorf(c, "--config is required for this command")) return } if err := options.Validate(args); err != nil { fmt.Fprintln(errout, kcmdutil.UsageErrorf(c, err.Error())) return } startProfiler()<|fim▁hole|> if kerrors.IsInvalid(err) { if details := err.(*kerrors.StatusError).ErrStatus.Details; details != nil { fmt.Fprintf(errout, "Invalid %s %s\n", details.Kind, details.Name) for _, cause := range details.Causes { fmt.Fprintf(errout, " %s: %s\n", cause.Field, cause.Message) } os.Exit(255) } } glog.Fatal(err) } }, } // start controllers on a non conflicting health port from the default master listenArg := &ListenArg{ ListenAddr: flagtypes.Addr{ Value: "127.0.0.1:8444", DefaultScheme: "https", DefaultPort: 8444, AllowPrefix: true, }.Default(), } var lockServiceName string options.MasterArgs = NewDefaultMasterArgs() options.MasterArgs.StartControllers = true options.MasterArgs.OverrideConfig = func(config *configapi.MasterConfig) error { config.ServingInfo.BindAddress = listenArg.ListenAddr.URL.Host if len(lockServiceName) > 0 { config.ControllerConfig.Election = &configapi.ControllerElectionConfig{ LockName: lockServiceName, LockNamespace: "kube-system", LockResource: configapi.GroupResource{ Resource: "configmaps", }, } } return nil } flags := cmd.Flags() // This command only supports reading from config and the listen argument flags.StringVar(&options.ConfigFile, "config", "", "Location of the master configuration file to run from. Required") cmd.MarkFlagFilename("config", "yaml", "yml") flags.StringVar(&lockServiceName, "lock-service-name", "", "Name of a service in the kube-system namespace to use as a lock, overrides config.") BindListenArg(listenArg, flags, "") return cmd, options }<|fim▁end|>
if err := options.StartMaster(); err != nil {
<|file_name|>package.py<|end_file_name|><|fim▁begin|># Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import os import sys from spack import * class Vtk(CMakePackage): """The Visualization Toolkit (VTK) is an open-source, freely available software system for 3D computer graphics, image processing and visualization. """ homepage = "http://www.vtk.org" url = "https://www.vtk.org/files/release/9.0/VTK-9.0.0.tar.gz" list_url = "http://www.vtk.org/download/" maintainers = ['chuckatkins', 'danlipsa'] version('9.0.0', sha256='15def4e6f84d72f82386617fe595ec124dda3cbd13ea19a0dcd91583197d8715') version('8.2.0', sha256='34c3dc775261be5e45a8049155f7228b6bd668106c72a3c435d95730d17d57bb') version('8.1.2', sha256='0995fb36857dd76ccfb8bb07350c214d9f9099e80b1e66b4a8909311f24ff0db') version('8.1.1', sha256='71a09b4340f0a9c58559fe946dc745ab68a866cf20636a41d97b6046cb736324') version('8.1.0', sha256='6e269f07b64fb13774f5925161fb4e1f379f4e6a0131c8408c555f6b58ef3cb7') version('8.0.1', sha256='49107352923dea6de05a7b4c3906aaf98ef39c91ad81c383136e768dcf304069') version('7.1.0', sha256='5f3ea001204d4f714be972a810a62c0f2277fbb9d8d2f8df39562988ca37497a') version('7.0.0', sha256='78a990a15ead79cdc752e86b83cfab7dbf5b7ef51ba409db02570dbdd9ec32c3') version('6.3.0', sha256='92a493354c5fa66bea73b5fc014154af5d9f3f6cee8d20a826f4cd5d4b0e8a5e') version('6.1.0', sha256='bd7df10a479606d529a8b71f466c44a2bdd11fd534c62ce0aa44fad91883fa34') # VTK7 defaults to OpenGL2 rendering backend variant('opengl2', default=True, description='Enable OpenGL2 backend') variant('osmesa', default=False, description='Enable OSMesa support') variant('python', default=False, description='Enable Python support') variant('qt', default=False, description='Build with support for Qt') variant('xdmf', default=False, description='Build XDMF file support') variant('ffmpeg', default=False, description='Build with FFMPEG support') variant('mpi', default=True, description='Enable MPI support') patch('gcc.patch', when='@6.1.0') # At the moment, we cannot build with both osmesa and qt, but as of # VTK 8.1, that should change conflicts('+osmesa', when='+qt') extends('python', when='+python') # Acceptable python versions depend on vtk version # We need vtk at least 8.0.1 for python@3, # and at least 9.0 for python@3.8 depends_on('python@2.7:2.9', when='@:8.0 +python', type=('build', 'run')) depends_on('python@2.7:3.7.9', when='@8.0.1:8.9 +python', type=('build', 'run')) depends_on('python@2.7:', when='@9.0: +python', type=('build', 'run')) # We need mpi4py if buidling python wrappers and using MPI depends_on('py-mpi4py', when='+python+mpi', type='run') # python3.7 compatibility patch backported from upstream # https://gitlab.kitware.com/vtk/vtk/commit/706f1b397df09a27ab8981ab9464547028d0c322 patch('python3.7-const-char.patch', when='@7.0.0:8.1.1 ^python@3.7:') # The use of the OpenGL2 backend requires at least OpenGL Core Profile # version 3.2 or higher. depends_on('gl@3.2:', when='+opengl2') depends_on('gl@1.2:', when='~opengl2') if sys.platform != 'darwin': depends_on('glx', when='~osmesa') depends_on('libxt', when='~osmesa') # Note: it is recommended to use mesa+llvm, if possible. # mesa default is software rendering, llvm makes it faster depends_on('mesa+osmesa', when='+osmesa') # VTK will need Qt5OpenGL, and qt needs '-opengl' for that depends_on('qt+opengl', when='+qt') depends_on('boost', when='+xdmf') depends_on('boost+mpi', when='+xdmf +mpi') depends_on('ffmpeg', when='+ffmpeg') depends_on('mpi', when='+mpi') depends_on('expat') depends_on('freetype') depends_on('glew') # set hl variant explicitly, similar to issue #7145 depends_on('hdf5+hl') depends_on('jpeg') depends_on('jsoncpp') depends_on('libxml2') depends_on('lz4') depends_on('netcdf-c~mpi', when='~mpi') depends_on('netcdf-c+mpi', when='+mpi') depends_on('netcdf-cxx') depends_on('libpng') depends_on('libtiff') depends_on('zlib') depends_on('eigen', when='@8.2.0:') depends_on('double-conversion', when='@8.2.0:') depends_on('sqlite', when='@8.2.0:') # For finding Fujitsu-MPI wrapper commands patch('find_fujitsu_mpi.patch', when='@:8.2.0%fj') def url_for_version(self, version): url = "http://www.vtk.org/files/release/{0}/VTK-{1}.tar.gz" return url.format(version.up_to(2), version) def setup_build_environment(self, env): # VTK has some trouble finding freetype unless it is set in # the environment env.set('FREETYPE_DIR', self.spec['freetype'].prefix) def cmake_args(self): spec = self.spec opengl_ver = 'OpenGL{0}'.format('2' if '+opengl2' in spec else '') cmake_args = [ '-DBUILD_SHARED_LIBS=ON', '-DVTK_RENDERING_BACKEND:STRING={0}'.format(opengl_ver), # In general, we disable use of VTK "ThirdParty" libs, preferring # spack-built versions whenever possible '-DVTK_USE_SYSTEM_LIBRARIES:BOOL=ON', # However, in a few cases we can't do without them yet '-DVTK_USE_SYSTEM_GL2PS:BOOL=OFF', '-DVTK_USE_SYSTEM_LIBHARU=OFF', '-DNETCDF_DIR={0}'.format(spec['netcdf-c'].prefix), '-DNETCDF_C_ROOT={0}'.format(spec['netcdf-c'].prefix), '-DNETCDF_CXX_ROOT={0}'.format(spec['netcdf-cxx'].prefix), # Allow downstream codes (e.g. VisIt) to override VTK's classes '-DVTK_ALL_NEW_OBJECT_FACTORY:BOOL=ON', # Disable wrappers for other languages. '-DVTK_WRAP_JAVA=OFF', '-DVTK_WRAP_TCL=OFF', ] # Some variable names have changed if spec.satisfies('@8.2.0:'): cmake_args.extend([ '-DVTK_USE_SYSTEM_OGG:BOOL=OFF', '-DVTK_USE_SYSTEM_THEORA:BOOL=OFF', '-DVTK_USE_SYSTEM_LIBPROJ:BOOL=OFF', '-DVTK_USE_SYSTEM_PUGIXML:BOOL=OFF', ]) else: cmake_args.extend([ '-DVTK_USE_SYSTEM_OGGTHEORA:BOOL=OFF', '-DVTK_USE_SYSTEM_LIBPROJ4:BOOL=OFF', ]) if '+mpi' in spec: if spec.satisfies('@:8.2.0'): cmake_args.extend([ '-DVTK_Group_MPI:BOOL=ON', '-DVTK_USE_SYSTEM_DIY2:BOOL=OFF' ]) else: cmake_args.extend([ '-DVTK_USE_MPI=ON' ]) if '+ffmpeg' in spec: cmake_args.extend(['-DModule_vtkIOFFMPEG:BOOL=ON']) # Enable/Disable wrappers for Python. if '+python' in spec: cmake_args.extend([ '-DVTK_WRAP_PYTHON=ON', '-DPYTHON_EXECUTABLE={0}'.format(spec['python'].command.path), ]) if '+mpi' in spec: cmake_args.append('-DVTK_USE_SYSTEM_MPI4PY:BOOL=ON') if spec.satisfies('@9.0.0: ^python@3:'): cmake_args.append('-DVTK_PYTHON_VERSION=3') else: cmake_args.append('-DVTK_WRAP_PYTHON=OFF') if 'darwin' in spec.architecture: cmake_args.extend([ '-DCMAKE_MACOSX_RPATH=ON' ]) if '+qt' in spec: qt_ver = spec['qt'].version.up_to(1) qt_bin = spec['qt'].prefix.bin qmake_exe = os.path.join(qt_bin, 'qmake') cmake_args.extend([ # Enable Qt support here. '-DVTK_QT_VERSION:STRING={0}'.format(qt_ver), '-DQT_QMAKE_EXECUTABLE:PATH={0}'.format(qmake_exe), '-DVTK_Group_Qt:BOOL=ON',<|fim▁hole|> # VTK to build with qt~webkit versions (see the documentation for # more info: http://www.vtk.org/Wiki/VTK/Tutorials/QtSetup). if '~webkit' in spec['qt']: cmake_args.extend([ '-DVTK_Group_Qt:BOOL=OFF', '-DModule_vtkGUISupportQt:BOOL=ON', '-DModule_vtkGUISupportQtOpenGL:BOOL=ON', ]) if '+xdmf' in spec: if spec.satisfies('^cmake@3.12:'): # This policy exists only for CMake >= 3.12 cmake_args.extend(["-DCMAKE_POLICY_DEFAULT_CMP0074=NEW"]) cmake_args.extend([ # Enable XDMF Support here "-DModule_vtkIOXdmf2:BOOL=ON", "-DModule_vtkIOXdmf3:BOOL=ON", "-DBOOST_ROOT={0}".format(spec['boost'].prefix), "-DBOOST_LIBRARY_DIR={0}".format(spec['boost'].prefix.lib), "-DBOOST_INCLUDE_DIR={0}".format(spec['boost'].prefix.include), "-DBOOST_NO_SYSTEM_PATHS:BOOL=ON", # This is needed because VTK has multiple FindBoost # and they stick to system boost if there's a system boost # installed with CMake "-DBoost_NO_BOOST_CMAKE:BOOL=ON", "-DHDF5_ROOT={0}".format(spec['hdf5'].prefix), # The xdmf project does not export any CMake file... "-DVTK_USE_SYSTEM_XDMF3:BOOL=OFF", "-DVTK_USE_SYSTEM_XDMF2:BOOL=OFF" ]) if '+mpi' in spec: cmake_args.extend(["-DModule_vtkIOParallelXdmf3:BOOL=ON"]) cmake_args.append('-DVTK_RENDERING_BACKEND:STRING=' + opengl_ver) if spec.satisfies('@:8.1.0'): cmake_args.append('-DVTK_USE_SYSTEM_GLEW:BOOL=ON') if '+osmesa' in spec: cmake_args.extend([ '-DVTK_USE_X:BOOL=OFF', '-DVTK_USE_COCOA:BOOL=OFF', '-DVTK_OPENGL_HAS_OSMESA:BOOL=ON']) else: cmake_args.append('-DVTK_OPENGL_HAS_OSMESA:BOOL=OFF') if spec.satisfies('@:7.9.9'): # This option is gone in VTK 8.1.2 cmake_args.append('-DOpenGL_GL_PREFERENCE:STRING=LEGACY') if 'darwin' in spec.architecture: cmake_args.extend([ '-DVTK_USE_X:BOOL=OFF', '-DVTK_USE_COCOA:BOOL=ON']) elif 'linux' in spec.architecture: cmake_args.extend([ '-DVTK_USE_X:BOOL=ON', '-DVTK_USE_COCOA:BOOL=OFF']) if spec.satisfies('@:6.1.0'): cmake_args.extend([ '-DCMAKE_C_FLAGS=-DGLX_GLXEXT_LEGACY', '-DCMAKE_CXX_FLAGS=-DGLX_GLXEXT_LEGACY' ]) # VTK 6.1.0 (and possibly earlier) does not use # NETCDF_CXX_ROOT to detect NetCDF C++ bindings, so # NETCDF_CXX_INCLUDE_DIR and NETCDF_CXX_LIBRARY must be # used instead to detect these bindings netcdf_cxx_lib = spec['netcdf-cxx'].libs.joined() cmake_args.extend([ '-DNETCDF_CXX_INCLUDE_DIR={0}'.format( spec['netcdf-cxx'].prefix.include), '-DNETCDF_CXX_LIBRARY={0}'.format(netcdf_cxx_lib), ]) # Garbage collection is unsupported in Xcode starting with # version 5.1; if the Apple clang version of the compiler # is 5.1.0 or later, unset the required Objective-C flags # to remove the garbage collection flags. Versions of VTK # after 6.1.0 set VTK_REQUIRED_OBJCXX_FLAGS to the empty # string. This fix was recommended on the VTK mailing list # in March 2014 (see # https://public.kitware.com/pipermail/vtkusers/2014-March/083368.html) if self.spec.satisfies('%apple-clang@5.1.0:'): cmake_args.extend(['-DVTK_REQUIRED_OBJCXX_FLAGS=']) # A bug in tao pegtl causes build failures with intel compilers if '%intel' in spec and spec.version >= Version('8.2'): cmake_args.append( '-DVTK_MODULE_ENABLE_VTK_IOMotionFX:BOOL=OFF') return cmake_args<|fim▁end|>
]) # NOTE: The following definitions are required in order to allow
<|file_name|>test_submain_package.py<|end_file_name|><|fim▁begin|>from mock import patch from nose.tools import eq_ from helper import TestCase import appvalidator.submain as submain class TestSubmainPackage(TestCase): @patch("appvalidator.submain.test_inner_package", lambda x, z: "success") def test_package_pass(self): "Tests the test_package function with simple data" self.setup_err()<|fim▁hole|> with open(name) as pack: result = submain.test_package(self.err, pack, name) self.assert_silent() eq_(result, "success") @patch("appvalidator.submain.test_inner_package", lambda x, z: "success") def test_package_corrupt(self): "Tests the test_package function fails with a non-zip" self.setup_err() name = "tests/resources/junk.xpi" with open(name) as pack: result = submain.test_package(self.err, pack, name) self.assert_failed() def test_package_corrupt(self): "Tests the test_package function fails with a corrupt file" self.setup_err() name = "tests/resources/corrupt.xpi" result = submain.test_package(self.err, name, name) self.assert_failed(with_errors=True, with_warnings=True)<|fim▁end|>
name = "tests/resources/submain/install_rdf.xpi"
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>use pkg_config::Config; fn main() {<|fim▁hole|> if std::env::var_os("CARGO_FEATURE_CLIENT").is_some() { Config::new().probe("wayland-client").unwrap(); } if std::env::var_os("CARGO_FEATURE_CURSOR").is_some() { Config::new().probe("wayland-cursor").unwrap(); } if std::env::var_os("CARGO_FEATURE_EGL").is_some() { Config::new().probe("wayland-egl").unwrap(); } if std::env::var_os("CARGO_FEATURE_SERVER").is_some() { Config::new().probe("wayland-server").unwrap(); } }<|fim▁end|>
if std::env::var_os("CARGO_FEATURE_DLOPEN").is_some() { // Do not link to anything return; }
<|file_name|>callback.rs<|end_file_name|><|fim▁begin|>// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use crate::call::server::{RequestContext, UnaryRequestContext}; use crate::call::{BatchContext, Call}; use crate::cq::CompletionQueue; use crate::server::{self, RequestCallContext}; pub struct Request { ctx: RequestContext, } impl Request { pub fn new(rc: RequestCallContext) -> Request { let ctx = RequestContext::new(rc); Request { ctx } } pub fn context(&self) -> &RequestContext { &self.ctx } pub fn resolve(mut self, cq: &CompletionQueue, success: bool) { let mut rc = self.ctx.take_request_call_context().unwrap(); if !success { server::request_call(rc, cq); return; } match self.ctx.handle_stream_req(cq, &mut rc) { Ok(_) => server::request_call(rc, cq), Err(ctx) => ctx.handle_unary_req(rc, cq), } } } pub struct UnaryRequest { ctx: UnaryRequestContext, } impl UnaryRequest { pub fn new(ctx: RequestContext, rc: RequestCallContext) -> UnaryRequest { let ctx = UnaryRequestContext::new(ctx, rc);<|fim▁hole|> pub fn batch_ctx(&self) -> &BatchContext { self.ctx.batch_ctx() } pub fn request_ctx(&self) -> &RequestContext { self.ctx.request_ctx() } pub fn resolve(mut self, cq: &CompletionQueue, success: bool) { let mut rc = self.ctx.take_request_call_context().unwrap(); if !success { server::request_call(rc, cq); return; } let reader = self.ctx.batch_ctx_mut().recv_message(); self.ctx.handle(&mut rc, cq, reader); server::request_call(rc, cq); } } /// A callback to wait for status for the aborted rpc call to be sent. pub struct Abort { ctx: BatchContext, _call: Call, } impl Abort { pub fn new(call: Call) -> Abort { Abort { ctx: BatchContext::new(), _call: call, } } pub fn batch_ctx(&self) -> &BatchContext { &self.ctx } }<|fim▁end|>
UnaryRequest { ctx } }
<|file_name|>homebrew_tap.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Daniel Jaouen <dcj24@cornell.edu> # (c) 2016, Indrajit Raychaudhuri <irc+code@indrajit.com> # # Based on homebrew (Andrew Dunham <andrew@du.nham.ca>) # # This file is part of Ansible # # 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 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 License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: homebrew_tap author: - "Indrajit Raychaudhuri (@indrajitr)" - "Daniel Jaouen (@danieljaouen)" short_description: Tap a Homebrew repository. description: - Tap external Homebrew repositories. version_added: "1.6" options: name: description: - The GitHub user/organization repository to tap. required: true aliases: ['tap'] url: description: - The optional git URL of the repository to tap. The URL is not assumed to be on GitHub, and the protocol doesn't have to be HTTP. Any location and protocol that git can handle is fine. - I(name) option may not be a list of multiple taps (but a single tap instead) when this option is provided. required: false version_added: "2.2" state: description: - state of the repository. choices: [ 'present', 'absent' ] required: false default: 'present' requirements: [ homebrew ] ''' EXAMPLES = ''' - homebrew_tap: name: homebrew/dupes - homebrew_tap: name: homebrew/dupes state: absent - homebrew_tap: name: homebrew/dupes,homebrew/science state: present - homebrew_tap: name: telemachus/brew url: 'https://bitbucket.org/telemachus/brew' ''' import re def a_valid_tap(tap): '''Returns True if the tap is valid.''' regex = re.compile(r'^([\w-]+)/(homebrew-)?([\w-]+)$') return regex.match(tap) def already_tapped(module, brew_path, tap):<|fim▁hole|> rc, out, err = module.run_command([ brew_path, 'tap', ]) taps = [tap_.strip().lower() for tap_ in out.split('\n') if tap_] tap_name = re.sub('homebrew-', '', tap.lower()) return tap_name in taps def add_tap(module, brew_path, tap, url=None): '''Adds a single tap.''' failed, changed, msg = False, False, '' if not a_valid_tap(tap): failed = True msg = 'not a valid tap: %s' % tap elif not already_tapped(module, brew_path, tap): if module.check_mode: module.exit_json(changed=True) rc, out, err = module.run_command([ brew_path, 'tap', tap, url, ]) if already_tapped(module, brew_path, tap): changed = True msg = 'successfully tapped: %s' % tap else: failed = True msg = 'failed to tap: %s' % tap else: msg = 'already tapped: %s' % tap return (failed, changed, msg) def add_taps(module, brew_path, taps): '''Adds one or more taps.''' failed, unchanged, added, msg = False, 0, 0, '' for tap in taps: (failed, changed, msg) = add_tap(module, brew_path, tap) if failed: break if changed: added += 1 else: unchanged += 1 if failed: msg = 'added: %d, unchanged: %d, error: ' + msg msg = msg % (added, unchanged) elif added: changed = True msg = 'added: %d, unchanged: %d' % (added, unchanged) else: msg = 'added: %d, unchanged: %d' % (added, unchanged) return (failed, changed, msg) def remove_tap(module, brew_path, tap): '''Removes a single tap.''' failed, changed, msg = False, False, '' if not a_valid_tap(tap): failed = True msg = 'not a valid tap: %s' % tap elif already_tapped(module, brew_path, tap): if module.check_mode: module.exit_json(changed=True) rc, out, err = module.run_command([ brew_path, 'untap', tap, ]) if not already_tapped(module, brew_path, tap): changed = True msg = 'successfully untapped: %s' % tap else: failed = True msg = 'failed to untap: %s' % tap else: msg = 'already untapped: %s' % tap return (failed, changed, msg) def remove_taps(module, brew_path, taps): '''Removes one or more taps.''' failed, unchanged, removed, msg = False, 0, 0, '' for tap in taps: (failed, changed, msg) = remove_tap(module, brew_path, tap) if failed: break if changed: removed += 1 else: unchanged += 1 if failed: msg = 'removed: %d, unchanged: %d, error: ' + msg msg = msg % (removed, unchanged) elif removed: changed = True msg = 'removed: %d, unchanged: %d' % (removed, unchanged) else: msg = 'removed: %d, unchanged: %d' % (removed, unchanged) return (failed, changed, msg) def main(): module = AnsibleModule( argument_spec=dict( name=dict(aliases=['tap'], type='list', required=True), url=dict(default=None, required=False), state=dict(default='present', choices=['present', 'absent']), ), supports_check_mode=True, ) brew_path = module.get_bin_path( 'brew', required=True, opt_dirs=['/usr/local/bin'] ) taps = module.params['name'] url = module.params['url'] if module.params['state'] == 'present': if url is None: # No tap URL provided explicitly, continue with bulk addition # of all the taps. failed, changed, msg = add_taps(module, brew_path, taps) else: # When an tap URL is provided explicitly, we allow adding # *single* tap only. Validate and proceed to add single tap. if len(taps) > 1: msg = "List of muliple taps may not be provided with 'url' option." module.fail_json(msg=msg) else: failed, changed, msg = add_tap(module, brew_path, taps[0], url) if failed: module.fail_json(msg=msg) else: module.exit_json(changed=changed, msg=msg) elif module.params['state'] == 'absent': failed, changed, msg = remove_taps(module, brew_path, taps) if failed: module.fail_json(msg=msg) else: module.exit_json(changed=changed, msg=msg) # this is magic, see lib/ansible/module_common.py from ansible.module_utils.basic import * if __name__ == '__main__': main()<|fim▁end|>
'''Returns True if already tapped.'''
<|file_name|>core.js<|end_file_name|><|fim▁begin|><|fim▁hole|>// Project: SproutCore - JavaScript Application Framework // Copyright: ©2006-2011 Strobe Inc. and contributors. // Portions ©2008-2011 Apple Inc. All rights reserved. // License: Licensed under MIT license (see license.js) // ==========================================================================<|fim▁end|>
// ==========================================================================
<|file_name|>MeanCenteredFacesDemo.java<|end_file_name|><|fim▁begin|>package uk.ac.soton.ecs.comp3204.l3; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagLayout; import java.io.IOException; import javax.swing.JPanel; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.data.dataset.VFSGroupDataset; import org.openimaj.image.DisplayUtilities.ImageComponent;<|fim▁hole|>import org.openimaj.image.ImageUtilities; import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider; import uk.ac.soton.ecs.comp3204.utils.Utils; import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration; /** * Visualise mean-centered face images * * @author Jonathon Hare (jsh2@ecs.soton.ac.uk) * */ @Demonstration(title = "Mean-centred faces demo") public class MeanCenteredFacesDemo implements Slide { @Override public Component getComponent(int width, int height) throws IOException { final VFSGroupDataset<FImage> dataset = FaceDatasetProvider.getDataset(); final FImage mean = dataset.getRandomInstance().fill(0f); for (final FImage i : dataset) { mean.addInplace(i); } mean.divideInplace(dataset.numInstances()); final JPanel outer = new JPanel(); outer.setOpaque(false); outer.setPreferredSize(new Dimension(width, height)); outer.setLayout(new GridBagLayout()); final JPanel base = new JPanel(); base.setOpaque(false); base.setPreferredSize(new Dimension(width, height - 50)); base.setLayout(new FlowLayout()); for (int i = 0; i < 60; i++) { final FImage img = dataset.getRandomInstance().subtract(mean).normalise(); final ImageComponent ic = new ImageComponent(true, false); ic.setAllowPanning(false); ic.setAllowZoom(false); ic.setShowPixelColours(false); ic.setShowXYPosition(false); ic.setImage(ImageUtilities.createBufferedImageForDisplay(img)); base.add(ic); } outer.add(base); return outer; } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException { new SlideshowApplication(new MeanCenteredFacesDemo(), 1024, 768, Utils.BACKGROUND_IMAGE); } }<|fim▁end|>
import org.openimaj.image.FImage;
<|file_name|>defaults-bg_BG.js<|end_file_name|><|fim▁begin|>/*! * Bootstrap-select v1.13.2 (https://developer.snapappointments.com/bootstrap-select) * * Copyright 2012-2018 SnapAppointments, LLC * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE) */ (function (root, factory) { if (root === undefined && window !== undefined) root = window; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module unless amdModuleId is set define(["jquery"], function (a0) { return (factory(a0)); }); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(require("jquery")); } else { factory(root["jQuery"]);<|fim▁hole|>}(this, function (jQuery) { (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Нищо избрано', noneResultsText: 'Няма резултат за {0}', countSelectedText: function (numSelected, numTotal) { return (numSelected == 1) ? "{0} избран елемент" : "{0} избрани елемента"; }, maxOptionsText: function (numAll, numGroup) { return [ (numAll == 1) ? 'Лимита е достигнат ({n} елемент максимум)' : 'Лимита е достигнат ({n} елемента максимум)', (numGroup == 1) ? 'Груповия лимит е достигнат ({n} елемент максимум)' : 'Груповия лимит е достигнат ({n} елемента максимум)' ]; }, selectAllText: 'Избери всички', deselectAllText: 'Размаркирай всички', multipleSeparator: ', ' }; })(jQuery); }));<|fim▁end|>
}
<|file_name|>format.py<|end_file_name|><|fim▁begin|>""" Contains format specification class and methods to parse it from JSON. .. codeauthor:: Tomas Krizek <tomas.krizek1@tul.cz> """ import json import re def get_root_input_type_from_json(data): """Return the root input type from JSON formatted string.""" return parse_format(json.loads(data)) def parse_format(data): """Returns root input type from data.""" input_types = {} data = data['ist_nodes'] root_id = data[0]['id'] # set root type for item in data: input_type = _get_input_type(item) if input_type is not None: input_types[input_type['id']] = input_type # register by id _substitute_ids_with_references(input_types) return input_types[root_id] SCALAR = ['Integer', 'Double', 'Bool', 'String', 'Selection', 'FileName'] def is_scalar(input_type): """Returns True if input_type is scalar.""" return input_type['base_type'] in SCALAR RE_PARAM = re.compile('^<([a-zA-Z][a-zA-Z0-9_]*)>$') def is_param(value): """Determine whether given value is a parameter string.""" if not isinstance(value, str): return False return RE_PARAM.match(value) def _substitute_ids_with_references(input_types): """Replaces ids or type names with python object references.""" input_type = {} def _substitute_implementations(): """Replaces implementation ids with input_types.""" impls = {} for id_ in input_type['implementations']: type_ = input_types[id_] impls[type_['name']] = type_ input_type['implementations'] = impls def _substitute_default_descendant(): """Replaces default descendant id with input_type.""" id_ = input_type.get('default_descendant', None) if id_ is not None: input_type['default_descendant'] = input_types[id_] def _substitute_key_type(): """Replaces key type with input_type.""" # pylint: disable=unused-variable, invalid-name for __, value in input_type['keys'].items(): value['type'] = input_types[value['type']] # pylint: disable=unused-variable, invalid-name for __, input_type in input_types.items(): if input_type['base_type'] == 'Array': input_type['subtype'] = input_types[input_type['subtype']] elif input_type['base_type'] == 'Abstract': _substitute_implementations() _substitute_default_descendant() elif input_type['base_type'] == 'Record': _substitute_key_type() def _get_input_type(data): """Returns the input_type data structure that defines an input type and its constraints for validation.""" if 'id' not in data or 'input_type' not in data: return None input_type = dict( id=data['id'], base_type=data['input_type'] ) input_type['name'] = data.get('name', '') input_type['full_name'] = data.get('full_name', '') input_type['description'] = data.get('description', '') input_type['attributes'] = data.get('attributes', {}) if input_type['base_type'] in ['Double', 'Integer']: input_type.update(_parse_range(data)) elif input_type['base_type'] == 'Array': input_type.update(_parse_range(data)) if input_type['min'] < 0: input_type['min'] = 0<|fim▁hole|> input_type['subtype'] = data['subtype'] elif input_type['base_type'] == 'FileName': input_type['file_mode'] = data['file_mode'] elif input_type['base_type'] == 'Selection': input_type['values'] = _list_to_dict(data['values'], 'name') elif input_type['base_type'] == 'Record': input_type['keys'] = _list_to_dict(data['keys']) input_type['implements'] = data.get('implements', []) input_type['reducible_to_key'] = data.get('reducible_to_key', None) elif input_type['base_type'] == 'Abstract': input_type['implementations'] = data['implementations'] input_type['default_descendant'] = data.get('default_descendant', None) return input_type def _parse_range(data): """Parses the format range properties - min, max.""" input_type = {} try: input_type['min'] = data['range'][0] except (KeyError, TypeError): # set default value input_type['min'] = float('-inf') try: input_type['max'] = data['range'][1] except (KeyError, TypeError): # set default value input_type['max'] = float('inf') return input_type def _list_to_dict(list_, key_label='key'): """ Transforms a list of dictionaries into a dictionary of dictionaries. Original dictionaries are assigned key specified in each of them by key_label. """ dict_ = {} for item in list_: dict_[item[key_label]] = item return dict_<|fim▁end|>
<|file_name|>test_azure_mgmt_wcfrelay.py<|end_file_name|><|fim▁begin|># 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. #-------------------------------------------------------------------------- import unittest import time from msrestazure.azure_exceptions import CloudError import azure.mgmt.relay.models from azure.mgmt.relay.models import RelayNamespace, Sku, SkuTier, Relaytype, AuthorizationRule, AccessRights, AccessKeys, WcfRelay, ErrorResponseException, ErrorResponse from azure.common.credentials import ServicePrincipalCredentials from devtools_testutils import AzureMgmtTestCase, ResourceGroupPreparer<|fim▁hole|> def setUp(self): super(MgmtWcfRelayTest, self).setUp() self.relay_client = self.create_mgmt_client( azure.mgmt.relay.RelayManagementClient ) @ResourceGroupPreparer() def test_wcfrelay_curd(self, resource_group, location): resource_group_name = resource_group.name #Create a Namespace namespace_name = "testingpythontestcaseeventhubnamespaceEventhub" namespaceparameter = RelayNamespace(location, {'tag1': 'value1', 'tag2': 'value2'}, Sku(SkuTier.standard)) creatednamespace = self.relay_client.namespaces.create_or_update(resource_group_name, namespace_name, namespaceparameter).result() self.assertEqual(creatednamespace.name, namespace_name) # # # Get created Namespace # getnamespaceresponse = self.relay_client.namespaces.get(resource_group_name, namespace_name) self.assertEqual(getnamespaceresponse.name, namespace_name) # Create a WcfRelay wcfrelay_name = "testingpythontestcasewcfrelay" wcfrelayparameter = WcfRelay( relay_type=Relaytype.net_tcp, requires_client_authorization=True, requires_transport_security=True, user_metadata="User data for WcfRelay" ) createdwcfrelayresponse = self.relay_client.wcf_relays.create_or_update(resource_group_name, namespace_name, wcfrelay_name, wcfrelayparameter) self.assertEqual(createdwcfrelayresponse.name, wcfrelay_name) self.assertEqual(createdwcfrelayresponse.requires_client_authorization, True) #Get the created wcfRelay geteventhubresponse = self.relay_client.wcf_relays.get(resource_group_name, namespace_name, wcfrelay_name) self.assertEqual(geteventhubresponse.name, wcfrelay_name) self.assertEqual(geteventhubresponse.requires_transport_security, True) self.assertEqual(geteventhubresponse.user_metadata, "User data for WcfRelay") #Get the List of wcfRealy by namespaces getlistbynamespacewcfrelayresponse = list(self.relay_client.wcf_relays.list_by_namespace(resource_group_name, namespace_name)) self.assertGreater(len(getlistbynamespacewcfrelayresponse), 0) # update the Created eventhub wcfrelayupdateparameter = WcfRelay( relay_type=Relaytype.net_tcp, user_metadata="User data for WcfRelay updated" ) updatewcfrelayresponse = self.relay_client.wcf_relays.create_or_update(resource_group_name, namespace_name, wcfrelay_name, wcfrelayupdateparameter) self.assertEqual(updatewcfrelayresponse.name, wcfrelay_name) self.assertEqual(updatewcfrelayresponse.requires_transport_security, True) self.assertEqual(updatewcfrelayresponse.requires_client_authorization, True) self.assertEqual(updatewcfrelayresponse.user_metadata, "User data for WcfRelay updated") # Create a new authorizationrule authoRule_name = "testingauthrulepy" createwcfrelayauthorule = self.relay_client.wcf_relays.create_or_update_authorization_rule(resource_group_name, namespace_name, wcfrelay_name, authoRule_name,[AccessRights('Send'),AccessRights('Listen')]) self.assertEqual(createwcfrelayauthorule.name, authoRule_name, "Authorization rule name not as created - create_or_update_authorization_rule ") self.assertEqual(len(createwcfrelayauthorule.rights), 2) # Get the created authorizationrule getwcfrelayauthorule = self.relay_client.wcf_relays.get_authorization_rule(resource_group_name, namespace_name, wcfrelay_name, authoRule_name) self.assertEqual(getwcfrelayauthorule.name, authoRule_name, "Authorization rule name not as passed as parameter - get_authorization_rule ") self.assertEqual(len(getwcfrelayauthorule.rights), 2, "Access rights mis match as created - get_authorization_rule ") # update the rights of the authorizatiorule getwcfrelayauthorule.rights.append('Manage') updatewcfrelayauthorule = self.relay_client.wcf_relays.create_or_update_authorization_rule(resource_group_name, namespace_name, wcfrelay_name, authoRule_name, getwcfrelayauthorule.rights) self.assertEqual(updatewcfrelayauthorule.name, authoRule_name, "Authorization rule name not as passed as parameter for update call - create_or_update_authorization_rule ") self.assertEqual(len(updatewcfrelayauthorule.rights), 3, "Access rights mis match as updated - create_or_update_authorization_rule ") #list all the authorization ruels for the given namespace wcfrelayauthorulelist = list(self.relay_client.wcf_relays.list_authorization_rules(resource_group_name, namespace_name, wcfrelay_name)) self.assertEqual(len(wcfrelayauthorulelist), 1, "number of authorization rule mismatch with the created + default = 2 - list_authorization_rules") #List keys for the authorization rule listkeysauthorizationrule = self.relay_client.wcf_relays.list_keys(resource_group_name, namespace_name, wcfrelay_name, authoRule_name) self.assertIsNotNone(listkeysauthorizationrule) # regenerate Keys for authorizationrule - Primary regenratePrimarykeyauthorizationrule = self.relay_client.wcf_relays.regenerate_keys(resource_group_name, namespace_name, wcfrelay_name, authoRule_name, 'PrimaryKey') self.assertNotEqual(listkeysauthorizationrule.primary_key,regenratePrimarykeyauthorizationrule.primary_key) # regenerate Keys for authorizationrule - Primary regenrateSecondarykeyauthorizationrule = self.relay_client.wcf_relays.regenerate_keys(resource_group_name,namespace_name, wcfrelay_name, authoRule_name, 'SecondaryKey') self.assertNotEqual(listkeysauthorizationrule.secondary_key, regenrateSecondarykeyauthorizationrule.secondary_key) # delete the authorizationrule self.relay_client.wcf_relays.delete_authorization_rule(resource_group_name, namespace_name, wcfrelay_name, authoRule_name) # Delete the created WcfRelay getwcfrelayresponse = self.relay_client.wcf_relays.delete(resource_group_name, namespace_name, wcfrelay_name) # Delete the create namespace self.relay_client.namespaces.delete(resource_group_name, namespace_name).result() # ------------------------------------------------------------------------------ if __name__ == '__main__': unittest.main()<|fim▁end|>
class MgmtWcfRelayTest(AzureMgmtTestCase):
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.contrib.sites.models import Site from django.utils._os import safe_join from django.views.generic import TemplateView from skin.conf import settings from skin.template.loaders.util import get_site_skin class TemplateSkinView(TemplateView): """ A view that extends Djangos base TemplateView to allow you to set up skins. """ skin_name = None skin_path = None def get_skin_name(self): if self.skin_name is None: return settings.SKIN_NAME else: return self.skin_name def get_skin(self): return get_site_skin(site=Site.objects.get_current(), name=self.get_skin_name()) def get_skin_path(self): if self.skin_path is not None: return self.skin_path skin = self.get_skin() if skin is not None: return skin.path else: return None <|fim▁hole|> template_names = super(TemplateSkinView, self).get_template_names() skin_path = self.get_skin_path() skin_template_names = [] if skin_path is not None: for template_name in template_names: skin_template_names.append(safe_join(skin_path, template_name)) return skin_template_names + template_names<|fim▁end|>
def get_template_names(self):
<|file_name|>QuestionActivity.java<|end_file_name|><|fim▁begin|>package com.hackathon.hackathon2014.activity; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import com.hackathon.hackathon2014.R; import com.hackathon.hackathon2014.webservice.PostRequestHandler; import com.hackathon.hackathon2014.webservice.RestProvider; import com.hackathon.hackathon2014.adapter.QuestionListAdapter; import com.hackathon.hackathon2014.model.Question; import java.util.List; public class QuestionActivity extends Activity { public static String EXTRA_QUESTION = "question"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_question); if (savedInstanceState == null) { getFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.question, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); }<|fim▁hole|> /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_question, container, false); Toast.makeText(rootView.getContext(),"Loading...",Toast.LENGTH_LONG).show(); RestProvider.getQuestions(new PostRequestHandler<List<Question>>() { @Override public void handle(List<Question> questions) { QuestionListAdapter questionListAdapter = new QuestionListAdapter(getActivity(), questions); ListView listView = (ListView) rootView.findViewById(R.id.questionListView); listView.setAdapter(questionListAdapter); listView.setOnItemClickListener(new OpenAnswerEvent(getActivity(), questions)); } }); return rootView; } private class OpenAnswerEvent implements android.widget.AdapterView.OnItemClickListener { private List<Question> questions; private Activity activity; private OpenAnswerEvent(Activity activity, List<Question> questions) { this.activity = activity; this.questions = questions; } @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Question question = questions.get(i); question.setSelected(true); Intent intent = new Intent(activity,CategoryActivity.class); intent.putExtra(EXTRA_QUESTION, question); activity.startActivity(intent); final ImageView questionIcon = (ImageView) view.findViewById(R.id.questionIcon); QuestionListAdapter.renderChecked(question.isSelected(), questionIcon, R.drawable.ok_enable, R.drawable.ok_disable); } } } }<|fim▁end|>
<|file_name|>url_fixer_upper_unittest.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdlib.h> #include "base/basictypes.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/net/url_fixer_upper.h" #include "net/base/net_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/url_parse.h" namespace { class URLFixerUpperTest : public testing::Test { }; }; namespace url_parse { std::ostream& operator<<(std::ostream& os, const Component& part) { return os << "(begin=" << part.begin << ", len=" << part.len << ")"; } } // namespace url_parse struct SegmentCase { const std::string input; const std::string result; const url_parse::Component scheme; const url_parse::Component username; const url_parse::Component password; const url_parse::Component host; const url_parse::Component port; const url_parse::Component path; const url_parse::Component query; const url_parse::Component ref; }; static const SegmentCase segment_cases[] = { { "http://www.google.com/", "http", url_parse::Component(0, 4), // scheme url_parse::Component(), // username url_parse::Component(), // password url_parse::Component(7, 14), // host url_parse::Component(), // port url_parse::Component(21, 1), // path url_parse::Component(), // query url_parse::Component(), // ref }, { "aBoUt:vErSiOn", "about", url_parse::Component(0, 5), // scheme url_parse::Component(), // username url_parse::Component(), // password url_parse::Component(6, 7), // host url_parse::Component(), // port url_parse::Component(), // path url_parse::Component(), // query url_parse::Component(), // ref }, { "about:host/path?query#ref", "about", url_parse::Component(0, 5), // scheme url_parse::Component(), // username url_parse::Component(), // password url_parse::Component(6, 4), // host url_parse::Component(), // port url_parse::Component(10, 5), // path url_parse::Component(16, 5), // query url_parse::Component(22, 3), // ref }, { "about://host/path?query#ref", "about", url_parse::Component(0, 5), // scheme url_parse::Component(), // username url_parse::Component(), // password url_parse::Component(8, 4), // host url_parse::Component(), // port url_parse::Component(12, 5), // path url_parse::Component(18, 5), // query url_parse::Component(24, 3), // ref }, { "chrome:host/path?query#ref", "chrome", url_parse::Component(0, 6), // scheme url_parse::Component(), // username url_parse::Component(), // password url_parse::Component(7, 4), // host url_parse::Component(), // port url_parse::Component(11, 5), // path url_parse::Component(17, 5), // query url_parse::Component(23, 3), // ref }, { "chrome://host/path?query#ref", "chrome", url_parse::Component(0, 6), // scheme url_parse::Component(), // username url_parse::Component(), // password url_parse::Component(9, 4), // host url_parse::Component(), // port url_parse::Component(13, 5), // path url_parse::Component(19, 5), // query url_parse::Component(25, 3), // ref<|fim▁hole|> }, { " www.google.com:124?foo#", "http", url_parse::Component(), // scheme url_parse::Component(), // username url_parse::Component(), // password url_parse::Component(4, 14), // host url_parse::Component(19, 3), // port url_parse::Component(), // path url_parse::Component(23, 3), // query url_parse::Component(27, 0), // ref }, { "user@www.google.com", "http", url_parse::Component(), // scheme url_parse::Component(0, 4), // username url_parse::Component(), // password url_parse::Component(5, 14), // host url_parse::Component(), // port url_parse::Component(), // path url_parse::Component(), // query url_parse::Component(), // ref }, { "ftp:/user:P:a$$Wd@..ftp.google.com...::23///pub?foo#bar", "ftp", url_parse::Component(0, 3), // scheme url_parse::Component(5, 4), // username url_parse::Component(10, 7), // password url_parse::Component(18, 20), // host url_parse::Component(39, 2), // port url_parse::Component(41, 6), // path url_parse::Component(48, 3), // query url_parse::Component(52, 3), // ref }, { "[2001:db8::1]/path", "http", url_parse::Component(), // scheme url_parse::Component(), // username url_parse::Component(), // password url_parse::Component(0, 13), // host url_parse::Component(), // port url_parse::Component(13, 5), // path url_parse::Component(), // query url_parse::Component(), // ref }, { "[::1]", "http", url_parse::Component(), // scheme url_parse::Component(), // username url_parse::Component(), // password url_parse::Component(0, 5), // host url_parse::Component(), // port url_parse::Component(), // path url_parse::Component(), // query url_parse::Component(), // ref }, // Incomplete IPv6 addresses (will not canonicalize). { "[2001:4860:", "http", url_parse::Component(), // scheme url_parse::Component(), // username url_parse::Component(), // password url_parse::Component(0, 11), // host url_parse::Component(), // port url_parse::Component(), // path url_parse::Component(), // query url_parse::Component(), // ref }, { "[2001:4860:/foo", "http", url_parse::Component(), // scheme url_parse::Component(), // username url_parse::Component(), // password url_parse::Component(0, 11), // host url_parse::Component(), // port url_parse::Component(11, 4), // path url_parse::Component(), // query url_parse::Component(), // ref }, { "http://:b005::68]", "http", url_parse::Component(0, 4), // scheme url_parse::Component(), // username url_parse::Component(), // password url_parse::Component(7, 10), // host url_parse::Component(), // port url_parse::Component(), // path url_parse::Component(), // query url_parse::Component(), // ref }, // Can't do anything useful with this. { ":b005::68]", "", url_parse::Component(0, 0), // scheme url_parse::Component(), // username url_parse::Component(), // password url_parse::Component(), // host url_parse::Component(), // port url_parse::Component(), // path url_parse::Component(), // query url_parse::Component(), // ref }, }; TEST(URLFixerUpperTest, SegmentURL) { std::string result; url_parse::Parsed parts; for (size_t i = 0; i < arraysize(segment_cases); ++i) { SegmentCase value = segment_cases[i]; result = URLFixerUpper::SegmentURL(value.input, &parts); EXPECT_EQ(value.result, result); EXPECT_EQ(value.scheme, parts.scheme); EXPECT_EQ(value.username, parts.username); EXPECT_EQ(value.password, parts.password); EXPECT_EQ(value.host, parts.host); EXPECT_EQ(value.port, parts.port); EXPECT_EQ(value.path, parts.path); EXPECT_EQ(value.query, parts.query); EXPECT_EQ(value.ref, parts.ref); } } // Creates a file and returns its full name as well as the decomposed // version. Example: // full_path = "c:\foo\bar.txt" // dir = "c:\foo" // file_name = "bar.txt" static bool MakeTempFile(const base::FilePath& dir, const base::FilePath& file_name, base::FilePath* full_path) { *full_path = dir.Append(file_name); return file_util::WriteFile(*full_path, "", 0) == 0; } // Returns true if the given URL is a file: URL that matches the given file static bool IsMatchingFileURL(const std::string& url, const base::FilePath& full_file_path) { if (url.length() <= 8) return false; if (std::string("file:///") != url.substr(0, 8)) return false; // no file:/// prefix if (url.find('\\') != std::string::npos) return false; // contains backslashes base::FilePath derived_path; net::FileURLToFilePath(GURL(url), &derived_path); return base::FilePath::CompareEqualIgnoreCase(derived_path.value(), full_file_path.value()); } struct FixupCase { const std::string input; const std::string desired_tld; const std::string output; } fixup_cases[] = { {"www.google.com", "", "http://www.google.com/"}, {" www.google.com ", "", "http://www.google.com/"}, {" foo.com/asdf bar", "", "http://foo.com/asdf%20%20bar"}, {"..www.google.com..", "", "http://www.google.com./"}, {"http://......", "", "http://....../"}, {"http://host.com:ninety-two/", "", "http://host.com:ninety-two/"}, {"http://host.com:ninety-two?foo", "", "http://host.com:ninety-two/?foo"}, {"google.com:123", "", "http://google.com:123/"}, {"about:", "", "chrome://version/"}, {"about:foo", "", "chrome://foo/"}, {"about:version", "", "chrome://version/"}, {"about:usr:pwd@hst/pth?qry#ref", "", "chrome://usr:pwd@hst/pth?qry#ref"}, {"about://usr:pwd@hst/pth?qry#ref", "", "chrome://usr:pwd@hst/pth?qry#ref"}, {"chrome:usr:pwd@hst/pth?qry#ref", "", "chrome://usr:pwd@hst/pth?qry#ref"}, {"chrome://usr:pwd@hst/pth?qry#ref", "", "chrome://usr:pwd@hst/pth?qry#ref"}, {"www:123", "", "http://www:123/"}, {" www:123", "", "http://www:123/"}, {"www.google.com?foo", "", "http://www.google.com/?foo"}, {"www.google.com#foo", "", "http://www.google.com/#foo"}, {"www.google.com?", "", "http://www.google.com/?"}, {"www.google.com#", "", "http://www.google.com/#"}, {"www.google.com:123?foo#bar", "", "http://www.google.com:123/?foo#bar"}, {"user@www.google.com", "", "http://user@www.google.com/"}, {"\xE6\xB0\xB4.com" , "", "http://xn--1rw.com/"}, // It would be better if this next case got treated as http, but I don't see // a clean way to guess this isn't the new-and-exciting "user" scheme. {"user:passwd@www.google.com:8080/", "", "user:passwd@www.google.com:8080/"}, // {"file:///c:/foo/bar%20baz.txt", "", "file:///C:/foo/bar%20baz.txt"}, {"ftp.google.com", "", "ftp://ftp.google.com/"}, {" ftp.google.com", "", "ftp://ftp.google.com/"}, {"FTP.GooGle.com", "", "ftp://ftp.google.com/"}, {"ftpblah.google.com", "", "http://ftpblah.google.com/"}, {"ftp", "", "http://ftp/"}, {"google.ftp.com", "", "http://google.ftp.com/"}, // URLs which end with 0x85 (NEL in ISO-8859). { "http://google.com/search?q=\xd0\x85", "", "http://google.com/search?q=%D0%85" }, { "http://google.com/search?q=\xec\x97\x85", "", "http://google.com/search?q=%EC%97%85" }, { "http://google.com/search?q=\xf0\x90\x80\x85", "", "http://google.com/search?q=%F0%90%80%85" }, // URLs which end with 0xA0 (non-break space in ISO-8859). { "http://google.com/search?q=\xd0\xa0", "", "http://google.com/search?q=%D0%A0" }, { "http://google.com/search?q=\xec\x97\xa0", "", "http://google.com/search?q=%EC%97%A0" }, { "http://google.com/search?q=\xf0\x90\x80\xa0", "", "http://google.com/search?q=%F0%90%80%A0" }, // URLs containing IPv6 literals. {"[2001:db8::2]", "", "http://[2001:db8::2]/"}, {"[::]:80", "", "http://[::]/"}, {"[::]:80/path", "", "http://[::]/path"}, {"[::]:180/path", "", "http://[::]:180/path"}, // TODO(pmarks): Maybe we should parse bare IPv6 literals someday. {"::1", "", "::1"}, // Semicolon as scheme separator for standard schemes. {"http;//www.google.com/", "", "http://www.google.com/"}, {"about;chrome", "", "chrome://chrome/"}, // Semicolon left as-is for non-standard schemes. {"whatsup;//fool", "", "whatsup://fool"}, // Semicolon left as-is in URL itself. {"http://host/port?query;moar", "", "http://host/port?query;moar"}, // Fewer slashes than expected. {"http;www.google.com/", "", "http://www.google.com/"}, {"http;/www.google.com/", "", "http://www.google.com/"}, // Semicolon at start. {";http://www.google.com/", "", "http://%3Bhttp//www.google.com/"}, }; TEST(URLFixerUpperTest, FixupURL) { for (size_t i = 0; i < arraysize(fixup_cases); ++i) { FixupCase value = fixup_cases[i]; EXPECT_EQ(value.output, URLFixerUpper::FixupURL(value.input, value.desired_tld).possibly_invalid_spec()) << "input: " << value.input; } // Check the TLD-appending functionality FixupCase tld_cases[] = { {"google", "com", "http://www.google.com/"}, {"google.", "com", "http://www.google.com/"}, {"google..", "com", "http://www.google.com/"}, {".google", "com", "http://www.google.com/"}, {"www.google", "com", "http://www.google.com/"}, {"google.com", "com", "http://google.com/"}, {"http://google", "com", "http://www.google.com/"}, {"..google..", "com", "http://www.google.com/"}, {"http://www.google", "com", "http://www.google.com/"}, {"9999999999999999", "com", "http://www.9999999999999999.com/"}, {"google/foo", "com", "http://www.google.com/foo"}, {"google.com/foo", "com", "http://google.com/foo"}, {"google/?foo=.com", "com", "http://www.google.com/?foo=.com"}, {"www.google/?foo=www.", "com", "http://www.google.com/?foo=www."}, {"google.com/?foo=.com", "com", "http://google.com/?foo=.com"}, {"http://www.google.com", "com", "http://www.google.com/"}, {"google:123", "com", "http://www.google.com:123/"}, {"http://google:123", "com", "http://www.google.com:123/"}, }; for (size_t i = 0; i < arraysize(tld_cases); ++i) { FixupCase value = tld_cases[i]; EXPECT_EQ(value.output, URLFixerUpper::FixupURL(value.input, value.desired_tld).possibly_invalid_spec()); } } // Test different types of file inputs to URIFixerUpper::FixupURL. This // doesn't go into the nice array of fixups above since the file input // has to exist. TEST(URLFixerUpperTest, FixupFile) { // this "original" filename is the one we tweak to get all the variations base::FilePath dir; base::FilePath original; ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir)); ASSERT_TRUE(MakeTempFile( dir, base::FilePath(FILE_PATH_LITERAL("url fixer upper existing file.txt")), &original)); // reference path GURL golden(net::FilePathToFileURL(original)); // c:\foo\bar.txt -> file:///c:/foo/bar.txt (basic) #if defined(OS_WIN) GURL fixedup(URLFixerUpper::FixupURL(base::WideToUTF8(original.value()), std::string())); #elif defined(OS_POSIX) GURL fixedup(URLFixerUpper::FixupURL(original.value(), std::string())); #endif EXPECT_EQ(golden, fixedup); // TODO(port): Make some equivalent tests for posix. #if defined(OS_WIN) // c|/foo\bar.txt -> file:///c:/foo/bar.txt (pipe allowed instead of colon) std::string cur(base::WideToUTF8(original.value())); EXPECT_EQ(':', cur[1]); cur[1] = '|'; EXPECT_EQ(golden, URLFixerUpper::FixupURL(cur, std::string())); FixupCase file_cases[] = { {"c:\\This%20is a non-existent file.txt", "", "file:///C:/This%2520is%20a%20non-existent%20file.txt"}, // \\foo\bar.txt -> file://foo/bar.txt // UNC paths, this file won't exist, but since there are no escapes, it // should be returned just converted to a file: URL. {"\\\\SomeNonexistentHost\\foo\\bar.txt", "", "file://somenonexistenthost/foo/bar.txt"}, // We do this strictly, like IE8, which only accepts this form using // backslashes and not forward ones. Turning "//foo" into "http" matches // Firefox and IE, silly though it may seem (it falls out of adding "http" // as the default protocol if you haven't entered one). {"//SomeNonexistentHost\\foo/bar.txt", "", "http://somenonexistenthost/foo/bar.txt"}, {"file:///C:/foo/bar", "", "file:///C:/foo/bar"}, // Much of the work here comes from GURL's canonicalization stage. {"file://C:/foo/bar", "", "file:///C:/foo/bar"}, {"file:c:", "", "file:///C:/"}, {"file:c:WINDOWS", "", "file:///C:/WINDOWS"}, {"file:c|Program Files", "", "file:///C:/Program%20Files"}, {"file:/file", "", "file://file/"}, {"file:////////c:\\foo", "", "file:///C:/foo"}, {"file://server/folder/file", "", "file://server/folder/file"}, // These are fixups we don't do, but could consider: // // {"file:///foo:/bar", "", "file://foo/bar"}, // {"file:/\\/server\\folder/file", "", "file://server/folder/file"}, }; #elif defined(OS_POSIX) #if defined(OS_MACOSX) #define HOME "/Users/" #else #define HOME "/home/" #endif URLFixerUpper::home_directory_override = "/foo"; FixupCase file_cases[] = { // File URLs go through GURL, which tries to escape intelligently. {"/This%20is a non-existent file.txt", "", "file:///This%2520is%20a%20non-existent%20file.txt"}, // A plain "/" refers to the root. {"/", "", "file:///"}, // These rely on the above home_directory_override. {"~", "", "file:///foo"}, {"~/bar", "", "file:///foo/bar"}, // References to other users' homedirs. {"~foo", "", "file://" HOME "foo"}, {"~x/blah", "", "file://" HOME "x/blah"}, }; #endif for (size_t i = 0; i < arraysize(file_cases); i++) { EXPECT_EQ(file_cases[i].output, URLFixerUpper::FixupURL(file_cases[i].input, file_cases[i].desired_tld).possibly_invalid_spec()); } EXPECT_TRUE(base::DeleteFile(original, false)); } TEST(URLFixerUpperTest, FixupRelativeFile) { base::FilePath full_path, dir; base::FilePath file_part( FILE_PATH_LITERAL("url_fixer_upper_existing_file.txt")); ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir)); ASSERT_TRUE(MakeTempFile(dir, file_part, &full_path)); full_path = base::MakeAbsoluteFilePath(full_path); ASSERT_FALSE(full_path.empty()); // make sure we pass through good URLs for (size_t i = 0; i < arraysize(fixup_cases); ++i) { FixupCase value = fixup_cases[i]; base::FilePath input = base::FilePath::FromUTF8Unsafe(value.input); EXPECT_EQ(value.output, URLFixerUpper::FixupRelativeFile(dir, input).possibly_invalid_spec()); } // make sure the existing file got fixed-up to a file URL, and that there // are no backslashes EXPECT_TRUE(IsMatchingFileURL(URLFixerUpper::FixupRelativeFile(dir, file_part).possibly_invalid_spec(), full_path)); EXPECT_TRUE(base::DeleteFile(full_path, false)); // create a filename we know doesn't exist and make sure it doesn't get // fixed up to a file URL base::FilePath nonexistent_file( FILE_PATH_LITERAL("url_fixer_upper_nonexistent_file.txt")); std::string fixedup(URLFixerUpper::FixupRelativeFile(dir, nonexistent_file).possibly_invalid_spec()); EXPECT_NE(std::string("file:///"), fixedup.substr(0, 8)); EXPECT_FALSE(IsMatchingFileURL(fixedup, nonexistent_file)); // make a subdir to make sure relative paths with directories work, also // test spaces: // "app_dir\url fixer-upper dir\url fixer-upper existing file.txt" base::FilePath sub_dir(FILE_PATH_LITERAL("url fixer-upper dir")); base::FilePath sub_file( FILE_PATH_LITERAL("url fixer-upper existing file.txt")); base::FilePath new_dir = dir.Append(sub_dir); base::CreateDirectory(new_dir); ASSERT_TRUE(MakeTempFile(new_dir, sub_file, &full_path)); full_path = base::MakeAbsoluteFilePath(full_path); ASSERT_FALSE(full_path.empty()); // test file in the subdir base::FilePath relative_file = sub_dir.Append(sub_file); EXPECT_TRUE(IsMatchingFileURL(URLFixerUpper::FixupRelativeFile(dir, relative_file).possibly_invalid_spec(), full_path)); // test file in the subdir with different slashes and escaping. base::FilePath::StringType relative_file_str = sub_dir.value() + FILE_PATH_LITERAL("/") + sub_file.value(); ReplaceSubstringsAfterOffset(&relative_file_str, 0, FILE_PATH_LITERAL(" "), FILE_PATH_LITERAL("%20")); EXPECT_TRUE(IsMatchingFileURL(URLFixerUpper::FixupRelativeFile(dir, base::FilePath(relative_file_str)).possibly_invalid_spec(), full_path)); // test relative directories and duplicate slashes // (should resolve to the same file as above) relative_file_str = sub_dir.value() + FILE_PATH_LITERAL("/../") + sub_dir.value() + FILE_PATH_LITERAL("///./") + sub_file.value(); EXPECT_TRUE(IsMatchingFileURL(URLFixerUpper::FixupRelativeFile(dir, base::FilePath(relative_file_str)).possibly_invalid_spec(), full_path)); // done with the subdir EXPECT_TRUE(base::DeleteFile(full_path, false)); EXPECT_TRUE(base::DeleteFile(new_dir, true)); // Test that an obvious HTTP URL isn't accidentally treated as an absolute // file path (on account of system-specific craziness). base::FilePath empty_path; base::FilePath http_url_path(FILE_PATH_LITERAL("http://../")); EXPECT_TRUE(URLFixerUpper::FixupRelativeFile( empty_path, http_url_path).SchemeIs("http")); }<|fim▁end|>
<|file_name|>activate.go<|end_file_name|><|fim▁begin|>package model import ( "errors" ) var ( ErrAlreadyActivated = errors.New("ErrAlreadyActivated") ) /* Activate activates the account, or returns an error if the account was already activated, or the token given is invalid.<|fim▁hole|>*/ func (a *Account) Activate(token string) (err error, conflict bool) { if a.IsActive() { return ErrAlreadyActivated, true } if token != a.ActivateToken { return ErrInvalidCredentials, true } a.ActivateToken = "" return a.Update(a), false }<|fim▁end|>
<|file_name|>product_loader.py<|end_file_name|><|fim▁begin|>import os import xlrd import configparser import logging from ..entities import product def process_cell(cell): """Converts the given cell to the appropriate value.""" if cell.value == 'NA': return '' ttype = cell.ctype # get the cell's 'type' if ttype == xlrd.XL_CELL_EMPTY or ttype == xlrd.XL_CELL_TEXT or ttype == xlrd.XL_CELL_BLANK: return cell.value if ttype == xlrd.XL_CELL_NUMBER or ttype == xlrd.XL_CELL_DATE or ttype == xlrd.XL_CELL_BOOLEAN: # convert these types to strings return float(cell.value) if cell.ctype == xlrd.XL_CELL_ERROR: # do not process - instead, return the correct error message return xlrd.error_text_from_code[cell.value] def process_row(row_as_array): """Convert a row of cells from xlrd into values that are more intuitive to work with ie not xlrd 'objects'.""" for cell in row_as_array: cell.value = process_cell(cell) return row_as_array def build_products(filepath): """Reads data from excel spreadsheets to build data representations of products.""" """All attributes of product objects are stored as strings so the user is responsible for casting types.""" config = configparser.ConfigParser() config.read('settings.ini') product_list = []<|fim▁hole|> try: logging.info("Loading products from spreadsheet at {0}...".format(filepath)) workbook = xlrd.open_workbook(filepath) product_worksheet_name = str(config['File Locations']['Title of Product Worksheet']) worksheet = workbook.sheet_by_name(product_worksheet_name) num_rows = worksheet.nrows - 1 num_cells = worksheet.ncols - 1 # map column names to indices for readability CODE_COL = 0 NAME_COL = 1 VISC_40_LOW_COL = 2 VISC_40_HIGH_COL = 3 VISC_100_LOW_COL = 4 VISC_100_HIGH_COL = 5 row_index = 1 while row_index < num_rows: # sanitize row curr_row = process_row(worksheet.row(row_index)) # we can skip the header rows row_index += 1 # fetch values from the spreadsheet using xlrd library code = curr_row[CODE_COL].value name = curr_row[NAME_COL].value visc_40_low = curr_row[VISC_40_LOW_COL].value visc_40_high = curr_row[VISC_40_HIGH_COL].value visc_100_low = curr_row[VISC_100_LOW_COL].value visc_100_high = curr_row[VISC_100_HIGH_COL].value # all elemental values should be formatted as floats elemental_values = { 'Aluminum' : curr_row[6].value, 'Barium' : curr_row[7].value, 'Calcium' : curr_row[8].value, 'Copper' : curr_row[9].value, 'Iron' : curr_row[10].value, 'Lead' : curr_row[11].value, 'Nickel' : curr_row[12].value, 'Nitrogen' : curr_row[13].value, 'Molybdenum' : curr_row[14].value, 'Silicon' : curr_row[15].value, 'Silver' : curr_row[16].value, 'Sulphur' : curr_row[17].value, 'Titanium' : curr_row[18].value, 'Magnesium' : curr_row[19].value, 'Phosphorus' : curr_row[20].value, 'Zinc' : curr_row[21].value } family_group = curr_row[22].value demulse = curr_row[23].value dyed = curr_row[24].value # create a new product object based on these attributes p = product.Product(code, name, elemental_values, demulse, dyed, visc_40_low, visc_40_high, visc_100_low,visc_100_high) #add the new product to the list of products to return product_list.append(p) logging.info("Products loaded: " +str(len(product_list))) return product_list except ValueError as e: logging.error("Value error occurred in processing row #"+str(row_index), exc_info=True) pass<|fim▁end|>
<|file_name|>homegenie.statistics.js<|end_file_name|><|fim▁begin|>// // namespace : HG.Statistics // info : - // HG.Statistics = HG.Statistics || {}; // HG.Statistics.ServiceCall = function (fn, opt1, opt2, callback) { $.ajax({ url: '/' + HG.WebApp.Data.ServiceKey + '/' + HG.WebApp.Data.ServiceDomain + '/Statistics/' + fn + '/' + opt1 + '/' + opt2, type: 'GET', dataType: 'text', success: function (data) { var value = eval(data); if (typeof value == 'undefined') { value = data; } else if (typeof value[0] != 'undefined' && typeof value[0].ResponseValue != 'undefined') { value = value[0].ResponseValue; } callback(value); } }); }; // // namespace : HG.Statistics.Global // info : - // HG.Statistics.Global = HG.Statistics.Global || {}; HG.Statistics.Global.GetWattsCounter = function (callback) { $.ajax({ url: '/' + HG.WebApp.Data.ServiceKey + '/' + HG.WebApp.Data.ServiceDomain + '/Statistics/Global.CounterTotal/Meter.Watts', type: 'GET', dataType: 'text', success: function (data) { <|fim▁hole|> callback(counter.ResponseValue); } }); }; // // namespace : HG.Statistics.Database // info : - // HG.Statistics.Database = HG.Statistics.Database || {}; HG.Statistics.Database.Reset = function () { $.get('/' + HG.WebApp.Data.ServiceKey + '/' + HG.WebApp.Data.ServiceDomain + '/Statistics/Database.Reset/' + (new Date().getTime()), function (data) { }); };<|fim▁end|>
var counter = eval(data)[0];
<|file_name|>primitivesIndex.NIRI.py<|end_file_name|><|fim▁begin|># This is added to the reduction object dictionary, but only one reduction # object per AstroData Type. NOTE: primitives are the member functions of a # Reduction Object. localPrimitiveIndex = { "NIRI": ("primitives_NIRI.py", "NIRIPrimitives"), "NIRI_IMAGE": ("primitives_NIRI_IMAGE.py", "NIRI_IMAGEPrimitives"),<|fim▁hole|><|fim▁end|>
}
<|file_name|>go.js<|end_file_name|><|fim▁begin|>$(document).ready(function() { $.getJSON('/backend/go/' + go_term['id'] + '/locus_details', function(data) {<|fim▁hole|> $.getJSON('/backend/go/' + go_term['id'] + '/ontology_graph', function(data) { var cy = create_cytoscape_vis("cy", layout, graph_style, data, null, false, "goOntology"); create_cy_download_button(cy, "cy_download", go_term['display_name'] + '_ontology') if(data['all_children'] != null && data['all_children'].length > 0) { var children_div = document.getElementById("children"); var more_children_div = document.getElementById("children_see_more"); for(var i=0; i < data['all_children'].length; i++) { var a = document.createElement('a'); a.innerHTML = data['all_children'][i]['display_name']; a.href = data['all_children'][i]['link'] if(i < 20) { children_div.appendChild(a); } else { more_children_div.appendChild(a); } if(i != data['all_children'].length-1) { var comma = document.createElement('span'); comma.innerHTML = ' &bull; '; if(i < 20) { children_div.appendChild(comma); } else { more_children_div.appendChild(comma); } } } if(data['all_children'].length <= 20) { $("#children_see_more_button").hide(); } } else { $("#children_wrapper").hide() } }); }); function create_go_table(data) { var manualDatatable = []; var manualGenes = {}; var htpDatatable = []; var htpGenes = {}; var computationalDatatable = []; var computationalGenes = {}; for (var i=0; i < data.length; i++) { var type = data[i].annotation_type; if (type === 'manually curated') { manualDatatable.push(go_data_to_table(data[i], i)); manualGenes[data[i]["locus"]["id"]] = true; } else if (type === 'high-throughput') { htpDatatable.push(go_data_to_table(data[i], i)); htpGenes[data[i]["locus"]["id"]] = true; } else if (type === 'computational') { computationalDatatable.push(go_data_to_table(data[i], i)); computationalGenes[data[i]["locus"]["id"]] = true; } } set_up_header('manual_go_table', manualDatatable.length, 'entry', 'entries', Object.keys(manualGenes).length, 'gene', 'genes'); set_up_header('htp_go_table', htpDatatable.length, 'entry', 'entries', Object.keys(htpGenes).length, 'gene', 'genes'); set_up_header('computational_go_table', computationalDatatable.length, 'entry', 'entries', Object.keys(computationalGenes).length, 'gene', 'genes'); var options = {}; options["bPaginate"] = true; options["aaSorting"] = [[3, "asc"]]; options["bDestroy"] = true; // options["oLanguage"] = {"sEmptyTable": "No genes annotated directly to " + go_term['display_name']}; options["aoColumns"] = [ //Use of mData {"bSearchable":false, "bVisible":false,"aTargets":[0],"mData":0}, //evidence_id {"bSearchable":false, "bVisible":false,"aTargets":[1],"mData":1}, //analyze_id {"aTargets":[2],"mData":2}, //gene {"bSearchable":false, "bVisible":false,"aTargets":[3],"mData":3}, //gene systematic name {"aTargets":[4],"mData":4}, //gene ontology term -----> qualifier {"bSearchable":false, "bVisible":false,"aTargets":[5],"mData":5}, //gene ontology term id {"aTargets":[6],"mData":6}, //qualifier -----> gene ontology term {"bSearchable":false, "bVisible":false,"aTargets":[7],"mData":7}, //aspect {"aTargets":[8],"mData":8}, //evidence -----> annotation_extension {"aTargets":[9],"mData":9}, //method -----> evidence {"bSearchable":false,"bVisible":false,"aTargets":[10],"mData":10}, //source -----> method {"aTargets":[11],"mData":11}, //assigned on -----> source {"aTargets":[12],"mData":12}, //annotation_extension -----> assigned on {"aTargets":[13],"mData":13} // reference ]; create_or_hide_table(manualDatatable, options, "manual_go_table", go_term["display_name"], go_term["link"], go_term["id"], "manually curated", data); create_or_hide_table(htpDatatable, options, "htp_go_table", go_term["display_name"], go_term["link"], go_term["id"], "high-throughput", data); create_or_hide_table(computationalDatatable, options, "computational_go_table", go_term["display_name"], go_term["link"], go_term["id"], "computational", data); } function create_or_hide_table(tableData, options, tableIdentifier, goName, goLink, goId, annotationType, originalData) { if (tableData.length) { var localOptions = $.extend({ aaData: tableData, oLanguage: { sEmptyTable: 'No genes annotated directly to ' + goName } }, options); var table = create_table(tableIdentifier, localOptions); create_analyze_button(tableIdentifier + "_analyze", table, "<a href='" + goLink + "' class='gene_name'>" + goName + "</a> genes", true); create_download_button(tableIdentifier + "_download", table, goName + "_annotations"); if(go_term['descendant_locus_count'] > go_term['locus_count']) { create_show_child_button(tableIdentifier + "_show_children", table, originalData, "/backend/go/" + goId + "/locus_details_all", go_data_to_table, function(table_data) { var genes = {}; for (var i=0; i < table_data.length; i++) { genes[table_data[i][1]] = true; } set_up_header(tableIdentifier, table_data.length, 'entry', 'entries', Object.keys(genes).length, 'gene', 'genes'); }, annotationType); } return table; } else { $("#" + tableIdentifier + "_header").remove(); var $parent = $("#" + tableIdentifier).parent(); var emptyMessage = "There are no " + annotationType + " annotations for " + goName + "."; $parent.html(emptyMessage); } }; var graph_style = cytoscape.stylesheet() .selector('node') .css({ 'content': 'data(name)', 'font-family': 'helvetica', 'font-size': 14, 'text-outline-width': 3, 'text-valign': 'center', 'width': 30, 'height': 30, 'border-color': '#fff', 'background-color': "#43a0df", 'text-outline-color': '#fff', 'color': '#888' }) .selector('edge') .css({ 'content': 'data(name)', 'font-family': 'helvetica', 'font-size': 12, 'color': 'grey', 'width': 2, 'source-arrow-shape': 'triangle' }) .selector("node[sub_type='FOCUS']") .css({ 'width': 30, 'height': 30, 'background-color': "#fade71", 'text-outline-color': '#fff', 'color': '#888' }) .selector("node[id='NodeMoreChildren']") .css({ 'width': 30, 'height': 30, 'shape': 'rectangle' }); // .selector("node[sub_type='HAS_CHILDREN']") // .css( // {'background-color': "#165782" // }) // .selector("node[sub_type='HAS_DESCENDANTS']") // .css( // {'background-color': "#43a0df" // }) // .selector("node[sub_type='NO_DESCENDANTS']") // .css( // {'background-color': "#c9e4f6" // }); var layout = { "name": "breadthfirst", "fit": true, "directed": true };<|fim▁end|>
create_go_table(data); });
<|file_name|>TCPMondrian.py<|end_file_name|><|fim▁begin|>#import printStatWithName from AZutilities import dataUtilities from AZutilities import paramOptUtilities from trainingMethods import AZorngRF from trainingMethods import AZorngCvSVM import Orange import orange import math import copy import string """ Module for calculation of non conformity scores and the corresponding p-values and conformal predictions for binary classifiers. getPvalue | | getScore | | {Methods to calculate the non-conf score} """ def meanStd(data): """ Calculate mean and standard deviation of data data[]: """ length, mean, std = len(data), 0, 0 for elem in data: mean = mean + elem mean = mean / float(length) for elem in data: std = std + (elem - mean) ** 2 std = math.sqrt(std / float(length)) mean = round(mean, 3) std = round(std, 3) return mean, std def getScore(idx, extTrain, SVMparam, method = "minNN", maxDistRatio = None, measure = None): """ Calculates non-conformity score for the example with index idx in the data set extTrain method: 1) minNN - Get relative (all ex with diff labels) min distance in feature space from ex with idx in extTrain to the rest of extTrain with the same label as idx 2) avgNN - average distance to 10 NN of the two diff classes """ if method == "minNN": alpha = minNN(idx, extTrain, measure) elif method == "avgNN": alpha = avgNN(idx, extTrain, measure) elif method == "scaledMinNN": print "There is some problem with the scaling" alpha = minNN(idx, extTrain, maxDistRatio, measure) elif method == "kNNratio": alpha = kNNratio(idx, extTrain, measure) elif method == "kNNratioStruct": alpha = kNNratioStruct(idx, extTrain, measure) elif method == "probPred": alpha, SVMparam = probPred(idx, extTrain, SVMparam) elif method == "LLOO": alpha = LLOO(idx, extTrain, measure) elif method == "LLOOprob": alpha = LLOOprob(idx, extTrain, measure) elif method == "LLOOprob_b": alpha = LLOOprob_b(idx, extTrain, measure) else: alpha = None print "Method not implemented" return alpha, SVMparam def descRange(idx, extTrain): """ Use the fraction of descriptors in the train set range. Not possible to use. Alpha must reflect the non-conformity with the rest of the train set with a given lable. Inside our outside the range is not predictive for which class the example belongs to. """ # Deselect example idx in extTrain idxList = range(0,idx) idxList.extend(range(idx+1,len(extTrain))) train = extTrain.get_items(idxList) # Get the idx example idxEx = extTrain.get_items([idx]) # Loop over att attributes to see if the idxEx values are within the range of train outRangeCount = 0 stat = Orange.statistics.basic.Domain(train) #print "%20s %5s %5s %5s" % ("feature", "min", "max", "avg") for a in stat: if a: #print "%20s %5.3f %5.3f %5.3f" % (a.variable.name, a.min, a.max, a.avg) #print idxEx[0][a.variable.name] idxValue = idxEx[0][a.variable.name] trainMin = a.min trainMax = a.max try: if idxValue < trainMin: outRangeCount = outRangeCount + 1 elif idxValue > trainMax: outRangeCount = outRangeCount + 1 except: pass alpha = float(outRangeCount)/len(extTrain.domain.attributes) return alpha def trainSVMOptParam(train, SVMparam): # Optimize parameters #SVMparam = [1.0, 0.05] if not SVMparam: trainDataFile = "/scratch/trainDataTmp.tab" train.save(trainDataFile) learner = AZorngCvSVM.CvSVMLearner() param = paramOptUtilities.getOptParam(learner, trainDataFile, paramList = None, useGrid = False, verbose = 1, queueType = "NoSGE", runPath = None, nExtFolds = None, nFolds = 10, logFile = "", getTunedPars = True, fixedParams = {}) optC = float(param[1]["C"]) optGamma = float(param[1]["gamma"]) SVMparam = [optC, optGamma] else: optC = SVMparam[0] optGamma = SVMparam[1] #print "Optimal SVM parameters ", optC, optGamma model = AZorngCvSVM.CvSVMLearner(train, C = optC, gamma = optGamma) return model, SVMparam def probPred(idx, extTrain, SVMparam): """ Use the RF prediction probability to set the non-conf score """ attrList = ["SMILES_1"] extTrain = dataUtilities.attributeDeselectionData(extTrain, attrList) # Deselect example idx in extTrain idxList = range(0,idx) idxList.extend(range(idx+1,len(extTrain))) train = extTrain.get_items(idxList) # Train a model model = AZorngRF.RFLearner(train) #model, SVMparam = trainSVMOptParam(train, SVMparam) # Predict example idx predList = model(extTrain[idx], returnDFV = True) pred = predList[0].value prob = predList[1] actual = extTrain[idx].get_class().value #print pred, actual, prob # More non conforming if prediction is different from actual label if pred != actual: alpha = 1.0 + abs(prob) else: alpha = 1.0 - abs(prob) #print alpha return alpha, SVMparam def minNN(idx, extTrain, maxDistRatio = None, measure = None): """ Use the ratio between the distance to the nearest neighbor of the same and of the other class Two versions exist, with and without scaling with the max distance ratio within the train set. """ attrList = ["SMILES_1"] extTrain = dataUtilities.attributeDeselectionData(extTrain, attrList) distListSame = [] distListDiff = [] #measure = Orange.distance.Euclidean(extTrain) if not measure: measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain) for runIdx in range(len(extTrain)): if runIdx != idx: dist = measure(extTrain[idx], extTrain[runIdx]) if extTrain[idx].get_class().value == extTrain[runIdx].get_class().value: distListSame.append(dist) else: distListDiff.append(dist) minDistSame = min(distListSame) minDistDiff = min(distListDiff) if minDistDiff == 0: if maxDistRatio: alpha = 1.0 else: alpha = max(distListDiff) else: if maxDistRatio: alpha = minDistSame/(float(minDistDiff)*maxDistRatio) else: alpha = minDistSame/float(minDistDiff) #fid = open("tempFile.txt", "a") #fid.write(str(minDistSame)+"\t"+str(minDistDiff)+"\t"+str(maxDistRatio)+"\t"+str(alpha)+"\n") #fid.close() return alpha def avgNN(idx, extTrain, measure = None): """ Use the ratio between the distance to the kNN of the same and of the other class """ attrList = ["SMILES_1"] extTrain = dataUtilities.attributeDeselectionData(extTrain, attrList) distListSame = [] distListDiff = [] #measure = Orange.distance.Euclidean(extTrain) if not measure: measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain) for runIdx in range(len(extTrain)): if runIdx != idx: dist = measure(extTrain[idx], extTrain[runIdx]) if extTrain[idx].get_class().value == extTrain[runIdx].get_class().value: distListSame.append(dist) else: distListDiff.append(dist) distListSame.sort() avgSame = sum(distListSame[0:10])/10.0 distListDiff.sort() avgDiff = sum(distListDiff[0:10])/10.0 if avgDiff == 0: alpha = max(distListDiff) else: alpha = avgSame/float(avgDiff) return alpha def kNNratio(idx, extTrain, measure = None): """ Use the fraction of kNN with the same response. """ attrList = ["SMILES_1"] extTrain = dataUtilities.attributeDeselectionData(extTrain, attrList) distList = [] if not measure: #measure = instances.MahalanobisConstructor(extTrain) measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain) for runIdx in range(len(extTrain)): if runIdx != idx: dist = measure(extTrain[idx], extTrain[runIdx]) distList.append(dist) # Get the distance of the 10th NN distList.sort() thresDist = distList[9] # Find the labels of the 10 NN sameCount = 0 for runIdx in range(len(extTrain)): if runIdx != idx: dist = measure(extTrain[idx], extTrain[runIdx]) if dist <= thresDist: if extTrain[idx].get_class().value == extTrain[runIdx].get_class().value: sameCount = sameCount + 1 alpha = 1.00 - float(sameCount)/10.0 return alpha def kNNratioInd(train, calSet, measure = None): """ Use the fraction of kNN with the same response. """ if not measure: #measure = instances.MahalanobisConstructor(extTrain) measure = orange.ExamplesDistanceConstructor_Euclidean(train) alphaList = [] for predEx in calSet: distList = [] for runIdx in range(len(train)): dist = measure(predEx, train[runIdx]) distList.append(dist) # Get the distance of the 10th NN distList.sort() thresDist = distList[9] # Find the labels of the 10 NN sameCount = 0 for runIdx in range(len(train)): dist = measure(predEx, train[runIdx]) if dist <= thresDist: if predEx.get_class().value == train[runIdx].get_class().value: sameCount = sameCount + 1 alpha = 1.00 - float(sameCount)/10.0 alphaList.append(alpha) return alphaList, train def kNNratioStruct(idx, extTrain, measure = None): """ Use the fraction of kNN with the same response. """ from rdkit import Chem from rdkit.Chem.Fingerprints import FingerprintMols from rdkit import DataStructs # Daylight like fp smiles = extTrain[idx]["SMILES_1"].value mol = Chem.MolFromSmiles(smiles) fp = FingerprintMols.FingerprintMol(mol) simList = [] for runIdx in range(len(extTrain)): if runIdx != idx: smiles0 = extTrain[runIdx]["SMILES_1"].value mol0 = Chem.MolFromSmiles(smiles0) fp0 = FingerprintMols.FingerprintMol(mol0) tanSim = DataStructs.FingerprintSimilarity(fp,fp0) simList.append(tanSim) # Get the distance of the 10th NN simList.sort(reverse = True) thresDist = simList[9] # Find the labels of the 10 NN sameCount = 0 for runIdx in range(len(extTrain)): if runIdx != idx: smiles0 = extTrain[runIdx]["SMILES_1"].value mol0 = Chem.MolFromSmiles(smiles0) fp0 = FingerprintMols.FingerprintMol(mol0) tanSim = DataStructs.FingerprintSimilarity(fp,fp0) if tanSim >= thresDist: if extTrain[idx].get_class().value == extTrain[runIdx].get_class().value: sameCount = sameCount + 1 alpha = 1.00 - float(sameCount)/10.0 return alpha def LLOO(idx, extTrain, measure = None): """ Use the fraction of kNN correctly predicted by a local model Hard coded to 20 NN. Modeling method. RF of Tree? """ attrList = ["SMILES_1"] extTrain = dataUtilities.attributeDeselectionData(extTrain, attrList) distList = [] if not measure: measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain) for runIdx in range(len(extTrain)): if runIdx != idx: dist = measure(extTrain[idx], extTrain[runIdx]) distList.append(dist) # Get the distance of the 20th NN distList.sort() thresDist = distList[19] # Find the labels of the 20 NN kNN = [] for runIdx in range(len(extTrain)): dist = measure(extTrain[idx], extTrain[runIdx]) if dist <= thresDist: kNN.append(extTrain[runIdx]) kNNtrain = dataUtilities.DataTable(kNN) # Find the fraction of correctly predicted ex in a LOO over kNN corrPred = 0 for idx in range(len(kNNtrain)): # Deselect example idx in extTrain idxList = range(0,idx) idxList.extend(range(idx+1,len(kNNtrain))) train = kNNtrain.get_items(idxList) # Train a model model = AZorngRF.RFLearner(train) #model = Orange.classification.tree.TreeLearner(train) pred = model(kNNtrain[idx]).value actual = kNNtrain[idx].get_class().value if pred == actual: corrPred = corrPred + 1 alpha = 1.0 - float(corrPred)/len(kNNtrain) return alpha def LLOOprob(idx, extTrain, measure = None): """ Use the fraction of kNN correctly predicted by a local model Hard coded to 20 NN. Modeling method. RF of Tree? """ distList = [] if not measure: measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain) for runIdx in range(len(extTrain)): if runIdx != idx: dist = measure(extTrain[idx], extTrain[runIdx]) distList.append(dist) # Get the distance of the 20th NN distList.sort() thresDist = distList[50] # Smaller number of NN does not work with returnDFV # Find the predEx and the 20 NN kNN = [] for runIdx in range(len(extTrain)): dist = measure(extTrain[idx], extTrain[runIdx]) if dist <= thresDist: kNN.append(extTrain[runIdx]) kNNtrain = dataUtilities.DataTable(kNN) # Find the fraction of correctly predicted ex in a LOO over kNN alphaList = [] for iidx in range(len(kNNtrain)): # Deselect example idx in extTrain idxList = range(0,iidx) idxList.extend(range(iidx+1,len(kNNtrain))) train = kNNtrain.get_items(idxList) # Get prediction and pred probability model = AZorngRF.RFLearner(train) predList = model(kNNtrain[iidx], returnDFV = True) pred = predList[0].value prob = predList[1] actual = kNNtrain[iidx].get_class().value # alpha should be greater the less certain the model try: if pred != actual: alpha = 1.0 + abs(prob) else: alpha = 1.0 - abs(prob) alphaList.append(alpha) except: pass alpha = sum(alphaList)/float(len(alphaList)) return alpha def LLOOprob_b(idx, extTrain, measure = None): """ Use the fraction of kNN correctly predicted by a local model Hard coded to 50 NN. Modeling method. RF of Tree? """ distList = [] if not measure: measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain) for runIdx in range(len(extTrain)): if runIdx != idx: dist = measure(extTrain[idx], extTrain[runIdx]) distList.append(dist) # Get the distance of the 50th NN distList.sort() thresDist = distList[50] # Smaller number of NN does not work with returnDFV # Find the predEx and the 20 NN kNN = [] for runIdx in range(len(extTrain)): dist = measure(extTrain[idx], extTrain[runIdx]) if dist <= thresDist: kNN.append(extTrain[runIdx]) kNNtrain = dataUtilities.DataTable(kNN) # Find the fraction of correctly predicted ex in a LOO over kNN alphaList = [] alphaEx = 0 for iidx in range(len(kNNtrain)): # Deselect example idx in extTrain idxList = range(0,iidx) idxList.extend(range(iidx+1,len(kNNtrain))) train = kNNtrain.get_items(idxList) # Get prediction and pred probability model = AZorngRF.RFLearner(train) predList = model(kNNtrain[iidx], returnDFV = True) pred = predList[0].value prob = predList[1] actual = kNNtrain[iidx].get_class().value # The prob of the predEx is more important dist = measure(extTrain[idx], kNNtrain[iidx]) # alpha should be greater the less certain the model try: if pred != actual: alpha = 1.0 + abs(prob) if dist < 0.001: alphaEx = alpha else: alpha = 1.0 - abs(prob) if dist < 0.001: alphaEx = alpha alphaList.append(alpha) except: pass alpha = alphaEx + sum(alphaList)/float(len(alphaList)) return alpha def getMeanStd(extTrain): # Get the min dist for all ex in the data set minSame = [] minDiff = [] measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain) for idx in range(len(extTrain)): distListSame = [] distListDiff = [] for iidx in range(len(extTrain)): if idx != iidx: dist = measure(extTrain[idx], extTrain[iidx]) if extTrain[idx].get_class().value == extTrain[iidx].get_class().value: distListSame.append(dist) else: distListDiff.append(dist) minSame.append(min(distListSame))<|fim▁hole|> # Calculate mean and std of all the min distances meanSame, stdSame = meanStd(minSame) meanDiff, stdDiff = meanStd(minDiff) return meanSame, stdSame, meanDiff, stdDiff def getMinDistRatio(train): """ Calculate the minDistSame and minDistDiff ratio for all ex in the data set and select the greatest quotient. Used to scale the minDist ratios in the non-conf score. """ # Get the min dist for all ex in the data set minSame = [] minDiff = [] minRatio = [] measure = orange.ExamplesDistanceConstructor_Euclidean(extTrain) for idx in range(len(train)): distListSame = [] distListDiff = [] for iidx in range(len(train)): if idx != iidx: dist = measure(train[idx], train[iidx]) if train[idx].get_class().value == train[iidx].get_class().value: distListSame.append(dist) else: distListDiff.append(dist) minSame.append(min(distListSame)) minDiff.append(min(distListDiff)) if min(distListDiff) == 0: alpha = max(distListDiff) else: minRatio.append(min(distListSame)/float(min(distListDiff))) # Calculate min, mean and std of all the min distances meanSame, stdSame = meanStd(minSame) meanDiff, stdDiff = meanStd(minDiff) maxDistRatio = max(minRatio) return maxDistRatio def getPvalueFromList(nonConfList): trainList = nonConfList[0:len(nonConfList)-1] alphaPredEx = nonConfList[len(nonConfList)-1] moreNonConfList = [] for score in trainList: if score > alphaPredEx: moreNonConfList.append(score) pvalue = len(moreNonConfList)/float(len(trainList)) return pvalue def getPvalue(train, predEx, label, SVMparam, method = "avgNN", measure = None): """ method; avgNN, scaledMinNN, minNN, kNNratio """ # Set label to class of predEx newPredEx = Orange.data.Table(predEx.domain, [predEx]) newPredEx[0][newPredEx.domain.classVar] = label # Add predEx to train extTrain = dataUtilities.concatenate([train, newPredEx], True) extTrain = extTrain[0] # Calculate a non-conf score for each ex in train + predEx with given label if method == "scaledMinNN": # Calculate average and std of min distanses in train set maxDistRatio = getMinDistRatio(train) nonConfList = [] nonConfListMondrian = [] for idx in range(len(extTrain)): if method == "scaledMinNN": alpha = getScore(idx, extTrain, method, maxDistRatio) else: alpha, SVMparam = getScore(idx, extTrain, SVMparam, method, None, measure) nonConfList.append(alpha) if extTrain[idx].get_class().value == label: nonConfListMondrian.append(alpha) #nonConfListSorted = copy.deepcopy(nonConfList) #nonConfListSorted.sort() #nonConfListMondrianSorted = copy.deepcopy(nonConfListMondrian) #nonConfListMondrianSorted.sort() #fid = open("NonConf.txt", "w") #for ex in nonConfListSorted: # fid.write(str(ex)+"\n") #fid.close() # The last non-conf score is that of predEx # The p-value is the fraction of ex with alpha gt that of predEx pvalue = getPvalueFromList(nonConfList) pvalueMondrian = getPvalueFromList(nonConfListMondrian) return pvalue, pvalueMondrian, SVMparam def printResults(pvalues, labels, actualLabel, method, resultsFile, name): confLevel = 0.95 #print "OBS! Assuming two labels!!!" #print "Confidence level in predicting label ", labels[0] conf1 = round(1-pvalues[1], 3) #print "Confidence level in predicting label ", labels[1] conf2 = round(1-pvalues[0], 3) #print "Requiering 95% confidence gives " if conf1 > confLevel and conf2 < confLevel: # print "Label ", labels[0], "is predicted with at least 95% conf" prediction = labels[0] elif conf1 < confLevel and conf2 > confLevel: # print "Label ", labels[1], "is predicted with at least 95% conf" prediction = labels[1] elif conf1 <= confLevel and conf2 <= confLevel: # print "No prediction can be given at 95% confidence. Both?" prediction = "Both" else: # if conf1 > confLevel and conf2 > confLevel: # print "Predicting both labels. Empty?" prediction = "Empty" fid = open(resultsFile, "a") fid.write(str(name)+"\t"+actualLabel+"\t"+labels[0]+"\t"+labels[1]+"\t"+str(pvalues[0])+"\t"+str(pvalues[1])+"\t"+str(conf1)+"\t"+str(conf2)+"\t"+prediction+"\n") fid.close() return prediction def printStat(resDict, labels): # Print statistics T0 = 0 T1 = 0 F0 = 0 F1 = 0 Both = 0 Empty = 0 for key, values in resDict.iteritems(): if values["actualLabel"] == labels[0]: if values["actualLabel"] == values["prediction"]: T0 = T0 + 1 elif values["prediction"] == "Both": Both = Both + 1 elif values["prediction"] == "Empty": Empty = Empty + 1 elif values["prediction"] == labels[1]: F1 = F1 + 1 if values["actualLabel"] == labels[1]: if values["actualLabel"] == values["prediction"]: T1 = T1 + 1 elif values["prediction"] == "Both": Both = Both + 1 elif values["prediction"] == "Empty": Empty = Empty + 1 elif values["prediction"] == labels[0]: F0 = F0 + 1 print "True ", labels[0], ": ", T0 print "True ", labels[1], ": ", T1 print "False ", labels[0], ": ", F0 print "False ", labels[1], ": ", F1 print "Both: ", Both print "Empty: ", Empty def getRFAcc(train, work): model = AZorngRF.RFLearner(train) TP = 0 TN = 0 FP = 0 FN = 0 for ex in work: pred = model(ex).value actual = ex.get_class().value if actual == "POS": if pred == "POS": TP = TP + 1 else: FN = FN + 1 elif actual == "NEG": if pred == "NEG": TN = TN + 1 else: FP = FP + 1 print "TP\tTN\tFP\tFN\n" print str(TP)+"\t"+str(TN)+"\t"+str(FP)+"\t"+str(FN)+"\n" fid = open("RFresults.txt", "a") fid.write(str(TP)+"\t"+str(TN)+"\t"+str(FP)+"\t"+str(FN)+"\n") fid.close() def getRFprobAcc(train, work, probThres): model = AZorngRF.RFLearner(train) TP = 0 TN = 0 FP = 0 FN = 0 noPred = 0 for ex in work: actual = ex.get_class().value predList = model(ex, returnDFV = True) pred = predList[0].value prob = predList[1] if abs(prob) > probThres: if actual == "POS": if pred == "POS": TP = TP + 1 else: FN = FN + 1 elif actual == "NEG": if pred == "NEG": TN = TN + 1 else: FP = FP + 1 else: noPred = noPred + 1 print "TP\tTN\tFP\tFN\tnoPred\n" print str(TP)+"\t"+str(TN)+"\t"+str(FP)+"\t"+str(FN)+"\t"+str(noPred)+"\n" fid = open("RFprob"+str(probThres)+"Results.txt", "a") fid.write(str(TP)+"\t"+str(TN)+"\t"+str(FP)+"\t"+str(FN)+"\t"+str(noPred)+"\n") fid.close() def getProbPredAlpha(model, ex): predList = model(ex, returnDFV = True) pred = predList[0].value prob = predList[1] actual = ex.get_class().value # More non conforming if prediction is different from actual label if pred != actual: alpha = 1.0 + abs(prob) else: alpha = 1.0 - abs(prob) return alpha def probPredInd(trainSet, calSet): """ Use the RF prediction probability to set the non-conf score """ attrList = ["SMILES_1"] trainSet = dataUtilities.attributeDeselectionData(trainSet, attrList) # Train a model model = AZorngRF.RFLearner(trainSet) # Get the list of NC for all ex in calSet alphaList = [] for ex in calSet: alpha = getProbPredAlpha(model, ex) alphaList.append(alpha) return alphaList, model def getScores(trainSet, calSet, method): #if method == "minNN": # alpha = minNN(idx, extTrain, measure) #elif method == "avgNN": # alpha = avgNN(idx, extTrain, measure) #elif method == "scaledMinNN": # print "There is some problem with the scaling" # alpha = minNN(idx, extTrain, maxDistRatio, measure) if method == "kNNratio": alphaList, model = kNNratioInd(trainSet, calSet) #elif method == "kNNratioStruct": # alpha = kNNratioStruct(idx, extTrain, measure) elif method == "probPred": alphaList, model = probPredInd(trainSet, calSet) #elif method == "LLOO": # alpha = LLOO(idx, extTrain, measure) #elif method == "LLOOprob": # alpha = LLOOprob(idx, extTrain, measure) #elif method == "LLOOprob_b": # alpha = LLOOprob_b(idx, extTrain, measure) #else: # alpha = None # print "Method not implemented" return alphaList, model def getIndPvalue(model, NClist, predEx, label, method = "avgNN", measure = None): """ method; avgNN, scaledMinNN, minNN, kNNratio """ # Set label to class of predEx newPredEx = Orange.data.Table(predEx.domain, [predEx]) newPredEx[0][newPredEx.domain.classVar] = label # Calculate the NC score of predEx if method == "probPred": alpha = getProbPredAlpha(model, newPredEx[0]) elif method == "kNNratio": alphaList, model = kNNratioInd(model, newPredEx) # model is the train set for NN methods alpha = alphaList[0] # The p-value is the fraction of ex with alpha gt that of predEx moreNonConfList = [] for score in NClist: if score > alpha: moreNonConfList.append(score) pvalue = len(moreNonConfList)/float(len(NClist)) return pvalue def getConfPred(train, work, method, SVMparam, measure = None, resultsFile = "CPresults.txt", verbose = False): """ method - non-conformity score method """ # Get conformal predictions resDict = {} idx = 0 for predEx in work: labels = train.domain.classVar.values pvalues = [] pvaluesMondrian = [] for label in labels: if method == "combo": pvalue1 = getPvalue(train, predEx, label, "kNNratio", measure) pvalue2 = getPvalue(train, predEx, label, "probPred") pvalue = (pvalue1 + pvalue2)/2.0 else: pvalue, pvalueMondrian, SVMparam = getPvalue(train, predEx, label, SVMparam, method, measure) pvalues.append(pvalue) pvaluesMondrian.append(pvalueMondrian) actualLabel = predEx.get_class().value name = None prediction = printResults(pvalues, labels, actualLabel, method, resultsFile, name) MondrianFile = resultsFile+"_Mondrian.txt" predictionMondrian = printResults(pvaluesMondrian, labels, actualLabel, method, MondrianFile, name) idx = idx + 1 resDict[idx] = {"actualLabel": actualLabel, "prediction": predictionMondrian} if verbose: printStat(resDict, labels) return SVMparam, resDict def getIndConfPred(train, work, method, measure = None, resultsFile = "CPresults.txt", verbose = False): """ Partition train into a training and a calibration set (10%). Use the non-conf scores of the cal set to predict all examples in work. method - non-conformity score method """ # Randomily select 10% of train as a cal set indices2 = Orange.data.sample.SubsetIndices2(p0=0.10) ind = indices2(train) calSet = train.select(ind, 0) trainSet = train.select(ind, 1) # Calculate NC for the calibration set NClist, model = getScores(trainSet, calSet, method) # Calculate p-values for all ex in work resDict = {} idx = 0 for predEx in work: labels = predEx.domain.classVar.values pvalues = [] for label in labels: if method == "combo": pvalue1 = getIndPvalue(model, NClist, predEx, label, "kNNratio", measure) pvalue2 = getIndPvalue(model, NClist, predEx, label, "probPred") pvalue = (pvalue1 + pvalue2)/2.0 else: pvalue = getIndPvalue(model, NClist, predEx, label, method, measure) pvalues.append(pvalue) actualLabel = predEx.get_class().value prediction = printResults(pvalues, labels, actualLabel, method, resultsFile) idx = idx + 1 resDict[idx] = {"actualLabel": actualLabel, "prediction": prediction} #print "Break after the first example" #if idx == 1: break if __name__ == "__main__": """ Assumptions; Binary classification This main will test the implemented CP methods in a 10 fold CV """ data = dataUtilities.DataTable("HLMSeries2_rdkPhysChemPrepClass.txt") attrList = ['"Medivir;HLM (XEN025);CLint (uL/min/mg);(Num)"', 'Structure', '"MV Number"', "rdk.MolecularFormula"] data = dataUtilities.attributeDeselectionData(data, attrList) print "Select all attributes" descListList = [[]] for attr in data.domain.attributes: descListList[0].append(attr.name) #methods = ["kNNratio", "minNN", "avgNN", "probPred", "combo", "LLOO", "LLOOprob"] # Non-conformity score method methods = ["probPred"] cpMethod = "transductive" # inductive or transductive #print "Temp position to save comp time!!" # Append to python path /home/kgvf414/dev/AZOrange0.5.5/orangeDependencies/src/orange/orange/Orange/distance/ #import instances #measure = instances.MahalanobisConstructor(data) measure = None methodIdx = 1 method = methods[0] idx = 0 descResultsFile = "CPresults.txt" fid = open(descResultsFile, "w") fid.close() for descList in descListList: SVMparam = [] idx = idx + 1 resultsFile = "CPresults.txt" fid = open(resultsFile, "w") fid.write("Name\tActualLabel\tLabel1\tLabel2\tPvalue1\tPvalue2\tConf1\tConf2\tPrediction\n") fid.close() MondrianFile = resultsFile+"_Mondrian" fid = open(MondrianFile, "w") fid.write("Name\tActualLabel\tLabel1\tLabel2\tPvalue1\tPvalue2\tConf1\tConf2\tPrediction\n") fid.close() # Run a 10 fold CV nFolds = 10 ind = Orange.data.sample.SubsetIndicesCV(data, nFolds) for idx in range(nFolds): work = data.select(ind, idx) train = None for iidx in range(nFolds): if iidx != idx: if not train: train = data.select(ind, iidx) else: train.extend(data.select(ind, iidx)) print "Length of train ", len(train) print "Length of work ", len(work) # Create results file and get the conformal predictions if cpMethod == "transductive": #SVMparam = getConfPred(train, work, method, descList, SVMparam, measure, resultsFile, True) SVMparam, resDict = getConfPred(train, work, method, SVMparam, measure, resultsFile, True) elif cpMethod == "inductive": print "Please note, only kNNratio and probPred implemented for ICP!" getIndConfPred(train, work, method, measure, resultsFile, verbose = True) else: print "Valid cpMethod values are 'transductive' and 'inductive'" print descList fid = open(descResultsFile, "a") fid.write(str(descList)+"\n") fid.close() print "OBS copy printstatwithname" #printStatWithName.readAndPrint(resultsFile, descResultsFile)<|fim▁end|>
minDiff.append(min(distListDiff))
<|file_name|>country.js<|end_file_name|><|fim▁begin|>var articles = null; function restore_all_articles_view() { $("#allbtn").button('toggle'); $('#articleslist').empty(); $('#articleslist').append(articles); $('#filterwarning').hide(); } function switch_category(category) { if (typeof category != "undefined") { $("#articleslist").empty(); var filtered = articles.filter('.'.concat(category)); $("#articleslist").append(filtered); } else { restore_all_articles_view(); } timeandtips("#articleslist"); } $(document).ready(function() { timeandtips(); articles = $('#articleslist article'); $('#searchfield').removeAttr("disabled"); }); $("#searchfield").keyup(function(event) { var text = $('#searchfield').val(); if (text.length >= 3) { $("#allbtn").button('toggle'); var found = articles.filter('article:containsi("'.concat(text, '")')); $('#filterwarning').show(); $('#articleslist').empty(); $('#articleslist').append(found); } else if (text.length == 0) { restore_all_articles_view(); }<|fim▁hole|><|fim▁end|>
});
<|file_name|>378_kth_smallest_element_in_a_sorted_matrix.py<|end_file_name|><|fim▁begin|># 378. Kth Smallest Element in a Sorted Matrix # # Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. # # Note that it is the kth smallest element in the sorted order, not the kth distinct element. # # Example: # # matrix = [ # [ 1, 5, 9], # [10, 11, 13], # [12, 13, 15] # ], # k = 8, # # return 13. # # Note: # You may assume k is always valid, 1 <= k <= n2. # https://nb4799.neu.edu/wordpress/?p=2017 from heapq import * class Solution: def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ # heapq.merge: Merge multiple sorted inputs into a single sorted output # (for example, merge timestamped entries from multiple log files). # Returns an iterator over the sorted values. return list(merge(*matrix))[k-1] # Maintain a min-heap with k element, initialized by the elements of the first row. # Since it is a min-heap, and note the property that rows and columns are already sorted in ascending order, # the heap root after popping k-1 times is the k-th smallest element of the whole matrix.<|fim▁hole|> h = [] for i in range(min(len(matrix[0]), k)): heappush(h, (matrix[0][i], 0, i)) # pop k-1 times for i in range(k-1): val, x, y = heappop(h) if x < len(matrix) - 1: heappush(h, (matrix[x+1][y], x+1, y)) return h[0][0] # smallest element in heap. 0th index in tuple # binary search # We can eventually find the k-th smallest element by shrinking the search range in binary search. # Binary search is feasible for this problem since left, right,and mid in binary search are integers # and we know that matrix elements are integers. # The algorithm takes O(nlogN) time (N is the range of matrix[0][0] ~ matrix[n-1][n-1]) and O(1) space. # Time complexity analysis: the outer loop executes at most O(logN) times. # The inner for loop executes at most O(n) times. def kthSmallest(self, matrix, k): n = len(matrix) L = matrix[0][0] R = matrix[n-1][n-1] while L < R: mid = L + ((R - L) >> 1) count = 0 j = n - 1 for i in range(n): while j >= 0 and matrix[i][j] > mid: j -= 1 count += j+1 if count >= k: R = mid else: L = mid + 1 return L sol = Solution() matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ] k = 8 print(sol.kthSmallest(matrix, k))<|fim▁end|>
# When popping the heap, we also need to push necessary matrix elements into the heap. # Time complexity is O(KlogK) (every heap operation takes O(logK)) def kthSmallest(self, matrix, k): # element in the heap: (val, x coord, y coord)
<|file_name|>pipe_select_interrupter.hpp<|end_file_name|><|fim▁begin|>// // detail/pipe_select_interrupter.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_DETAIL_PIPE_SELECT_INTERRUPTER_HPP #define BOOST_ASIO_DETAIL_PIPE_SELECT_INTERRUPTER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if !defined(BOOST_WINDOWS) #if !defined(__CYGWIN__) #if !defined(__SYMBIAN32__) #if !defined(BOOST_ASIO_HAS_EVENTFD) #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { <|fim▁hole|>class pipe_select_interrupter { public: // Constructor. BOOST_ASIO_DECL pipe_select_interrupter(); // Destructor. BOOST_ASIO_DECL ~pipe_select_interrupter(); // Interrupt the select call. BOOST_ASIO_DECL void interrupt(); // Reset the select interrupt. Returns true if the call was interrupted. BOOST_ASIO_DECL bool reset(); // Get the read descriptor to be passed to select. int read_descriptor() const { return read_descriptor_; } private: // The read end of a connection used to interrupt the select call. This file // descriptor is passed to select such that when it is time to stop, a single // byte will be written on the other end of the connection and this // descriptor will become readable. int read_descriptor_; // The write end of a connection used to interrupt the select call. A single // byte may be written to this to wake up the select which is waiting for the // other end to become readable. int write_descriptor_; }; } // namespace detail } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # include <boost/asio/detail/impl/pipe_select_interrupter.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) #endif // !defined(BOOST_ASIO_HAS_EVENTFD) #endif // !defined(__SYMBIAN32__) #endif // !defined(__CYGWIN__) #endif // !defined(BOOST_WINDOWS) #endif // BOOST_ASIO_DETAIL_PIPE_SELECT_INTERRUPTER_HPP<|fim▁end|>
<|file_name|>reddit_handler.py<|end_file_name|><|fim▁begin|>""" ========================================== Author: Tyler Brockett Username: /u/tylerbrockett Description: Alert Bot (Formerly sales__bot) Date Created: 11/13/2015 Date Last Edited: 12/20/2016 Version: v2.0 ========================================== """ import praw import traceback from utils.logger import Logger from utils.color import Color from utils import output from prawcore.exceptions import Redirect from prawcore.exceptions import Forbidden class RedditHandler: def __init__(self, credentials): output.startup_message(credentials) self.credentials = credentials self.reddit = self.connect() self.NUM_POSTS = 20 def connect(self): try: reddit = praw.Reddit( client_id=self.credentials['client_id'], client_secret=self.credentials['client_secret'], password=self.credentials['password'], user_agent=self.credentials['user_agent'], username=self.credentials['username']) return reddit except: raise RedditHelperException('Error connecting to Reddit\n\n' + traceback.format_exc()) def disconnect(self): self.reddit = None def reset(self): try: self.disconnect() self.reddit = self.connect() except: raise RedditHelperException(RedditHelperException.RESET_EXCEPTION + '\n\n' + traceback.format_exc()) def get_instance(self): return self.reddit def get_unread(self): ret = [] unread = self.reddit.inbox.unread(limit=None) for message in unread: ret.append(message) ret.reverse() return ret def get_message(self, message_id): return self.reddit.inbox.message(message_id) def send_message(self, redditor, subject, body): try: self.reddit.redditor(redditor).message(subject, body) except: Logger.log(traceback.format_exc(), Color.RED) raise RedditHelperException(RedditHelperException.SEND_MESSAGE_EXCEPTION) def get_submissions(self, subreddit): submissions = [] posts = 200 if (subreddit == 'all') else self.NUM_POSTS try: subs = self.reddit.subreddit(subreddit).new(limit=posts) for submission in subs: submissions.append(submission) except Forbidden as e: Logger.log(traceback.format_exc(), Color.RED) return [] except Exception as e: Logger.log(traceback.format_exc(), Color.RED) raise RedditHelperException(RedditHelperException.GET_SUBMISSIONS_EXCEPTION) return submissions def get_original_message_id(self, received_message, database): message = received_message while message.parent_id and len(database.get_subscriptions_by_message_id(str(message.author), message.id)) == 0: message = self.reddit.inbox.message(message.parent_id[3:]) return message.id def check_invalid_subreddits(self, subreddits): invalid = [] for subreddit in subreddits: try: for submission in self.reddit.subreddit(subreddit).new(limit=1): print('subreddit is valid') except Redirect: # was praw.errors.InvalidSubreddit without 'len()' around call in the try block<|fim▁hole|> class RedditHelperException(Exception): SEND_MESSAGE_EXCEPTION = 'Error sending message' RESET_EXCEPTION = 'Error resetting connection to Reddit' GET_SUBMISSIONS_EXCEPTION = 'Error getting submissions' def __init__(self, error_args): Exception.__init__(self, 'Reddit Exception: {0}'.format(error_args)) self.errorArgs = error_args<|fim▁end|>
Logger.log(traceback.format_exc(), Color.RED) invalid.append(subreddit) return invalid
<|file_name|>configurationService.test.ts<|end_file_name|><|fim▁begin|>/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { VSBuffer } from 'vs/base/common/buffer'; import { Event } from 'vs/base/common/event'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { Schemas } from 'vs/base/common/network'; import { URI } from 'vs/base/common/uri'; import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { ConfigurationService } from 'vs/platform/configuration/common/configurationService'; import { IFileService } from 'vs/platform/files/common/files'; import { FileService } from 'vs/platform/files/common/fileService'; import { InMemoryFileSystemProvider } from 'vs/platform/files/common/inMemoryFilesystemProvider'; import { NullLogService } from 'vs/platform/log/common/log'; import { Registry } from 'vs/platform/registry/common/platform'; suite('ConfigurationService', () => { let fileService: IFileService; let settingsResource: URI; const disposables: DisposableStore = new DisposableStore(); setup(async () => { fileService = disposables.add(new FileService(new NullLogService())); const diskFileSystemProvider = disposables.add(new InMemoryFileSystemProvider()); fileService.registerProvider(Schemas.file, diskFileSystemProvider); settingsResource = URI.file('settings.json'); }); teardown(() => disposables.clear()); test('simple', async () => { await fileService.writeFile(settingsResource, VSBuffer.fromString('{ "foo": "bar" }')); const testObject = disposables.add(new ConfigurationService(settingsResource, fileService)); await testObject.initialize(); const config = testObject.getValue<{ foo: string; }>(); assert.ok(config); assert.strictEqual(config.foo, 'bar'); }); test('config gets flattened', async () => { await fileService.writeFile(settingsResource, VSBuffer.fromString('{ "testworkbench.editor.tabs": true }')); const testObject = disposables.add(new ConfigurationService(settingsResource, fileService)); await testObject.initialize(); const config = testObject.getValue<{ testworkbench: { editor: { tabs: boolean; }; }; }>(); assert.ok(config); assert.ok(config.testworkbench); assert.ok(config.testworkbench.editor); assert.strictEqual(config.testworkbench.editor.tabs, true); }); test('error case does not explode', async () => { await fileService.writeFile(settingsResource, VSBuffer.fromString(',,,,')); const testObject = disposables.add(new ConfigurationService(settingsResource, fileService)); await testObject.initialize(); const config = testObject.getValue<{ foo: string; }>(); assert.ok(config); }); test('missing file does not explode', async () => { const testObject = disposables.add(new ConfigurationService(URI.file('__testFile'), fileService)); await testObject.initialize(); const config = testObject.getValue<{ foo: string }>(); assert.ok(config); }); test('trigger configuration change event when file does not exist', async () => { const testObject = disposables.add(new ConfigurationService(settingsResource, fileService)); await testObject.initialize(); return new Promise<void>((c, e) => { disposables.add(Event.filter(testObject.onDidChangeConfiguration, e => e.source === ConfigurationTarget.USER)(() => { assert.strictEqual(testObject.getValue('foo'), 'bar'); c(); })); fileService.writeFile(settingsResource, VSBuffer.fromString('{ "foo": "bar" }')).catch(e); }); }); test('trigger configuration change event when file exists', async () => { const testObject = disposables.add(new ConfigurationService(settingsResource, fileService)); await fileService.writeFile(settingsResource, VSBuffer.fromString('{ "foo": "bar" }')); await testObject.initialize(); return new Promise<void>((c) => { disposables.add(Event.filter(testObject.onDidChangeConfiguration, e => e.source === ConfigurationTarget.USER)(async (e) => { assert.strictEqual(testObject.getValue('foo'), 'barz'); c(); })); fileService.writeFile(settingsResource, VSBuffer.fromString('{ "foo": "barz" }')); }); }); test('reloadConfiguration', async () => { await fileService.writeFile(settingsResource, VSBuffer.fromString('{ "foo": "bar" }')); const testObject = disposables.add(new ConfigurationService(settingsResource, fileService)); await testObject.initialize(); let config = testObject.getValue<{ foo: string; }>(); assert.ok(config); assert.strictEqual(config.foo, 'bar'); await fileService.writeFile(settingsResource, VSBuffer.fromString('{ "foo": "changed" }')); // force a reload to get latest await testObject.reloadConfiguration(); config = testObject.getValue<{ foo: string;<|fim▁hole|> }>(); assert.ok(config); assert.strictEqual(config.foo, 'changed'); }); test('model defaults', async () => { interface ITestSetting { configuration: { service: { testSetting: string; } }; } const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ 'id': '_test', 'type': 'object', 'properties': { 'configuration.service.testSetting': { 'type': 'string', 'default': 'isSet' } } }); let testObject = disposables.add(new ConfigurationService(URI.file('__testFile'), fileService)); await testObject.initialize(); let setting = testObject.getValue<ITestSetting>(); assert.ok(setting); assert.strictEqual(setting.configuration.service.testSetting, 'isSet'); await fileService.writeFile(settingsResource, VSBuffer.fromString('{ "testworkbench.editor.tabs": true }')); testObject = disposables.add(new ConfigurationService(settingsResource, fileService)); setting = testObject.getValue<ITestSetting>(); assert.ok(setting); assert.strictEqual(setting.configuration.service.testSetting, 'isSet'); await fileService.writeFile(settingsResource, VSBuffer.fromString('{ "configuration.service.testSetting": "isChanged" }')); await testObject.reloadConfiguration(); setting = testObject.getValue<ITestSetting>(); assert.ok(setting); assert.strictEqual(setting.configuration.service.testSetting, 'isChanged'); }); test('lookup', async () => { const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ 'id': '_test', 'type': 'object', 'properties': { 'lookup.service.testSetting': { 'type': 'string', 'default': 'isSet' } } }); const testObject = disposables.add(new ConfigurationService(settingsResource, fileService)); testObject.initialize(); let res = testObject.inspect('something.missing'); assert.strictEqual(res.value, undefined); assert.strictEqual(res.defaultValue, undefined); assert.strictEqual(res.userValue, undefined); res = testObject.inspect('lookup.service.testSetting'); assert.strictEqual(res.defaultValue, 'isSet'); assert.strictEqual(res.value, 'isSet'); assert.strictEqual(res.userValue, undefined); await fileService.writeFile(settingsResource, VSBuffer.fromString('{ "lookup.service.testSetting": "bar" }')); await testObject.reloadConfiguration(); res = testObject.inspect('lookup.service.testSetting'); assert.strictEqual(res.defaultValue, 'isSet'); assert.strictEqual(res.userValue, 'bar'); assert.strictEqual(res.value, 'bar'); }); test('lookup with null', async () => { const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ 'id': '_testNull', 'type': 'object', 'properties': { 'lookup.service.testNullSetting': { 'type': 'null', } } }); const testObject = disposables.add(new ConfigurationService(settingsResource, fileService)); testObject.initialize(); let res = testObject.inspect('lookup.service.testNullSetting'); assert.strictEqual(res.defaultValue, null); assert.strictEqual(res.value, null); assert.strictEqual(res.userValue, undefined); await fileService.writeFile(settingsResource, VSBuffer.fromString('{ "lookup.service.testNullSetting": null }')); await testObject.reloadConfiguration(); res = testObject.inspect('lookup.service.testNullSetting'); assert.strictEqual(res.defaultValue, null); assert.strictEqual(res.value, null); assert.strictEqual(res.userValue, null); }); });<|fim▁end|>
<|file_name|>cache.rs<|end_file_name|><|fim▁begin|>use std::env; use std::ffi::OsStr; use std::fs; use std::io::Read; use std::iter; use std::path::{Path, PathBuf}; use app_dirs::{get_app_root, AppDataType}; use flate2::read::GzDecoder; use log::debug; use reqwest::{blocking::Client, Proxy}; use std::time::{Duration, SystemTime}; use tar::Archive; use walkdir::{DirEntry, WalkDir}; use crate::error::TealdeerError::{self, CacheError, UpdateError}; use crate::types::{OsType, PathSource}; #[derive(Debug)] pub struct Cache { url: String, os: OsType, } #[derive(Debug)] pub struct PageLookupResult { page_path: PathBuf, patch_path: Option<PathBuf>, } impl PageLookupResult { pub fn with_page(page_path: PathBuf) -> Self { Self { page_path, patch_path: None, } } pub fn with_optional_patch(mut self, patch_path: Option<PathBuf>) -> Self { self.patch_path = patch_path;<|fim▁hole|> pub fn paths(&self) -> impl Iterator<Item = &Path> { iter::once(self.page_path.as_path()).chain(self.patch_path.as_deref().into_iter()) } } impl Cache { pub fn new<S>(url: S, os: OsType) -> Self where S: Into<String>, { Self { url: url.into(), os, } } /// Return the path to the cache directory. pub fn get_cache_dir() -> Result<(PathBuf, PathSource), TealdeerError> { // Allow overriding the cache directory by setting the // $TEALDEER_CACHE_DIR env variable. if let Ok(value) = env::var("TEALDEER_CACHE_DIR") { let path = PathBuf::from(value); if path.exists() && path.is_dir() { return Ok((path, PathSource::EnvVar)); } return Err(CacheError( "Path specified by $TEALDEER_CACHE_DIR \ does not exist or is not a directory." .into(), )); }; // Otherwise, fall back to user cache directory. match get_app_root(AppDataType::UserCache, &crate::APP_INFO) { Ok(dirs) => Ok((dirs, PathSource::OsConvention)), Err(_) => Err(CacheError( "Could not determine user cache directory.".into(), )), } } /// Download the archive fn download(&self) -> Result<Vec<u8>, TealdeerError> { let mut builder = Client::builder(); if let Ok(ref host) = env::var("HTTP_PROXY") { if let Ok(proxy) = Proxy::http(host) { builder = builder.proxy(proxy); } } if let Ok(ref host) = env::var("HTTPS_PROXY") { if let Ok(proxy) = Proxy::https(host) { builder = builder.proxy(proxy); } } let client = builder.build().unwrap_or_else(|_| Client::new()); let mut resp = client.get(&self.url).send()?; let mut buf: Vec<u8> = vec![]; let bytes_downloaded = resp.copy_to(&mut buf)?; debug!("{} bytes downloaded", bytes_downloaded); Ok(buf) } /// Decompress and open the archive fn decompress<R: Read>(reader: R) -> Archive<GzDecoder<R>> { Archive::new(GzDecoder::new(reader)) } /// Update the pages cache. pub fn update(&self) -> Result<(), TealdeerError> { // First, download the compressed data let bytes: Vec<u8> = self.download()?; // Decompress the response body into an `Archive` let mut archive = Self::decompress(&bytes[..]); // Determine paths let (cache_dir, _) = Self::get_cache_dir()?; // Make sure that cache directory exists debug!("Ensure cache directory {:?} exists", &cache_dir); fs::create_dir_all(&cache_dir) .map_err(|e| UpdateError(format!("Could not create cache directory: {}", e)))?; // Clear cache directory // Note: This is not the best solution. Ideally we would download the // archive to a temporary directory and then swap the two directories. // But renaming a directory doesn't work across filesystems and Rust // does not yet offer a recursive directory copying function. So for // now, we'll use this approach. Self::clear()?; // Extract archive archive .unpack(&cache_dir) .map_err(|e| UpdateError(format!("Could not unpack compressed data: {}", e)))?; Ok(()) } /// Return the duration since the cache directory was last modified. pub fn last_update() -> Option<Duration> { if let Ok((cache_dir, _)) = Self::get_cache_dir() { if let Ok(metadata) = fs::metadata(cache_dir.join("tldr-master")) { if let Ok(mtime) = metadata.modified() { let now = SystemTime::now(); return now.duration_since(mtime).ok(); }; }; }; None } /// Return the platform directory. fn get_platform_dir(&self) -> Option<&'static str> { match self.os { OsType::Linux => Some("linux"), OsType::OsX => Some("osx"), OsType::SunOs => Some("sunos"), OsType::Windows => Some("windows"), OsType::Other => None, } } /// Check for pages for a given platform in one of the given languages. fn find_page_for_platform( page_name: &str, cache_dir: &Path, platform: &str, language_dirs: &[String], ) -> Option<PathBuf> { language_dirs .iter() .map(|lang_dir| cache_dir.join(lang_dir).join(platform).join(page_name)) .find(|path| path.exists() && path.is_file()) } /// Look up custom patch (<name>.patch). If it exists, store it in a variable. fn find_patch(patch_name: &str, custom_pages_dir: Option<&Path>) -> Option<PathBuf> { custom_pages_dir .map(|custom_dir| custom_dir.join(patch_name)) .filter(|path| path.exists() && path.is_file()) } /// Search for a page and return the path to it. pub fn find_page( &self, name: &str, languages: &[String], custom_pages_dir: Option<&Path>, ) -> Option<PageLookupResult> { let page_filename = format!("{}.md", name); let patch_filename = format!("{}.patch", name); let custom_filename = format!("{}.page", name); // Get cache dir let cache_dir = match Self::get_cache_dir() { Ok((cache_dir, _)) => cache_dir.join("tldr-master"), Err(e) => { log::error!("Could not get cache directory: {}", e); return None; } }; let lang_dirs: Vec<String> = languages .iter() .map(|lang| { if lang == "en" { String::from("pages") } else { format!("pages.{}", lang) } }) .collect(); // Look up custom page (<name>.page). If it exists, return it directly if let Some(config_dir) = custom_pages_dir { let custom_page = config_dir.join(custom_filename); if custom_page.exists() && custom_page.is_file() { return Some(PageLookupResult::with_page(custom_page)); } } let patch_path = Self::find_patch(&patch_filename, custom_pages_dir.as_deref()); // Try to find a platform specific path next, append custom patch to it. if let Some(pf) = self.get_platform_dir() { if let Some(page) = Self::find_page_for_platform(&page_filename, &cache_dir, pf, &lang_dirs) { return Some(PageLookupResult::with_page(page).with_optional_patch(patch_path)); } } // Did not find platform specific results, fall back to "common" Self::find_page_for_platform(&page_filename, &cache_dir, "common", &lang_dirs) .map(|page| PageLookupResult::with_page(page).with_optional_patch(patch_path)) } /// Return the available pages. pub fn list_pages(&self) -> Result<Vec<String>, TealdeerError> { // Determine platforms directory and platform let (cache_dir, _) = Self::get_cache_dir()?; let platforms_dir = cache_dir.join("tldr-master").join("pages"); let platform_dir = self.get_platform_dir(); // Closure that allows the WalkDir instance to traverse platform // specific and common page directories, but not others. let should_walk = |entry: &DirEntry| -> bool { let file_type = entry.file_type(); let file_name = match entry.file_name().to_str() { Some(name) => name, None => return false, }; if file_type.is_dir() { if file_name == "common" { return true; } if let Some(platform) = platform_dir { return file_name == platform; } } else if file_type.is_file() { return true; } false }; // Recursively walk through common and (if applicable) platform specific directory let mut pages = WalkDir::new(platforms_dir) .min_depth(1) // Skip root directory .into_iter() .filter_entry(|e| should_walk(e)) // Filter out pages for other architectures .filter_map(Result::ok) // Convert results to options, filter out errors .filter_map(|e| { let path = e.path(); let extension = &path.extension().and_then(OsStr::to_str).unwrap_or(""); if e.file_type().is_file() && extension == &"md" { path.file_stem() .and_then(|stem| stem.to_str().map(|s| s.into())) } else { None } }) .collect::<Vec<String>>(); pages.sort(); pages.dedup(); Ok(pages) } /// Delete the cache directory. pub fn clear() -> Result<(), TealdeerError> { let (path, _) = Self::get_cache_dir()?; if path.exists() && path.is_dir() { fs::remove_dir_all(&path).map_err(|_| { CacheError(format!( "Could not remove cache directory ({}).", path.display() )) })?; } else if path.exists() { return Err(CacheError(format!( "Cache path ({}) is not a directory.", path.display() ))); } else { return Err(CacheError(format!( "Cache path ({}) does not exist.", path.display() ))); }; Ok(()) } } /// Unit Tests for cache module #[cfg(test)] mod tests { use super::*; #[test] fn test_page_lookup_result_iter_with_patch() { let lookup = PageLookupResult::with_page(PathBuf::from("test.page")) .with_optional_patch(Some(PathBuf::from("test.patch"))); let mut iter = lookup.paths(); assert_eq!(iter.next(), Some(Path::new("test.page"))); assert_eq!(iter.next(), Some(Path::new("test.patch"))); assert_eq!(iter.next(), None); } #[test] fn test_page_lookup_result_iter_no_patch() { let lookup = PageLookupResult::with_page(PathBuf::from("test.page")); let mut iter = lookup.paths(); assert_eq!(iter.next(), Some(Path::new("test.page"))); assert_eq!(iter.next(), None); } }<|fim▁end|>
self }
<|file_name|>whatsapp.js<|end_file_name|><|fim▁begin|>/** * WhatsApp service provider<|fim▁hole|> module.exports = { popupUrl: 'whatsapp://send?text={title}%0A{url}', popupWidth: 600, popupHeight: 450 };<|fim▁end|>
*/
<|file_name|>pipeline.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, print_function import logging from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from sentry.pipeline import Pipeline from sentry.models import Identity, IdentityStatus, IdentityProvider from . import default_manager IDENTITY_LINKED = _("Your {identity_provider} account has been associated with your Sentry account") logger = logging.getLogger('sentry.identity') class IdentityProviderPipeline(Pipeline): logger = logger pipeline_name = 'identity_provider' provider_manager = default_manager provider_model_cls = IdentityProvider def redirect_url(self): associate_url = reverse('sentry-extension-setup', kwargs={ # TODO(adhiraj): Remove provider_id from the callback URL, it's unused. 'provider_id': 'default', }) # Use configured redirect_url if specified for the pipeline if available return self.config.get('redirect_url', associate_url) def finish_pipeline(self): identity = self.provider.build_identity(self.state.data) defaults = { 'status': IdentityStatus.VALID, 'scopes': identity.get('scopes', []), 'data': identity.get('data', {}), 'date_verified': timezone.now(), } identity, created = Identity.objects.get_or_create( idp=self.provider_model,<|fim▁hole|> user=self.request.user, external_id=identity['id'], defaults=defaults, ) if not created: identity.update(**defaults) messages.add_message(self.request, messages.SUCCESS, IDENTITY_LINKED.format( identity_provider=self.provider.name, )) self.state.clear() # TODO(epurkhiser): When we have more identities and have built out an # identity management page that supports these new identities (not # social-auth ones), redirect to the identities page. return HttpResponseRedirect(reverse('sentry-account-settings'))<|fim▁end|>
<|file_name|>userThread.py<|end_file_name|><|fim▁begin|>#This thread handles user operations of only 1 user #, and is connected to the matchmaking thread and to the database thread #The list of operations is as follows: #userType: 0 for normal, 1 for facebook # ID | ARGUMENTS # 0 --- User signup | userType(fb or normal),id,name,email,password # 1 --- User login | userType,id,name,email,password # 2 --- Change password | newPassword # 3 --- Forgot password | email,name # 4 --- Confirm password change code| email,name,code # 5 --- Start game | - #The separator in the messages can be a space and messages are terminated with \n #so the final form of the messages is: # 0 0 userType id name email password # 1 1 userType id name email password # 2 2 newPassword # 3 3 email,name # 4 4 email,name,code # 5 5 import socket,Queue from threading import * PORT = 11337 #This function-thread listens on a port for connections def listener(queueToDatabase,queueToMatchMaking,setupSocket): <|fim▁hole|> setupSocket.bind(('0.0.0.0',PORT)) setupSocket.setblocking(True) while True: setupSocket.settimeout(None) setupSocket.listen(1) print 'LISTENING' replySocket,address = setupSocket.accept() #now create a new userThread uThread = Thread(target=userThread,args=(replySocket,queueToDatabase,queueToMatchMaking)) uThread.start() replySocket.send('0\n') print 'Created new user thread' print('Listener Thread ends now') setupSocket.close() #dbQueue is for communicating with database thread #matchQueue is for communicating with matchmaking thread def userThread(replySocket,dbQueue,matchQueue,userType = None,userId = None,name = None,email = None): answerQueue = Queue.Queue() replySocket.settimeout(None) while True: message = replySocket.recv(512) #Connection shut down on other side if len(message) == 0: print 'CLIENT SOCKET SHUT DOWN' break print "MESSAGE IS " + message args = message.split() #After game message if (len(args) == 1 and args[0] != '5'): continue #Now check operation type if args[0] == '0': userType = args[1] userId = args[2] name = args[3] email = args[4] password = args[5] #Check user type if userType == '0':#normal user data = {'operation':0,'answer':answerQueue,'name':name,'email':email,'password':password} elif userType == '1':#Facebook user data = {'operation':1,'answer':answerQueue,'id':userId,'name':name,'email':email} elif args[0] == '1': userType = args[1] userId = args[2] name = None if args[3] == '0' else args[3] email = None if args[4] == '0' else args[4] password = args[5] if userType == '0':#normal user data = {'operation':2,'answer':answerQueue,'name':name,'email':email,'password':password} elif userType == '1':#Facebook user data = {'operation':3,'answer':answerQueue,'id':userId} elif args[0] == '2': password = args[1] data = {'operation':6,'answer':answerQueue,'name':name,'email':email,'newPass':password} elif args[0] == '3': email = None if args[1] == '0' else args[1] name = None if args[2] == '0' else args[2] data = {'operation':7,'answer':answerQueue,'name':name,'email':email} elif args[0] == '4': email = None if args[1] == '0' else args[1] name = None if args[2] == '0' else args[2] code = int(args[3]) data = {'operation':8,'answer':answerQueue,'name':name,'email':email,'code':code} elif args[0] == '5': if userType == '0': data = {'operation':9,'answer':answerQueue,'name':name,'email':email} elif userType == '1': data = {'operation':10,'answer':answerQueue,'id':userId} #get user data dbQueue.put(data) playerToken = answerQueue.get() playerToken['type'] = userType playerToken['socket'] = replySocket #now send to matchmaking thread print 'Send data to %s' % name replySocket.send('0\n') matchQueue.put(playerToken) print 'Send data to match making thread' break #now send data dbQueue.put(data) result = answerQueue.get() print 'result of operation is %r' % result if result: replySocket.send('0\n') else: replySocket.send('1\n') #Terminate thread print 'User Thread out'<|fim▁end|>
#Configure server Socket setupSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #Listen on all interfaces