text
stringlengths
1
1.05M
import re def extract_text_from_html(html): pattern = r'<[^>]*>' clean_html = re.sub(pattern, '', html) # Remove all HTML tags return [clean_html.strip()] # Return the extracted text content as a list
package com.xplmc.example.esdatafeeder.common.config; import org.apache.commons.lang3.StringUtils; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.Assert; import java.net.InetAddress; import java.net.UnknownHostException; /** * Elasticsearch2.x configuration * * @author luke */ @Configuration @EnableConfigurationProperties(MyElasticsearchProperties.class) public class MyElasticsearch2xConfiguration { private static final Logger logger = LoggerFactory.getLogger(MyElasticsearch2xConfiguration.class); private static final String COMMA = ","; private static final String COLON = ":"; private final MyElasticsearchProperties properties; public MyElasticsearch2xConfiguration(MyElasticsearchProperties properties) { this.properties = properties; } @Bean public TransportClient transportClient() throws UnknownHostException { // elasticsearch cluster info Settings settings = Settings.settingsBuilder() .put("client.transport.sniff", true) .put("cluster.name", properties.getClusterName()).build(); // build a TransportClient TransportClient client = TransportClient.builder().settings(settings).build(); // add cluster nodes Assert.hasText(properties.getClusterNodes(), "[Assertion failed]elasticsearch.cluster-nodes not configured"); for (String clusterNode : StringUtils.split(properties.getClusterNodes(), COMMA)) { String hostname = StringUtils.substringBefore(clusterNode, COLON); String port = StringUtils.substringAfter(clusterNode, COLON); Assert.hasText(hostname, "[Assertion failed]wrong elasticsearch.cluster-nodes format,hostname is required"); Assert.hasText(port, "[Assertion failed]wrong elasticsearch.cluster-nodes format,port is required"); logger.info("adding transport address: " + clusterNode); client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostname), Integer.parseInt(port))); } return client; } }
<filename>imports/vx/client/code/master.js import { combineReducers, createStore } from "redux" import { persistStore, persistReducer } from "redux-persist" import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2" import storage from "redux-persist/lib/storage" import { setCurrentLocale } from "/imports/vx/client/code/actions" import {setFunctionUpdateTimestamp} from "/imports/vx/client/code/actions" React = require("react") ReactDOM = require("react-dom") const persistConfig = { key: "root", storage, stateReconciler: autoMergeLevel2, blacklist: ["loading"] } const persistedReducer = persistReducer(persistConfig, combineReducers(VXApp.unionedReducers())) Store = createStore(persistedReducer) Persistor = persistStore(Store, null, () => { const keyCount = Object.keys(Store.getState()).length console.log(`master.js (vx) persistor *rehydration* finished property keyCount=${keyCount}`) }) document.title = Util.i18n("master.page_title") /** * General client-side error handler. Note that JQuery recommendation is NOT to use a JQuery error * event handler for the window object because it is not possible to get the error, URL and line * argument values. */ window.onerror = (error, url, line) => { if (error) { // Seems to occur on iOS if the device sleeps and restarts: if (error.indexOf("INVALID_STATE_ERR") >= 0) { return } // Software is under development and being changed: if (error.indexOf("Uncaught SyntaxError") >= 0) { return } // Reference preview window is displaying something that is imposing "same origin" policy: if (error.indexOf("Script error") >= 0) { return } // Chrome iOS throws this, but it has no symptoms: if (error.indexOf("SyntaxError: Unexpected token ')'") >= 0) { return } } OLog.error(`master.js window onerror event, error=${error} url=${url} line=${line}`) } document.addEventListener("touchstart", event => { UX.touchCount = event.touches.length }, false) document.addEventListener("touchend", event => { UX.touchCount = event.touches.length }, false) /** * Detects changes in user logLevel. */ Tracker.autorun(() => { let logLevel = Util.getProfileValue("logLevel") if (_.isNumber(logLevel)) { OLog.setLogLevel(logLevel) } }) Tracker.autorun(() => { let locale = Util.getProfileValue("locale") Store.dispatch(setCurrentLocale(locale)) }) Tracker.autorun(function() { // Reactive: if user ID changes, re-initialize: let userId = Meteor.userId() if (!userId) { if (UXState.notificationObserver) { console.log("master.js autorun notification observer *stop*") UXState.notificationObserver.stop() UXState.notificationObserver = null } return } let myNotificationsRequest = {} myNotificationsRequest.criteria = { recipientId : userId, PNOTIFY_processed : { $exists : false }, date : { $gte : new Date() } } myNotificationsRequest.options = { sort : { date : -1 } } console.log("master.js autorun notification observer *subscribe*") Meteor.subscribe("my_notifications", myNotificationsRequest) // Timeout allows initialization to complete. Without this PNotify can throw errors during initialization trying to find // attribute CSS on an element that doesn't exist: Meteor.setTimeout(() => { UXState.notificationObserver = Notifications.find(myNotificationsRequest.criteria, myNotificationsRequest.options).observeChanges({ added : (id) => { let notification = Notifications.findOne({ _id : id }) if (!notification) { OLog.error(`master.js autorun notification observer could not find notificationId=${id}`) return } if (notification.PNOTIFY_processed) { return } // Strange, somehow it is possible during login/logout transition for this observer to still be observing the // previously-logged-in user. Let's make sure that this notification is for our user: if (notification.recipientId !== Meteor.userId()) { return } //console.log("master.js autorun: notification observer notificationId=" + id + " *added*", notification) if (Util.isNotificationDesired(notification, "PNOTIFY")) { // Sherpa has special checkbox for verbose notifications: if (Meteor.user().profile.verboseNotifications || notification.type === "ERROR") { let type = CX.NOTIFICATION_TYPE_MAP[notification.type] let icon = CX.NOTIFICATION_ICON_MAP[notification.icon] let text = Util.i18n(notification.key, notification.variables) UX.createNotification({ type : type, text : text, icon : icon }) } } // Let's give the systems five seconds before clearing so that notifications will be shown // on all workstations prior to clearing (users may be logged into multiple browser pages at the same time): Meteor.setTimeout(() => { Meteor.call("clearPNotify", id, true, (error, result) => { UX.notify(result, error, true) }) }, 5000) } }) }, 1000) }) Tracker.autorun(function() { const userId = Meteor.userId() if (!userId) { if (UXState.functionObserver) { UXState.functionObserver.stop() UXState.functionObserver = null } return } // Set up dependency on domain ID changes run tracker Util.getCurrentDomainId(userId) // Wait until we have publishing criteria in redux: let publishCurrentFunctions = Util.clone(Store.getState().publishCurrentFunctions) if (!publishCurrentFunctions) { // This can run prior to redux initialization but it will re-run later: return } publishCurrentFunctions.criteria.dateModified = { $gt: new Date() } Meteor.subscribe("my_functions", publishCurrentFunctions) UXState.functionObserver = Functions.find(publishCurrentFunctions.criteria).observe({ added : (newDocument) => { VXApp.addFunction(newDocument) }, changed : (newDocument, oldDocument) => { VXApp.changeFunction(newDocument, oldDocument) Store.dispatch(setFunctionUpdateTimestamp(new Date().toISOString())) }, removed : (oldDocument) => { VXApp.removeFunction(oldDocument) } }) })
<?php session_start(); $cookie_name = "session_token"; $cookie_value = md5(uniqid(rand(), true)); setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); ?>
/* * numerical integration example, as discussed in textbook: * * compute pi by approximating the area under the curve f(x) = 4 / (1 + x*x) * between 0 and 1. * * sequential version. */ #include <cstdio> #include <cstdlib> #include <cmath> /* copied from not-strictly-standard part of math.h */ #define M_PI 3.14159265358979323846 #include "timer.h" #define NUM_STEPS 400000000 /* main program */ int main(int argc, char *argv[]) { double start_time, end_time; double x, pi; double sum = 0.0; double step = 1.0/(double) NUM_STEPS; /* record start time */ start_time = get_time(); /* do computation */ for (int i=0; i < NUM_STEPS; ++i) { x = (i+0.5)*step; sum += 4.0/(1.0+x*x); } pi = step * sum; /* record end time */ end_time = get_time(); /* print results */ printf("sequential program results with %d steps:\n", NUM_STEPS); printf("computed pi = %g (%17.15f)\n",pi, pi); printf("difference between computed pi and math.h M_PI = %17.15f\n", fabs(pi - M_PI)); printf("time to compute = %g seconds\n", end_time - start_time); return EXIT_SUCCESS; }
#!/bin/bash #SBATCH -J Act_elu_1 #SBATCH --mail-user=eger@ukp.informatik.tu-darmstadt.de #SBATCH --mail-type=FAIL #SBATCH -e /work/scratch/se55gyhe/log/output.err.%j #SBATCH -o /work/scratch/se55gyhe/log/output.out.%j #SBATCH -n 1 # Number of cores #SBATCH --mem-per-cpu=2000 #SBATCH -t 23:59:00 # Hours, minutes and seconds, or '#SBATCH -t 10' -only mins #module load intel python/3.5 python3 /home/se55gyhe/Act_func/progs/meta.py elu 1 Adadelta 3 0.6651367297196616 375 1.03524375410082 glorot_normal PE-infersent
/* * Copyright 2017-present Open Networking Foundation * * 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.onosproject.d.config.sync.impl.netconf; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.onosproject.d.config.sync.DeviceConfigSynchronizationProviderRegistry; import org.onosproject.d.config.sync.DeviceConfigSynchronizationProviderService; import org.onosproject.net.device.DeviceService; import org.onosproject.net.provider.ProviderId; import org.onosproject.netconf.NetconfController; import org.onosproject.yang.model.SchemaContextProvider; import org.onosproject.yang.runtime.YangRuntimeService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.Beta; /** * Main component of Dynamic config synchronizer for NETCONF. * <p> * <ul> * <li> bootstrap Active and Passive synchronization modules * <li> start background anti-entropy mechanism for offline device configuration * </ul> */ @Component(immediate = true) public class NetconfDeviceConfigSynchronizerComponent { private final Logger log = LoggerFactory.getLogger(getClass()); /** * NETCONF dynamic config synchronizer provider ID. */ public static final ProviderId PID = new ProviderId("netconf", "org.onosproject.d.config.sync.netconf"); @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected DeviceConfigSynchronizationProviderRegistry registry; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected NetconfController netconfController; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected YangRuntimeService yangRuntimeService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected SchemaContextProvider schemaContextProvider; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected DeviceService deviceService; private NetconfDeviceConfigSynchronizerProvider provider; private DeviceConfigSynchronizationProviderService providerService; @Activate protected void activate() { provider = new NetconfDeviceConfigSynchronizerProvider(PID, new InnerNetconfContext()); providerService = registry.register(provider); // TODO (Phase 2 or later) // listen to NETCONF events (new Device appeared, etc.) // for PASSIVE "state" synchronization upward // TODO listen to DeviceEvents (Offline pre-configuration scenario) // TODO background anti-entropy mechanism log.info("Started"); } @Deactivate protected void deactivate() { registry.unregister(provider); log.info("Stopped"); } /** * Context object to provide reference to OSGi services, etc. */ @Beta public static interface NetconfContext { /** * Returns DeviceConfigSynchronizationProviderService interface. * * @return DeviceConfigSynchronizationProviderService */ DeviceConfigSynchronizationProviderService providerService(); SchemaContextProvider schemaContextProvider(); YangRuntimeService yangRuntime(); NetconfController netconfController(); } class InnerNetconfContext implements NetconfContext { @Override public NetconfController netconfController() { return netconfController; } @Override public YangRuntimeService yangRuntime() { return yangRuntimeService; } @Override public SchemaContextProvider schemaContextProvider() { return schemaContextProvider; } @Override public DeviceConfigSynchronizationProviderService providerService() { return providerService; } } }
const dateArr = date.split('/'); const day = dateArr[1]; const month = dateArr[0]; console.log('Day:', day); console.log('Month:', month);
#include <UUIDGenerator.h> UUIDGenerator::UUIDGenerator() { } UUIDGenerator::~UUIDGenerator() { } std::string UUIDGenerator::createUuid() { boost::uuids::uuid uuid = boost::uuids::random_generator()(); return boost::uuids::to_string(uuid); }
def find_min(arr): # Initialize the minimum value min_val = arr[0] # Iterate through the array for i in range(1, len(arr)): if arr[i] < min_val: min_val = arr[i] return min_val
function countSubstring(str1, str2) { let count = 0; for (let i = 0; i < str1.length; i++) { if (str1[i] === str2[0]) { let isSubstring = true; for (let j = 0; j < str2.length; j++) { if (str1[i + j] !== str2[j]) { isSubstring = false; break; } } if (isSubstring) { count++; i += str2.length - 1; } } } return count; }
import Visualizer from '../classes/visualizer' import { interpolateRgb, interpolateBasis, interpolateHcl } from 'd3-interpolate' import { getRandomElement } from '../util/array' import { fractalmirror } from '../util/canvases/rotating_fractal_mirror' import { rainbow } from '../util/color_themes' export default class RotatingFractalMirror extends Visualizer { constructor () { super({ volumeSmoothing: 10 }) this.theme = rainbow this.counter = 1 this.rotation = 20 this.height = 200 this.section = 0 this.overallRotation = 0 this.sidesList = [5, 6, 8] this.sides=5 } hooks () { this.sync.on('tatum', tatum => { if (this.rotation>300) { this.rotation=60 } if (this.rotation>150 && this.rotation<210) { this.rotation=210 } if (this.overallRotation>360) { this.overallRotation=0 } this.rotation++ this.overallRotation++ }) this.sync.on('beat', beat => { if (this.rotation>300) { this.rotation=60 } if (this.rotation>150 && this.rotation<210) { this.rotation=210 } if (this.overallRotation>360) { this.overallRotation=0 } this.rotation+= 2 this.overallRotation++ }) this.sync.on('bar', bar => { this.lastColor = this.nextColor || getRandomElement(this.theme) this.nextColor = getRandomElement(this.theme.filter(color => color !== this.nextColor)) this.counter++ if (this.counter%15==0) { this.counter=1 } }) this.sync.on('segment', segment => { //on every segment }) this.sync.on('section', section => { //on every section this.sides = getRandomElement(this.sidesList) }) } paint ({ ctx, height, width, now }) { const bar = interpolateBasis([0, this.sync.volume * 10, 0])(this.sync.bar.progress) const beat = interpolateBasis([0, this.sync.volume * 300, 0])(this.sync.beat.progress) const tatum = interpolateBasis([0, this.sync.volume * 200, 0])(this.sync.tatum.progress) ctx.fillStyle = 'rgba(0, 0, 0, .3)' //Fill the background black at alpha 0.3 for fade effect ctx.fillRect(0, 0, width, height) //Fill the whole screen ctx.lineWidth = 1 // Define line width ctx.strokeStyle = interpolateHcl(this.lastColor, this.nextColor)(this.sync.bar.progress) // transition between colors smoothly fractalmirror(ctx, this.height, width/2, height/2, this.rotation, this.overallRotation, 12) // fractalmirror(ctx, this.height, width/4, height/2, this.rotation, this.overallRotation, this.sides) // fractalmirror(ctx, this.height, (3*width)/4, height/2, this.rotation, this.overallRotation, this.sides) ctx.stroke() } }
package org.f5n.aoc2020.days; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.f5n.aoc2020.utils.Day; import org.f5n.aoc2020.utils.Input; import org.f5n.aoc2020.utils.IntResult; import org.f5n.aoc2020.utils.Result; import org.f5n.aoc2020.utils.Utils; public class Day15 extends Day { protected List<Integer> input; public Day15(List<Integer> input) { this.input = input; this.input.add(0, 0); } private int run (int limit) { int i = 1; int cur = 0; int last = 0; Map<Integer, ArrayList<Integer>> r = new HashMap<Integer, ArrayList<Integer>>(); while (i <= limit) { if (i < input.size()) { last = input.get(i); ArrayList<Integer> li = new ArrayList<Integer>(); li.add(i); r.put(last, li); ++i; continue; } if (r.containsKey(last)) { if (r.get(last).size() == 1) { cur = 0; r.get(cur).add(i); } else { int len = r.get(last).size(); cur = r.get(last).get(len-1) - r.get(last).get(len-2); if (!r.containsKey(cur)) { r.put(cur, new ArrayList<Integer>()); } r.get(cur).add(i); while (r.get(cur).size() > 2) { r.get(cur).remove(0); } } } last = cur; ++i; } return cur; } protected Result part1(Input limit) { int cur = run(limit.getIntValue()); return new IntResult(cur); } protected Result part2(Input limit) { int cur = run(limit.getIntValue()); return new IntResult(cur); } }
/*! * Copyright (c) 2019 Digital Bazaar, Inc. All rights reserved. */ 'use strict'; export {default as BrAddressForm} from './BrAddressForm.vue';
<filename>Magazine-Api/src/main/java/DB/DAOs/Magazine/Financials/AdUpdate.java package DB.DAOs.Magazine.Financials; import DB.DBConnection; import DB.Domain.Financial.Ad; import BackendUtilities.Parser; import java.sql.PreparedStatement; import java.sql.SQLException; /** * * @author jefemayoneso */ public class AdUpdate { Parser parser = new Parser(); private final String SQL_UPDATE_AD = "UPDATE `Ad` SET advertiser_paid=?,expiration_date=?,start_date=?,shown_counter=?,type=?,advertiser=?,shown_url=?," + "video_url=?,img_local_path=?,text=? WHERE (id=?)"; public int update(Ad ad) { try ( PreparedStatement ps = DBConnection.getConnection().prepareStatement(SQL_UPDATE_AD)) { configurePsUpdate(ps, ad); return ps.executeUpdate(); } catch (Exception e) { System.out.println("Cannot update Ad at [AdUpdate] " + e.getMessage()); return 0; } } private void configurePsUpdate(PreparedStatement ps, Ad ad) throws SQLException { new AdInsert().configurePsInsertAd(ps, ad); ps.setInt(11, ad.getId()); } }
import { Component } from "@angular/core"; @Component({ selector: 'pm-products', templateUrl: './product-list.component.html' }) export class ProductListComponent{ pageTitle: string = "Product List"; imageWidth: number = 50; imageMargin: number = 2; showImage: boolean = false; products: any[] = [ { "productId" : 1, "productName" : 'Golden Cart', "productCode" : 'PM001', "price" : 2, "available": true, "rating" : 4.5, "imageUrl" : 'assets/images/garden_cart.png' }, { "productId" : 2, "productName" : 'Hammer', "productCode" : 'PM002', "price" : 3, "available": false, "rating" : 3.5, "imageUrl" : 'assets/images/hammer.png' } ] /** this method will toggle the image listed on web page*/ toggleImage(): void{ this.showImage = !this.showImage; } }
#!/bin/bash # # Usage: # ./html.sh <function name> set -o nounset set -o pipefail set -o errexit basic-head() { local title=$1 cat <<EOF <!DOCTYPE html> <html> <head> <title>$title</title> <style> body { margin: 0 auto; width: 40em; } #home-link { text-align: right; } </style> </head> <body> <p id="home-link"> <a href="/">oilshell.org</a> </p> <h3>$title</h3> <p> EOF } basic-tail() { cat <<EOF </body> </html> EOF } "$@"
package org.springframework.transaction.interceptor; import org.aopalliance.aop.Advice; import org.springframework.aop.ClassFilter; import org.springframework.aop.Pointcut; import org.springframework.aop.support.AbstractPointcutAdvisor; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * Advisor driven by a {@link TransactionAttributeSource}, used to include * a {@link TransactionInterceptor} only for methods that are transactional. * * <p>Because the AOP framework caches advice calculations, this is normally * faster than just letting the TransactionInterceptor run and find out * itself that it has no work to do. * * @author <NAME> * @author <NAME> * @see #setTransactionInterceptor * @see TransactionProxyFactoryBean */ @SuppressWarnings("serial") public class TransactionAttributeSourceAdvisor extends AbstractPointcutAdvisor { @Nullable private TransactionInterceptor transactionInterceptor; private final TransactionAttributeSourcePointcut pointcut = new TransactionAttributeSourcePointcut() { @Override @Nullable protected TransactionAttributeSource getTransactionAttributeSource() { return (transactionInterceptor != null ? transactionInterceptor.getTransactionAttributeSource() : null); } }; /** * Create a new TransactionAttributeSourceAdvisor. */ public TransactionAttributeSourceAdvisor() { } /** * Create a new TransactionAttributeSourceAdvisor. * @param interceptor the transaction interceptor to use for this advisor */ public TransactionAttributeSourceAdvisor(TransactionInterceptor interceptor) { setTransactionInterceptor(interceptor); } /** * Set the transaction interceptor to use for this advisor. */ public void setTransactionInterceptor(TransactionInterceptor interceptor) { this.transactionInterceptor = interceptor; } /** * Set the {@link ClassFilter} to use for this pointcut. * Default is {@link ClassFilter#TRUE}. */ public void setClassFilter(ClassFilter classFilter) { this.pointcut.setClassFilter(classFilter); } @Override public Advice getAdvice() { Assert.state(this.transactionInterceptor != null, "No TransactionInterceptor set"); return this.transactionInterceptor; } @Override public Pointcut getPointcut() { return this.pointcut; } }
/* * Universidad Carlos III de Madrid (UC3M) * Programacion 2016-2017 */ package bomberman; import bomberman.client.ClientManager; import bomberman.server.GameEngine; /** * The main class of the MiniDungeon game. * * @author Planning and Learning Group (PLG) */ public class Game extends Constants { /** * The entry point of the application * * @param args * the command line arguments * @throws java.lang.InterruptedException */ public static void main(String[] args) throws InterruptedException { // Game initialization System.out.println("Strarting..."); boolean runApplication = true; GameEngine engine= new GameEngine(); ClientManager manager = new ClientManager(engine); String lastAction = ""; /////////////// // GAME LOOP // /////////////// //long contador=0; while (runApplication) { // si el jugador muere se acaba el juego if (engine.isGameFinished()) { engine.setAlert("Game Over"); runApplication = false; } //Calculate next game state engine.performAction(lastAction); //if (engine.getAlert()) { //} //Update game screen manager.updateView(lastAction); //Get last action from user. lastAction = manager.getLastAction(); // Adequate way to exit the program if (lastAction.equalsIgnoreCase("exit game")){ runApplication=false; } try{ // IMPORTANT THREAD METHOD Thread.sleep((long) (1 / (double) G_FPS * 1000)); System.out.println(engine.getContador()); engine.setContador(engine.getContador()+1); }catch(InterruptedException ie){ System.out.println("Game Loop Error: "); ie.printStackTrace(); } } System.out.println("...end of program"); System.exit(0); } }
IN_MB=(1024*1024) INFO=cat /proc/net/dev | grep "wlan" | awk '{print $2/IN_MB}' notify-send -h int:y:10 -u normal -t 10000 "Total Bytes Received ${INFO}"
<filename>spark/spark-tensorflow-connector/src/main/scala/org/tensorflow/spark/datasources/tfrecords/udf/DataFrameTfrConverter.scala package org.tensorflow.spark.datasources.tfrecords.udf //import com.sun.rowset.internal.Row import org.apache.spark.sql.Row import org.apache.spark.sql.expressions.UserDefinedFunction import org.apache.spark.sql.functions.udf import org.tensorflow.spark.datasources.tfrecords.serde.DefaultTfRecordRowEncoder object DataFrameTfrConverter { def getRowToTFRecordExampleUdf: UserDefinedFunction = udf(rowToTFRecordExampleUdf _ ) private def rowToTFRecordExampleUdf(row: Row): Array[Byte] = { DefaultTfRecordRowEncoder.encodeExample(row).toByteArray } def getRowToTFRecordSequenceExampleUdf: UserDefinedFunction = udf(rowToTFRecordSequenceExampleUdf _ ) private def rowToTFRecordSequenceExampleUdf(row: Row): Array[Byte] = { DefaultTfRecordRowEncoder.encodeSequenceExample(row).toByteArray } }
<filename>spec/teambition/has_teambition_account_spec.rb describe Teambition::HasTeambitionAccout do before(:example) do @base = Class.new { include Teambition::HasTeambitionAccout } end it 'wraps API' do obj = Class.new(@base) do has_teambition_account token: :token, namespace: :tb end.new obj.define_singleton_method(:token) { 'my-token' } expect(obj.tb.token).to eql(obj.token) end context 'with nil token' do it 'fails' do expect do Class.new(@base) do has_teambition_account token: nil end.new end.to raise_error(ArgumentError) end end context 'with nil namespace' do it 'mix-in API with a token delegation' do obj = Class.new(@base) do attr_accessor :my_token has_teambition_account token: :my_token, namespace: nil end.new obj.my_token = 'my-token' expect(obj.token).to eql('my-token') end context 'when delegate :token to :token' do it 'still works' do # This situation equals to `include Teambition::API` directly obj = Class.new(@base) do has_teambition_account token: :token, namespace: nil end.new obj.token = 'my-token' expect(obj.token).to eql('my-token') end end end end
import React from 'react' import ValidatedForm from 'core/components/validatedForm/ValidatedForm' import PicklistField from 'core/components/validatedForm/PicklistField' import SubmitButton from 'core/components/SubmitButton' import createAddComponents from 'core/helpers/createAddComponents' import ClusterPicklist from 'k8s/components/common/ClusterPicklist' import NamespacePicklist from 'k8s/components/common/NamespacePicklist' import RbacChecklist from './RbacChecklist' import TextField from 'core/components/validatedForm/TextField' import { rolesCacheKey } from './actions' import useParams from 'core/hooks/useParams' const defaultParams = { rbac: {}, } export const AddRoleForm = ({ onComplete }) => { const { params, getParamsUpdater } = useParams(defaultParams) return ( <ValidatedForm onSubmit={onComplete}> <TextField id="name" label="Name" required /> <PicklistField DropdownComponent={ClusterPicklist} id="clusterId" label="Cluster" onChange={getParamsUpdater('clusterId')} value={params.clusterId} required /> <PicklistField DropdownComponent={NamespacePicklist} disabled={!params.clusterId} id="namespace" label="Namespace" clusterId={params.clusterId} onChange={getParamsUpdater('namespace')} value={params.namespace} required /> { params.clusterId && <RbacChecklist id="rbac" clusterId={params.clusterId} onChange={getParamsUpdater('rbac')} value={params.rbac} /> } <SubmitButton>Add Role</SubmitButton> </ValidatedForm> ) } export const options = { cacheKey: rolesCacheKey, FormComponent: AddRoleForm, listUrl: '/ui/kubernetes/rbac', name: 'AddRole', title: 'Add Role', } const { AddPage } = createAddComponents(options) export default AddPage
package com.ctrip.persistence.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.ctrip.persistence.repository.ElementTplParamGroupRepository; import com.ctrip.persistence.service.ElementTplParamGroupService; /** * Created by juntao on 2/3/16. * * @author <EMAIL> */ @Service public class ElementTplParamGroupServiceImpl implements ElementTplParamGroupService { @Resource private ElementTplParamGroupRepository elementTplParamGroupRepository; @Override public String getNameById(Long id) { // TODO Auto-generated method stub return elementTplParamGroupRepository.getNameById(id); } }
<filename>docs/dir_d328eab022aecca8ee55c02040e03a9a.js var dir_d328eab022aecca8ee55c02040e03a9a = [ [ "process.h", "process_8h.html", [ [ "Process", "class_tux_proc_1_1_process.html", "class_tux_proc_1_1_process" ] ] ], [ "region.h", "region_8h.html", [ [ "Region", "class_tux_proc_1_1_region.html", "class_tux_proc_1_1_region" ] ] ] ];
package com.modesteam.urutau.builder; import com.modesteam.urutau.model.UrutaUser; import com.modesteam.urutau.model.system.Password; public class UserBuilder { private String email; private String login; private String name; private String lastName; private String password; private String passwordVerify; private Long id; public UserBuilder id(Long id) { this.id = id; return this; } public UserBuilder email(String email) { this.email = email; return this; } public UserBuilder login(String login) { this.login = login; return this; } public UserBuilder name(String name) { this.name = name; return this; } public UserBuilder lastName(String lastName) { this.lastName = lastName; return this; } public UserBuilder password(String password) { this.password = password; return this; } public UserBuilder passwordVerify(String passwordVerify) { this.passwordVerify = passwordVerify; return this; } public UrutaUser build() { UrutaUser user = new UrutaUser(); user.setUserID(id); user.setEmail(email); user.setLogin(login); user.setName(name); user.setLastName(lastName); Password p = new Password(); p.setUserPasswordPassed(password); user.setPassword(p); user.setPasswordVerify(passwordVerify); return user; } }
#!/bin/bash set -exu export DEBIAN_FRONTEND=noninteractive apt update apt install -V -y lsb-release . $(dirname $0)/commonvar.sh apt install -V -y \ ${repositories_dir}/${distribution}/pool/${code_name}/${channel}/*/*/*_${architecture}.deb td-agent --version case ${code_name} in xenial) apt install -V -y gnupg wget apt-transport-https ;; *) apt install -V -y gnupg1 wget ;; esac /usr/sbin/td-agent-gem install --no-document serverspec wget -qO - https://packages.confluent.io/deb/6.0/archive.key | apt-key add - echo "deb [arch=${architecture}] https://packages.confluent.io/deb/6.0 stable main" > /etc/apt/sources.list.d/confluent.list apt update && apt install -y confluent-community-2.13 ${java_jdk} netcat-openbsd export KAFKA_OPTS=-Dzookeeper.4lw.commands.whitelist=ruok /usr/bin/zookeeper-server-start /etc/kafka/zookeeper.properties & N_POLLING=30 n=1 while true ; do sleep 1 status=$(echo ruok | nc localhost 2181) if [ "$status" = "imok" ]; then break fi n=$((n + 1)) if [ $n -ge $N_POLLING ]; then echo "failed to get response from zookeeper-server" exit 1 fi done /usr/bin/kafka-server-start /etc/kafka/server.properties & n=1 while true ; do sleep 1 status=$(/usr/bin/zookeeper-shell localhost:2181 ls /brokers/ids | sed -n 6p) if [ "$status" = "[0]" ]; then break fi n=$((n + 1)) if [ $n -ge $N_POLLING ]; then echo "failed to get response from kafka-server" exit 1 fi done /usr/bin/kafka-topics --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test /usr/sbin/td-agent -c /fluentd/serverspec/test.conf & export PATH=/opt/td-agent/bin:$PATH export INSTALLATION_TEST=true cd /fluentd && rake serverspec:linux
#!/bin/sh # Sequential search times for n>=131,072 were too costly. We skipped # these; your mileage may vary CODE=../../../../Code BIN=$CODE/bin NT=100 SZ=524288 P="1.0 0.5 0.0" Z="4096 8192 16384 32768 65536 131072 262144 524288" REPORT=table5-2.output rm -f $REPORT CONFIG=config5-2.rc for z in $Z do for p in $P do echo "# generated" > $CONFIG # Just BinaryTree for >= 131072, otherwise both if [ $z -ge 131072 ] then echo "BINS=$CODE/Search/binarySearchInteger" >> $CONFIG else echo "BINS=$CODE/Search/binarySearchInteger $CODE/Search/searchInteger" >> $CONFIG fi echo "TRIALS=$NT" >> $CONFIG echo "LOW=$SZ" >> $CONFIG echo "HIGH=$SZ" >> $CONFIG echo "INCREMENT=*2" >> $CONFIG echo "EXTRAS=-p $p -z $z" >> $CONFIG LINE=`$BIN/suiteRun.sh $CONFIG | tail -1 | sed 's/,/ /g' | awk '{print $2 " " $3; }'` echo "$z $p $LINE" >> $REPORT done done awk -f table5-2.awk $REPORT rm -f $REPORT $CONFIG
import os from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import Session from typing import Tuple from .models.implementation import Base def setup_database(logger, db_filename) -> Tuple[Session, bool]: """Create new SQLite daabase and set up connection""" # https://docs.sqlalchemy.org/en/latest/dialects/sqlite.html url = "sqlite+pysqlite:///" + db_filename engine = create_engine(url, echo=False) if not os.path.exists(db_filename): logger.info("Initializing new database %s", db_filename) init_db(engine) new = True else: new = False Session = sessionmaker(bind=engine) session = Session(autocommit=True) return session, new def init_db(engine): Base.metadata.create_all(engine)
"""This package contains modules with utility functions for acceptance, acceptance and performance tests. """ __author__ = "<NAME>" __copyright__ = "Copyright (C) 2016 ACK CYFRONET AGH" __license__ = "This software is released under the MIT license cited in " \ "LICENSE.txt"
package io.github.brightloong.leetcode.top.interview; /** * @author BrightLoong * @date 2020/3/11 09:28 * @description */ public class Num1013 { public static boolean canThreePartsEqualSum(int[] A) { if (A == null) { return false; } //计算和 int sum = 0; for (int value : A) { sum += value; } //不能被3整除 if (sum % 3 != 0) { return false; } int sum1 = 0; int i = 0; for (int value : A) { //取第一个满足的索引就好,反正到第二个满足的中间这一段相加=0 sum1 += value; if (sum1 == sum/3) { sum1 = 0; i++; } } return i>=3; } public static void main(String[] args) { System.out.println(canThreePartsEqualSum(new int[]{1,-1,1,-1})); } }
/* 1: */ package com.four.common.tpm; /* 2: */ /* 3: */ import java.io.Serializable; /* 4: */ import java.sql.Timestamp; /* 5: */ /* 6: */ public class RecordTpm /* 7: */ implements Serializable /* 8: */ { /* 9: */ protected Long devId; /* 10: */ protected Long userId; /* 11: */ protected Timestamp timestamp; /* 12: 13 */ protected Boolean isNative = Boolean.valueOf(true); /* 13: */ protected String photoPath; /* 14: */ protected Timestamp create; /* 15: */ protected Long creatorId; /* 16: */ protected Timestamp modifyTime; /* 17: */ protected Long modifierId; /* 18: */ protected String verify; /* 19: 22 */ protected Integer validate = Integer.valueOf(1); /* 20: */ /* 21: */ public Long getDevId() /* 22: */ { /* 23: 25 */ return this.devId; /* 24: */ } /* 25: */ /* 26: */ public void setDevId(Long devId) /* 27: */ { /* 28: 29 */ this.devId = devId; /* 29: */ } /* 30: */ /* 31: */ public Long getUserId() /* 32: */ { /* 33: 33 */ return this.userId; /* 34: */ } /* 35: */ /* 36: */ public void setUserId(Long userId) /* 37: */ { /* 38: 37 */ this.userId = userId; /* 39: */ } /* 40: */ /* 41: */ public Timestamp getTimestamp() /* 42: */ { /* 43: 41 */ return this.timestamp; /* 44: */ } /* 45: */ /* 46: */ public void setTimestamp(Timestamp timestamp) /* 47: */ { /* 48: 45 */ this.timestamp = timestamp; /* 49: */ } /* 50: */ /* 51: */ public Boolean getIsNative() /* 52: */ { /* 53: 49 */ return this.isNative; /* 54: */ } /* 55: */ /* 56: */ public void setIsNative(Boolean isNative) /* 57: */ { /* 58: 53 */ this.isNative = isNative; /* 59: */ } /* 60: */ /* 61: */ public String getPhotoPath() /* 62: */ { /* 63: 57 */ return this.photoPath; /* 64: */ } /* 65: */ /* 66: */ public void setPhotoPath(String photoPath) /* 67: */ { /* 68: 61 */ this.photoPath = photoPath; /* 69: */ } /* 70: */ /* 71: */ public Timestamp getCreate() /* 72: */ { /* 73: 65 */ return this.create; /* 74: */ } /* 75: */ /* 76: */ public void setCreate(Timestamp create) /* 77: */ { /* 78: 69 */ this.create = create; /* 79: */ } /* 80: */ /* 81: */ public Long getCreatorId() /* 82: */ { /* 83: 73 */ return this.creatorId; /* 84: */ } /* 85: */ /* 86: */ public void setCreatorId(Long creatorId) /* 87: */ { /* 88: 77 */ this.creatorId = creatorId; /* 89: */ } /* 90: */ /* 91: */ public Timestamp getModifyTime() /* 92: */ { /* 93: 81 */ return this.modifyTime; /* 94: */ } /* 95: */ /* 96: */ public void setModifyTime(Timestamp modifyTime) /* 97: */ { /* 98: 85 */ this.modifyTime = modifyTime; /* 99: */ } /* 100: */ /* 101: */ public Long getModifierId() /* 102: */ { /* 103: 89 */ return this.modifierId; /* 104: */ } /* 105: */ /* 106: */ public void setModifierId(Long modifierId) /* 107: */ { /* 108: 93 */ this.modifierId = modifierId; /* 109: */ } /* 110: */ /* 111: */ public String getVerify() /* 112: */ { /* 113: 97 */ return this.verify; /* 114: */ } /* 115: */ /* 116: */ public void setVerify(String verify) /* 117: */ { /* 118:101 */ this.verify = verify; /* 119: */ } /* 120: */ /* 121: */ public Integer getValidate() /* 122: */ { /* 123:105 */ return this.validate; /* 124: */ } /* 125: */ /* 126: */ public void setValidate(Integer validate) /* 127: */ { /* 128:109 */ this.validate = validate; /* 129: */ } /* 130: */ } /* Location: E:\Henuo\public\public\bin\convertdata-1.0.jar * Qualified Name: com.four.common.tpm.RecordTpm * JD-Core Version: 0.7.0.1 */
<gh_stars>1-10 package com.levy.oa.model; import java.util.List; public class GeneralManagerModel extends StaffModel<GeneralManagerModel> { private static final long serialVersionUID = 4853123355218348139L; private final int classNum = 1; private List<VicePresidentModel> vps; public GeneralManagerModel(){ set("classN",classNum); } }
class Temperature { let fahrenheitValue: Double init(fahrenheitValue: Double) { self.fahrenheitValue = fahrenheitValue } func celsiusValue() -> Double { return (fahrenheitValue - 32) * 5/9 } func stringFromTemperature() -> String { let celsius = celsiusValue() return "\(Int(celsius))°" } } let temperature = Temperature(fahrenheitValue: 32) let formatter = TemperatureFormatter() print(formatter.stringFromTemperature(temperature)) // Output: "0°"
# Install guest additions sudo apt-get install virtualbox-guest-dkms sudo apt-get install git # Change directory cd ~/VirtualBox\ VMs/ # Set variables VM_NAME="ubuntu16" VM_HD_PATH="ubuntu16.vdi" # The path to VM hard disk (to be created). HD_SIZE=10000 RAM_SIZE=4096 VRAM_SIZE=128 VM_ISO_PATH=~/ubuntu-16.04.3-server-amd64.iso # Change path as needed # SHARED_PATH=~ # Share home directory with the VM # Create and modify VM spec vboxmanage createvm --name $VM_NAME --ostype Ubuntu_64 --register vboxmanage createhd --filename $VM_NAME.vdi --size $HD_SIZE vboxmanage storagectl $VM_NAME --name "SATA Controller" --add sata --controller IntelAHCI vboxmanage storageattach $VM_NAME --storagectl "SATA Controller" --port 0 --device 0 --type hdd --medium $VM_HD_PATH vboxmanage storagectl $VM_NAME --name "IDE Controller" --add ide vboxmanage storageattach $VM_NAME --storagectl "IDE Controller" --port 0 --device 0 --type dvddrive --medium $VM_ISO_PATH vboxmanage modifyvm $VM_NAME --ioapic on vboxmanage modifyvm $VM_NAME --memory $RAM_SIZE --vram $VRAM_SIZE vboxmanage modifyvm $VM_NAME --nic1 nat vboxmanage modifyvm $VM_NAME --natpf1 "guestssh,tcp,,2222,,22" vboxmanage modifyvm $VM_NAME --natdnshostresolver1 on # vboxmanage sharedfolder add $VM_NAME --name shared --hostpath $SHARED_PATH --automount # Go through Ubuntu installation in a GUI environment, because installing headless is impossible in our case vboxmanage startvm $VM_NAME # After initial setup and installation of openssh-server via GUI, start vm with command vboxmanage startvm $VM_NAME --type headless # Connect to VM via ssh ssh -p 2222 capstone@localhost
#!/usr/bin/env bash set -o pipefail SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" REPO_DIR="$(realpath "${SCRIPT_DIR}/..")" source "${SCRIPT_DIR}/common.sh" RET_CODE=0 ARTIFACT_DIR="${ARTIFACT_DIR:=dist}" ARTIFACT_DIR="$(readlink -m "${ARTIFACT_DIR}")" TEST_OUT="${ARTIFACT_DIR}/test.out" COVER_OUT="${ARTIFACT_DIR}/coverage.out" JUNIT_XML="${ARTIFACT_DIR}/junit.xml" COVERAGE_HTML="${ARTIFACT_DIR}/coverage.html" FAKE_GOPATH_ROOT="/tmp/goroot-kubevirt-tekton-tasks" FAKE_KV_GOPATH="${FAKE_GOPATH_ROOT}/src/github.com/kubevirt" FAKE_REPO_GOPATH="${FAKE_KV_GOPATH}/kubevirt-tekton-tasks" rm -rf "${TEST_OUT}" "${COVER_OUT}" "${JUNIT_XML}" "${COVERAGE_HTML}" "${FAKE_GOPATH_ROOT}" mkdir -p "${ARTIFACT_DIR}" visit "${REPO_DIR}/modules" for MODULE_DIR in $(ls | grep -vE "^(tests)$"); do visit "$MODULE_DIR" if [ -f go.mod ]; then DIST_DIR=dist mkdir -p ${DIST_DIR} go test -v -coverprofile=${DIST_DIR}/coverage.out -covermode=atomic \ $(go list ./... | grep -v utilstest) | tee ${DIST_DIR}/test.out CURRENT_RET_CODE=$? if [ "${CURRENT_RET_CODE}" -ne 0 ]; then RET_CODE=${CURRENT_RET_CODE} fi cat ${DIST_DIR}/test.out >> "${TEST_OUT}" if [ -f "${COVER_OUT}" ]; then sed "/^mode.*/d" dist/coverage.out >> "${COVER_OUT}" # remove first line with mode else cp ${DIST_DIR}/coverage.out "${COVER_OUT}" fi fi leave done leave if type go-junit-report > /dev/null; then sed 's/\x1B\[[0-9;]\{1,\}[A-Za-z]//g' "${TEST_OUT}" | go-junit-report > "${JUNIT_XML}" fi mkdir -p "${FAKE_KV_GOPATH}" ln -s "$(pwd)" "${FAKE_REPO_GOPATH}" GOPATH="${FAKE_GOPATH_ROOT}" export "GOPATH=${GOPATH}" go tool cover -html "${COVER_OUT}" -o "${COVERAGE_HTML}" rm -rf "${FAKE_GOPATH_ROOT}" exit $RET_CODE
#!/bin/bash set -euo pipefail placeholder="üüü" # shellcheck disable=SC2016 open_brackets_escaped='{{ `{{` }}' # shellcheck disable=SC2016 close_brackets_escaped='{{ `}}` }}' disclaimer="# THIS FILE IS GENERATED WITH 'make generate' - DO NOT EDIT MANUALLY" replace () { local filename=$1 local from=$2 local to=$3 sed -i.bak "s/$from/$to/g" "$filename" && rm "$filename".bak # https://stackoverflow.com/a/44877280 } replace_all () { local filename=$1 replace "$filename" '{{' $placeholder replace "$filename" '}}' "$close_brackets_escaped" replace "$filename" $placeholder "$open_brackets_escaped" replace "$filename" '\[\[' '{{' replace "$filename" '\]\]' '}}' echo $disclaimer | cat - $filename > $filename.modified mv $filename.modified $filename } for i in dx; do mkdir -p $(pwd)/helm/kyverno-policies-$i/templates cp -a $(pwd)/policies/$i/. $(pwd)/helm/kyverno-policies-$i/templates # based on https://github.com/koalaman/shellcheck/wiki/SC2044 while IFS= read -r -d '' filename do replace_all "$filename" done < <(find "$(pwd)"/helm/kyverno-policies-"$i"/templates -name '*.yaml' -print0) done
<reponame>mishadynin/ideal<filename>bootstrapped/ideal/library/elements/writeonly_equality_comparable.java // Autogenerated from library/elements.i package ideal.library.elements; public interface writeonly_equality_comparable extends writeonly_value, any_equality_comparable { }
define([ 'app', 'pakka', 'text!modules/views/signup-page/signup-page.html', 'text!modules/views/signup-page/signup-page.css', 'modules/ajax/ajax', 'modules/router/router-implementation', ], function(app, pakka, Markup, StyleSheet, ajax, router) { return pakka({ name: 'login-page', html: Markup, css: StyleSheet, controller: function(context) { context.$set('data', {}); context.login = function(e) { e.preventDefault(); router.redirect('login'); } context.signup = function(e) { e.preventDefault(); if (context.$get('data.password') != context.$get('confirmPassword')) { context.$set('message', 'confirm password is not matching!'); return; } context.$set('message', 'signing up...'); ajax.signup({ data: context.$get('data'), success: function(res) { if (res && res.username) { context.$set('message', res.username + ' is now signed up!'); } else { context.$set('message', 'well this is awkward!'); } }, error: function(res) { context.$set('message', res); } }) } } }) })
<filename>zfchat-api/app/router.js 'use strict'; /** * @param {Egg.Application} app - egg application */ module.exports = app => { //io 你可以把它当成 require('socket.io') const { router, controller, io } = app; router.get('/', controller.home.index); //当服务器收到客户端的addMessage事件之后,会交给addMessage方法来处理 //向服务器发射一个新的消息,并且让服务器广播给所有的客户端 io.route('addMessage', io.controller.room.addMessage); //获取所有的历史消息 io.route('getAllMessages', io.controller.room.getAllMessages); //注册或者登录 router.post('/login', controller.user.login); //验证用户身份 router.post('/validate', controller.user.validate); //创建新的房间 router.post('/createRoom', controller.rooms.createRoom); //返回所有的房间列表 router.get('/getAllRooms', controller.rooms.getAllRooms); };
#!/usr/bin/env bash ############################################################################## # Copyright (c) 2016-20, Lawrence Livermore National Security, LLC and CHAI # project contributors. See the COPYRIGHT file for details. # # SPDX-License-Identifier: BSD-3-Clause ############################################################################## find . -type f -iname '*.hpp' -o -iname '*.cpp' | grep -v -e blt -e tpl | xargs clang-format -i
<gh_stars>0 /* * Copyright 2008-2013 NVIDIA Corporation * Modifications Copyright© 2019 Advanced Micro Devices, Inc. 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. */ #include <thrust/device_malloc_allocator.h> #include <thrust/device_vector.h> #include <thrust/host_vector.h> #include "test_header.hpp" TESTS_DEFINE(VectorManipulationTests, FullTestsParams); TYPED_TEST(VectorManipulationTests, TestVectorManipulation) { using Vector = typename TestFixture::input_type; using T = typename Vector::value_type; using Iterator = typename Vector::iterator; const std::vector<size_t> sizes = get_sizes(); for(auto size : sizes) { thrust::host_vector<T> src = get_random_data<T>( size, std::numeric_limits<T>::min(), std::numeric_limits<T>::max()); ASSERT_EQ(src.size(), size); // basic initialization Vector test0(size); Vector test1(size, T(3)); ASSERT_EQ(test0.size(), size); ASSERT_EQ(test1.size(), size); ASSERT_EQ((test1 == std::vector<T>(size, T(3))), true); // initializing from other vector std::vector<T> stl_vector(src.begin(), src.end()); Vector cpy0 = src; Vector cpy1(stl_vector); Vector cpy2(stl_vector.begin(), stl_vector.end()); ASSERT_EQ(cpy0, src); ASSERT_EQ(cpy1, src); ASSERT_EQ(cpy2, src); // resizing Vector vec1(src); vec1.resize(size + 3); ASSERT_EQ(vec1.size(), size + 3); vec1.resize(size); ASSERT_EQ(vec1.size(), size); ASSERT_EQ(vec1, src); vec1.resize(size + 20, T(11)); Vector tail(vec1.begin() + size, vec1.end()); ASSERT_EQ((tail == std::vector<T>(20, T(11))), true); // shrinking a vector should not invalidate iterators Iterator first = vec1.begin(); vec1.resize(10); ASSERT_EQ(first, vec1.begin()); vec1.resize(0); ASSERT_EQ(vec1.size(), 0); ASSERT_EQ(vec1.empty(), true); vec1.resize(10); ASSERT_EQ(vec1.size(), 10); vec1.clear(); ASSERT_EQ(vec1.size(), 0); vec1.resize(5); ASSERT_EQ(vec1.size(), 5); // push_back Vector vec2; for(size_t i = 0; i < 10; ++i) { ASSERT_EQ(vec2.size(), i); vec2.push_back((T)i); ASSERT_EQ(vec2.size(), i + 1); for(size_t j = 0; j <= i; j++) ASSERT_EQ(vec2[j], j); ASSERT_EQ(vec2.back(), i); } // pop_back for(size_t i = 10; i > 0; --i) { ASSERT_EQ(vec2.size(), i); ASSERT_EQ(vec2.back(), i - 1); vec2.pop_back(); ASSERT_EQ(vec2.size(), i - 1); for(size_t j = 0; j < i; j++) ASSERT_EQ(vec2[j], j); } } }
#!/bin/sh echo '****************************************************************************' echo ' copy_wars.sh ' echo ' by niuren.zhu ' echo ' 2017.06.23 ' echo ' 说明: ' echo ' 1. 遍历工作目录,寻找war包到./ibas_packages。 ' echo ' 2. 参数1,工作目录。 ' echo '****************************************************************************' # 设置参数变量 # 启动目录 STARTUP_FOLDER=$(pwd) # 工作目录默认第一个参数 WORK_FOLDER=$1 # 修正相对目录为启动目录 if [ "${WORK_FOLDER}" = "./" ]; then WORK_FOLDER=${STARTUP_FOLDER} fi # 未提供工作目录,则取启动目录 if [ "${WORK_FOLDER}" = "" ]; then WORK_FOLDER=${STARTUP_FOLDER} fi PACKAGES_FOLDER=${STARTUP_FOLDER}/ibas_packages if [ ! -e ${PACKAGES_FOLDER} ]; then mkdir ${PACKAGES_FOLDER} fi echo --工作的目录:${WORK_FOLDER} echo --程序的目录:${PACKAGES_FOLDER} # 获取编译顺序 if [ ! -e ${WORK_FOLDER}/compile_order.txt ]; then ls -l ${WORK_FOLDER} | awk '/^d/{print $NF}' >${WORK_FOLDER}/compile_order.txt fi # 遍历当前目录 # 初始化顺序文件 if [ -e ${PACKAGES_FOLDER}/ibas.deploy.order.txt ]; then rm -rf ${PACKAGES_FOLDER}/ibas.deploy.order.txt fi while read folder; do if [ -e ${WORK_FOLDER}/${folder}/release/ ]; then find ${WORK_FOLDER}/${folder}/release/ -name "*.service-*.war" -type f -exec cp {} ${PACKAGES_FOLDER} \; find ${WORK_FOLDER}/${folder}/release/ -name "*.service-*.war" -type f -exec echo {} \; | awk -F'[/]' '{print $NF}' >>${PACKAGES_FOLDER}/ibas.deploy.order.txt fi done <${WORK_FOLDER}/compile_order.txt | sed 's/\r//g' echo --程序清单: ls ${PACKAGES_FOLDER}
import tensorflow as tf from tensorflow.keras.layers import Dense model = tf.keras.Sequential([ Dense(64, activation='relu', input_shape=(num_features,)), Dense(32, activation='relu'), Dense(16, activation='relu'), Dense(1) ]) model.compile( optimizer='adam', loss=tf.keras.losses.MeanSquaredError() ) model.fit(X_train, y_train, epochs=10)
import React from 'react' import {Button, Panel} from 'react-bootstrap' import {NavLink} from 'react-router-dom' const EmptyCart = () => { return ( <div> <div className="emptyCart"> <Panel bsStyle="danger"> <Panel.Heading style={{textAlign: 'center'}}> <Panel.Title componentClass="h3"> No Products Currently In Cart </Panel.Title> </Panel.Heading> <Panel.Body> <img style={{ width: '35%', height: '20%' }} src="https://images.unsplash.com/photo-1516355161757-eed94aecaeab?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1234&q=80" alt="" /> <NavLink to="/products"> <Button className="pull-right" type="button" bsStyle="info"> Back to All Product </Button> </NavLink> </Panel.Body> </Panel> </div> </div> ) } export default EmptyCart
const tokenDAO = require('../daos/token'); // Authentication and Token Validation // module.exports.isLoggedIn = async (req, res, next) => { const uniqueToken = req.headers.authorization; try { if (uniqueToken) { const token = uniqueToken.split(' ')[1]; const userId = await tokenDAO.getUserFromToken(token); if (!userId) { return res.sendStatus(401); } else { req.userId = userId; req.token = token; next(); } } else { res.sendStatus(401); } } catch (e) { } };
def addSparseVectors(A, B): result = A for i in range(len(B)): if (B[i] != 0): result[i] += B[i] return result
#!/bin/bash dieharder -d 100 -g 2 -S 843417218
#!/bin/bash # Publishing to NPM echo "1) to NPM registry ..." npm publish --access public # Mirroring active repository from Bitbucket to GitHub echo "2) to GitHub mirror ..." git fetch --prune git push --prune https://wunderbon:${GITHUB_TOKEN}@github.com/wunderbon/json-schemas.git +refs/remotes/origin/*:refs/heads/* +refs/tags/*:refs/tags/* 1>&2 # Return status if [ "$?" = "0" ]; then # exit with success - important for ci system exit 0 else echo "Error while publishing JSON Schemas!" 1>&2 # exit with error - important for ci system exit 1 fi
/* * Copyright 2021 Hazelcast Inc. * * Licensed under the Hazelcast Community License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://hazelcast.com/hazelcast-community-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.jet.sql.impl.validate.operators.special; import com.hazelcast.jet.sql.impl.validate.HazelcastCallBinding; import com.hazelcast.jet.sql.impl.validate.operators.common.HazelcastSpecialOperator; import com.hazelcast.jet.sql.impl.validate.operators.typeinference.ReplaceUnknownOperandTypeInference; import org.apache.calcite.sql.SqlKind; import org.apache.calcite.sql.SqlValuesOperator; import static org.apache.calcite.sql.type.SqlTypeName.BIGINT; /** * Hazelcast equivalent of {@link SqlValuesOperator}. */ public class HazelcastValuesOperator extends HazelcastSpecialOperator { public HazelcastValuesOperator() { super("VALUES", SqlKind.VALUES, 2, true, b -> { throw new UnsupportedOperationException(); }, new ReplaceUnknownOperandTypeInference(BIGINT)); } @Override protected boolean checkOperandTypes(HazelcastCallBinding callBinding, boolean throwOnFailure) { throw new UnsupportedOperationException("never called for VALUES"); } }
def is_prime(num): if num < 2: return False for i in range(2, num): if num % i == 0: return False return True prime_nums = [num for num in range(1, 51) if is_prime(num)] print(prime_nums)
#!/usr/bin/env bats load _helpers @test "meshGateway/ServiceAccount: disabled by default" { cd `chart_dir` assert_empty helm template \ -s templates/mesh-gateway-serviceaccount.yaml \ . } @test "meshGateway/ServiceAccount: enabled with meshGateway, connectInject enabled" { cd `chart_dir` local actual=$(helm template \ -s templates/mesh-gateway-serviceaccount.yaml \ --set 'meshGateway.enabled=true' \ --set 'connectInject.enabled=true' \ . | tee /dev/stderr | yq 'length > 0' | tee /dev/stderr) [ "${actual}" = "true" ] } #-------------------------------------------------------------------- # global.imagePullSecrets @test "meshGateway/ServiceAccount: can set image pull secrets" { cd `chart_dir` local object=$(helm template \ -s templates/mesh-gateway-serviceaccount.yaml \ --set 'meshGateway.enabled=true' \ --set 'connectInject.enabled=true' \ --set 'global.imagePullSecrets[0].name=my-secret' \ --set 'global.imagePullSecrets[1].name=my-secret2' \ . | tee /dev/stderr) local actual=$(echo "$object" | yq -r '.imagePullSecrets[0].name' | tee /dev/stderr) [ "${actual}" = "my-secret" ] local actual=$(echo "$object" | yq -r '.imagePullSecrets[1].name' | tee /dev/stderr) [ "${actual}" = "my-secret2" ] }
#!/bin/bash # Downloads the needed APKs (using wget), installs them to the current device (using adb), # and configures them (using adb). The configuring consists of permission assignment # and running Kõnele's GetPutPreferenceActivity to change the Kõnele settings. # Work in progress (relies on an unreleased version of Kõnele). cmd=adb basedir=$(mktemp -d) ver_k6nele=1.6.98 ver_ekispeak=1.2.03 ver_trigger=0.1.21 ver_launcher=0.0.2 fakedir=$HOME/Desktop/APK/ function download { echo "wget -P $basedir $1" wget -P $basedir $1 } $cmd connect Android.local echo "Installing Kõnele..." download https://github.com/Kaljurand/K6nele/releases/download/v${ver_k6nele}/K6nele-${ver_k6nele}.apk ##cp $fakedir/K6nele-${ver_k6nele}.apk $basedir $cmd install $basedir/K6nele-${ver_k6nele}.apk $cmd shell pm grant ee.ioc.phon.android.speak android.permission.RECORD_AUDIO echo "Installing Speech Trigger..." download https://github.com/Kaljurand/speech-trigger/releases/download/v${ver_trigger}/SpeechTrigger-${ver_trigger}.apk $cmd install $basedir/SpeechTrigger-${ver_trigger}.apk $cmd shell pm grant ee.ioc.phon.android.speechtrigger android.permission.RECORD_AUDIO $cmd shell pm grant ee.ioc.phon.android.speechtrigger android.permission.WRITE_EXTERNAL_STORAGE echo "Installing EKI Speak..." download https://github.com/Kaljurand/EKISpeak/releases/download/v${ver_ekispeak}/EKISpeak-${ver_ekispeak}.apk $cmd install $basedir/EKISpeak-${ver_ekispeak}.apk echo "Installing Things Kõnele Launcher..." download https://github.com/Kaljurand/things-k6nelelauncher/releases/download/v${ver_launcher}/things-k6nelelauncher-${ver_launcher}.apk $cmd install $basedir/things-k6nelelauncher-${ver_launcher}.apk $cmd shell pm grant ee.ioc.phon.android.things.k6nelelauncher com.google.android.things.permission.USE_PERIPHERAL_IO echo "Installed the following APKs:" ls -l $basedir $cmd shell 'pm list packages' echo "Installation done. Reboot using: adb shell reboot" echo "or start the app by: adb shell am start -n ee.ioc.phon.android.things.k6nelelauncher/.ActivityLauncherActivity"
<reponame>peter-stuhlmann/UnderConstructionPage import React from 'react'; import styled from 'styled-components'; // components import Container from '../components/Container'; // data import footer from '../data/footer'; export default function Footer() { return ( <Container footer> <Text dangerouslySetInnerHTML={{ __html: footer.content }} /> </Container> ); } const Text = styled.p` text-align: center; color: #aaa; font-size: 0.9em; margin: 0; a { color: #aaa; text-decoration: none; } @media (max-width: 480px) { span { &:first-child { display: none; } &:last-child { display: block; } } } `;
// @flow import { ipcRenderer } from 'electron'; import log from 'electron-log'; import React, { Component } from 'react'; import ReactLoading from 'react-loading'; import { Redirect } from 'react-router-dom'; import ReactTooltip from 'react-tooltip'; import { session, loginCounter, eventEmitter } from '../index'; import navBar from './NavBar'; import BottomBar from './BottomBar'; function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } let displayedTransactionCount = 50; type Props = { syncStatus: number, unlockedBalance: number, lockedBalance: number, transactions: Array<string>, history: any, importkey: boolean, importseed: boolean }; export default class Home extends Component<Props> { props: Props; constructor(props?: Props) { super(props); this.state = { transactions: session.getTransactions( 0, displayedTransactionCount, false ), totalTransactionCount: session.getTransactions().length, importkey: false, importseed: false, loginFailed: session.loginFailed, changePassword: false, firstStartup: session.firstStartup, darkmode: session.darkMode }; this.handleLoginFailure = this.handleLoginFailure.bind(this); this.handleImportFromSeed = this.handleImportFromSeed.bind(this); this.handleImportFromKey = this.handleImportFromKey.bind(this); this.refreshListOnNewTransaction = this.refreshListOnNewTransaction.bind( this ); this.openNewWallet = this.openNewWallet.bind(this); this.handlePasswordChange = this.handlePasswordChange.bind(this); } componentDidMount() { ipcRenderer.setMaxListeners(1); ipcRenderer.on('handlePasswordChange', this.handlePasswordChange); ipcRenderer.on('importSeed', this.handleImportFromSeed); ipcRenderer.on('importKey', this.handleImportFromKey); if (session.wallet !== undefined) { session.wallet.on('transaction', this.refreshListOnNewTransaction); } eventEmitter.on('openNewWallet', this.openNewWallet); eventEmitter.on('loginFailed', this.handleLoginFailure); if (session.firstLoadOnLogin && this.state.loginFailed === false) { this.switchOffAnimation(); } if (!this.state.loginFailed) { loginCounter.userLoginAttempted = false; } } componentWillUnmount() { displayedTransactionCount = 50; this.setState({ transactions: session.getTransactions(0, displayedTransactionCount, false) }); ipcRenderer.off('importSeed', this.handleImportFromSeed); ipcRenderer.off('handlePasswordChange', this.handlePasswordChange); ipcRenderer.off('importKey', this.handleImportFromKey); eventEmitter.off('openNewWallet', this.openNewWallet); eventEmitter.off('loginFailed', this.handleLoginFailure); if (session.wallet !== undefined) { session.wallet.off('transaction', this.refreshListOnNewTransaction); } } async switchOffAnimation() { await sleep(1000); session.firstLoadOnLogin = false; } handlePasswordChange() { this.setState({ changePassword: true }); } handleLoginFailure() { this.setState({ loginFailed: true }); } refreshListOnNewTransaction() { log.debug('Transaction found, refreshing transaction list...'); displayedTransactionCount++; this.setState({ transactions: session.getTransactions( 0, displayedTransactionCount, false ), totalTransactionCount: session.getTransactions().length, unlockedBalance: session.getUnlockedBalance(), lockedBalance: session.getLockedBalance() }); } openNewWallet() { log.debug('Initialized new wallet session, refreshing transaction list...'); displayedTransactionCount = 50; this.setState({ transactions: session.getTransactions( 0, displayedTransactionCount, false ), totalTransactionCount: session.getTransactions().length, unlockedBalance: session.getUnlockedBalance(), lockedBalance: session.getLockedBalance() }); } handleImportFromSeed(evt, route) { clearInterval(this.interval); this.setState({ importseed: true }); } handleImportFromKey(evt, route) { clearInterval(this.interval); this.setState({ importkey: true }); } handleLoadMore(evt, route) { evt.preventDefault(); displayedTransactionCount += 50; this.setState({ transactions: session.getTransactions(0, displayedTransactionCount, false) }); } handleShowAll(evt, route) { evt.preventDefault(); displayedTransactionCount = this.state.totalTransactionCount; this.setState({ transactions: session.getTransactions( 0, this.state.totalTransactionCount, false ) }); } resetDefault(evt, route) { evt.preventDefault(); displayedTransactionCount = 50; this.setState({ transactions: session.getTransactions(0, displayedTransactionCount, false) }); } render() { if (this.state.firstStartup === true) { return <Redirect to="/firststartup" />; } if (this.state.changePassword === true) { return <Redirect to="/changepassword" />; } if (this.state.importkey === true) { return <Redirect to="/importkey" />; } if (this.state.importseed === true) { return <Redirect to="/import" />; } if (this.state.loginFailed === true) { return <Redirect to="/login" />; } return ( <div> {this.state.darkmode === false && ( <div className="wholescreen"> <ReactTooltip effect="solid" border type="dark" multiline place="top" /> {navBar('wallet', false)} <div className={ session.firstLoadOnLogin ? 'maincontent-homescreen-fadein' : 'maincontent-homescreen' } > <table className="table is-striped is-hoverable is-fullwidth is-family-monospace"> <thead> <tr> <th>Date</th> <th>Hash</th> <th className="has-text-right">Amount</th> <th className="has-text-right">Balance</th> </tr> </thead> <tbody> {this.state.transactions.map((tx, index) => { return ( <tr key={index}> <td data-tip={ tx[0] === 0 ? 'This transaction is unconfirmed. Should be confirmed within 30 seconds!' : `Block ${tx[4]}` } > {tx[0] === 0 && ( <p className="has-text-danger">Unconfirmed</p> )} {tx[0] > 0 && ( <p>{session.convertTimestamp(tx[0])}</p> )} </td> <td>{tx[1]}</td> {tx[2] < 0 && ( <td> <p className="has-text-danger has-text-right"> {session.atomicToHuman(tx[2], true)} </p> </td> )} {tx[2] > 0 && ( <td> <p className="has-text-right"> {session.atomicToHuman(tx[2], true)} </p> </td> )} <td> <p className="has-text-right"> {session.atomicToHuman(tx[3], true)} </p> </td> </tr> ); })} </tbody> </table> {this.state.transactions.length < this.state.totalTransactionCount && ( <form> <div className="field"> <div className="buttons"> <button type="submit" className="button is-success" onClick={this.handleShowAll.bind(this)} > Show all </button> <button type="submit" className="button is-warning" onClick={this.handleLoadMore.bind(this)} > Load more </button> <button type="submit" className="button is-danger" onClick={this.resetDefault.bind(this)} > Reset </button> </div> </div> </form> )} </div> <BottomBar /> </div> )} {this.state.darkmode === true && ( <div className="wholescreen has-background-dark"> <ReactTooltip effect="solid" border type="light" multiline place="top" /> {navBar('wallet', true)} <div className={ session.firstLoadOnLogin ? 'maincontent-homescreen-fadein has-background-dark' : 'maincontent-homescreen has-background-dark' } > {' '} <table className="table is-striped is-hoverable is-fullwidth is-family-monospace table-darkmode"> <thead> <tr> <th className="has-text-white">Date</th> <th className="has-text-white">Hash</th> <th className="has-text-white has-text-right">Amount</th> <th className="has-text-white has-text-right">Balance</th> </tr> </thead> <tbody> {this.state.transactions.map((tx, index) => { return ( <tr key={index}> <td data-tip={ tx[0] === 0 ? 'This transaction is unconfirmed. Should be confirmed within 30 seconds!' : `Block ${tx[4]}` } > {tx[0] === 0 && ( <p className="has-text-danger">Unconfirmed</p> )} {tx[0] > 0 && ( <p>{session.convertTimestamp(tx[0])}</p> )} </td> <td>{tx[1]}</td> {tx[2] < 0 && ( <td> <p className="has-text-danger has-text-right"> {session.atomicToHuman(tx[2], true)} </p> </td> )} {tx[2] > 0 && ( <td> <p className="has-text-right"> {session.atomicToHuman(tx[2], true)} </p> </td> )} <td> <p className="has-text-right"> {session.atomicToHuman(tx[3], true)} </p> </td> </tr> ); })} </tbody> </table> {this.state.transactions.length < this.state.totalTransactionCount && ( <form> <div className="field"> <div className="buttons"> <button type="submit" className="button is-success" onClick={this.handleShowAll.bind(this)} > Show all </button> <button type="submit" className="button is-warning" onClick={this.handleLoadMore.bind(this)} > Load more </button> <button type="submit" className="button is-danger" onClick={this.resetDefault.bind(this)} > Reset </button> </div> </div> </form> )} </div> <BottomBar /> </div> )} </div> ); } }
/* * <NAME> * 10445765 * * index.js is the main script that creates all visualizations on the visualizations page. * * Sources: * //https://bl.ocks.org/johnwalley/e1d256b81e51da68f7feb632a53c3518 * //https://www.w3schools.com/howto/howto_css_modals.asp * //https://api.jquery.com/scroll/ **/ window.onload = function() { var currentProvince = "Nederland"; var topic = "income"; var titel = "Yearly income"; var subtitel = "x 1000 euro"; var year = "2006"; // Retrieve data var data2006 = "../../data/data_2006.json"; var data2007 = "../../data/data_2007.json"; var data2008 = "../../data/data_2008.json"; var data2009 = "../../data/data_2009.json"; var data2010 = "../../data/data_2010.json"; var data2011 = "../../data/data_2011.json"; var data2012 = "../../data/data_2012.json"; var data2013 = "../../data/data_2013.json"; var data2014 = "../../data/data_2014.json"; var data2015 = "../../data/data_2015.json"; var nld = "../../data/nld.json"; d3.queue() .defer(d3.json, data2006) .defer(d3.json, data2007) .defer(d3.json, data2008) .defer(d3.json, data2009) .defer(d3.json, data2010) .defer(d3.json, data2011) .defer(d3.json, data2012) .defer(d3.json, data2013) .defer(d3.json, data2014) .defer(d3.json, data2015) .defer(d3.json, nld) .await(callback); function callback(error, data2006, data2007, data2008, data2009, data2010, data2011, data2012, data2013, data2014, data2015, nld) { if (error) throw error; // Create object with data per year var years = { "2006" : data2006.data_2006, "2007" : data2007.data_2007, "2008" : data2008.data_2008, "2009" : data2009.data_2009, "2010" : data2010.data_2010, "2011" : data2011.data_2011, "2012" : data2012.data_2012, "2013" : data2013.data_2013, "2014" : data2014.data_2014, "2015" : data2015.data_2015, } // Change values causes of death, education and social security for (var key in years){ changeDataValues(years[key]); } // Initial data per province var provinceDataOne = getProvinceData(years[year], "Limburg"); var provinceDataTwo = getProvinceData(years[year], currentProvince); // Create initial visualizations var pyramidSettings = createPyramid(provinceDataOne, provinceDataTwo, currentProvince); var barSettings = createBarchart(); var mapSettings = createMap(nld, years[year], year, currentProvince, topic, titel, subtitel); var settings = { nld: nld, years : years, pyramidSettings: pyramidSettings, barSettings: barSettings, mapSettings: mapSettings, topic: topic, }; updateMap(nld, years[year], year, currentProvince, topic, titel, subtitel, settings); updatePyramid(provinceDataOne, provinceDataTwo, currentProvince, pyramidSettings); updateBarchart(provinceDataOne, provinceDataTwo, currentProvince, topic, titel, subtitel, barSettings); // Create slider var sliderData = d3.range(0, 10).map(function (d) { return new Date(2006 + d, 10, 3); }); var slider = d3.sliderHorizontal() .min(d3.min(sliderData)) .max(d3.max(sliderData)) .step(1000 * 60 * 60 * 24 * 365) .width(400) .tickFormat(d3.timeFormat('%Y')) .tickValues(sliderData) .on('onchange', val => { var sliderValue = d3.select(".parameter-value").text() changeYear(sliderValue, currentProvince, settings, topic, titel, subtitel); }); var g = d3.select("div#slider").append("svg") .attr("width", 500) .attr("height", 100) .append("g") .attr("transform", "translate(30,30)") .style('fill', "#fbb4ae"); g.call(slider); // Change barchart when topic is chosen function changeTopic(){ year = d3.select(".parameter-value").text(); topic = this.getAttribute("id"); // Get correct title and subtitle var texts = getTopic(topic); var titel = texts.titel; var subtitel = texts.subtitel; // Get current chosen province currentProvince = getChosenProvince(currentProvince); // Get correct data and update chart var data = years[year]; provinceDataOne = getProvinceData(data, "Limburg"); provinceDataTwo = getProvinceData(data, currentProvince); updateBarchart(provinceDataOne, provinceDataTwo, currentProvince, topic, titel, subtitel, barSettings); } // Call changeTopic when dropdown item is chosen document.getElementById("birthsanddeaths").onclick=changeTopic; document.getElementById("causesofdeath").onclick=changeTopic; document.getElementById("income").onclick=changeTopic; document.getElementById("socialsecurity").onclick=changeTopic; document.getElementById("education").onclick=changeTopic; document.getElementById("migration").onclick=changeTopic; // Scroll functions $("#scrollUp").click(function() { $('html, body').animate({ scrollTop: $("#container1").offset().top }, 1000); }); $("#scrollDown").click(function() { $('html, body').animate({ scrollTop: $("#container1").offset().top }, 1000); }); $("path").click(function() { $('html, body').animate({ scrollTop: $("#slidercol").offset().top }, 1000); }); // Info button with pop up screen var modal = document.getElementById('myModal'); var btn = document.getElementById("infoButton"); var span = document.getElementsByClassName("close")[0]; // When the user clicks on the button, open the modal btn.onclick = function() { modal.style.display = "block"; } // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } } }
<gh_stars>1-10 #include "pch.h" #include "ds3runtime.h" #include "logging.h" namespace hoodie_script { void DS3RuntimeScripting::setAsyncMode(const bool& async) { this->async = async; } void DS3RuntimeScripting::attach() { attached = true; if (!async) { for (auto&& hook : hooks) { hook->install(); } } else { asyncModeThreadHandle = CreateThread(NULL, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(asyncModeThreadProc), NULL, 0, NULL); } } bool DS3RuntimeScripting::detach() { attached = false; if (!async) { for (auto&& hook : hooks) { hook->uninstall(); } } else { asyncModeThreadHandle = NULL; } while (true) { auto itr = std::find_if(scripts.begin(), scripts.end(), [](auto&& script) { bool detachResult = true; if (script->isAttached()) detachResult = script->onDetach(); if (detachResult) script->remove(); else { logging::write_line("Script {} was unable to detach...", script->getName()); script->setDetaching(); } return detachResult; }); if (itr == scripts.end()) break; auto moveDestroy = std::move(*itr); scripts.erase(itr); } return true; } void DS3RuntimeScripting::addHook(std::unique_ptr<jump_hook> hook) { hooks.push_back(std::move(hook)); } void DS3RuntimeScripting::runScript(std::unique_ptr<ScriptModule> script) { if (script->isAsync()) reinterpret_cast<AsyncModule*>(script.get())->createThread(script.get()); scripts.insert(scripts.begin(), std::move(script)); } bool DS3RuntimeScripting::removeScript(const uint64_t& uniqueId) { for (int i = 0; i < scripts.size(); i++) if (uniqueId == scripts[i]->getUniqueId()) { bool detachResult = true; if (scripts[i]->isAttached()) detachResult = scripts[i]->onDetach(); if (detachResult) scripts[i]->remove(); else scripts[i]->setDetaching(); return detachResult; } return false; } bool DS3RuntimeScripting::removeScript(const std::string& name) { for (int i = 0; i < scripts.size(); i++) if (name == scripts[i]->getName()) { bool detachResult = true; if (scripts[i]->isAttached()) detachResult = scripts[i]->onDetach(); if (detachResult) scripts[i]->remove(); else scripts[i]->setDetaching(); return detachResult; } return false; } void DS3RuntimeScripting::executeScripts() { while (true) { auto itr = std::find_if(scripts.begin(), scripts.end(), [](auto&& script) { return script->isRemoved(); }); if (itr == scripts.end()) break; auto moveDestroy = std::move(*itr); scripts.erase(itr); } for (auto&& script : scripts) if (!script->isAsync()) { if (!script->isAttached() && script->onAttach()) script->setAttached(); else if (script->isDetaching() && script->onDetach()) script->remove(); else script->execute(); } } ScriptModule* DS3RuntimeScripting::accessScript(const uint64_t& scriptUniqueId) { ScriptModule* matchingScript = nullptr; for (auto&& script : scripts) if (script->getUniqueId() == scriptUniqueId) { matchingScript = script.get(); break; } return matchingScript; } ScriptModule* DS3RuntimeScripting::accessScript(const std::string& name) { ScriptModule* matchingScript = nullptr; for (auto&& script : scripts) if (script->getName().compare(name) == 0) { matchingScript = script.get(); break; } return matchingScript; } jump_hook* DS3RuntimeScripting::accessHook(const std::string& name) { jump_hook* matchingHook = nullptr; for (auto&& hook : hooks) if (hook->getName().compare(name) == 0) { matchingHook = hook.get(); break; } return matchingHook; } void DS3RuntimeScripting::setGameThreadId(const DWORD& threadId) { gameThreadId = threadId; } DWORD DS3RuntimeScripting::getGameThreadId() { return gameThreadId; } std::string DS3RuntimeScripting::utf8_encode(const std::wstring &wstr) { if (wstr.empty()) return std::string(); int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], static_cast<int>(wstr.size()), NULL, 0, NULL, NULL); std::string strTo(size_needed, 0); WideCharToMultiByte(CP_UTF8, 0, &wstr[0], static_cast<int>(wstr.size()), &strTo[0], size_needed, NULL, NULL); return strTo; } std::wstring DS3RuntimeScripting::utf8_decode(const std::string &str) { if (str.empty()) return std::wstring(); int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], static_cast<int>(str.size()), NULL, 0); std::wstring wstrTo(size_needed, 0); MultiByteToWideChar(CP_UTF8, 0, &str[0], static_cast<int>(str.size()), &wstrTo[0], size_needed); return wstrTo; } void DS3RuntimeScripting::asyncModeThreadProc() { while (ds3runtime_global->asyncModeThreadHandle != NULL) { ds3runtime_global->executeScripts(); } } }
const expect = require('expect'); const request = require('supertest'); const {ObjectID} = require('mongodb'); const {app} = require('./../server'); const {Todo} = require('./../models/todo'); const {User} = require('./../models/user'); const {testTodos, populateTodos, testUsers, populateUsers} = require('./seed/seed'); beforeEach(populateUsers); beforeEach(populateTodos); describe('POST /todos', () => { it('should create a new todo', (done) => { const text = 'Test todo text'; request(app) .post('/todos') .set('x-auth', testUsers[0].tokens[0].token) .send({text}) .expect(200) .expect((res) => { expect(res.body.text).toBe(text); }) .end((err, res) => { if (err) return done(err); Todo.find({text}).then((todos) => { expect(todos.length).toBe(1); expect(todos[0].text).toBe(text); done(); }).catch((e) => done(e)); }); }); it('should not create todo with invalid body data', (done) => { request(app) .post('/todos') .set('x-auth', testUsers[0].tokens[0].token) .send({}) .expect(400) .end((err, res) => { if (err) return done(err); Todo.find().then((todos) => { expect(todos.length).toBe(2); done(); }).catch(e => done(e)); }); }); }); describe('GET /todos', () => { it('should get all todos', (done) => { request(app) .get('/todos') .set('x-auth', testUsers[0].tokens[0].token) .expect(200) .expect((res) => { expect(res.body.todos.length).toBe(1); }) .end(done); }); }); describe('GET /todos/:id', () => { it('should return todo document', (done) => { request(app) .get(`/todos/${testTodos[0]._id.toHexString()}`) .set('x-auth', testUsers[0].tokens[0].token) .expect(200) .expect(res => { expect(res.body.todo.text).toBe(testTodos[0].text); }) .end(done); }); it('should not return todo document created by other user', (done) => { request(app) .get(`/todos/${testTodos[1]._id.toHexString()}`) .set('x-auth', testUsers[0].tokens[0].token) .expect(404) .end(done); }); it('should return 404 if todo not found', (done) => { const missing = new ObjectID().toHexString(); request(app) .get(`/todos/${missing}`) .set('x-auth', testUsers[0].tokens[0].token) .expect(404) .end(done); }); it('should return 404 for invalid object ids', (done) => { request(app) .get('/todos/123') .set('x-auth', testUsers[0].tokens[0].token) .expect(404) .end(done); }); }); describe('DELETE /todos/:id', () => { it('should remove a todo', (done) => { const hexId = testTodos[0]._id.toHexString(); request(app) .delete(`/todos/${hexId}`) .set('x-auth', testUsers[0].tokens[0].token) .expect(200) .expect(res => { expect(res.body.todo._id).toBe(hexId); }) .end((err, res) => { if (err) return done(err); Todo.findById(res._id).then(todo => { expect(todo).toNotExist(); done(); }).catch(e => done(e)); }); }); it('should not remove a todo owned by another user', (done) => { const hexId = testTodos[0]._id.toHexString(); request(app) .delete(`/todos/${hexId}`) .set('x-auth', testUsers[1].tokens[0].token) .expect(404) .end((err, res) => { if (err) return done(err); Todo.findById(hexId).then(todo => { expect(todo).toExist(); done(); }).catch(e => done(e)); }); }); it('should return 404 if todo not found', (done) => { const missing = new ObjectID().toHexString(); request(app) .delete(`/todos/${missing}`) .set('x-auth', testUsers[1].tokens[0].token) .expect(404) .end(done); }); it('should return 404 for invalid object ids', (done) => { request(app) .delete('/todos/123') .set('x-auth', testUsers[1].tokens[0].token) .expect(404) .end(done); }); }); describe('PATCH /todos/:id', () => { it('should update the todo', (done) => { const hexID = testTodos[0]._id.toHexString(); const update = { text: 'abc123', completed: true }; request(app) .patch(`/todos/${hexID}`) .set('x-auth', testUsers[0].tokens[0].token) .send(update) .expect(200) .expect(res => { expect(res.body.todo.text).toBe(update.text); expect(res.body.todo.completed).toBe(true); expect(res.body.todo.completedAt).toBeA('number'); }) .end(done); }); it('should not update the todo of another user', (done) => { const hexID = testTodos[0]._id.toHexString(); const update = { text: 'abc123', completed: true }; request(app) .patch(`/todos/${hexID}`) .set('x-auth', testUsers[1].tokens[0].token) .send(update) .expect(404) .end(done); }); it('should clear completedAt when todo is not completed', (done) => { const hexID = testTodos[1]._id.toHexString(); const update = { text: 'xyz321', completed: false }; request(app) .patch(`/todos/${hexID}`) .set('x-auth', testUsers[1].tokens[0].token) .send(update) .expect(200) .expect(res => { expect(res.body.todo.text).toBe(update.text); expect(res.body.todo.completed).toBe(false); expect(res.body.todo.completedAt).toNotExist() }) .end(done); }); }); describe('GET /users/me', () => { it('should return user if authenticated', (done) => { request(app) .get('/users/me') .set('x-auth', testUsers[0].tokens[0].token) .expect(200) .expect((res) => { expect(res.body._id).toBe(testUsers[0]._id.toHexString()); expect(res.body.email).toBe(testUsers[0].email); }) .end(done); }); it('should return 401 if not authenticated', (done) => { request(app) .get('/users/me') .expect(401) .expect((res) => { expect(res.body).toEqual({}); }) .end(done); }); }); describe('POST /users', () => { it('should create a user', (done) => { const newUser = { email: '<EMAIL>', password: '<PASSWORD>' } request(app) .post('/users') .send(newUser) .expect(200) .expect((res) => { expect(res.headers['x-auth']).toExist(); expect(res.body._id).toExist(); expect(res.body.email).toBe(newUser.email); }) .end((err) => { if (err) return done(err); User.findOne({email: newUser.email}).then(user => { expect(user).toExist(); expect(user.password).toNotBe(newUser.password); done(); }).catch(e => done(e)); }); }); it('should return validation errors if request invalid', (done) => { const invalidUser = { email: 'abc', password: '1' }; request(app) .post('/users') .send(invalidUser) .expect(400) .end(done); }); it('should not create user if email in use', (done) => { const alreadyExistUser = { email: testUsers[0].email, password: '<PASSWORD>' }; request(app) .post('/users') .send(alreadyExistUser) .expect(400) .end(done); }); }); describe('POST /users/login', () => { it('should login user and return auth token', (done) => { request(app) .post('/users/login') .send({ email: testUsers[1].email, password: <PASSWORD> }) .expect(200) .expect((res) => { expect(res.headers['x-auth']).toExist(); }) .end((err, res) => { if (err) return done(err); User.findById(testUsers[1]._id).then(user => { expect(user.tokens[1]).toInclude({ access: 'auth', token: res.headers['x-auth'] }); done(); }).catch(e => done(e)); }); }); it('should reject invalid login', (done) => { request(app) .post('/users/login') .send({ email: testUsers[1].email, password: '<PASSWORD>' }) .expect(400) .expect((res) => { expect(res.headers['x-auth']).toNotExist(); }) .end((err, res) => { if (err) return done(err); User.findById(testUsers[1]._id).then(user => { expect(user.tokens.length).toBe(1); done(); }).catch(e => done(e)); }); }); }); describe('DELETE /users/me/token', () => { it('should remove auth token on logout', (done) => { request(app) .delete('/users/me/token') .set('x-auth', testUsers[0].tokens[0].token) .expect(200) .end((err, res) => { if (err) return done(err); User.findById(testUsers[0]._id).then(user => { expect(user.tokens.length).toBe(0); done(); }).catch(e => done(e)); }); }); });
/* * Copyright [2020-2030] [https://www.stylefeng.cn] * * 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. * * Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点: * * 1.请不要删除和修改根目录下的LICENSE文件。 * 2.请不要删除和修改Guns源码头部的版权声明。 * 3.请保留源码和相关描述文件的项目出处,作者声明等。 * 4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns * 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns * 6.若您的项目无法满足以上几点,可申请商业授权 */ package cn.stylefeng.roses.kernel.log.api.pojo.loginlog; import cn.stylefeng.roses.kernel.rule.annotation.ChineseDescription; import cn.stylefeng.roses.kernel.rule.pojo.request.BaseRequest; import lombok.Data; import lombok.EqualsAndHashCode; import javax.validation.constraints.NotNull; import java.util.Date; /** * 登录日志表 * * @author chenjinlong * @date 2021/1/13 11:06 */ @EqualsAndHashCode(callSuper = true) @Data public class SysLoginLogRequest extends BaseRequest { /** * 主键id */ @NotNull(message = "llgId不能为空", groups = {detail.class}) @ChineseDescription("主鍵id") private Long llgId; /** * 日志名称 */ @ChineseDescription("日志名称") private String llgName; /** * 是否执行成功 */ @ChineseDescription("是否执行成功") private String llgSucceed; /** * 具体消息 */ @ChineseDescription("具体消息") private String llgMessage; /** * 登录ip */ @ChineseDescription("登录ip") private String llgIpAddress; /** * 用户id */ @ChineseDescription("用户id") private Long userId; /** * 创建时间 */ @ChineseDescription("创建时间") private Date createTime; /** * 开始时间 */ @ChineseDescription("开始时间") private String beginTime; /** * 结束时间 */ @ChineseDescription("结束时间") private String endTime; }
function fibonacci(n) { let resultArray = [0, 1]; for (let i = 2; i <=n; i++) { resultArray.push(resultArray[i-2] + resultArray[i-1]) } return resultArray.slice(0, n); } console.log('The first 10 numbers in the Fibonacci sequence are ', fibonacci(10));
package es.redmic.api.administrative.controller; /*- * #%L * API * %% * Copyright (C) 2019 REDMIC Project / Server * %% * 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. * #L% */ import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import es.redmic.api.common.controller.RBaseController; import es.redmic.es.administrative.service.ProjectESService; import es.redmic.models.es.administrative.dto.ProjectDTO; import es.redmic.models.es.administrative.model.Project; import es.redmic.models.es.common.dto.BodyItemDTO; import es.redmic.models.es.common.dto.ElasticSearchDTO; import es.redmic.models.es.common.dto.JSONCollectionDTO; import es.redmic.models.es.common.dto.SuperDTO; import es.redmic.models.es.common.query.dto.DataQueryDTO; import es.redmic.models.es.common.query.dto.MetadataQueryDTO; import es.redmic.models.es.common.query.dto.SimpleQueryDTO; @RestController @RequestMapping(value = "${controller.mapping.PROJECT_BY_PROGRAM}") public class ProjectProgramController extends RBaseController<Project, ProjectDTO, MetadataQueryDTO>{ private ProjectESService _service; @Autowired public ProjectProgramController(ProjectESService service) { super(service); this._service = service; } @PostMapping(value = "/_search") @ResponseBody public SuperDTO findAll(@PathVariable("programId") Long programId, @RequestBody DataQueryDTO queryDTO, BindingResult bindingResult) { queryDTO.addTerm("path.split", programId); processQuery(queryDTO, bindingResult); JSONCollectionDTO result = _service.find(queryDTO); return new ElasticSearchDTO(result, result.getTotal()); } @GetMapping(value = "/_suggest") @ResponseBody public SuperDTO _suggest(@PathVariable("programId") Long programId, @RequestParam("fields") String[] fields, @RequestParam("text") String text, @RequestParam(required = false, value = "size") Integer size) { SimpleQueryDTO queryDTO = _service.createSimpleQueryDTOFromSuggestQueryParams(fields, text, size); processQuery((DataQueryDTO) queryDTO); queryDTO.addTerm("path.split", programId); List<String> response = _service.suggest(convertToDataQuery((DataQueryDTO)queryDTO)); return new ElasticSearchDTO(response, response.size()); } @GetMapping(value = "/{id}") @ResponseBody public SuperDTO findById(@PathVariable("programId") String programId, @PathVariable("id") String id) { return new BodyItemDTO<ProjectDTO>(_service.get(id)); } }
class Flight: def __init__(self, airline, origin, destination, num_passengers, departure_time, arrival_time, flight_number): self.airline = airline self.origin = origin self.destination = destination self.num_passengers = num_passengers self.departure_time = departure_time self.arrival_time = arrival_time self.flight_number = flight_number def main(): # Create flight object flight1 = Flight("Delta", "New York", "Los Angeles", 20, "4:00PM", "10:00PM", "DL123") if __name__== "__main__": main()
const colors = { grey: '#333', snow: '#f5f5f5', lightGrey: '#f9f9f9', white: '#fff', blue: '#007291', red: '#c21703', orange: '#d8460b', yellow: '#f5c600', brown: '#9b4923', cream: '#EAE8CF', salmon: '#FE6856' } export default colors
package com.lbs.api.json.model /** { "PreparationInfo": { "IsPreparationRequired": true }, "ReservedVisitsLimitInfo": { "CanReserve": true, "HasPatientLimit": false, "MaxReservedVisitsCount": null, "Message": "", "ReservedVisitsCount": null } } */ case class ReservationResponse(preparationInfo: PreparationInfo, reservedVisitsLimitInfo: ReservedVisitsLimitInfo) extends SerializableJsonObject case class PreparationInfo(isPreparationRequired: Boolean) extends SerializableJsonObject case class ReservedVisitsLimitInfo(canReserve: Boolean, hasPatientLimit: Boolean, maxReservedVisitsCount: Option[Int], message: String, reservedVisitsCount: Option[Int]) extends SerializableJsonObject
<gh_stars>0 /** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.selenium.page; import java.util.List; import org.junit.Assert; import org.olat.selenium.page.coaching.CoachingPage; import org.olat.selenium.page.core.AdministrationPage; import org.olat.selenium.page.course.MyCoursesPage; import org.olat.selenium.page.graphene.OOGraphene; import org.olat.selenium.page.group.GroupsPage; import org.olat.selenium.page.qpool.QuestionPoolPage; import org.olat.selenium.page.repository.AuthoringEnvPage; import org.olat.selenium.page.repository.CatalogAdminPage; import org.olat.selenium.page.repository.CatalogPage; import org.olat.selenium.page.user.PortalPage; import org.olat.selenium.page.user.UserAdminPage; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; /** * Page fragment which control the navigation bar with the static sites. * * Initial date: 20.06.2014<br> * @author srosse, <EMAIL>, http://www.frentix.com * */ public class NavigationPage { private static final By navigationSitesBy = By.cssSelector("ul.o_navbar_sites"); private static final By authoringEnvTabBy = By.cssSelector("li.o_site_author_env > a"); private static final By questionPoolTabBy = By.cssSelector("li.o_site_qpool > a"); private static final By coachingTabBy = By.cssSelector("li.o_site_coaching > a"); private static final By portalBy = By.cssSelector("li.o_site_portal > a"); private static final By myCoursesBy = By.cssSelector("li.o_site_repository > a"); private static final By userManagementBy = By.cssSelector("li.o_site_useradmin > a"); private static final By administrationBy = By.cssSelector("li.o_site_admin > a"); private static final By catalogBy = By.cssSelector("li.o_site_catalog > a"); private static final By catalogAdministrationBy = By.cssSelector("li.o_site_catalog_admin > a"); private static final By groupsBy = By.cssSelector("li.o_site_groups > a"); public static final By myCoursesAssertBy = By.xpath("//div[contains(@class,'o_segments')]//a[contains(@onclick,'search.mycourses.student')]"); public static final By portalAssertBy = By.className("o_portal"); public static final By toolbarBackBy = By.cssSelector("li.o_breadcrumb_back>a"); private final WebDriver browser; private NavigationPage(WebDriver browser) { this.browser = browser; } public static final NavigationPage load(WebDriver browser) { OOGraphene.waitElement(navigationSitesBy, browser); return new NavigationPage(browser); } public NavigationPage assertOnNavigationPage() { WebElement navigationSites = browser.findElement(navigationSitesBy); Assert.assertTrue(navigationSites.isDisplayed()); return this; } public AuthoringEnvPage openAuthoringEnvironment() { try { navigate(authoringEnvTabBy); OOGraphene.waitElement(By.className("o_sel_author_env"), browser); return new AuthoringEnvPage(browser); } catch (Error | Exception e) { OOGraphene.takeScreenshot("Open authoring environment", browser); throw e; } } public QuestionPoolPage openQuestionPool() { navigate(questionPoolTabBy); return new QuestionPoolPage(browser) .assertOnQuestionPool(); } public CoachingPage openCoaching() { navigate(coachingTabBy); return new CoachingPage(browser); } public PortalPage openPortal() { navigate(portalBy); return new PortalPage(browser); } public MyCoursesPage openMyCourses() { try { navigate(myCoursesBy); OOGraphene.waitElement(myCoursesAssertBy, browser); return new MyCoursesPage(browser); } catch (Error | Exception e) { OOGraphene.takeScreenshot("Open my courses", browser); throw e; } } public UserAdminPage openUserManagement() { navigate(userManagementBy); return UserAdminPage.getUserAdminPage(browser); } public AdministrationPage openAdministration() { navigate(administrationBy); return new AdministrationPage(browser); } public CatalogAdminPage openCatalogAdministration() { navigate(catalogAdministrationBy); return new CatalogAdminPage(browser); } public CatalogPage openCatalog() { navigate(catalogBy); return new CatalogPage(browser); } public GroupsPage openGroups(WebDriver currentBrowser) { navigate(groupsBy); return GroupsPage.getPage(currentBrowser); } private void navigate(By linkBy) { List<WebElement> links = browser.findElements(linkBy); if(links.isEmpty() || !links.get(0).isDisplayed()) { //try to open the more menu openMoreMenu(); } OOGraphene.waitElement(linkBy, browser); browser.findElement(linkBy).click(); OOGraphene.waitBusy(browser); OOGraphene.waitingTransition(browser); } public void openCourse(String title) { By courseTab = By.xpath("//li/a[@title='" + title + "']"); List<WebElement> courseLinks = browser.findElements(courseTab); if(courseLinks.isEmpty() || !courseLinks.get(0).isDisplayed()) { openMoreMenu(); courseLinks = browser.findElements(courseTab); } Assert.assertFalse(courseLinks.isEmpty()); courseLinks.get(0).click(); OOGraphene.waitBusy(browser); } private void openMoreMenu() { By openMoreBy = By.cssSelector("#o_navbar_more a.dropdown-toggle"); OOGraphene.waitElement(openMoreBy, browser); browser.findElement(openMoreBy).click(); //wait the small transition By openedMoreMenuby = By.cssSelector("#o_navbar_more ul.dropdown-menu.dropdown-menu-right"); OOGraphene.waitElement(openedMoreMenuby, browser); } public NavigationPage closeTab() { By closeBy = By.xpath("//li//a[contains(@class,'o_navbar_tab_close')]"); browser.findElement(closeBy).click(); OOGraphene.waitBusy(browser); return this; } }
#!/bin/bash -e source /srv/sites/parentnode/mac_environment/scripts/functions.sh echo "" echo "ask test" echo "" # Standard email format: "david@think.dk" email_array=("[A-Za-z0-9\.\-]+@[A-Za-z0-9\.\-]+\.[a-z]{2,10}") email=$(ask "Enter email" "${email_array[@]}" "Email") # Username can both be an alias name:"superslayer2000", and a normal full name: "Bo Von Niedermeier" and "bo" username_array=("[A-Za-z0-9[:space:]]{2,50}") username=$(ask "Enter username" "${username_array[@]}" "Username") # Password format e.g: testPassword!2000@$ #password_array=("[A-Za-z0-9\!\@\$]{8,30}") #password1=$( ask "Enter password" "${password_array[@]}" "Password") #echo "" #password2=$( ask "Enter password again" "${password_array[@]}" "Password") #echo "" password_array=("[A-Za-z0-9\!\@\$]{8,30}") outputHandler "comment" "For security measures the terminal will not display how many characters you input" outputHandler "comment" "Password format: between 8 and 30 characters, non casesensitive letters, numbers and # ! @ \$ special characters " password1=$(ask "Enter password" "${password_array[@]}" "password") echo password2=$(ask "Confirm password" "${password_array[@]}" "password") echo # As long the first password input do not match the second password input it will prompt you in a loop to hit the correct keys til it finds a match if [ "$password1" != "$password2" ]; then while [ true ] do outputHandler "comment" "Passwords doesn't match" password_array=("[A-Za-z0-9\!\@\$]{8,30}") password1=$(ask "Enter password anew" "${password_array[@]}" "password") echo password2=$(ask "Confirm password" "${password_array[@]}" "password") echo # If there is a match it will break the loop if [ "$password1" == "$password2" ]; then outputHandler "comment" "Passwords Match" break fi export password1 done else outputHandler "comment" "Password Match" export password1 fi # While loop if not a match #if [ "$password1" != "$password2" ]; then # while [ true ] # do # echo "Password doesn't match" # echo # #password1=$( ask "Enter mariadb password" "${password_array[@]}" "Password") # password1=$( ask "Enter mariadb password" "${password_array[@]}" "Password") # echo "" # password2=$( ask "Enter mariadb password again" "${password_array[@]}" "Password") # echo "" # if [ "$password1" == "$password2" ]; # then # echo "Password Match" # break # fi # echo # done #else # echo "Password Match" #fi #export password1 echo "$email" echo "$username" echo "$password1"
<gh_stars>1-10 firebase.auth().languageCode = 'fr'; var user = undefined; document.getElementById('login_btn').onclick = function() { location.href = 'https://auth.infogare.fr/redirect.htm?returnurl=' + encodeURIComponent(location.href)+'&service=infogare&version=release'; } function loginWithToken(token) { firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL) .then(() => { firebase.auth().signInWithCustomToken(token).then((user) => { console.log(user.user.displayName); window.location.href = location.pathname; }); }); } function loginWithToken(token) { firebase.auth().signInWithCustomToken(token).then((user) => { console.log(user.user.displayName); window.location.href = location.pathname; }); } function login(email, password) { var params = new URLSearchParams(location.search); document.getElementById('checkemail').hidden = true; document.getElementById('checkpassword').hidden = true; document.getElementById('emailexists').hidden = true; document.getElementById('passwordweak').hidden = true; document.getElementById('checkusername').hidden = true; document.getElementById('error').hidden = true; var pers; if (document.getElementById('stay_connected').checked) { pers = firebase.auth.Auth.Persistence.LOCAL; } else { pers = firebase.auth.Auth.Persistence.SESSION; } firebase.auth().setPersistence(pers).then(() => { firebase.auth().signInWithEmailAndPassword(email, password) .then((userCredential) => { // Signed in var user = userCredential.user; firebase.database().ref('users/'+user.uid).get().then((snapshot) => { if (snapshot.val().tfa) { SecretCode = snapshot.val().tfacode; $('#tfa').modal('show'); } else { if (params.has('redirect')) { window.location.href = params.get('redirect'); } else { window.location.href='index.htm'; } } }); // ... }) .catch((error) => { var errorCode = error.code; var errorMessage = error.message; if (errorCode == 'auth/invalid-email') { document.getElementById('checkemail').hidden = false; }else if (errorCode == 'auth/wrong-password') { document.getElementById('checkpassword').hidden = false; } document.getElementById('error').hidden = false; }); }); } function signin(email, password, username) { document.getElementById('checkemail').hidden = true; document.getElementById('checkpassword').hidden = true; document.getElementById('emailexists').hidden = true; document.getElementById('passwordweak').hidden = true; document.getElementById('checkusername').hidden = true; document.getElementById('error').hidden = true; if (username == null) { document.getElementById('checkusername').hidden = false; document.getElementById('error').hidden = false; }else{ firebase.auth().createUserWithEmailAndPassword(email, password) .then((userCredential) => { // Signed in var user = userCredential.user; user.updateProfile({ displayName: username }).then(function() { firebase.database().ref('users').child(user.uid).update({ newsletter: document.getElementById('newsletter').checked }).then(() => { window.location.href = 'index.htm'; }) }).catch(function(error) { // An error happened. }); // ... }) .catch((error) => { var errorCode = error.code; var errorMessage = error.message; if (errorCode == 'auth/email-already-in-use') { document.getElementById('emailexists').hidden = false; }else if (errorCode == 'auth/weak-password') { document.getElementById('passwordweak').hidden = false; }else if (errorCode == 'invalid-email') { document.getElementById('checkemail').hidden = false; } document.getElementById('error').hidden = false; }); } } function checkLogin() { firebase.auth().onAuthStateChanged(function(user) { if (user) { document.getElementById('mnu_login').hidden = true; document.getElementById('mnu_gares').hidden = false; document.getElementById('mnu_compte').hidden = false; document.getElementById('mnu_username').innerText = user.displayName; document.getElementById('mnu_users').hidden = false; document.getElementById('mnu_logout').hidden = false; if (user.photoURL) { document.getElementById('mnu_user_photo').src = user.photoURL; document.getElementById('mnu_user_photo').style.display = 'block'; document.getElementById('mnu_user_no_photo').style.display = 'none'; } if (location.host === 'beta.infogare.fr') { checkBeta(user.uid); } this.user = user; } else { document.getElementById('mnu_login').hidden = false; document.getElementById('mnu_gares').hidden = true; document.getElementById('mnu_compte').hidden = true; document.getElementById('mnu_username').innerText = 'Non connecté'; document.getElementById('mnu_users').hidden = true; document.getElementById('mnu_logout').hidden = true; if (location.host === 'beta.infogare.fr') { checkBeta(user.uid); } } }); } function logout() { firebase.auth().signOut().then(() => { window.location.href="index.htm"; }).catch((error) => { console.error(error.message); }); } function checkBeta(userid) { firebase.database().ref('users/'+userid).get().then((snapshot) => { if (!snapshot.val().beta) { logout(); window.location.replace('beta_access_refused.htm'); } }); }
package org.fcrepo.lambdora.service.api; /** * A Fedora Container interface * * @author dbernstein */ public interface Container extends FedoraResource { }
const fetch = require("node-fetch"); const Discord = require('discord.js') const client = new Discord.Client() module.exports = { category: 'Fun', aliases: ['huggy'], minArgs: 0, maxArgs: -1, expectedArgs: "", description: 'hug sum1', callback: ({message, args, text, client, prefix, instance}) => { if (message.mentions.members.size == 1) { async function gift() { let member = message.mentions.members.first() let member2 = message.author let member3 = member2.tag const response = await fetch(`https://api.giphy.com/v1/gifs/random?api_key=vx9sXJ6uR6QCmbUIbKB7UBTMm2VTtHmE&tag=hug&rating=g`); const data = await response.json(); let gif = data.data.image_original_url const Embed = new Discord.MessageEmbed() .setColor(0x00AE86) .setTimestamp() .setTitle(`${member3} gave ${member.user.tag} a hug!`) .setImage(gif) message.reply(Embed) message.react(`${tick}`) } gift(); } } }
package edu.uwp.appfactory.racinezoo.Model; import java.util.Objects; import edu.uwp.appfactory.racinezoo.Util.Config; /** * Created by hanh on 2/18/17. */ public class DetailItem { private String title; private Object data; private int type; public DetailItem(String title, Object data, int type){ this.data = data; this.title = title; this.type = type; } public DetailItem(String title, Object data){ this.data = data; this.title = title; this.type = Config.DETAIL_TYPE_GENERAL; } public String getTitle() { return title; } public Object getContent() { return data; } public int getType() { return type; } }
def transposeMatrix(matrix): transpose = [] for i in range(len(matrix[0])) : new_row = [] for row in matrix: new_row.append(row[i]) transpose.append(new_row) return transpose
// Construct an array that stores the grades of all the students grades = [90, 85, 82, 75, 70, 65, 80, 81, 73]; // Loop through the array sum = 0; numOfGrades = grades.length; for (int i = 0; i < numOfGrades; i++) { sum += grades[i]; } // Calculate the average grade averageGrade = sum/numOfGrades; // Print the average grade console.log("Average Grade: " + averageGrade); // Generate a report report = "" report += "Number of Students: " + numOfGrades + "\n"; report += "Average Grade: " + String(averageGrade); console.log(report);
#! /bin/bash # # A script to collect help texts of rhui-manager's commands recursively. # # Author: Satoru SATOH <ssato at redhat.com> # License: MIT # # Usage: ./collect_rhui-manager_help_recur.sh # # Example: # # [root@rhui-2 ~]# ./collect_rhui-manager_help_recur.sh # rhui-manager # Usage: rhui-manager [options] [command] # # OPTIONS # -h/--help show this help message and exit # --debug enables debug logging # --config absolute path to the configuration file; defaults to /etc/rhui/rhui.conf # --server location of the RHUA server (overrides the config file) # --username if specified, previously saved authentication credentials are ignored and this username is used to login # --password used in conjunction with --username # # COMMANDS # cert : Red Hat content certificate management # packages : package manipulation on repositories # repo : repository listing and manipulation # status : RHUI status and health information # cds : associated cds commands # client : Red Hat client management # # Options: # # rhui-manager cert # Red Hat content certificate management # info : display information about the current content certificate # upload : uploads a new content certificate # repair : reloads a content certificate # # rhui-manager cert info # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # info: display information about the current content certificate # # rhui-manager cert upload # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # upload: uploads a new content certificate # --cert - full path to the new content certificate (required) # --key - full path to the new content certificate's key # # rhui-manager cert repair # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # repair: reloads a content certificate # --cert - full path to the new content certificate # --key - full path to the new content certificate's key # --force - force a repair, to be used w/ --cert and --key # # rhui-manager packages # package manipulation on repositories # upload : uploads a package or directory of packages to a repository # list : lists all packages in a repository # # rhui-manager packages upload # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # upload: uploads a package or directory of packages to a repository # --repo_id - id of the repository where the packages will be uploaded (required) # --packages - path to an .rpm file or directory of RPMs that will be uploaded (required) # # rhui-manager packages list # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # list: lists all packages in a repository # --repo_id - id of the repository to list packages for (required) # # rhui-manager repo # repository listing and manipulation # list : lists all repositories in the RHUI # info : displays information on an individual repo # add : add a Red Hat respository to the RHUA # sync : sync a repository # unused : list of products available but not synced to the RHUA # # rhui-manager repo list # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # list: lists all repositories in the RHUI # # rhui-manager repo info # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # info: displays information on an individual repo # --repo_id - identifies the repository to display (required) # # rhui-manager repo add # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # add: add a Red Hat respository to the RHUA # --product_name - repository id to add the RHUA (required) # # rhui-manager repo sync # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # sync: sync a repository # --repo_id - identifies the repository to display (required) # # rhui-manager repo unused # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # unused: list of products available but not synced to the RHUA # # rhui-manager status # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # status: RHUI status and health information # --code - if specified, only a numeric code for the result will be displayed # # rhui-manager cds # associated cds commands # available : list of cds servers available to sync # sync : sync content to specified cds # associate : associate a repo with a cds # clusters : list of cds clusters # repos : list of repositories for provided cluster # # rhui-manager cds available # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # available: list of cds servers available to sync # # rhui-manager cds sync # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # sync: sync content to specified cds # --cds_id - identifies the cds to sync (required) # # rhui-manager cds clusters # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # clusters: list of cds clusters # # rhui-manager cds repos # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # repos: list of repositories for provided cluster # --cluster_name - name of cluster (required) # # rhui-manager client # Red Hat client management # labels : list the labels required for client certificate creation # cert : create a content certificate for a rhui client # rpm : create a client config rpm # # rhui-manager client labels # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # labels: list the labels required for client certificate creation # # rhui-manager client cert # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # cert: create a content certificate for a rhui client # --repo_label - identifies the repositories to add. Comma delimited string of repo labels (required) # --name - identifies the certificate name (required) # --days - number of days cert will be valid (required) # --dir - directory where the certificate will be stored (required) # # rhui-manager client rpm # Usage: rhui-manager [options] # # Options: # -h, --help show this help message and exit # rpm: create a client config rpm # --private_key - entitlement private key (required) # --entitlement_cert - entitlement certificate (required) # --primary_cds - the cds used as the primary load balancer for a the cds cluster (required) # --ca_cert - full path to CA certificate (required) # --rpm_version - version number of the client config rpm (required) # --rpm_name - name of the client config rpm (required) # --dir - directory where the rpm will be created (required) # [root@rhui-2 ~]# # set -e list_subcmds_from_out () { test "x$@" = "x" || echo "$@" | sed -nr 's/\s+([^\s:]+):.*/\1/p' } list_subcmds_recur () { local sc=$@ local help=$($sc --help) local scs=$(list_subcmds_from_out "$help") echo "# $sc"; echo "$help" for ssc in $scs; do list_subcmds_recur $sc $ssc; done } list_subcmds_recur ${@:-rhui-manager}
import { Readable, Writable, Transform } from 'readable-stream'; import { IBuildState } from './BuildState'; import { IStep } from './Step'; export interface IPipelineNode { readonly prev: IPipelineNode[]; readonly step: IStep; readonly next: IPipelineNode[]; readonly alias: string; readonly stream: Readable | Writable | Transform | undefined; } /** * This class represents a single Node in a Pipeline. Each Node * is connected to other Nodes upstream (prev) and downstream (next). */ export declare class PipelineNode implements IPipelineNode { readonly prev: PipelineNode[]; readonly step: IStep; readonly next: PipelineNode[]; get stream(): Readable | Writable | Transform | undefined; get alias(): string; private connected; private _stream; constructor(step: IStep); connect(state: IBuildState): Promise<void>; pipe(nodes: PipelineNode | PipelineNode[]): void; /** * Based on the position in the Pipeline, will setup * this node's stream. */ makeStream(state: IBuildState): Promise<Readable | Writable | Transform>; }
// Generated by Haxe 3.4.0 (function () { "use strict"; var MainJS = function() { console.log("[JS] loading data example"); var req = new XMLHttpRequest(); req.open("GET","http://ip.jsontest.com/"); req.onload = function() { console.log("[JS] Your IP-address: " + JSON.parse(req.response).ip); }; req.onerror = function(error) { window.console.error("[JS] error: " + error); }; req.send(); }; MainJS.main = function() { new MainJS(); }; MainJS.main(); })();
<gh_stars>10-100 import React, {memo} from 'react' import styled from 'styled-components' import playIcon from '@/assets/icon/play.svg' import previewIcon from '@/assets/icon/preview.svg' import themeIcon from '@/assets/icon/theme.svg' import {RouteComponentProps, withRouter} from 'react-router' import {FixedSpace, FlexSpace, IconButton, PageHeader} from '@/components/page-header' import {useStore} from 'reto' import {EditPageStore} from '@/stores/edit-page.store' import {enterFullscreen} from '@/utils/fullscreen' const SearchInput = styled.input` font-size: 15px; border: none; flex: auto; font-weight: normal; font-family: inherit; color: inherit; ::placeholder { color: #E5E5E5; } :focus { outline: none; caret-color: #17AE7E; } ` export const EditPageHeader = withRouter(memo<RouteComponentProps>((props) => { const editPageStore = useStore(EditPageStore) function togglePreview() { editPageStore.setShowPreview(!editPageStore.showPreview) } function startPresentation() { props.history.push('/presentation/0') } return ( <PageHeader> {/*<IconButton src={searchIcon}/>*/} {/*<SearchInput placeholder='Search every document...' spellCheck={false}/>*/} {/*<FixedSpace/>*/} <FlexSpace/> <IconButton src={previewIcon} onClick={togglePreview}/> <FixedSpace/> <IconButton src={themeIcon} onClick={() => {props.history.push('./edit/theme')}}/> <IconButton src={playIcon} onClick={startPresentation}/> {/*<FixedSpace/>*/} {/*<IconButton src={exportIcon} onClick={() => {console.log(editPageStore.slideElementsRef.current)}}/>*/} {/*<IconButton src={shareIcon}/>*/} </PageHeader> ) }))
package biz.kasual.recyclerfragmentsample.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.Collections; import java.util.Comparator; import java.util.List; import biz.kasual.recyclerfragmentsample.adapters.SampleAdapter; import biz.kasual.recyclerfragmentsample.adapters.SampleSectionViewAdapter; import biz.kasual.recyclerfragmentsample.models.Sample; /** * Created by <NAME> on 06/11/2015. */ public class CustomSectionRecyclerFragment extends AbstractRecyclerFragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View contentView = super.onCreateView(inflater, container, savedInstanceState); configureFragment(mRecyclerView, mSampleAdapter, new SampleSectionViewAdapter(getActivity())); List<Sample> samples = SampleAdapter.buildSamples(); Collections.sort(samples, new Comparator<Sample>() { @Override public int compare(Sample lhs, Sample rhs) { return lhs.getRate() - rhs.getRate(); } }); displayItems(samples); return contentView; } @Override public String sortSectionMethod() { return "getRate"; } }
<filename>gofiql/util.go package gofiql import ( "bytes" "fmt" "regexp" ) // spitExpression takes in input a constraint expression and splits it // into its component parts, i.e. left operand, right operand and // operator. // It makese uses of a regular expression. func splitExpression(expression *string) (*string, *string, *string, error) { re := regexp.MustCompile(expressionRx) if re == nil { return nil, nil, nil, fmt.Errorf("Problem with the regexp: unable to compile") } match := re.FindAllStringSubmatch(*expression, -1) if len(match) == 0 { return nil, nil, nil, fmt.Errorf("No match found for %s", *expression) } names := re.SubexpNames() if len(names) != 4 { return nil, nil, nil, fmt.Errorf("Problem with the regexp: not enough names") } var lOperand, rOperand, operator string for i, v := range match[0] { if names[i] == "lOperand" { lOperand = v } else if names[i] == "rOperand" { rOperand = v } else if names[i] == "operator" { operator = v } } return &lOperand, &operator, &rOperand, nil } // tabs concatenas tabs according to the depth and so the // indication of the tree level provided in input. func tabs(depth int) string { var buffer bytes.Buffer for i := 0; i < depth; i++ { buffer.WriteString("\t") } return buffer.String() } // checkParenthesis checks the parenthesis of an expression. // It returns 'false' in case of malformed parenthesis combination, // 'true' elsewhere. func checkParenthesis(expression *string) bool { chars := []byte(*expression) stack := newStack() cntr := 0 for _, char := range chars { if char == lParenthesisByte { cntr++ stack.push(&lParenthesis) } if char == rParenthesisByte { cntr-- stack.pop() } } if cntr == 0 && stack.len() == 0 { return true } return false } // PrettyPrinting performs an AST traversal and prints out // the tree in a pretty hierarchical format. func PrettyPrinting(root *Node, depth int) { fmt.Printf("%s%s\n", tabs(depth), root.expression.String()) if root.lChild != nil { PrettyPrinting(root.lChild, depth+1) } if root.rChild != nil { PrettyPrinting(root.rChild, depth+1) } } // stack provides a basic implementation of the stack logic // based off a string slice. type stack struct { stack []*string } // newStack creates a new slice backing the stack. func newStack() *stack { return &stack{ stack: make([]*string, 0), } } // Push pushes an element on the stack func (s *stack) push(v *string) { s.stack = append(s.stack, v) } // Top returns the topmost element without removing it from // the datastructure. func (s *stack) top() *string { if len(s.stack) > 0 { return s.stack[len(s.stack)-1] } return nil } // Pop returns the topmost elemet and removes it from the // datastructure. func (s *stack) pop() *string { if len(s.stack) > 0 { v := s.stack[len(s.stack)-1] s.stack = s.stack[:len(s.stack)-1] return v } return nil } // Len returns the length in terms of element of the backing // datastructure. func (s *stack) len() int { return len(s.stack) }
package be.wyckd.datastructures; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; public class QueueTest { private Queue<Integer> queue; @Before public void setUp(){ queue = new Queue<>(); } @Test public void enqueElement_shouldAddElement(){ queue.enqueue(5); assertThat(queue.dequeue(), is(5)); } @Test public void dequeue_shouldPopElements_inOrder(){ queue.enqueue(5); queue.enqueue(7); queue.enqueue(9); assertThat(queue.dequeue(), is(5)); assertThat(queue.dequeue(), is(7)); assertThat(queue.dequeue(), is(9)); } }
<gh_stars>0 /* * Copyright (c) 2015. Seagate Technology PLC. All rights reserved. */ package com.seagate.alto.provider.lyve.response; import com.google.gson.Gson; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Match { @SerializedName("match_type") @Expose public MatchType matchType; @SerializedName("metadata") @Expose public Metadata metadata; @Override public String toString() { return new Gson().toJson(this); } }
<filename>src/engine/events/KeyReleaseEvent.java package engine.events; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; /** * Event that releases KeyReleaseEvent * @author estellehe */ public class KeyReleaseEvent extends Event { private KeyEvent event; private boolean isGaming; /** * Creates a new KeyReleaseEvent * @param event event of key release * @param isGaming whether or not engine is gaming */ public KeyReleaseEvent(KeyEvent event, boolean isGaming) { super(EventType.RELEASE.getType()); this.event = event; this.isGaming = isGaming; } /** * @return key code of event */ public KeyCode getKeyCode() { return event.getCode(); } /** * @return whether or not engine is gaming */ public boolean isGaming() { return isGaming; } }
echo "####################################################################" echo "## Full Test Scripts for CB-Spider IID Working Version - 2020.04.22." echo "## 1. VPC: Create -> Add-Subnet -> List -> Get" echo "## 2. SecurityGroup: Create -> List -> Get" echo "## 3. KeyPair: Create -> List -> Get" echo "## 4. VM: StartVM -> List -> Get -> ListStatus -> GetStatus -> Suspend -> Resume -> Reboot" echo "## ---------------------------------" echo "## 4. VM: Terminate(Delete)" echo "## 3. KeyPair: Delete" echo "## 2. SecurityGroup: Delete" echo "## 1. VPC: Remove-Subnet -> Delete" echo "####################################################################" echo "####################################################################" echo "## 1. VPC: Create -> List -> Get" echo "####################################################################" curl -H "${AUTH}" -sX POST http://localhost:1024/spider/vpc -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'", "ReqInfo": { "Name": "vpc-01", "IPv4_CIDR": "192.168.0.0/16", "SubnetInfoList": [ { "Name": "subnet-01", "IPv4_CIDR": "192.168.1.0/24"} ] } }' |json_pp curl -H "${AUTH}" -sX POST http://localhost:1024/spider/vpc/vpc-01/subnet -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'", "ReqInfo": { "Name": "subnet-02", "IPv4_CIDR": "192.168.2.0/24" } }' |json_pp curl -H "${AUTH}" -sX GET http://localhost:1024/spider/vpc -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp curl -H "${AUTH}" -sX GET http://localhost:1024/spider/vpc/vpc-01 -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp echo "#-----------------------------" echo "####################################################################" echo "## 2. SecurityGroup: Create -> List -> Get" echo "####################################################################" curl -H "${AUTH}" -sX POST http://localhost:1024/spider/securitygroup -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'", "ReqInfo": { "Name": "sg-01", "VPCName": "vpc-01", "SecurityRules": [ {"FromPort": "1", "ToPort" : "65535", "IPProtocol" : "tcp", "Direction" : "inbound", "CIDR" : "0.0.0.0/0"} ] } }' |json_pp curl -H "${AUTH}" -sX GET http://localhost:1024/spider/securitygroup -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp curl -H "${AUTH}" -sX GET http://localhost:1024/spider/securitygroup/sg-01 -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp echo "#-----------------------------" echo "####################################################################" echo "## 3. KeyPair: Create -> List -> Get" echo "####################################################################" curl -H "${AUTH}" -sX POST http://localhost:1024/spider/keypair -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'", "ReqInfo": { "Name": "keypair-01" } }' |json_pp curl -H "${AUTH}" -sX GET http://localhost:1024/spider/keypair -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp curl -H "${AUTH}" -sX GET http://localhost:1024/spider/keypair/keypair-01 -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp echo "#-----------------------------" echo "####################################################################" echo "## 4. VM: StartVM -> List -> Get -> ListStatus -> GetStatus -> Suspend -> Resume -> Reboot" echo "####################################################################" curl -H "${AUTH}" -sX POST http://localhost:1024/spider/vm -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'", "ReqInfo": { "Name": "vm-01", "ImageName": "'${IMAGE_NAME}'", "VPCName": "vpc-01", "SubnetName": "subnet-01", "SecurityGroupNames": [ "sg-01" ], "VMSpecName": "'${SPEC_NAME}'", "KeyPairName": "keypair-01"} }' |json_pp echo "============== sleep 1 after start VM" sleep 1 curl -H "${AUTH}" -sX GET http://localhost:1024/spider/vm -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp echo "============== after List VM" curl -H "${AUTH}" -sX GET http://localhost:1024/spider/vm/vm-01 -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp echo "============== after Get VM" curl -H "${AUTH}" -sX GET http://localhost:1024/spider/vmstatus -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp echo "============== after List VM Status" curl -H "${AUTH}" -sX GET http://localhost:1024/spider/vmstatus/vm-01 -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp echo "============== after Get VM Status" curl -H "${AUTH}" -sX GET http://localhost:1024/spider/controlvm/vm-01?action=suspend -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp echo "============== sleep 1 after suspend VM" sleep 1 curl -H "${AUTH}" -sX GET http://localhost:1024/spider/controlvm/vm-01?action=resume -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp echo "============== sleep 1 after resume VM" sleep 1 curl -H "${AUTH}" -sX GET http://localhost:1024/spider/controlvm/vm-01?action=reboot -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp echo "============== sleep 1 after reboot VM" sleep 1 echo "#-----------------------------" echo "####################################################################" echo "####################################################################" echo "####################################################################" echo "####################################################################" echo "## 4. VM: Terminate(Delete)" echo "####################################################################" curl -H "${AUTH}" -sX DELETE http://localhost:1024/spider/vm/vm-01 -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp echo "============== sleep 1 after delete VM" sleep 1 echo "####################################################################" echo "## 3. KeyPair: Delete" echo "####################################################################" curl -H "${AUTH}" -sX DELETE http://localhost:1024/spider/keypair/keypair-01 -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp echo "####################################################################" echo "## 2. SecurityGroup: Delete" echo "####################################################################" curl -H "${AUTH}" -sX DELETE http://localhost:1024/spider/securitygroup/sg-01 -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp echo "####################################################################" echo "## 1. VPC: Remove-Subnet -> Delete" echo "####################################################################" curl -H "${AUTH}" -sX DELETE http://localhost:1024/spider/vpc/vpc-01/subnet/subnet-02 -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp curl -H "${AUTH}" -sX DELETE http://localhost:1024/spider/vpc/vpc-01 -H 'Content-Type: application/json' -d '{ "ConnectionName": "'${CONN_CONFIG}'"}' |json_pp
<reponame>dmitric/studio import React, { Component } from 'react' import { Button, Slider, Popover, PopoverInteractionKind, Position } from "@blueprintjs/core" export default class StudioToolbar extends Component { constructor (props) { super(props) this.onToggle = this.onToggle.bind(this) this.onPrevious = this.onPrevious.bind(this) this.onNext = this.onNext.bind(this) this.onFrameChange = this.onFrameChange.bind(this) this.onFrameRelease = this.onFrameRelease.bind(this) this.onFrameDelete = this.onFrameDelete.bind(this) this.onFrameAdd = this.onFrameAdd.bind(this) this.onFileSelect = this.onFileSelect.bind(this) this.createFrame = this.createFrame.bind(this) } onToggle () { this.props.framePlayer.toggle() if (this.props.framePlayer.isPlaying()) { if (this.props.debug) { this.props.debugToaster.show({ message: 'Player started', iconName: 'play'}) } } else { if (this.props.debug) { this.props.debugToaster.show({ message: 'Player paused', iconName: 'pause'}) } } } onPrevious () { this.props.framePlayer.moveToPreviousFrame() if (this.props.debug) { this.props.debugToaster.show({ message: 'Previous frame', iconName: 'step-backward'}) } } onNext () { this.props.framePlayer.moveToNextFrame() if (this.props.debug) { this.props.debugToaster.show({ message: 'Next frame', iconName: 'step-forward'}) } } onFrameChange (result) { this.props.framePlayer.moveToFrame(result-1) } onFrameRelease (result) { if (this.props.debug) { this.props.debugToaster.show({ message: `Skipped to frame ${result}`, iconName: 'arrows-horizontal'}) } } onFrameDelete (result) { if (this.props.debug) { this.props.debugToaster.show({ message: `Removed frame ${result+1}`, iconName: 'delete'}) } this.props.framePlayer.removeFrame(result) } onFrameAdd (event) { this.refs.file.click() } onFileSelect (e) { let files = [] if (e.dataTransfer) { files = e.dataTransfer.files } else if (e.target) { files = e.target.files } for (var i = 0; i < files.length; i++) { this.createFrame(files[i]) } } createFrame (file) { const reader = new FileReader() reader.onloadend = (e) => { this.props.framePlayer.addFrame({url: e.target.result}) if (this.props.debug) { this.props.debugToaster.show({ message: `Added frame`, iconName: 'add'}) } } reader.readAsDataURL(file) } render () { let framesContent if (this.props.framePlayer.frames.length) { framesContent = this.props.framePlayer.frames.map((frame, ii) => { let styles = { width: '70px', textAlign: 'center'} let classNames = 'pt-callout' if (this.props.framePlayer.currentFrameIndex === ii) { styles.backgroundColor = 'rgba(195, 228, 22, 0.25)' } return ( <td className={classNames} key={ii} style={styles} onClick={() => this.onFrameChange(ii+1) } > <div className='frame-preview'> <img alt={ii} src={frame.url} /> </div> <Button iconName='delete' text='Remove' className='pt-minimal' onClick={() => this.onFrameDelete(ii) } /> </td> ) }) } else { framesContent = ( <td className='pt-callout' style={{width: '427px', height: '125px', textAlign: 'center'}}> Click the + button to add a frame </td> ) } const popoverContent = ( <div className='group' style={{ width: '500px'}} > <div style={{ float: 'left', width: '427px', overflowX: 'auto', height: '100%' }}> <table> <tbody> <tr> {framesContent} </tr> </tbody> </table> </div> <div style={{ float: 'left', height: '125px', marginTop: '2px', marginLeft: '5px'}} className="pt-callout pt-intent-primary"> <Button iconName='add' className='pt-large pt-intent-primary fill-height' onClick={this.onFrameAdd} /> <form> <input type="file" ref="file" multiple accept='image/*' onChange={this.onFileSelect} style={{display: "none"}} /> </form> </div> </div> ) const hasFrames = this.props.framePlayer.frames.length >= 1 return ( <div className='StudioToolbar'> <div className='pt-card' style={{ marginBottom: '10px'}}> <div className='left-button' style={{ position: "absolute", left: 10, top: 25, bottom: 0}}> <Popover content={popoverContent} interactionKind={PopoverInteractionKind.CLICK} position={Position.TOP_LEFT} lazy={true} popoverClassName='pt-bound-width'> <Button iconName="properties" /> </Popover> </div> <div className='buttons' style={{ marginBottom: "10px"}}> <Button iconName="step-backward" className="pt-large" onClick={this.onPrevious} />&nbsp; <Button iconName={this.props.framePlayer.isPlaying() ? "pause": "play"} className="pt-large" onClick={this.onToggle} />&nbsp; <Button iconName="step-forward" className="pt-large" onClick={this.onNext} /> </div> <div className="slider"> <Slider value={ hasFrames ? this.props.framePlayer.currentFrameIndex + 1 : 1} min={1} max={ Math.max(this.props.framePlayer.frames.length, 2)} initialValue={1} disabled={this.props.framePlayer.frames.length <= 1} renderLabel={false} onChange={this.onFrameChange} onRelease={this.onFrameRelease} /> </div> <div className='right-button' style={{ position: "absolute", right: 10, top: 25, bottom: 0}}> <Button iconName={this.props.fullScreen ? 'minimize' : 'fullscreen'} onClick={this.props.toggleFullScreen} /> </div> </div> { hasFrames ? `${this.props.framePlayer.currentFrameIndex+1} / ${this.props.framePlayer.frames.length}` : 'No frames' } </div> ) } }
from django.conf import settings # import the settings file def in_prod(request): return {"IN_PROD" : not settings.DEBUG}
import { SearchResponse } from '@clinia/client-search'; export interface MultiResponse<THit = any> { results: Array<SearchResponse<THit>>; }
/** * Created by admin on 2017/12/21. */ var path = require('path') var webpack = require('webpack') var context = path.join(__dirname, '..') module.exports = { entry: { vendor: ['vue','vue-router','axios'] }, output: { path: path.join(context, 'static/js'), filename: '[name].dll.js', library: '[name]' }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js' } }, plugins: [ new webpack.DllPlugin({ path: path.join(context, '[name].manifest.json'), name: '[name]', context: context }), // 压缩js代码 new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, output: { // 删除打包后的注释 comments: false } }), ] }
<reponame>orkestra/OrkestraApplicationBundle ;(function($) { window.Orkestra = window.Orkestra || {}; Orkestra.Modal = Orkestra.Modal || {}; var _createHeader = function(title) { this.$header = $(document.createElement('div')) .addClass('modal-header') .html($(document.createElement('h3')).addClass('modal-title').html(title)) .prepend('<button type="button" class="close js-cancel-button">&times;</button>') .appendTo(this.$el); }; var _createContent = function(content) { this.$content = $(document.createElement('div')) .addClass('modal-body') .html(content) .appendTo(this.$el); }; var _createFooter = function() { this.$footer = $(document.createElement('div')) .addClass('modal-footer'); if (this.options.cancelButton) { this.$footer.append( $(document.createElement('button')) .attr({ type: 'button', 'class': 'js-cancel-button btn btn-default' }) .html('<i class="icon-remove"></i> ' + this.options.cancelLabel) ); } if (this.options.acceptButton) { this.$footer.append( $(document.createElement('button')) .attr({ type: 'submit', 'class': 'js-accept-button btn btn-primary' }) .html('<i class="icon-ok"></i> ' + this.options.acceptLabel) ); } this.$footer.appendTo(this.$el); }; var _defaults = { acceptButton: true, acceptLabel: 'Save Changes', cancelButton: true, cancelLabel: 'Cancel' }; /** * A Modal window. * * Available events: * - before_show, show, * - before_hide, hide * - before_cancel, cancel * - before_accept, accept * - bind * * @type Orkestra.Modal.GenericModalView */ Orkestra.Modal.GenericModalView = Backbone.View.extend({ className: 'modal', $header: null, $content: null, $footer: null, $form: null, $acceptButton: null, $cancelButton: null, context: null, initialize: function() { this.options = $.extend({}, _defaults, this.options); this.on('before_show', this.render, this); this.on('show', function() { Orkestra.bindEnhancements(this.$el); }, this); if (this.options.accept) { this.on('accept', this.options.accept, this); } if (this.options.cancel) { this.on('cancel', this.options.cancel, this); } }, trigger: function(eventName, callback) { var beforeEventName = 'before_' + eventName, deferred = $.Deferred(); var self = this, eventCallback = function() { callback.apply(self); Backbone.Events.trigger.call(self, eventName); }; deferred.done(eventCallback); var eventArgs = { view: self, deferred: deferred, eventName: eventName, callback: eventCallback }; Backbone.Events.trigger.call(self, beforeEventName, eventArgs); if ('pending' === deferred.state()) { deferred.resolve(); } }, bindControlsToForm: function(form, options) { Orkestra.form.bind(form, options); this.stopListening(this, 'before_accept'); this.listenTo(this, 'before_accept', function(eventArgs) { eventArgs.deferred.reject(); $(form).submit(); }); }, bind: function() { var context = arguments; this.trigger('bind', function() { this.context = context; }); return this; }, show: function() { this.trigger('show', function() { this.$el.modal(this.options); }); }, hide: function() { this.trigger('hide', function() { this.$el.modal('hide'); }); }, render: function() { _createHeader.call(this, this.options.title); _createContent.call(this, this.options.content); _createFooter.call(this); this.$el.addClass('fade'); this.$acceptButton = this.$('.js-accept-button'); this.$cancelButton = this.$('.js-cancel-button'); var self = this; this.$cancelButton.unbind('click.cancel').bind('click.cancel', function() { self.trigger('cancel', function() { self.hide(); }); }); this.$acceptButton.unbind('click.accept').bind('click.accept', function() { self.trigger('accept', function() { self.hide(); }); }); return this; } }); })(jQuery);
#!/bin/bash act -P ubuntu-latest=nektos/act-environments-ubuntu:18.04
/* * Copyright (c) CERN 2013-2015 * * Copyright (c) Members of the EMI Collaboration. 2010-2013 * See http://www.eu-emi.eu/partners for details on the copyright * holders. * * 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. */ #ifndef DELEGCRED_H_ #define DELEGCRED_H_ /** * DelegCred API. * Define the interface for retrieving a the User Credentials for a given user * DN */ class DelegCred { public: /** * Get name of a file containing the credentials for the requested user * @param userDn [IN] The distinguished name of the user * @param id [IN] The credential id needed to retrieve the user's * credentials (may be a passoword or an identifier, depending on the * implementation) */ static std::string getProxyFile(const std::string &userDn, const std::string &id); /** * Returns true if the certificate in the given file name is still valid * @param filename [IN] trhe name of the file containing the proxy certificate * @return true if the certificate in the given file name is still valid */ static bool isValidProxy(const std::string &filename, std::string &message); private: /** * Generate a name for the file that should contain the proxy certificate. * The length of this name shoud be (MAX_FILENAME - 7) maximum. * @param userDn [IN] the user DN passed to the get method * @param id [IN] the credential id passed to the get method * @return the generated file name */ static std::string generateProxyName(const std::string &userDn, const std::string &id); /** * Get a new Certificate and store in into a file * @param userDn [IN] the user DN passed to the get method * @param id [IN] the credential id passed to the get method * @param fname [IN] the name of a temporary file where the new proxy * certificate should be stored */ static void getNewCertificate(const std::string &userDn, const std::string &credId, const std::string &fname); /** * Returns the validity time that the cached copy of the certificate should * have. * @return the validity time that the cached copy of the certificate should * have */ static unsigned long minValidityTime(); /** * Forbid instantiation */ DelegCred(); }; #endif // DELEGCRED_H_
/***************************** LICENSE START *********************************** Copyright 2009-2020 ECMWF and INPE. This software is distributed under the terms of the Apache License version 2.0. In applying this license, ECMWF does not waive the privileges and immunities granted to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction. ***************************** LICENSE END *************************************/ #ifndef TREENODEWIDGET_HPP_ #define TREENODEWIDGET_HPP_ #include "ui_TreeNodeWidget.h" #include "NodeWidget.hpp" #include "VProperty.hpp" class AttributeFilter; class NodeStateFilter; class ServerFilter; class VParamFilterMenu; class VSettings; class VTreeServer; class TreeNodeWidget : public NodeWidget, public VPropertyObserver, protected Ui::TreeNodeWidget { Q_OBJECT public: TreeNodeWidget(ServerFilter*,QWidget* parent=nullptr); ~TreeNodeWidget() override; void populateDockTitleBar(DashboardDockTitleWidget* tw) override; void rerender() override; bool initialSelectionInView() override; void writeSettings(VComboSettings*) override; void readSettings(VComboSettings*) override; void notifyChange(VProperty*) override; protected Q_SLOTS: void on_actionBreadcrumbs_triggered(bool b); void slotSelectionChangedInView(VInfo_ptr info); void slotAttsChanged(); void firstScanEnded(const VTreeServer*); protected: enum ViewLayoutMode {StandardLayoutMode,CompactLayoutMode}; void initAtts(); void detachedChanged() override {} void setViewLayoutMode(ViewLayoutMode); VParamFilterMenu *stateFilterMenu_; VParamFilterMenu *attrFilterMenu_; VParamFilterMenu *iconFilterMenu_; ViewLayoutMode viewLayoutMode_; VProperty* layoutProp_; static AttributeFilter* lastAtts_; std::string firstSelectionPath_; }; #endif
#!/bin/bash # -*- mode: shell-script ; -*- # # parse_ini.sh # ---- Read .ini file and output with shell variable definitions. # Nanigashi Uji (53845049+nanigashi-uji@users.noreply.github.com) # function parse_ini () { # Prepare Help Messages local funcstatus=0; local echo_usage_bk=$(declare -f echo_usage) local sed_list_section_bk=$(declare -f sed_list_section) local cleanup_bk=$(declare -f cleanup) local tmpfiles=() local tmpdirs=() function echo_usage () { if [ "$0" == "${BASH_SOURCE:-$0}" ]; then local this=$0 else local this="${FUNCNAME[1]}" fi echo "[Usage] % $(basename ${this}) -list file [files ...]" 1>&2 echo " % $(basename ${this}) [options] file [files ...]" 1>&2 echo "" 1>&2 echo "[Options]" 1>&2 echo " -l,--list : List sections " 1>&2 echo " -S,--sec-select name : Section name to select" 1>&2 echo " -T,--sec-select-regex expr : Section reg. expr. to select" 1>&2 echo " -V,--variable-select name : variable name to select" 1>&2 echo " -W,--variable-select-regex expr : variable reg. expr. to select" 1>&2 echo " -L,--local : Definition as local variables (B-sh)" 1>&2 echo " -e,--env : Definition as enviromnental variables" 1>&2 echo " -q,--quot : Definition by quoting with double/single-quotation." 1>&2 echo " -c,--csh,--tcsh : Output for csh statement (default: B-sh)" 1>&2 echo " -b,--bsh,--bash : Output for csh statement (default)" 1>&2 echo " -s,--sec-prefix : add prefix: 'sectionname_' to variable names. " 1>&2 echo " -v,--verbose : Verbose messages " 1>&2 echo " -h,--help : Show Help (this message)" 1>&2 echo "" 1>&2 echo " --------------------------------------------------------------------------" 1>&2 echo "" 1>&2 echo "[.ini file format]" 1>&2 echo "" 1>&2 echo " [section] modulename/'global' " 1>&2 echo " parameter_name=value" 1>&2 echo "" 1>&2 echo " parameter_name:" 1>&2 echo " No 4-spaces/tabs before variable_name; Otherwise it will be treated" 1>&2 echo " as the following contents of its previous line." 1>&2 echo "" 1>&2 echo " value:" 1>&2 echo " it will be quoted by \"...\" or '...' by -q/--quot option" 1>&2 echo "" 1>&2 echo " The text from [#;] to the end of line will be treated as comment.(Ignored)" 1>&2 echo "" 1>&2 echo " If backslash (\) exists at the end of line, the following line will be treated" 1>&2 echo " as continous line. If line starts with four spaces/tabs, it will be treated as the" 1>&2 echo " continous line of the preveous line" 1>&2 echo "" 1>&2 return } function sed_list_section () { local inifile="$1" if [ ! -f "${inifile}" ]; then if [ ${verbose:-0} -ne 0 ]; then echo "File not exists or not usual file: ${inifile}" 1>&2 fi return 1 fi if [ ${verbose:-0} -ne 0 ]; then echo "# Section in file: ${inifile}" 1>&2 fi ${SED:-sed} ${sedopt:--E} -n -e ':begin $!N;s/[#;]([^[:space:]]|[[:blank:]])*([^\\[:space:]]|[[:blank:]])(\n)/\3/;s/[#;]([^[:space:]]|[[:blank:]])*(\\)(\n)/\2\3/;$s/[#;]([^[:space:]]|[[:blank:]])*$//;/(\\\n|\n[[:blank:]]{4})/ { s/[[:blank:]]*(\\\n|\n[[:blank:]]{4})[[:blank:]]*/ /;t begin };/^[[:blank:]]*\n/ D;/\n[[:blank:]]*$/ {s/\n[[:blank:]]*$//;t begin };/^\[([^[:space:]]|[[:blank:]])*\]/!D;s/\[[[:blank:]]*//;s/[[:blank:]]*\]([^[:space:]]|[[:blank:]])*//;P;D' "${inifile}" || return 1 return 0 } local hndlrhup_bk=$(trap -p SIGHUP) local hndlrint_bk=$(trap -p SIGINT) local hndlrquit_bk=$(trap -p SIGQUIT) local hndlrterm_bk=$(trap -p SIGTERM) trap -- 'cleanup ; kill -1 $$' SIGHUP trap -- 'cleanup ; kill -2 $$' SIGINT trap -- 'cleanup ; kill -3 $$' SIGQUIT trap -- 'cleanup ; kill -15 $$' SIGTERM function cleanup () { # removr temporary files and directories if [ ${#tmpfiles} -gt 0 ]; then rm -f "${tmpfiles[@]}" fi if [ ${#tmpdirs} -gt 0 ]; then rm -rf "${tmpdirs[@]}" fi # Restore signal handler if [ -n "${hndlrhup_bk}" ] ; then eval "${hndlrhup_bk}" ; else trap -- 1 ; fi if [ -n "${hndlrint_bk}" ] ; then eval "${hndlrint_bk}" ; else trap -- 2 ; fi if [ -n "${hndlrquit_bk}" ] ; then eval "${hndlrquit_bk}" ; else trap -- 3 ; fi if [ -n "${hndlrterm_bk}" ] ; then eval "${hndlrterm_bk}" ; else trap -- 15 ; fi # Restore functions unset sed_list_section test -n "${sed_list_section_bk}" && eval ${sed_list_section_bk%\}}" ; }" unset echo_usage test -n "${echo_usage_bk}" && eval ${echo_usage_bk%\}}" ; }" unset cleanup test -n "${cleanup_bk}" && eval ${cleanup_bk%\}}" ; }" } # Analyze command line options local opt=0 local secprefix=0 local aslocalvar=0 local forcsh=0 local forcequoat=0 local asenvvar=0 local args=() local verbose=0 local secselexps=() local varselexps=() local secselexps2=() while [ ${#} -gt 0 ] ; do case "$1" in -c|--csh) local forcsh=1 shift ;; -q|--quot) local forcequoat=1 shift ;; -l|--list) local opt=1 shift ;; -L|--local) local aslocalvar=1 shift ;; -e|--env*) local asenvvar=1 shift ;; -s|--sec-prefix) local secprefix=1 shift ;; -v|--verbose) local verbose=1 shift ;; -h|--help) echo_usage cleanup return 0 ;; -S|--sec-select) shift [ $# -le 0 ] && { echo_usage ; cleanup ; return 1 ; } local secselexps=( "${secselexps[@]}" "$(${SED:-sed} ${sedopt:--E} -e 's/([\\.*\^$()])/\\\1/g' <<< "$1")" ) local secselexps2=( "${secselexps2[@]}" "$(${SED:-sed} ${sedopt:--E} -e 's/[^[:alnum:]_]/_/g' -e 's/([\\.*\^$()])/\\\1/g' <<< "$1")" ) shift ;; -T|--sec-select-regex) shift [ $# -le 0 ] && { echo_usage ; cleanup ; return 1 ; } local secselexps=( "${secselexps[@]}" "$1" ) local secselexps2=( "${secselexps2[@]}" "$(${SED:-sed} ${sedopt:--E} -e 's/[^[:alnum:]_\\.*\^$()]/_/g' <<< "$1")" ) shift ;; -V|--variable-select) shift [ $# -le 0 ] && { echo_usage ; cleanup ; return 1 ; } local varselexps=( "${varselexps[@]}" "$(${SED:-sed} ${sedopt:--E} -e 's/[^[:alnum:]_]/_/g' -e 's/([\\.*\^$()])/\\\1/g' <<< "$1")" ) shift ;; -W|--variable-select-regex) shift [ $# -le 0 ] && { echo_usage ; cleanup ; return 1 ; } local varselexps=( "${varselexps[@]}" "$(${SED:-sed} ${sedopt:--E} -e 's/[^[:alnum:]_\\.*\^$()]/_/g' <<< "$1")" ) shift ;; *) local args=( "$1" "${args[@]}" ) shift ;; esac done case ${OSTYPE} in darwin) local sedopt="-E" ;; *) local sedopt="-E" ;; esac local scriptpath="${BASH_SOURCE:-$0}" local scriptdir="$(dirname "${scriptpath}")" if [ "$0" == "${BASH_SOURCE:-$0}" ]; then local this="$(basename "${scriptpath}")" else local this="${FUNCNAME[0]}" fi # local tmpdir0=$(mktemp -d "${this}.tmp.XXXXXX" ) # local tmpdirs=( "${tmpdirs[@]}" "${tmpdir0}" ) # local tmpfile0=$(mktemp "${this}.tmp.XXXXXX" ) # local tmpfiles=( "${tmpfiles[@]}" "${tmpfile0}" ) if [ ${opt} -eq 1 ]; then if [ ${#args[@]} -le 0 ]; then if [ ${verbose:-0} -ne 0 ]; then echo_usage fi cleanup return 1 fi local inifile= for inifile in "${args[@]}"; do sed_list_section "${inifile}" || local funcstatus=1 done elif [ ${#args[@]} -lt 1 ]; then if [ ${verbose:-0} -ne 0 ]; then echo "Not enough arguments" 1>&2 fi local funcstatus=1 echo_usage else local sec_expr= local inifile= local list_sections=() for inifile in "${args[@]}"; do local list_sections=( "${list_sections[@]}" "$(sed_list_section "${inifile}")" ) done for sec_expr in "${secselexps[@]}"; do if ${GREP:-grep} -q -e "^${sec_expr}\$" <<< "${list_sections[@]}" ; then : else if [ ${verbose:-0} -ne 0 ]; then echo "No section will be selected by : ${sec_expr}" 1>&2 fi local funcstatus=1 fi done local inifile= local secprefixexp="" if [ ${secprefix:-0} -ne 0 ]; then local secprefixexp='\4' fi local vardefsep="=" local vardefprefix="" if [ ${forcsh:-0} -ne 0 ]; then if [ ${asenvvar:-0} -ne 0 ]; then local vardefprefix="setenv " local vardefsep=" " else local vardefprefix="set " fi elif [ ${aslocalvar} -ne 0 ]; then local vardefprefix="local " elif [ ${asenvvar:-0} -ne 0 ]; then local vardefprefix="export " fi local varvalexp='' if [ ${forcequoat:-0} -ne 0 ]; then local varvalexp='/^".*"$/!s/^(.*)$/"\1"/g;/^('"'"'.*'"'"'|".*")$/!s/^(.*)$/'"'"'\1'"'"'/g;' fi local sec_address='/^.*(\n)/' if [ ${#secselexps[@]} -gt 0 ]; then local sec_address="/^($(IFS=\|; echo "${secselexps[*]}"))(\n)/" fi local varseladdr='' if [ ${#varselexps[@]} -gt 0 ]; then if [ ${secprefix:-0} -ne 0 ]; then if [ ${#secselexps2[@]} -gt 0 ]; then local sec_expr="($(IFS=\|; echo "${secselexps2[*]}"))_" else local sec_expr="([^[:blank:]]+)_" fi local varseladdr="/^${vardefprefix}(${sec_expr}$(IFS=\|; echo "${varselexps[*]}"))${vardefsep}([^[:space:]]|[[:blank:]])*;(\n)/" else local varseladdr="/^${vardefprefix}($(IFS=\|; echo "${varselexps[*]}"))${vardefsep}([^[:space:]]|[[:blank:]])*;(\n)/" fi fi local inifile= for inifile in "${args[@]}"; do if [ ! -f "${inifile}" ];then if [ ${verbose:-0} -ne 0 ]; then echo "File not exists or not usual file: ${inifile}" 1>&2 fi local funcstatus=1 continue fi if [ ${verbose:-0} -ne 0 ]; then echo "# Variable definitions: ${inifile}" 1>&2 fi ${SED:-sed} ${sedopt:--E} -e '1 {H;x;s/^([^[:space:]]|[[:blank:]])*(\n)([^[:space:]]|[[:blank:]])*$/global\2global_/g;x;};:begin $!N;s/[#;]([^[:space:]]|[[:blank:]])*([^\\[:space:]]|[[:blank:]])(\n)/\3/;s/[#;]([^[:space:]]|[[:blank:]])*(\\)(\n)/\2\3/;$s/[#;]([^[:space:]]|[[:blank:]])*$//;/(\\\n|\n[[:blank:]]{4})/ {s/[[:blank:]]*(\\\n|\n[[:blank:]]{4})[[:blank:]]*/ /;t begin };/^[[:blank:]]*\n/ D;/\n[[:blank:]]*$/{s/\n[[:blank:]]*$//;t begin };/^([^[:space:]]|[[:blank:]])*\[([^[:space:]]|[[:blank:]])*\]/{s/^([^[:space:]]|[[:blank:]])*\[(([^[:space:]]|[[:blank:]])*)\](([^[:space:]]|[[:blank:]])*)(\n)/\2\6/g;s/^[[:blank:]]*//g; s/[[:blank:]]*(\n)/\1/g;h;x;s/(\n)([^[:space:]]|[[:blank:]])*$//;s/([^[:alnum:]_]|$)/_/g;x;H;x;s/(([^[:space:]]|[[:blank:]])*)(\n)(([^[:space:]]|[[:blank:]])*)(\n)(([^[:space:]]|[[:blank:]])*)$/\4\3\1/;x;D;};x;'"${sec_address}"'!{x;D;};x;/^(([^[:space:]=]|[[:blank:]])*)=(([^[:space:]]|[[:blank:]])*)/ {H;s/(([^[:space:]=]|[[:blank:]])*)=.*$/\1/g;s/^[[:blank:]]*//;s/[[:blank:]]*$//;s/[^[:alnum:]_]/_/g;H;g;s/^(([^[:space:]]|[[:blank:]])*\n){2}//;s/(\n([^[:space:]]|[[:blank:]])*){2}$//;s/^([^[:space:]=]|[[:blank:]])*=//g;'"${varvalexp}"'G;s/^(([^[:space:]]|[[:blank:]])*\n)(([^[:space:]]|[[:blank:]])*\n)(([^[:space:]]|[[:blank:]])*\n)(([^[:space:]]|[[:blank:]])*\n)(([^[:space:]]|[[:blank:]])*\n)/\1\5\9/;s/^(([^[:space:]]|[[:blank:]])*\n)(([^[:space:]]|[[:blank:]])*\n)(([^[:space:]]|[[:blank:]])*)(\n)(([^[:space:]]|[[:blank:]])*)$/\1\3\8\7\5/;s/^(([^[:space:]]|[[:blank:]])*)(\n)(([^[:space:]]|[[:blank:]])*)(\n)(([^[:space:]]|[[:blank:]])*)(\n([^[:space:]]|[[:blank:]])*)$/'"${vardefprefix}${secprefixexp}"'\7'"${vardefsep}"'\1;\9/;x;s/(\n([^[:space:]]|[[:blank:]])*){3}$//;x;'"${varseladdr}"'P;};D' "${inifile}" done fi # clean up cleanup local funcstatus=1 return ${funcstatus} } if [ "$0" == ${BASH_SOURCE:-$0} ]; then parse_ini "$@" fi
SELECT departments.department_name,employee_id,surname,firstname FROM (SELECT * FROM departments ) departments JOIN (SELECT * FROM employees) employees USING (department_id) WHERE employees.date_of_birth<DATE_SUB(curdate(),INTERVAL 55 YEAR)
import { EbmlDataTag } from "./EbmlDataTag"; import { BlockLacing } from "../enums/BlockLacing"; import { Tools } from "../../Tools"; import { EbmlTagId } from "../enums/EbmlTagId"; import { EbmlElementType } from "../enums/EbmlElementType"; export class Block extends EbmlDataTag { payload: Buffer; track: number; value: number; invisible: boolean; lacing: BlockLacing; constructor(subTypeId?: number) { super(subTypeId || EbmlTagId.Block, EbmlElementType.Binary); } protected writeTrackBuffer(): Buffer { return Tools.writeVint(this.track); } protected writeValueBuffer(): Buffer { let value = Buffer.alloc(2); value.writeInt16BE(this.value, 0); return value; } protected writeFlagsBuffer(): Buffer { let flags = 0x00; if(this.invisible) { flags |= 0x10; } switch(this.lacing) { case BlockLacing.None: break; case BlockLacing.Xiph: flags |= 0x04; break; case BlockLacing.EBML: flags |= 0x08; break; case BlockLacing.FixedSize: flags |= 0x0c; break; } return Buffer.of(flags); } encodeContent(): Buffer { return Buffer.concat([ this.writeTrackBuffer(), this.writeValueBuffer(), this.writeFlagsBuffer(), this.payload ]); } parseContent(data: Buffer): void { const track = Tools.readVint(data); this.track = track.value; this.value = Tools.readSigned(data.subarray(track.length, track.length+2)); let flags: number = data[track.length+2]; this.invisible = Boolean(flags & 0x10); switch(flags & 0x0c) { case 0x00: this.lacing = BlockLacing.None; break; case 0x04: this.lacing = BlockLacing.Xiph; break; case 0x08: this.lacing = BlockLacing.EBML; break; case 0x0c: this.lacing = BlockLacing.FixedSize; break; } this.payload = data.slice(track.length + 3); } }
<reponame>zenglongGH/spresense var unionCPSR__Type = [ [ "A", "unionCPSR__Type.html#a8dc2435a7c376c9b8dfdd9748c091458", null ], [ "b", "unionCPSR__Type.html#a2e735da6b6156874d12aaceb2017da06", null ], [ "C", "unionCPSR__Type.html#aa967d0e42ed00bd886b2c6df6f49a7e2", null ], [ "E", "unionCPSR__Type.html#a96bd175ed9927279dba40e76259dcfa7", null ], [ "F", "unionCPSR__Type.html#a20bbf5d5ba32cae380b7f181cf306f9e", null ], [ "GE", "unionCPSR__Type.html#acc18314a4088adfb93a9662c76073704", null ], [ "I", "unionCPSR__Type.html#a0d277e8b4d2147137407f526aa9e3214", null ], [ "IT0", "unionCPSR__Type.html#a5299532c92c92babc22517a433686b95", null ], [ "IT1", "unionCPSR__Type.html#a8bdd87822e3c00b3742c94a42b0654b9", null ], [ "J", "unionCPSR__Type.html#a5d4e06d8dba8f512c54b16bfa7150d9d", null ], [ "M", "unionCPSR__Type.html#a2bc38ab81bc2e2fd111526a58f94511f", null ], [ "N", "unionCPSR__Type.html#a26907b41c086a9f9e7b8c7051481c643", null ], [ "Q", "unionCPSR__Type.html#a0bdcd0ceaa1ecb8f55ea15075974eb5a", null ], [ "T", "unionCPSR__Type.html#ac5ec7329b5be4722abc3cef6ef2e9c1b", null ], [ "V", "unionCPSR__Type.html#aba74c9da04be21f1266d3816af79f8c3", null ], [ "w", "unionCPSR__Type.html#afd5ed10bab25f324a6fbb3e124d16fc9", null ], [ "Z", "unionCPSR__Type.html#a790f1950658257a87ac58d132eca9849", null ] ];
import numpy as np def movingAverage(data, n=3): """ calculate moving average from list of values =========================================================================== Input Meaning ---------- --------------------------------------------------------------- data np.array with data values n width of the window =========================================================================== Output Meaning ---------- --------------------------------------------------------------- data np.array with data values with moving average applied =========================================================================== """ dataCum = np.cumsum(data, dtype=float) dataCum[n:] = dataCum[n:] - dataCum[:-n] return dataCum[n-1:] / n
/* ====================================================== */ /* Implementation */ /* ====================================================== */ export const ASYNC_ACTION_SEPARATOR = '--->' export const ASYNC_ACTION_ID = 'ASYNC' export interface AsyncActionNames { REQUEST: string, SUCCESS: string, FAILURE: string, ALWAYS: string, NAME: string } function asyncActionObject(type: string): AsyncActionNames { return { REQUEST: `${type}${ASYNC_ACTION_SEPARATOR}REQUEST`, SUCCESS: `${type}${ASYNC_ACTION_SEPARATOR}SUCCESS`, FAILURE: `${type}${ASYNC_ACTION_SEPARATOR}FAILURE`, ALWAYS: `${type}${ASYNC_ACTION_SEPARATOR}ALWAYS`, NAME: type } } function asyncAction(type: string): string { return `${ASYNC_ACTION_ID}_${type}` } export { asyncAction, asyncActionObject }
<reponame>ruowan/avocado // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. import * as stringMap from '@ts-common/string-map' import { IErrorBase } from './errors' export type Report = { /** * This is a callback function to report validation tools result. */ readonly logResult: (error: any) => void /** * This is a callback function to report validation tools exception. */ readonly logError: (error: any) => void /** * This is a callback function to report an info. */ readonly logInfo: (info: any) => void } export type Config = { /** * Current working directory. */ readonly cwd: string /** * Environment variables. */ readonly env: stringMap.StringMap<string> /** * Arguments */ readonly args?: stringMap.StringMap<any> } export const defaultConfig = () => ({ cwd: process.cwd(), env: process.env, args: {}, }) export const isAzurePipelineEnv = (): boolean => process.env.SYSTEM_PULLREQUEST_TARGETBRANCH !== undefined /** * The function executes the given `tool` and prints errors to `stderr`. * * @param tool is a function which returns errors as `AsyncIterable`. */ // tslint:disable-next-line:no-async-without-await export const run = async <T extends IErrorBase>( tool: (config: Config) => AsyncIterable<T>, // tslint:disable-next-line:no-console no-unbound-method report: Report = { logResult: console.log, logError: console.error, logInfo: console.log }, config: Config = defaultConfig(), ): Promise<void> => { try { const errors = tool(config) // tslint:disable-next-line:no-let let errorsNumber = 0 for await (const e of errors) { errorsNumber += e.level !== 'Warning' && e.level !== 'Info' ? 1 : 0 report.logResult(e) } report.logInfo(`errors: ${errorsNumber}`) if (errorsNumber > 0) { if (isAzurePipelineEnv()) { console.log('##vso[task.setVariable variable=ValidationResult]failure') } // tslint:disable-next-line: no-object-mutation process.exitCode = 1 } else { if (isAzurePipelineEnv()) { console.log('##vso[task.setVariable variable=ValidationResult]success') } // tslint:disable-next-line: no-object-mutation process.exitCode = 0 } // tslint:disable-next-line:no-object-mutation } catch (e) { report.logInfo(`INTERNAL ERROR`) if (isAzurePipelineEnv()) { console.log('##vso[task.setVariable variable=ValidationResult]failure') } report.logError(e) // tslint:disable-next-line:no-object-mutation process.exitCode = 1 } }
from django.utils.formats import date_format as django_date_format DEFAULT_DATE_FORMAT = "M d, H:i:s (e)" def date_format(value, format_string=DEFAULT_DATE_FORMAT): """Simple wrapper for Django date_format() with a default format.""" return django_date_format(value, format_string)
<gh_stars>100-1000 #!/usr/bin/env python """Translate Wikipedia edit history XML files to JSON. This script assumes that the Wikipedia edit history XML files are ordered as follows: <mediawiki> ... <page> <title></title> <ns></ns> <id></id> <redirect title="" /> <!-- Optional --> <revision> <id>236939</id> <timestamp></timestamp> <contributor> <username></username> <id></id> </contributor> <comment></comment> <model></model> <format></format> <text xml:space="preserve"></text> <sha1></sha1> </revision> ... </page> </mediawiki> Specifically, it assumes that the title, ns, id, redirect tags for a page appear before the revisions. This is the format the files are in when they are downloaded from: https://dumps.wikimedia.org/enwiki/latest/ Example: This script is designed to be placed in the middle of a series of piped commands. Most often it will read data on stdin from a 7zip program and output JSON on stdout, often to a file or compression program, as follows: $ 7z e -so input_file.7z | xml_to_json.py | gzip > output_file.json.gz Attributes: NAMESPACE (str): The default namespace of all tags in the Wikipedia edit history XML file. REVISION (dict): A dictionary that stores the information from each revision as well as some information about the article in general. The variables are as follows: - article_title (str): The title of the article. - article_id (int): A unique identifier for each article. - article_namespace (int): The namespace of the article, as defined by Wikipedia. - redirect_target (str): If the article is a redirect, the target article's article_title, otherwise None. - revision_id (int): Unique identifier of the revision. - parent_id (int): Unique identifier of the parent of the revision. - timestamp (str): Time the revision was made. - user_name (str): The name of the user, or their IP address if not logged in. - user_id (int): A unique id of the user, or None if they were not logged in. - comment (str): The comment the user left about their edit. - minor (bool): True if the edit was marked as "minor", otherwise False. """ from copy import deepcopy from datetime import datetime import argparse import sys import xml.etree.cElementTree as ET import json NAMESPACE = "{http://www.mediawiki.org/xml/export-0.10/}" # JSON revision object REVISION = { # General article information "article_title": None, # string "article_id": None, # int "article_namespace": None, # int "redirect_target": None, # String # Revision specific information "revision_id": None, # int "parent_id": None, # int "timestamp": None, # date and time "user_name": None, # string or ip as string "user_id": None, # int if user, otherwise None "comment": None, # string "minor": False, # bool "full_text": None, # str } def fill_rev(revision, element, in_revision_tree, namespace='', save_full_text=False): """Fill the fields of a revision dictionary given an element from an XML Element Tree. Args: - revision (dict): A revision dictionary with fields already in place. - element (ElementTree Element): An element from ElementTree. - in_revision_tree (bool): True if inside a <revision> element, otherwise should be set to False. - namespace (Optional[str]): The XML name space that the tags exist in. - save_full_text (Optional [bool]): Save the full text of the article if True, otherwise set it to None. Returns: None """ if element.tag == namespace + "id": if in_revision_tree: revision["revision_id"] = int(element.text) else: revision["article_id"] = int(element.text) elif element.tag == namespace + "parentid": revision["parent_id"] = int(element.text) elif element.tag == namespace + "timestamp": revision["timestamp"] = element.text elif element.tag == namespace + "minor": revision["minor"] = True elif element.tag == namespace + "comment": revision["comment"] = element.text elif element.tag == namespace + "contributor": for child in element: if child.tag == namespace + "username" or child.tag == namespace + "ip": revision["user_name"] = child.text elif child.tag == namespace + "id": revision["user_id"] = int(child.text) elif element.tag == namespace + "title": revision["article_title"] = element.text elif element.tag == namespace + "ns": revision["article_namespace"] = int(element.text) elif element.tag == namespace + "redirect": revision["redirect_target"] = element.get("title") elif element.tag == namespace + "text": if save_full_text: revision["full_text"] = element.text # Set up command line flag handling parser = argparse.ArgumentParser( description="Transform Wikipedia XML to JSON.", usage="7z e -so input.7z | %(prog)s [options] > output.json", ) parser.add_argument( '-f', '--full-text', help="keep the full text of each article, otherwise set it to None", action="store_true", dest="save_full_text", default=False, ) parser.add_argument( '-l', '--latest-revision-only', help="keep only the latest revision of an article", action="store_true", dest="save_newest_only", default=False, ) # Run only if this script is being called directly if __name__ == "__main__": args = parser.parse_args() in_page = False in_revision = False for event, elem in ET.iterparse(sys.stdin, events=("start", "end")): # When a page element is started we set up a new revisions dictionary # with the article title, id, namespace, and redirection information. # This dictionary is then deepcopied for each revision. It is deleted # when a page ends. if event == "start" and elem.tag == NAMESPACE + "page": in_page = True page_rev = deepcopy(REVISION) if args.save_newest_only: newest = None newest_date = None elif event == "end" and elem.tag == NAMESPACE + "page": if args.save_newest_only: print json.dumps(newest) del newest del newest_date in_page = False del cur_rev del page_rev # When a revision starts we copy the current page dictionary and fill # it. Revisions are sorted last in the XML tree, so the page_rev # dictionary will be filled out by the time we reach them. if event == "start" and elem.tag == NAMESPACE + "revision": in_revision = True cur_rev = deepcopy(page_rev) elif event == "end" and elem.tag == NAMESPACE + "revision": for child in elem: fill_rev(cur_rev, child, in_revision, NAMESPACE, args.save_full_text) child.clear() in_revision = False if not args.save_newest_only: print json.dumps(cur_rev) else: if not newest: newest = cur_rev newest_date = datetime.strptime(cur_rev["timestamp"], "%Y-%m-%dT%H:%M:%SZ") else: test_date = datetime.strptime(cur_rev["timestamp"], "%Y-%m-%dT%H:%M:%SZ") if test_date > newest_date: newest = cur_rev newest_date = test_date elem.clear() # Otherwise if we are not in a revision, but are in a page, then the # elements are about the article and we save them into the page_rev # dictionary if event == "end" and in_page and not in_revision: fill_rev(page_rev, elem, in_revision, NAMESPACE, args.save_full_text) elem.clear()
<reponame>linxi159/dcgan_code import theano import theano.tensor as T def CategoricalCrossEntropy(y_true, y_pred): return T.nnet.categorical_crossentropy(y_pred, y_true).mean() def BinaryCrossEntropy(y_true, y_pred): return T.nnet.binary_crossentropy(y_pred, y_true).mean() def MeanSquaredError(y_true, y_pred): return T.sqr(y_pred - y_true).mean() def MeanAbsoluteError(y_true, y_pred): return T.abs_(y_pred - y_true).mean() def SquaredHinge(y_true, y_pred): return T.sqr(T.maximum(1. - y_true * y_pred, 0.)).mean() def Hinge(y_true, y_pred): return T.maximum(1. - y_true * y_pred, 0.).mean() cce = CCE = CategoricalCrossEntropy bce = BCE = BinaryCrossEntropy mse = MSE = MeanSquaredError mae = MAE = MeanAbsoluteError