text
stringlengths
1
1.05M
<reponame>resetius/graphtoys #pragma once #include "vk.h" #include "commandbuffer.h" struct RenderImpl; struct Frame { struct CommandBuffer cb; VkCommandBuffer cmd; VkFence fence; VkSemaphore acquire_image; VkSemaphore render_finished; }; void frame_init(struct Frame* frame, struct RenderImpl* r); void frame_destroy(struct Frame* frame); VkCommandBuffer frame_cb(struct Frame* frame);
package com.singularitycoder.folkdatabase.profile.model; public class ProfileContactItem { private int profileImage; private String name; private String dateTime; private String comment; private String activityName; public ProfileContactItem() { } public ProfileContactItem(String comment) { this.comment = comment; } // Comments public ProfileContactItem(int profileImage, String name, String dateTime, String comment) { this.profileImage = profileImage; this.name = name; this.dateTime = dateTime; this.comment = comment; } // Called By public ProfileContactItem(int profileImage, String name, String dateTime, String activityName, String empty) { this.profileImage = profileImage; this.name = name; this.dateTime = dateTime; this.activityName = activityName; } public int getProfileImage() { return profileImage; } public void setProfileImage(int profileImage) { this.profileImage = profileImage; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDateTime() { return dateTime; } public void setDateTime(String dateTime) { this.dateTime = dateTime; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getActivityName() { return activityName; } public void setActivityName(String activityName) { this.activityName = activityName; } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.composeLenses = exports.createLens = void 0; function createLens(get, set) { return { get, set }; } exports.createLens = createLens; function composeLenses(lens1, lens2) { return { get: (parent) => lens2.get(lens1.get(parent)), set: (parent) => (endChild) => lens1.set(parent)(lens2.set(lens1.get(parent))(endChild)) }; } exports.composeLenses = composeLenses; //# sourceMappingURL=lensUtils.js.map
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 25 11:02:49 2017 @author: Originally written by <NAME>; edited by <NAME> """ import os import uuid import datetime import time from xml.etree.cElementTree import Element, SubElement, Comment, tostring from xml.etree import ElementTree from xml.dom import minidom # from lxml import etree # from twisted.persisted.aot import prettify class mentionAnnotation(object): def __init__(self, tagObject, textSource=None, mentionClass=None, mentionid=None, annotatorid='pyConText_FINDER', span=None, start=None, end=None, spannedText=None, creationDate=None, XML=None, MentionXML=None): """Creates an annotation of Object""" self.textSource = textSource self.mentionid = str(mentionid) self.mentionClass = mentionClass self.annotatorid = annotatorid self.span = span self.start = start self.end = end self.spannedText = spannedText self.creationDate = creationDate self.XML = XML self.MentionXML = MentionXML self.setCreationDate() self.setXML() self.setMentionXML() def setTextSource(self, textSource): """Sets the text for spannedText""" self.textSource = textSource def setText(self, text): """Sets the text for spannedText""" self.spannedText = text def setSpan(self, markupSpan): self.span = markupSpan def setStart(self, start): self.start = start def setEnd(self, end): self.end = end def setMentionID(self, ID): self.mentionid = str(ID) def setCreationDate(self): self.creationDate = time.strftime("%c") # add time zone def setXML(self): """Creates an element tree that can later be appended to a parent tree""" annotation_body = Element("annotation") mentionID = SubElement(annotation_body, 'mention') mentionID.set('id', self.getMentionID()) # perhaps this needs to follow eHOST's schema annotatorID = SubElement(annotation_body, "annotator") annotatorID.set('id', 'eHOST_2010') annotatorID.text = self.getAnnotatorID() start = self.getSpan()[0]; end = self.getSpan()[1] print start, end # span = SubElement(annotation_body, "span",{"start":str(start),"end":str(end)}) #Why is this backwards? spannedText = SubElement(annotation_body, 'spannedText') spannedText.text = self.getText() creationDate = SubElement(annotation_body, "creationDate") creationDate.text = self.getCreationDate() self.XML = annotation_body # print(prettify(parent)) def setMentionXML(self): classMention = Element("classMention") classMention.set("id", self.getMentionID()) mentionClass = SubElement(classMention, "mentionClass") mentionClass.set("id", self.getMentionClass()) mentionClass.text = self.getText() self.MentionXML = classMention def getTextSource(self): return self.textSource def getMentionClass(self): return self.mentionClass def getMentionID(self): return self.mentionid def getText(self): return self.spannedText def getSpan(self): return self.span def getStart(self): return self.start def getEnd(self): return self.end def getAnnotatorID(self): return self.annotatorid def getCreationDate(self): return self.creationDate def getXML(self): return self.XML def getMentionXML(self): return self.MentionXML def stringXML(self): def prettify(elem): """Return a pretty-printed XML string for the Element. """ rough_string = ElementTree.tostring(elem, 'utf-8') reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent=" ") XML_string = prettify(self.getXML()) MentionXML_string = prettify(self.getMentionXML()) return XML_string + MentionXML_string def createAnnotation(ct, file_name, term, span, mention_class): # eventually mention_class will be defined by the logic """Takes a ConTextMarkup object and returns a list of annotation object""" annotation = mentionAnnotation(tagObject=ct, textSource=file_name, mentionClass=mention_class, mentionid=ct, spannedText=term, span=eval(span), start=eval(span)[0], end=eval(span)[1]) # MADE THIS THE DOCSPAN start, end = eval(span) annotation.setTextSource(file_name + ".txt") annotation.setText(term) annotation.setSpan(span) annotation.setStart(start) annotation.setEnd(end) annotation.setMentionID(ct) # print annotation.stringXML() return annotation def writeKnowtator(annotations, save_dir, text_source): # test_source should be read automatically from the XML string """Writes a .txt.knowtator.xml file for all annotations in a document Takes a list of mentionAnnotation objects, a source file name, and an outpath. 2/3/17: returns a single ElementTree Element object. Need to be able to turn this into a string.""" docOut = ""; outString = "" if not os.path.exists(save_dir): os.mkdir(save_dir) print text_source # with open(os.path.join(outpath,text_source+'.knowtator.xml'),'w') as f0: # f0.write(XMLstring) # f0.close() # return os.path.join(outpath,text_source+'.knowtator.xml') fout = open("%s/%s-PyConText.knowtator.xml" % (save_dir, text_source), "w") outString = """<?xml version="1.0" encoding="UTF-8"?>\n""" outString += """<annotations textSource="%s">\n""" % text_source docOut = outString; annotXML = "" ct = 1 for annotation in annotations: outString = "" outStringClsMent = "" start = str(annotation.getStart()); end = str(annotation.getEnd()) # print classAnnot;raw_input() outString += """ <annotation>\n""" outString += """ <mention id="pyCONTEXT_Instance_%s" />\n""" % str(ct) outString += """ <annotator id="01">%s</annotator>\n""" % annotation.getAnnotatorID() outString += """ <span start="%s" end="%s" />\n""" % (start, end) outString += """ <spannedText>%s</spannedText>\n""" % annotation.getText() outString += """ <creationDate>%s</creationDate>\n""" % time.strftime("%c") outString += """ </annotation>\n""" # create Knowtator mention class outStringClsMent += """ <classMention id="pyCONTEXT_Instance_%s">\n""" % str(ct) outStringClsMent += """ <mentionClass id="%s">%s</mentionClass>\n""" % ( annotation.getMentionClass(), annotation.getText()) outStringClsMent += """ </classMention>\n""" ct += 1 a = outString + outStringClsMent annotXML += a # print annotXML # ;raw_input() docOut += annotXML outString = "" footer = """ <pyCONTEXT_Adjudication_Status version="1.0">\n""" footer += """ <Adjudication_Selected_Annotators version="1.0" />\n""" footer += """ <Adjudication_Selected_Classes version="1.0" />\n""" footer += """ <Adjudication_Others>\n""" footer += """ <CHECK_OVERLAPPED_SPANS>true</CHECK_OVERLAPPED_SPANS>\n""" footer += """ <CHECK_ATTRIBUTES>true</CHECK_ATTRIBUTES>\n""" footer += """ <CHECK_RELATIONSHIP>false</CHECK_RELATIONSHIP>\n""" footer += """ <CHECK_CLASS>true</CHECK_CLASS>\n""" footer += """ <CHECK_COMMENT>false</CHECK_COMMENT>\n""" footer += """ </Adjudication_Others>\n""" footer += """ </pyCONTEXT_Adjudication_Status>\n""" footer += """</annotations>""" fout.write(docOut + footer) fout.close() # ;raw_input() # def main(): # # docAnnots={} # # lines=open(os.getcwd()+"/src/reportsOutput/eHOST_annotations.txt","r").readlines() # for l in lines[1:]: # fnameExt, fname, term, span, clas = l.strip().split("\t") # if fname in docAnnots.keys(): # docAnnots[fname]+=[(term, span, clas)] # else: # docAnnots[fname]=[(term, span, clas)] # # # for doc in docAnnots: # createdAnnots=[]; ct=1 # annots=docAnnots[doc] # for a in annots: # an=createAnnotation(str(ct), doc, a[0], a[1], a[2]) ## print an.getMentionID() ## print an.getSpan() ## print an.getText() ## print an.getMentionClass() # createdAnnots.append(an) # ct+=1 # writeKnowtator(createdAnnots, doc)#;raw_input() # # # # if __name__=='__main__': # # main()
<filename>src/commands/CommandContext.h /********************************************************************** Sneedacity: A Digital Audio Editor CommandContext.h Created by <NAME> on 4/22/16. **********************************************************************/ #ifndef __SNEEDACITY_COMMAND_CONTEXT__ #define __SNEEDACITY_COMMAND_CONTEXT__ #include <memory> #include "Identifier.h" class SneedacityProject; class wxEvent; class CommandOutputTargets; using CommandParameter = CommandID; class SNEEDACITY_DLL_API CommandContext { public: CommandContext( SneedacityProject &p , const wxEvent *e = nullptr , int ii = 0 , const CommandParameter &param = CommandParameter{} ); CommandContext( SneedacityProject &p, std::unique_ptr<CommandOutputTargets> target); ~CommandContext(); virtual void Status( const wxString &message, bool bFlush = false ) const; virtual void Error( const wxString &message ) const; virtual void Progress( double d ) const; // Output formatting... void StartArray() const; void EndArray() const; void StartStruct() const; void EndStruct() const; void StartField(const wxString &name) const; void EndField() const; void AddItem(const wxString &value , const wxString &name = {} ) const; void AddBool(const bool value , const wxString &name = {} ) const; void AddItem(const double value , const wxString &name = {} ) const; SneedacityProject &project; std::unique_ptr<CommandOutputTargets> pOutput; const wxEvent *pEvt; int index; CommandParameter parameter; }; #endif
<reponame>jmrafael/Streamlit-Authentication<gh_stars>10-100 from .. import const, trace_activity, AppError, DatabaseError from .. import tnow_iso , tnow_iso_str, dt_from_str, dt_from_ts, dt_to_str
<reponame>seimith/smithandsam<filename>src/pages/services.js<gh_stars>0 import PropTypes from "prop-types" import React, { useState } from "react" const Services = ({ siteTitle, color }) => { const SERVICE_NAME = { ADMIN: "admin", SOCIAL: "social", DEV: "dev", DES: "des", PROD: "prod", } const [toggleState, setToggleState] = useState(""); const toggle = (event) => { setToggleState(toggleState !== event.target.dataset["name"] ? event.target.dataset["name"] : ""); }; return ( <div style={{ background: color }} id="services"> <div className="ss-section"> <center> <h1 className="ss-section-header">{siteTitle}</h1> </center> <h3 data-name={SERVICE_NAME.ADMIN} onClick={ toggle }>Administrative Services { toggleState !== SERVICE_NAME.ADMIN ? " +" : " -" } </h3> { toggleState === SERVICE_NAME.ADMIN ? <ul> <li>Audio transcription</li> <li>Brochure & flyer creation</li> <li>Calendar management</li> <li>Data entry</li> <li>Email correspondence & management</li> <li>Meeting and event coordination</li> <li>PowerPoint Presentations / Google Presentations</li> <li>Proofreading and editing documents</li> <li>Task management (Jira, Trello, Notion)</li> <li>Voicemail (check and screen)</li> <li>Word Processing / Google Doc</li> <li>Webinar Assistance</li> </ul> : ""} <h3 data-name={SERVICE_NAME.DES} onClick={ toggle }>Design Services { toggleState !== SERVICE_NAME.DES ? " +" : " -" } </h3> { toggleState === SERVICE_NAME.DES ? <ul> <li>Vector art ("Affinity Designer")</li> <li>Canva asset creation</li> <li>Raster photoshopping</li> </ul> : "" } <h3 data-name={SERVICE_NAME.PROD} onClick={ toggle }>Project Management { toggleState !== SERVICE_NAME.PROD ? " +" : " -" } </h3> { toggleState === SERVICE_NAME.PROD ? <ul> <li>Plan and implement projects</li> <li>Help define project scope, goals and deliverables</li> <li>Define tasks and required resources</li> <li>Create schedule and project timeline</li> <li>Track deliverables</li> </ul> : "" } <h3 data-name={SERVICE_NAME.SOCIAL} onClick={ toggle }>Social Media Management { toggleState !== SERVICE_NAME.SOCIAL ? " +" : " -" } </h3> { toggleState === SERVICE_NAME.SOCIAL ? <ul> <li>Facebook</li> <li>LinkedIn</li> <li>Pinterest</li> <li>Twitter</li> <li>YouTube</li> <li>All of these include: <ul> <li>Account Setup</li> <li>Scheduled posts/video/tweets/likes</li> <li>Customer Engagements</li> </ul> </li> </ul> : "" } <h3 data-name={SERVICE_NAME.DEV} onClick={ toggle }>Website Development { toggleState !== SERVICE_NAME.DEV ? " +" : " -" } </h3> { toggleState === SERVICE_NAME.DEV ? <ul> <li>Develop mobile responsive website <ul> <li>React, HTML, CSS, Sass, Code Management in GitHub w/ pipeline to deploy to "Netlify")</li> </ul> </li> <li>Domain Setup</li> <li>Install and configure blog ("WordPress")</li> <li>Install eCommerce website ("Shopify")</li> <li>Customize WorkPress themes</li> <li>Design System Strategy <ul> <li>Application/Website UI auditing</li> <li>Component library planning</li> <li>Stylesheet guidelines</li> </ul> </li> </ul> : "" } </div> </div> ) } Services.propTypes = { siteTitle: PropTypes.string, } Services.defaultProps = { siteTitle: ``, } export default Services
<filename>node_modules/react-icons-kit/fa/facebookSquare.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.facebookSquare = void 0; var facebookSquare = { "viewBox": "0 0 1536 1792", "children": [{ "name": "path", "attribs": { "d": "M1248 128q119 0 203.5 84.5t84.5 203.5v960q0 119-84.5 203.5t-203.5 84.5h-188v-595h199l30-232h-229v-148q0-56 23.5-84t91.5-28l122-1v-207q-63-9-178-9-136 0-217.5 80t-81.5 226v171h-200v232h200v595h-532q-119 0-203.5-84.5t-84.5-203.5v-960q0-119 84.5-203.5t203.5-84.5h960z" } }] }; exports.facebookSquare = facebookSquare;
/* Copyright 2009-2015 <NAME> * * This file is part of the MOEA Framework. * * The MOEA Framework is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * The MOEA Framework is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the MOEA Framework. If not, see <http://www.gnu.org/licenses/>. */ package org.moeaframework.core; import java.io.NotSerializableException; import java.io.Serializable; import org.moeaframework.algorithm.AlgorithmException; /** * Interface for an optimization algorithm. An optimization algorithm operates * by performing a series of optimization steps, though the amount of work * performed by each step depends on the algorithm. For example, an algorithm * may completely solve a problem in one step or may require hundreds of * thousands of steps. */ public interface Algorithm { /** * Returns the problem being solved by this algorithm. * * @return the problem being solved by this algorithm */ public Problem getProblem(); /** * Returns the current best-known result. * * @return the current best-known result */ public NondominatedPopulation getResult(); /** * Performs one logical step of this algorithm. The amount of work performed * depends on the implementation. One invocation of this method may produce * one or many trial solutions. * <p> * This method should not be invoked when {@link #isTerminated()} returns * {@code true}. */ public void step(); /** * Evaluates the specified solution for the problem being solved by this * algorithm. * * @param solution the solution to be evaluated * @see Problem#evaluate(Solution) */ public void evaluate(Solution solution); /** * Returns the number of times the {@code evaluate} method was invoked. This * is the primary measure of runtime for optimization algorithms. * * @return the number of times the {@code evaluate} method was invoked */ public int getNumberOfEvaluations(); /** * Returns {@code true} if this algorithm is terminated; {@code false} * otherwise. * * @return {@code true} if this algorithm is terminated; {@code false} * otherwise * @see #terminate() */ public boolean isTerminated(); /** * Terminates this algorithm. Implementations should use this method to * free any underlying resources; however, the {@link #getResult()} and * {@link #getNumberOfEvaluations()} methods are still required to work * after termination. */ public void terminate(); /** * Returns a {@code Serializable} object representing the internal state of * this algorithm. * * @return a {@code Serializable} object representing the internal state of * this algorithm * @throws NotSerializableException if this algorithm does not support * serialization * @throws AlgorithmException if this algorithm has not yet been * initialized */ public Serializable getState() throws NotSerializableException; /** * Sets the internal state of of this algorithm. * * @param state the internal state of this algorithm * @throws NotSerializableException if this algorithm does not support * serialization * @throws AlgorithmException if this algorithm has already been * initialized */ public void setState(Object state) throws NotSerializableException; }
public class test_calculationParser { final static String expr = "1 + 3"; public static void main(String[] args) { try { System.out.println(calculationParser.evaluate(test_calculationParser.expr)); } catch (ParseException ex) { System.err.println(ex.getMessage()); } } }
import { MinimumMaximumRange } from './minimum-maximum-range'; export class SubtractionOptions { allowNegativeAnswers = false; enabled = false; minuendRange = new MinimumMaximumRange(100, 200); subtrahendRanges: MinimumMaximumRange[] = []; constructor() { this.subtrahendRanges.push(new MinimumMaximumRange(1, 100)); } get numberOfSubtrahends(): number { return this.subtrahendRanges.length; } addSubtrahend() { this.subtrahendRanges.push(new MinimumMaximumRange(1, 20)); } removeSubtrahend() { this.subtrahendRanges.splice(this.subtrahendRanges.length - 1, 1); } updateFromJson(jsonObject: SubtractionOptions) { this.allowNegativeAnswers = jsonObject.allowNegativeAnswers; this.enabled = jsonObject.enabled; this.minuendRange = jsonObject.minuendRange; this.subtrahendRanges = jsonObject.subtrahendRanges; } }
<gh_stars>0 package io.github.marcelbraghetto.dailydeviations.features.collection.logic.providers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import io.github.marcelbraghetto.dailydeviations.BuildConfig; import io.github.marcelbraghetto.dailydeviations.features.collection.logic.CollectionDisplayMode; import io.github.marcelbraghetto.dailydeviations.framework.artworks.models.CollectionFilterMode; import io.github.marcelbraghetto.dailydeviations.framework.foundation.sharedpreferences.contracts.SharedPreferencesProvider; import io.github.marcelbraghetto.dailydeviations.testconfig.RobolectricProperties; import static io.github.marcelbraghetto.dailydeviations.features.collection.logic.CollectionDisplayMode.SingleColumn; import static io.github.marcelbraghetto.dailydeviations.framework.artworks.models.CollectionFilterMode.Favourites; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Created by <NAME> on 12/06/16. */ @Config(constants = BuildConfig.class, sdk = RobolectricProperties.EMULATE_SDK) @RunWith(RobolectricGradleTestRunner.class) public class DefaultCollectionProviderTest { @Mock SharedPreferencesProvider mSharedPreferencesProvider; private DefaultCollectionProvider mProvider; @Before public void setUp() { MockitoAnnotations.initMocks(this); mProvider = new DefaultCollectionProvider(mSharedPreferencesProvider); } @Test public void getCollectionDisplayMode() { // Setup when(mSharedPreferencesProvider.getString(eq("Collection.CollectionDisplayMode"), anyString())).thenReturn("SingleColumn"); // Run CollectionDisplayMode mode = mProvider.getCollectionDisplayMode(); // Verify verify(mSharedPreferencesProvider).getString("Collection.CollectionDisplayMode", ""); assertThat(mode, is(SingleColumn)); } @Test public void setCollectionDisplayMode() { // Run mProvider.setCollectionDisplayMode(SingleColumn); // Verify verify(mSharedPreferencesProvider).saveString("Collection.CollectionDisplayMode", "SingleColumn"); } @Test public void getCollectionFilterMode() { // Setup when(mSharedPreferencesProvider.getString(eq("Collection.CollectionFilterMode"), anyString())).thenReturn("Favourites"); // Run CollectionFilterMode mode = mProvider.getCollectionFilterMode(); // Verify verify(mSharedPreferencesProvider).getString("Collection.CollectionFilterMode", ""); assertThat(mode, is(Favourites)); } @Test public void setCollectionFilterMode() { // Run mProvider.setCollectionFilterMode(Favourites); // Verify verify(mSharedPreferencesProvider).saveString("Collection.CollectionFilterMode", "Favourites"); } }
<reponame>psyking841/spark-pipeline-toolkit package com.span.spark.batch trait Params { def toCMLString: String }
<reponame>xsolve-pl/xsolve-feat import { SimpleCommand } from '../../executor/simple-command'; import { SummaryItemsSet } from '../../sets/summary-items-set'; import { FeaterVariablesSet } from '../../sets/feater-variables-set'; export class PrepareSummaryItemsCommand extends SimpleCommand { constructor( readonly featerVariables: FeaterVariablesSet, readonly summaryItems: SummaryItemsSet, ) { super(); } }
<filename>editor/src/js/savefile/project.ts /** * Initialization methods for loading, creating, and managing project state. * Containts "stock" setup methods for provided example resources and values. * * TODO: Make this the primary interface for savefile operations * TODO: Trigger events on project load/save instead of needing to call * createStockResources in exactly the right places * TODO: Track project dirty/saved status and handle autosaving */ import {OSCType} from '@/common/osc/osc_types'; import {createNewSignal} from 'chl/signal'; import {watchMediaFiles} from 'chl/media'; export function createStockResources(store, path) { // Add a few basic OSC signals if none exist yet. if (store.getters['signal/signal_list'].length === 0) { createNewSignal('Intensity', '/chlorophyll/intensity', [OSCType.FLOAT32]); createNewSignal('BPM', '/chlorophyll/tempo', [OSCType.FLOAT32]); createNewSignal('Color A', '/chlorophyll/color_a', [OSCType.COLOR]); createNewSignal('Color B', '/chlorophyll/color_b', [OSCType.COLOR]); createNewSignal('TouchOSC Fader 1', '/1/fader1', [OSCType.FLOAT32]); createNewSignal('TouchOSC Fader 2', '/1/fader2', [OSCType.FLOAT32]); } watchMediaFiles(store, path); }
<filename>test/languages/less.spec.ts import { newUnibeautify, Beautifier } from "unibeautify"; import beautifier from "../../src"; test(`should successfully beautify LESS text`, () => { const unibeautify = newUnibeautify(); unibeautify.loadBeautifier(beautifier); const text = `#header{color:black;.navigation{font-size:12px;}}`; const beautifierResult = `#header {\n\tcolor: black;\n\t.navigation {\n\t\tfont-size: 12px;\n\t}\n}`; return unibeautify .beautify({ languageName: "Less", options: { Less: { indent_style: "tab", indent_size: 1, }, }, text, }) .then(results => { expect(results).toBe(beautifierResult); }); });
<filename>logoutax.js function login_func(){ const signupForm=document.querySelector('#signup-form'); signupForm.addEventListener('submit',(e) => { e.preventDefault(); const email =signupForm['inputEmail'].value; const passward =signupForm['inputPassword'].value; //signup the user auth.createUserWithEmailAndPassword(email,passward).then(cred => { //console.log(cred.user); const modal= document.querySelector('#modal-signup'); //M.Modal.getInstance(modal).close(); signupForm.reset(); document.location.href = "./index.html?Signup=Successful"; }); }); const loginForm=document.querySelector('#login-form'); loginForm.addEventListener('submit',(e) => { e.preventDefault(); const email =loginForm['inputEmail'].value; const passward =loginForm['inputPassword'].value; auth.signInWithEmailAndPassword(email,passward).then(cred => { console.log(cred.user); const modal= document.querySelector('#modal-login'); //M.Modal.getInstance(modal).close(); loginForm.reset(); document.location.href = "./index.html?Login=Successful"; }); }); } function logout_func(){ firebase.auth().signOut(); document.location.href = "./index.html?Logout=Successful"; } firebase.auth().onAuthStateChanged(function (user) { if (user) { console.log("logged in"); document.getElementById('logout').style.display='block'; document.getElementById('login').style.display='none'; } else { console.log("logged out"); document.getElementById('logout').style.display='none'; document.getElementById('login').style.display='block'; } });
SELECT sex, AVG(age) FROM customers GROUP BY sex;
<reponame>Acidburn0zzz/skabus /* ISC license. */ #include <skalibs/types.h> #include <skalibs/sgetopt.h> #include <skalibs/strerr2.h> #include <skalibs/exec.h> #include <s6/config.h> #include <skabus/config.h> #include "skabus-rpcc.h" #define USAGE "skabus-rpc-client [ -v verbosity ] [ -d | -D ] [ -1 ] [ -c maxconn ] [ -b backlog ] [ -t timeout ] [ -T lameducktimeout ] [ -C pmprog:sep:flags ] [ -y ifname:ifprog:sep:flags ... ] rpccpath rpcdpath clientname" #define dieusage() strerr_dieusage(100, USAGE) int main (int argc, char const *const *argv) { unsigned int verbosity = 1 ; int flag1 = 0 ; int flagreuse = 1 ; unsigned int maxconn = 0 ; unsigned int backlog = (unsigned int)-1 ; unsigned int timeout = 0 ; unsigned int ltimeout = 0 ; PROG = "skabus-rpc-client" ; unsigned int ifn = 1 ; char const *interfaces[SKABUS_RPCC_INTERFACES_MAX] = { 0 } ; { subgetopt_t l = SUBGETOPT_ZERO ; for (;;) { register int opt = subgetopt_r(argc, argv, "Dd1v:c:b:t:T:C:y:", &l) ; if (opt == -1) break ; switch (opt) { case 'D' : flagreuse = 0 ; break ; case 'd' : flagreuse = 1 ; break ; case '1' : flag1 = 1 ; break ; case 'v' : if (!uint0_scan(l.arg, &verbosity)) dieusage() ; break ; case 'c' : if (!uint0_scan(l.arg, &maxconn)) dieusage() ; if (!maxconn) maxconn = 1 ; break ; case 'b' : if (!uint0_scan(l.arg, &backlog)) dieusage() ; break ; case 't' : if (!uint0_scan(l.arg, &timeout)) dieusage() ; break ; case 'T' : if (!uint0_scan(l.arg, &ltimeout)) dieusage() ; break ; case 'C' : interfaces[0] = l.arg ; break ; case 'y' : { if (ifn >= SKABUS_RPCC_INTERFACES_MAX) dietoomanyinterfaces() ; if (!l.arg[0]) dieemptyifname() ; interfaces[ifn++] = l.arg ; break ; } default : dieusage() ; } } argc -= l.ind ; argv += l.ind ; if (argc < 3) dieusage() ; } { unsigned int m = 0, pos = 0 ; char fmt[UINT_FMT * 5] ; char const *newargv[22 + 2 * ifn] ; newargv[m++] = S6_EXTBINPREFIX "s6-ipcserver-socketbinder" ; if (!flagreuse) newargv[m++] = "-D" ; newargv[m++] = "-a" ; newargv[m++] = "0700" ; if (backlog != (unsigned int)-1) { newargv[m++] = "-b" ; newargv[m++] = fmt + pos ; pos += uint_fmt(fmt + pos, backlog) ; fmt[pos++] = 0 ; } newargv[m++] = "--" ; newargv[m++] = *argv++ ; newargv[m++] = SKABUS_BINPREFIX "skabus-rpcc" ; if (verbosity != 1) { newargv[m++] = "-v" ; newargv[m++] = fmt + pos ; pos += uint_fmt(fmt + pos, verbosity) ; fmt[pos++] = 0 ; } if (flag1) newargv[m++] = "-1" ; if (maxconn) { newargv[m++] = "-c" ; newargv[m++] = fmt + pos ; pos += uint_fmt(fmt + pos, maxconn) ; fmt[pos++] = 0 ; } if (timeout) { newargv[m++] = "-t" ; newargv[m++] = fmt + pos ; pos += uint_fmt(fmt + pos, timeout) ; fmt[pos++] = 0 ; } if (ltimeout) { newargv[m++] = "-T" ; newargv[m++] = fmt + pos ; pos += uint_fmt(fmt + pos, timeout) ; fmt[pos++] = 0 ; } if (interfaces[0]) { newargv[m++] = "-X" ; newargv[m++] = interfaces[0] ; } for (unsigned int i = 1 ; i < ifn ; i++) { newargv[m++] = "-y" ; newargv[m++] = interfaces[i] ; } newargv[m++] = "--" ; newargv[m++] = *argv++ ; newargv[m++] = *argv++ ; newargv[m++] = 0 ; xexec(newargv) ; } }
<reponame>kyokan/fnd package wire import ( "fnd/crypto" "fnd.localhost/dwire" "io" ) type TreeBaseReq struct { HashCacher Name string } var _ Message = (*TreeBaseReq)(nil) func (d *TreeBaseReq) MsgType() MessageType { return MessageTypeTreeBaseReq } func (d *TreeBaseReq) Equals(other Message) bool { cast, ok := other.(*TreeBaseReq) if !ok { return false } return d.Name == cast.Name } func (d *TreeBaseReq) Encode(w io.Writer) error { return dwire.EncodeFields( w, d.Name, ) } func (d *TreeBaseReq) Decode(r io.Reader) error { return dwire.DecodeFields( r, &d.Name, ) } func (d *TreeBaseReq) Hash() (crypto.Hash, error) { return d.HashCacher.Hash(d) }
class Canhao { constructor() { var opcoes = { isStatic: true } this.corpo = Bodies.rectangle(180, 110, 130, 100, opcoes) World.add(mundo, this.corpo) } desenha() { noFill() rect(this.corpo.position.x, this.corpo.position.y, 130, 100) } }
def sort_dict_values(d): return sorted(d, key=d.get, reverse=True)
#!/bin/zsh xcrun -sdk macosx metal -c ../kramv/KramShaders.metal -o ../bin/KramShaders.air xcrun -sdk macosx metallib ../bin/KramShaders.air -o ../bin/KramShaders.metallib # don't need this after metallib built rm ../bin/KramShaders.air
#!/usr/bin/env bats setup() { load $BATS_TEST_DIRNAME/helper/common.bash export PATH=$PATH:~/go/bin export NOMS_VERSION_NEXT=1 cd $BATS_TMPDIR mkdir "dolt-repo-$$" cd "dolt-repo-$$" dolt init } teardown() { rm -rf "$BATS_TMPDIR/dolt-repo-$$" } @test "update table using csv" { run dolt table create -s `batshelper 1pk5col-ints.schema` test [ "$status" -eq 0 ] run dolt table import -u test `batshelper 1pk5col-ints.csv` [ "$status" -eq 0 ] [[ "$output" =~ "Rows Processed: 2, Additions: 2, Modifications: 0, Had No Effect: 0" ]] || false [[ "$output" =~ "Import completed successfully." ]] || false } @test "update table using schema with csv" { run dolt table create -s `batshelper 1pk5col-ints.schema` test [ "$status" -eq 0 ] run dolt table import -u -s `batshelper 1pk5col-ints.schema` test `batshelper 1pk5col-ints.csv` [ "$status" -eq 1 ] [[ "$output" =~ "schema is not supported for update operations" ]] || false } @test "update table using csv with newlines" { skip "We currently fail on CSV imports with newlines" run dolt table create -s `batshelper 1pk5col-strings.schema` test [ "$status" -eq 0 ] run dolt table import -u test `batshelper 1pk5col-strings-newlines.csv` [ "$status" -eq 0 ] } @test "update table using json" { run dolt table create -s `batshelper employees-sch.json` employees [ "$status" -eq 0 ] run dolt table import -u employees `batshelper employees-tbl.json` [ "$status" -eq 0 ] [[ "$output" =~ "Rows Processed: 3, Additions: 3, Modifications: 0, Had No Effect: 0" ]] || false [[ "$output" =~ "Import completed successfully." ]] || false } @test "update table using wrong json" { run dolt table create -s `batshelper employees-sch-wrong.json` employees [ "$status" -eq 0 ] run dolt table import -u employees `batshelper employees-tbl.json` [ "$status" -eq 0 ] [[ "$output" =~ "Rows Processed: 0, Additions: 0, Modifications: 0, Had No Effect: 0" ]] || false } @test "update table using schema with json" { run dolt table create -s `batshelper employees-sch-wrong.json` employees [ "$status" -eq 0 ] run dolt table import -u -s `batshelper employees-sch.json` employees `batshelper employees-tbl.json` [ "$status" -eq 1 ] [[ "$output" =~ "schema is not supported for update operations" ]] || false } @test "update table with json when table does not exist" { run dolt table import -u employees `batshelper employees-tbl.json` [ "$status" -eq 1 ] [[ "$output" =~ "The following table could not be found:" ]] || false }
def remove_chars(s, chars): res = "" for c in s: if c not in chars: res+=c return res #Example remove_str = remove_chars('The quick brown fox', 'o') print(remove_str) #The quick bwn fx
<reponame>fishing-mc/mcmgr const Webhook = require("../classes/webhook") const playerActionTemplate = { "embeds": [{ "title": "<player>", "color": 16777045, "description": "has <action> the game", "thumbnail": { "url": "https://cravatar.eu/helmavatar/<player>.png" }, }] } const serverTemplate = { "embeds": [{ "title": "<title>", "color": "<color>", "description": "<description>", "timestamp": "<timestamp>", "thumbnail": { "url": "<thumbnail>" }, }] } class Minehook extends Webhook { sendPlayerAction(player, action) { this.sendFormatted(playerActionTemplate, { player: player, action: action }) } sendServerStart() { this.sendFormatted(serverTemplate, { title: "Started", color: 0x55FF55/* minecraft green */, description: "Server has started", thumbnail: "https://hral.xyz/img/fishing/fish.png" }) } sendServerStop() { this.sendFormatted(serverTemplate, { title: "Stopped", color: 0xFF5555 /* minecraft red */, description: "Server has stopped", thumbnail: "https://hral.xyz/img/fishing/fish.png" }) } sendServerCrash() { let template = JSON.parse(JSON.stringify(serverTemplate)); template["embeds"][0]["image"] = { "url": "https://hral.xyz/img/fishing/car-crash.gif" } this.sendFormatted(template, { title: "Crashed", color: 0xAA0000 /* minecraft dark red */, description: "Server has crashed\\nRestarting in 5 seconds...", thumbnail: "https://hral.xyz/img/fishing/fish.png" }) } sendServerRestart() { let template = JSON.parse(JSON.stringify(serverTemplate)); template["embeds"][0]["image"] = { "url": "https://hral.xyz/img/fishing/car-restart.gif" } this.sendFormatted(template, { title: "Restarting", color: 0x00AA00 /* minecraft dark green */, description: "Server is restarting", thumbnail: "https://hral.xyz/img/fishing/fish.png" }) } } module.exports = Minehook
#!/bin/sh # This script can be found on https://github.com/Azure/azure-quickstart-templates/blob/master/torque-cluster/azuredeploy.sh # This script is part of azure deploy ARM template # This script assumes the Linux distribution to be Ubuntu (or at least have apt-get support) # This script will install Torque on a Linux cluster deployed on a set of Azure VMs # Basic info date > /tmp/azuredeploy.log.$$ 2>&1 whoami >> /tmp/azuredeploy.log.$$ 2>&1 echo $@ >> /tmp/azuredeploy.log.$$ 2>&1 # Usage if [ "$#" -ne 9 ]; then echo "Usage: $0 MASTER_NAME MASTER_IP WORKER_NAME WORKER_IP_BASE WORKER_IP_START NUM_OF_VM ADMIN_USERNAME ADMIN_PASSWORD TEMPLATE_BASE" >> /tmp/azuredeploy.log.$$ exit 1 fi # Preparation steps - hosts and ssh ################################### # Parameters MASTER_NAME=$1 MASTER_IP=$2 WORKER_NAME=$3 WORKER_IP_BASE=$4 WORKER_IP_START=$5 NUM_OF_VM=$6 ADMIN_USERNAME=$7 ADMIN_PASSWORD=$8 TEMPLATE_BASE=$9 # Update master node echo $MASTER_IP $MASTER_NAME >> /etc/hosts echo $MASTER_IP $MASTER_NAME > /tmp/hosts.$$ # Need to disable requiretty in sudoers, I'm root so I can do this. sed -i "s/Defaults\s\{1,\}requiretty/Defaults \!requiretty/g" /etc/sudoers # Update ssh config file to ignore unknow host # Note all settings are for azureuser, NOT root sudo -u $ADMIN_USERNAME sh -c "mkdir /home/$ADMIN_USERNAME/.ssh/;echo Host worker\* > /home/$ADMIN_USERNAME/.ssh/config; echo StrictHostKeyChecking no >> /home/$ADMIN_USERNAME/.ssh/config; echo UserKnownHostsFile=/dev/null >> /home/$ADMIN_USERNAME/.ssh/config" # Generate a set of sshkey under /honme/azureuser/.ssh if there is not one yet if ! [ -f /home/$ADMIN_USERNAME/.ssh/id_rsa ]; then sudo -u $ADMIN_USERNAME sh -c "ssh-keygen -f /home/$ADMIN_USERNAME/.ssh/id_rsa -t rsa -N ''" fi # Install sshpass to automate ssh-copy-id action sudo apt-get install -y epel-release >> /tmp/azuredeploy.log.$$ 2>&1 sudo apt-get install -y sshpass >> /tmp/azuredeploy.log.$$ 2>&1 # Loop through all worker nodes, update hosts file and copy ssh public key to it # The script make the assumption that the node is called %WORKER+<index> and have # static IP in sequence order i=0 while [ $i -lt $NUM_OF_VM ] do workerip=`expr $i + $WORKER_IP_START` echo 'I update host - '$WORKER_NAME$i >> /tmp/azuredeploy.log.$$ 2>&1 echo $WORKER_IP_BASE$workerip $WORKER_NAME$i >> /etc/hosts echo $WORKER_IP_BASE$workerip $WORKER_NAME$i >> /tmp/hosts.$$ sudo -u $ADMIN_USERNAME sh -c "sshpass -p '$ADMIN_PASSWORD' ssh-copy-id $WORKER_NAME$i" i=`expr $i + 1` done # Install Torque ################ # Prep packages sudo apt-get install -y libtool openssl-devel libxml2-devel boost-devel gcc gcc-c++ >> /tmp/azuredeploy.log.$$ 2>&1 # Download the source package cd /tmp >> /tmp/azuredeploy.log.$$ 2>&1 wget http://www.adaptivecomputing.com/index.php?wpfb_dl=2936 -O torque.tar.gz >> /tmp/azuredeploy.log.$$ 2>&1 tar xzvf torque.tar.gz >> /tmp/azuredeploy.log.$$ 2>&1 cd torque-5.1.1* >> /tmp/azuredeploy.log.$$ 2>&1 # Build ./configure >> /tmp/azuredeploy.log.$$ 2>&1 make >> /tmp/azuredeploy.log.$$ 2>&1 make packages >> /tmp/azuredeploy.log.$$ 2>&1 sudo make install >> /tmp/azuredeploy.log.$$ 2>&1 export PATH=/usr/local/bin/:/usr/local/sbin/:$PATH # Create and start trqauthd sudo cp contrib/init.d/trqauthd /etc/init.d/ >> /tmp/azuredeploy.log.$$ 2>&1 sudo chkconfig --add trqauthd >> /tmp/azuredeploy.log.$$ 2>&1 sudo sh -c "echo /usr/local/lib > /etc/ld.so.conf.d/torque.conf" >> /tmp/azuredeploy.log.$$ 2>&1 sudo ldconfig >> /tmp/azuredeploy.log.$$ 2>&1 sudo service trqauthd start >> /tmp/azuredeploy.log.$$ 2>&1 # Update config sudo sh -c "echo $MASTER_NAME > /var/spool/torque/server_name" >> /tmp/azuredeploy.log.$$ 2>&1 sudo env "PATH=$PATH" sh -c "echo 'y' | ./torque.setup root" >> /tmp/azuredeploy.log.$$ 2>&1 sudo sh -c "echo $MASTER_NAME > /var/spool/torque/server_priv/nodes" >> /tmp/azuredeploy.log.$$ 2>&1 # Start pbs_server sudo cp contrib/init.d/pbs_server /etc/init.d >> /tmp/azuredeploy.log.$$ 2>&1 sudo chkconfig --add pbs_server >> /tmp/azuredeploy.log.$$ 2>&1 sudo service pbs_server restart >> /tmp/azuredeploy.log.$$ 2>&1 # Start pbs_mom sudo cp contrib/init.d/pbs_mom /etc/init.d >> /tmp/azuredeploy.log.$$ 2>&1 sudo chkconfig --add pbs_mom >> /tmp/azuredeploy.log.$$ 2>&1 sudo service pbs_mom start >> /tmp/azuredeploy.log.$$ 2>&1 # Start pbs_sched sudo env "PATH=$PATH" pbs_sched >> /tmp/azuredeploy.log.$$ 2>&1 # Push packages to compute nodes i=0 while [ $i -lt $NUM_OF_VM ] do worker=$WORKER_NAME$i sudo -u $ADMIN_USERNAME scp /tmp/hosts.$$ $ADMIN_USERNAME@$worker:/tmp/hosts >> /tmp/azuredeploy.log.$$ 2>&1 sudo -u $ADMIN_USERNAME scp torque-package-mom-linux-x86_64.sh $ADMIN_USERNAME@$worker:/tmp/. >> /tmp/azuredeploy.log.$$ 2>&1 sudo -u $ADMIN_USERNAME ssh -tt $worker "echo '$ADMIN_PASSWORD' | sudo -kS sh -c 'cat /tmp/hosts>>/etc/hosts'" sudo -u $ADMIN_USERNAME ssh -tt $worker "echo '$ADMIN_PASSWORD' | sudo -kS /tmp/torque-package-mom-linux-x86_64.sh --install" sudo -u $ADMIN_USERNAME ssh -tt $worker "echo '$ADMIN_PASSWORD' | sudo -kS /usr/local/sbin/pbs_mom" echo $worker >> /var/spool/torque/server_priv/nodes i=`expr $i + 1` done # Restart pbs_server sudo service pbs_server restart >> /tmp/azuredeploy.log.$$ 2>&1 exit 0
package test; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * */ import jframe.jedis.service.JedisServiceImpl; import redis.clients.jedis.Jedis; /** * @author dzh * @date Aug 6, 2014 1:26:15 PM * @since 1.0 */ public class TestJedis { JedisServiceImpl redis; @Before public void init() throws Exception { redis = new JedisServiceImpl(); redis.start(redis.init( Thread.currentThread().getContextClassLoader().getResourceAsStream("test/redis.properties"), true)); } @Test public void testLoadConf() throws Exception { Jedis j = redis.getJedis("t1"); long l = j.incr("test.pay"); System.out.println(l); j.del("test.pay"); j = redis.getJedis(); l = j.incr("test.pay.d"); System.out.println(l); j.del("test.pay.d"); j.close(); } @Test public void testExpire() throws Exception { String key = "test.pay.expire"; Jedis j = redis.getJedis(); long l = j.incr(key); System.out.println(l); System.out.println(j.get(key)); j.expire(key, 2); Thread.sleep(4 * 1000); System.out.println(j.get(key)); j.close(); } @Test public void testString() throws Exception { // redis.getJedis(name) } @After public void stop() { redis.stop(); } }
#!/usr/bin/env bash # set SPHINX_SKIP_CONFIG_VALIDATION environment variable to true to skip # validation of configuration examples set -e if [[ ! $(command -v bazel) ]]; then # shellcheck disable=SC2016 echo 'ERROR: bazel must be installed and available in "$PATH" to build docs' >&2 exit 1 fi MAIN_BRANCH="refs/heads/main" RELEASE_TAG_REGEX="^refs/tags/v.*" # default is to build html only BUILD_TYPE=html if [[ "${AZP_BRANCH}" =~ ${RELEASE_TAG_REGEX} ]]; then DOCS_TAG="${AZP_BRANCH/refs\/tags\//}" export DOCS_TAG else BUILD_SHA=$(git rev-parse HEAD) export BUILD_SHA if [[ "${AZP_BRANCH}" == "${MAIN_BRANCH}" ]]; then # no need to build html, just rst BUILD_TYPE=rst fi fi # This is for local RBE setup, should be no-op for builds without RBE setting in bazelrc files. IFS=" " read -ra BAZEL_BUILD_OPTIONS <<< "${BAZEL_BUILD_OPTIONS:-}" BAZEL_BUILD_OPTIONS+=( "--action_env=DOCS_TAG" "--action_env=BUILD_SHA" "--action_env=SPHINX_SKIP_CONFIG_VALIDATION") # Building html/rst is determined by then needs of CI but can be overridden in dev. if [[ "${BUILD_TYPE}" == "html" ]] || [[ -n "${DOCS_BUILD_HTML}" ]]; then BUILD_HTML=1 fi if [[ "${BUILD_TYPE}" == "rst" ]] || [[ -n "${DOCS_BUILD_RST}" ]]; then BUILD_RST=1 fi # Build html/rst if [[ -n "${BUILD_RST}" ]]; then bazel build "${BAZEL_BUILD_OPTIONS[@]}" //docs:rst fi if [[ -n "${BUILD_HTML}" ]]; then bazel build "${BAZEL_BUILD_OPTIONS[@]}" //docs:html fi [[ -z "${DOCS_OUTPUT_DIR}" ]] && DOCS_OUTPUT_DIR=generated/docs rm -rf "${DOCS_OUTPUT_DIR}" mkdir -p "${DOCS_OUTPUT_DIR}" # Save html/rst to output directory if [[ -n "${BUILD_HTML}" ]]; then tar -xf bazel-bin/docs/html.tar -C "$DOCS_OUTPUT_DIR" fi if [[ -n "${BUILD_RST}" ]]; then gzip -c bazel-bin/docs/rst.tar > "$DOCS_OUTPUT_DIR"/envoy-docs-rst.tar.gz fi
<reponame>hominsu/FileCryptX // // Created by <NAME> on 2021/10/2. // #include <string> #include <iostream> #include "read_task.h" #include "../memory/data.h" /** * @brief 初始化读取任务,获取文件大小 * @param _file_name 文件名 * @return 是否初始化成功 */ bool ReadTask::Init(const std::string &_file_name) { if (_file_name.empty()) { return false; } file_name_ = _file_name; return true; } /** * 线程入口函数 */ void ReadTask::Main() { #ifdef Debug std::cout << "ReadTask::Main() Start, thread id: " << std::this_thread::get_id() << std::endl; #endif size_t read_bytes; size_t total_read_bytes = 0; if (!OpenFile()) { set_return(0); return; } constexpr size_t data_size = KB(512); constexpr size_t down_data_limit_size = MB(20); // 编译期异常检测 static_assert(data_size > KB(1) && data_size < MB(1), "data_size must between 1KB and 1MB"); static_assert(down_data_limit_size > data_size, "down_data_limit_size must greater than data_size"); // 设置下游节点的上游状态 next_->prev_status_ = true; while (is_running()) { if (ifs_.eof()) { break; } // 当下游节点的数据块总和超过 20MB 时阻塞 if (next_status_) { std::unique_lock<std::shared_mutex> lock(cv_mutex_); cv_.wait(cv_mutex_, [&]() -> bool { return next_->DataListNum() <= LimitNum(down_data_limit_size, data_size); }); } // 创建内存池空间管理对象 auto data = Data::Make(memory_resource_); // 申请空间 auto buf = data->New(data_size); // 读取文件 ifs_.read(static_cast<char *>(buf), data_size); read_bytes = ifs_.gcount(); if (read_bytes <= 0) { break; } data->set_size(read_bytes); total_read_bytes += read_bytes; if (total_read_bytes == data_bytes_) { data->set_end(true); } #ifdef Debug // std::cout << "[" << ifs_.gcount() << "]" << std::flush; #endif if (nullptr != next_) { next_->PushBack(data); } } ifs_.close(); #ifdef Debug std::cout << std::endl << "ReadTask::Main() End, thread id: " << std::this_thread::get_id() << std::endl; #endif // 设置下游节点的上游状态 next_->prev_status_ = false; set_return(data_bytes_); } /** * @brief 打开文件 * @return 是否打开 */ bool ReadTask::OpenFile() { ifs_.open(file_name_, std::ios::binary); if (!ifs_) { std::cerr << "open file: " << file_name_ << " failed" << std::endl; return false; } #ifdef Debug std::cout << "open file: " << file_name_ << " success" << std::endl; #endif // 计算文件长度 ifs_.seekg(0, std::ios::end); data_bytes_ = ifs_.tellg(); ifs_.seekg(0, std::ios::beg); #ifdef Debug std::cout << "file size = " << data_bytes_ << std::endl; #endif return true; }
<reponame>stefb965/JRAW<gh_stars>1-10 package net.dean.jraw.test; import net.dean.jraw.RedditClient; import net.dean.jraw.auth.NoSuchTokenException; import net.dean.jraw.auth.RefreshTokenHandler; import net.dean.jraw.auth.VolatileTokenStore; import net.dean.jraw.http.UserAgent; import org.testng.annotations.Test; import static org.testng.Assert.*; public class RefreshTokenHandlerTest { @Test public void testSave() throws NoSuchTokenException { RefreshTokenHandler handler = new RefreshTokenHandler(new VolatileTokenStore(), new RedditClient(UserAgent.of("test"))); assertFalse(handler.hasLastAuthenticated()); String username = "testUsername"; handler.writeToken(username, "token"); assertTrue(handler.isStored(username)); assertTrue(handler.hasLastAuthenticated()); assertEquals(handler.getLastAuthenticatedUser(), username); String username2 = "testUsername2"; handler.writeToken(username2, "token2"); assertTrue(handler.isStored(username2)); assertTrue(handler.hasLastAuthenticated()); assertEquals(handler.getLastAuthenticatedUser(), username2); } }
<reponame>tamanna037/commons-geometry /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.geometry.euclidean.threed; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.geometry.core.GeometryTestUtils; import org.apache.commons.geometry.core.RegionLocation; import org.apache.commons.geometry.core.partitioning.Split; import org.apache.commons.geometry.core.partitioning.SplitLocation; import org.apache.commons.geometry.euclidean.EuclideanTestUtils; import org.apache.commons.geometry.euclidean.threed.rotation.QuaternionRotation; import org.apache.commons.geometry.euclidean.twod.ConvexArea; import org.apache.commons.geometry.euclidean.twod.Vector2D; import org.apache.commons.numbers.angle.Angle; import org.apache.commons.numbers.core.Precision; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class VertexListConvexPolygon3DTest { private static final double TEST_EPS = 1e-10; private static final Precision.DoubleEquivalence TEST_PRECISION = Precision.doubleEquivalenceOfEpsilon(TEST_EPS); private static final Plane XY_PLANE_Z1 = Planes.fromPointAndPlaneVectors(Vector3D.of(0, 0, 1), Vector3D.Unit.PLUS_X, Vector3D.Unit.PLUS_Y, TEST_PRECISION); private static final List<Vector3D> TRIANGLE_VERTICES = Arrays.asList(Vector3D.of(0, 0, 1), Vector3D.of(1, 0, 1), Vector3D.of(0, 1, 1)); @Test void testProperties() { // act final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, TRIANGLE_VERTICES); // assert Assertions.assertFalse(p.isFull()); Assertions.assertFalse(p.isEmpty()); Assertions.assertTrue(p.isFinite()); Assertions.assertFalse(p.isInfinite()); Assertions.assertEquals(0.5, p.getSize(), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(1.0 / 3.0, 1.0 / 3.0, 1), p.getCentroid(), TEST_EPS); Assertions.assertSame(XY_PLANE_Z1, p.getPlane()); EuclideanTestUtils.assertVertexLoopSequence( Arrays.asList(Vector3D.of(0, 0, 1), Vector3D.of(1, 0, 1), Vector3D.of(0, 1, 1)), p.getVertices(), TEST_PRECISION); final Bounds3D bounds = p.getBounds(); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(0, 0, 1), bounds.getMin(), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(1, 1, 1), bounds.getMax(), TEST_EPS); } @Test void testCtor_validatesVertexListSize() { // act/assert GeometryTestUtils.assertThrowsWithMessage(() -> { new VertexListConvexPolygon3D(XY_PLANE_Z1, Arrays.asList(Vector3D.ZERO, Vector3D.Unit.PLUS_X)); }, IllegalArgumentException.class, "Convex polygon requires at least 3 points; found 2"); } @Test void testVertices_listIsImmutable() { // arrange final List<Vector3D> vertices = new ArrayList<>(TRIANGLE_VERTICES); final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, vertices); // act/assert Assertions.assertThrows(UnsupportedOperationException.class, () -> p.getVertices().add(Vector3D.of(-1, 0, 1))); } @Test void testGetCentroid_linearVertices() { // this should not happen with all of the checks in place for constructing these // instances; this test is to ensure that the centroid computation can still handle // the situation // arrange final List<Vector3D> vertices = Arrays.asList(Vector3D.ZERO, Vector3D.of(0.5, 0, 0), Vector3D.of(2, 0, 0)); final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, vertices); // act final Vector3D center = p.getCentroid(); // assert EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(1, 0, 0), center, TEST_EPS); } @Test void testGetSubspaceRegion() { // arrange final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, TRIANGLE_VERTICES); // act final ConvexArea area = p.getEmbedded().getSubspaceRegion(); // assert Assertions.assertFalse(area.isFull()); Assertions.assertFalse(area.isEmpty()); Assertions.assertTrue(area.isFinite()); Assertions.assertFalse(area.isInfinite()); Assertions.assertEquals(0.5, area.getSize(), TEST_EPS); final List<Vector2D> vertices = area.getVertices(); Assertions.assertEquals(3, vertices.size()); EuclideanTestUtils.assertCoordinatesEqual(Vector2D.ZERO, vertices.get(0), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector2D.of(1, 0), vertices.get(1), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector2D.of(0, 1), vertices.get(2), TEST_EPS); } @Test void testToTriangles_threeVertices() { // arrange final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, TRIANGLE_VERTICES); // act final List<Triangle3D> tris = p.toTriangles(); // assert Assertions.assertEquals(1, tris.size()); final Triangle3D a = tris.get(0); Assertions.assertSame(XY_PLANE_Z1, a.getPlane()); EuclideanTestUtils.assertVertexLoopSequence(TRIANGLE_VERTICES, a.getVertices(), TEST_PRECISION); } @Test void testToTriangles_fiveVertices() { // arrange final Vector3D p1 = Vector3D.of(1, 1, 1); final Vector3D p2 = Vector3D.of(2, 1.2, 1); final Vector3D p3 = Vector3D.of(3, 2, 1); final Vector3D p4 = Vector3D.of(1, 4, 1); final Vector3D p5 = Vector3D.of(0, 2, 1); final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, Arrays.asList(p1, p2, p3, p4, p5)); // act final List<Triangle3D> tris = p.toTriangles(); // assert Assertions.assertEquals(3, tris.size()); final Triangle3D a = tris.get(0); Assertions.assertSame(XY_PLANE_Z1, a.getPlane()); EuclideanTestUtils.assertVertexLoopSequence(Arrays.asList(p2, p3, p4), a.getVertices(), TEST_PRECISION); final Triangle3D b = tris.get(1); Assertions.assertSame(XY_PLANE_Z1, b.getPlane()); EuclideanTestUtils.assertVertexLoopSequence(Arrays.asList(p2, p4, p5), b.getVertices(), TEST_PRECISION); final Triangle3D c = tris.get(2); Assertions.assertSame(XY_PLANE_Z1, c.getPlane()); EuclideanTestUtils.assertVertexLoopSequence(Arrays.asList(p2, p5, p1), c.getVertices(), TEST_PRECISION); } @Test void testClassify() { // arrange final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, Arrays.asList( Vector3D.of(1, 2, 1), Vector3D.of(3, 2, 1), Vector3D.of(3, 4, 1), Vector3D.of(1, 4, 1) )); // act/assert checkPoints(p, RegionLocation.INSIDE, Vector3D.of(2, 3, 1)); checkPoints(p, RegionLocation.BOUNDARY, Vector3D.of(1, 3, 1), Vector3D.of(3, 3, 1), Vector3D.of(2, 2, 1), Vector3D.of(2, 4, 1)); checkPoints(p, RegionLocation.OUTSIDE, Vector3D.of(2, 3, 0), Vector3D.of(2, 3, 2), Vector3D.of(0, 3, 1), Vector3D.of(4, 3, 1), Vector3D.of(2, 1, 1), Vector3D.of(2, 5, 1)); } @Test void testClosest() { // arrange final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, Arrays.asList( Vector3D.of(1, 2, 1), Vector3D.of(3, 2, 1), Vector3D.of(3, 4, 1), Vector3D.of(1, 4, 1) )); // act/assert EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(2, 3, 1), p.closest(Vector3D.of(2, 3, 1)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(2, 3, 1), p.closest(Vector3D.of(2, 3, 100)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(3, 4, 1), p.closest(Vector3D.of(3, 5, 10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(3, 4, 1), p.closest(Vector3D.of(3, 4, 10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(3, 3, 1), p.closest(Vector3D.of(3, 3, 10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(3, 2, 1), p.closest(Vector3D.of(3, 2, 10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(3, 2, 1), p.closest(Vector3D.of(3, 1, 10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(1, 4, 1), p.closest(Vector3D.of(0, 5, -10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(1, 4, 1), p.closest(Vector3D.of(1, 5, -10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(2, 4, 1), p.closest(Vector3D.of(2, 5, -10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(3, 4, 1), p.closest(Vector3D.of(3, 5, -10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(3, 4, 1), p.closest(Vector3D.of(4, 5, -10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(1, 2, 1), p.closest(Vector3D.of(0, 2, 1)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(1, 2, 1), p.closest(Vector3D.of(1, 2, 1)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(2, 2, 1), p.closest(Vector3D.of(2, 2, 1)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(3, 2, 1), p.closest(Vector3D.of(3, 2, 1)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(3, 2, 1), p.closest(Vector3D.of(4, 2, 1)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(1, 3, 1), p.closest(Vector3D.of(0, 3, -10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(1, 3, 1), p.closest(Vector3D.of(1, 3, -10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(2, 3, 1), p.closest(Vector3D.of(2, 3, -10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(3, 3, 1), p.closest(Vector3D.of(3, 3, -10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(3, 3, 1), p.closest(Vector3D.of(4, 3, -10)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(1, 2, 1), p.closest(Vector3D.of(-100, -100, -100)), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.of(3, 3.5, 1), p.closest(Vector3D.of(100, 3.5, 100)), TEST_EPS); } @Test void testTransform() { // arrange final AffineTransformMatrix3D t = AffineTransformMatrix3D.identity() .rotate(QuaternionRotation.fromAxisAngle(Vector3D.Unit.PLUS_Y, -Angle.PI_OVER_TWO)) .scale(1, 1, 2) .translate(Vector3D.of(1, 0, 0)); final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, Arrays.asList( Vector3D.of(1, 2, 1), Vector3D.of(3, 2, 1), Vector3D.of(3, 4, 1), Vector3D.of(1, 4, 1) )); // act final VertexListConvexPolygon3D result = p.transform(t); // assert Assertions.assertFalse(result.isFull()); Assertions.assertFalse(result.isEmpty()); Assertions.assertTrue(result.isFinite()); Assertions.assertFalse(result.isInfinite()); Assertions.assertEquals(8, result.getSize(), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.Unit.MINUS_X, result.getPlane().getNormal(), TEST_EPS); EuclideanTestUtils.assertVertexLoopSequence( Arrays.asList(Vector3D.of(0, 2, 2), Vector3D.of(0, 2, 6), Vector3D.of(0, 4, 6), Vector3D.of(0, 4, 2)), result.getVertices(), TEST_PRECISION); } @Test void testReverse() { // arrange final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, Arrays.asList( Vector3D.of(1, 2, 1), Vector3D.of(3, 2, 1), Vector3D.of(3, 4, 1), Vector3D.of(1, 4, 1) )); // act final VertexListConvexPolygon3D result = p.reverse(); // assert Assertions.assertFalse(result.isFull()); Assertions.assertFalse(result.isEmpty()); Assertions.assertTrue(result.isFinite()); Assertions.assertFalse(result.isInfinite()); Assertions.assertEquals(4, result.getSize(), TEST_EPS); EuclideanTestUtils.assertCoordinatesEqual(Vector3D.Unit.MINUS_Z, result.getPlane().getNormal(), TEST_EPS); EuclideanTestUtils.assertVertexLoopSequence( Arrays.asList(Vector3D.of(1, 4, 1), Vector3D.of(3, 4, 1), Vector3D.of(3, 2, 1), Vector3D.of(1, 2, 1)), result.getVertices(), TEST_PRECISION); } @Test void testSplit_plus() { // arrange final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, TRIANGLE_VERTICES); final Plane splitter = Planes.fromPointAndNormal(Vector3D.ZERO, Vector3D.Unit.PLUS_X, TEST_PRECISION); // act final Split<PlaneConvexSubset> split = p.split(splitter); // assert Assertions.assertEquals(SplitLocation.PLUS, split.getLocation()); Assertions.assertNull(split.getMinus()); Assertions.assertSame(p, split.getPlus()); } @Test void testSplit_minus() { // arrange final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, TRIANGLE_VERTICES); final Plane splitter = Planes.fromPointAndNormal(Vector3D.ZERO, Vector3D.Unit.MINUS_Z, TEST_PRECISION); // act final Split<PlaneConvexSubset> split = p.split(splitter); // assert Assertions.assertEquals(SplitLocation.MINUS, split.getLocation()); Assertions.assertSame(p, split.getMinus()); Assertions.assertNull(split.getPlus()); } @Test void testSplit_both() { // arrange final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, TRIANGLE_VERTICES); final Plane splitter = Planes.fromPointAndNormal(Vector3D.ZERO, Vector3D.of(-1, 1, 0), TEST_PRECISION); // act final Split<PlaneConvexSubset> split = p.split(splitter); // assert Assertions.assertEquals(SplitLocation.BOTH, split.getLocation()); final PlaneConvexSubset minus = split.getMinus(); EuclideanTestUtils.assertVertexLoopSequence( Arrays.asList(Vector3D.of(0, 0, 1), Vector3D.of(1, 0, 1), Vector3D.of(0.5, 0.5, 1)), minus.getVertices(), TEST_PRECISION); final PlaneConvexSubset plus = split.getPlus(); EuclideanTestUtils.assertVertexLoopSequence( Arrays.asList(Vector3D.of(0, 0, 1), Vector3D.of(0.5, 0.5, 1), Vector3D.of(0, 1, 1)), plus.getVertices(), TEST_PRECISION); } @Test void testSplit_neither() { // arrange final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, TRIANGLE_VERTICES); final Plane splitter = Planes.fromPointAndNormal(Vector3D.of(0, 0, 1), Vector3D.of(0, 1e-15, -1), TEST_PRECISION); // act final Split<PlaneConvexSubset> split = p.split(splitter); // assert Assertions.assertEquals(SplitLocation.NEITHER, split.getLocation()); Assertions.assertNull(split.getMinus()); Assertions.assertNull(split.getPlus()); } @Test void testToString() { // arrange final VertexListConvexPolygon3D p = new VertexListConvexPolygon3D(XY_PLANE_Z1, TRIANGLE_VERTICES); // act final String str = p.toString(); // assert GeometryTestUtils.assertContains("VertexListConvexPolygon3D[normal= (", str); GeometryTestUtils.assertContains("vertices= [", str); } private static void checkPoints(final ConvexPolygon3D ps, final RegionLocation loc, final Vector3D... pts) { for (final Vector3D pt : pts) { Assertions.assertEquals(loc, ps.classify(pt), "Unexpected location for point " + pt); } } }
FROM alpine:latest WORKDIR /app COPY server.js . RUN apk update && apk add nodejs EXPOSE 80 CMD ["node", "server.js"] # server.js const http = require('http'); const os = require('os'); http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(`Hostname: ${os.hostname()}\n`); }).listen(80);
#!/bin/sh cur=$( cd "$(dirname "$0")" pwd ) echo "update the test script、client and server yaml files" sed -i "s#cd stream/#cd $cur/#g" $cur/tuning_stream_client.yaml sed -i "s# .*stream/Makefile# $cur/Makefile#g" $cur/tuning_stream_server.yaml echo "copy the server yaml file to /etc/atuned/tuning/" cp tuning_stream_server.yaml /etc/atuned/tuning/ wget http://www.cs.virginia.edu/stream/FTP/Code/stream.c
const isDivisible = (a, b) => { if(a % b === 0) { return true; } else { return false; } } // Usage isDivisible(10, 5) // true
/** * Copyright (C) 2013 <EMAIL> (<EMAIL>) * * 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 io.motown.ocpp.v15.soap.centralsystem; import io.motown.domain.api.chargingstation.*; import io.motown.domain.api.chargingstation.MeterValue; import io.motown.domain.api.security.AddOnIdentity; import io.motown.domain.api.security.TypeBasedAddOnIdentity; import io.motown.ocpp.soaputils.header.SoapHeaderReader; import io.motown.ocpp.v15.soap.centralsystem.schema.*; import io.motown.ocpp.v15.soap.centralsystem.schema.FirmwareStatus; import io.motown.ocpp.viewmodel.domain.*; import org.apache.cxf.continuations.Continuation; import org.apache.cxf.continuations.ContinuationProvider; import org.junit.Before; import org.junit.Test; import javax.xml.ws.WebServiceContext; import javax.xml.ws.handler.MessageContext; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import static io.motown.domain.api.chargingstation.test.ChargingStationTestUtils.*; import static io.motown.ocpp.v15.soap.V15SOAPTestUtils.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; public class MotownCentralSystemServiceTest { private static final String ADD_ON_TYPE = "OCPPS15"; private static final AddOnIdentity OCPPS15_ADD_ON_IDENTITY = new TypeBasedAddOnIdentity(ADD_ON_TYPE, ADD_ON_ID); private MotownCentralSystemService motownCentralSystemService; private DomainService domainService; private SoapHeaderReader soapHeaderReader; @Before public void setup() { motownCentralSystemService = new MotownCentralSystemService(); motownCentralSystemService.setContinuationTimeout(100); soapHeaderReader = mock(SoapHeaderReader.class); when(soapHeaderReader.getChargingStationAddress(any(MessageContext.class))).thenReturn(LOCALHOST); motownCentralSystemService.setSoapHeaderReader(soapHeaderReader); domainService = mock(DomainService.class); motownCentralSystemService.setDomainService(domainService); motownCentralSystemService.setAddOnId(ADD_ON_ID); motownCentralSystemService.setContext(mock(WebServiceContext.class)); } private void prepareAuthorization(AuthorizationResultStatus expectedStatus) throws InterruptedException, ExecutionException { WebServiceContext webServiceContext = mock(WebServiceContext.class); MessageContext messageContext = mock(MessageContext.class); ContinuationProvider continuationProvider = mock(ContinuationProvider.class); Continuation continuation = mock(Continuation.class); Future future = mock(Future.class); AuthorizationResult authorizationResult = mock(AuthorizationResult.class); when(authorizationResult.getStatus()).thenReturn(expectedStatus); when(future.isDone()).thenReturn(true); when(future.get()).thenReturn(authorizationResult); when(continuation.getObject()).thenReturn(future); when(continuationProvider.getContinuation()).thenReturn(continuation); when(messageContext.get(any())).thenReturn(continuationProvider); when(webServiceContext.getMessageContext()).thenReturn(messageContext); motownCentralSystemService.setContext(webServiceContext); } @Test public void authorizeAcceptedVerifyResponse() throws InterruptedException, ExecutionException { prepareAuthorization(AuthorizationResultStatus.ACCEPTED); AuthorizeRequest request = new AuthorizeRequest(); request.setIdTag(IDENTIFYING_TOKEN.getToken()); AuthorizeResponse response = motownCentralSystemService.authorize(request, CHARGING_STATION_ID.getId()); assertEquals(AuthorizationStatus.ACCEPTED, response.getIdTagInfo().getStatus()); } @Test public void authorizeInvalidVerifyResponse() throws InterruptedException, ExecutionException { prepareAuthorization(AuthorizationResultStatus.INVALID); AuthorizeRequest request = new AuthorizeRequest(); request.setIdTag(IDENTIFYING_TOKEN.getToken()); AuthorizeResponse response = motownCentralSystemService.authorize(request, CHARGING_STATION_ID.getId()); assertEquals(AuthorizationStatus.INVALID, response.getIdTagInfo().getStatus()); } @Test public void authorizeBlockedVerifyResponse() throws InterruptedException, ExecutionException { prepareAuthorization(AuthorizationResultStatus.BLOCKED); AuthorizeRequest request = new AuthorizeRequest(); request.setIdTag(IDENTIFYING_TOKEN.getToken()); AuthorizeResponse response = motownCentralSystemService.authorize(request, CHARGING_STATION_ID.getId()); assertEquals(AuthorizationStatus.BLOCKED, response.getIdTagInfo().getStatus()); } @Test public void authorizeExpiredVerifyResponse() throws InterruptedException, ExecutionException { prepareAuthorization(AuthorizationResultStatus.EXPIRED); AuthorizeRequest request = new AuthorizeRequest(); request.setIdTag(IDENTIFYING_TOKEN.getToken()); AuthorizeResponse response = motownCentralSystemService.authorize(request, CHARGING_STATION_ID.getId()); assertEquals(AuthorizationStatus.EXPIRED, response.getIdTagInfo().getStatus()); } private void prepareDataTransfer(IncomingDataTransferResultStatus expectedStatus) throws InterruptedException, ExecutionException { WebServiceContext webServiceContext = mock(WebServiceContext.class); MessageContext messageContext = mock(MessageContext.class); ContinuationProvider continuationProvider = mock(ContinuationProvider.class); Continuation continuation = mock(Continuation.class); Future future = mock(Future.class); IncomingDataTransferResult incomingDataTransferResult = mock(IncomingDataTransferResult.class); when(incomingDataTransferResult.getStatus()).thenReturn(expectedStatus); when(future.isDone()).thenReturn(true); when(future.get()).thenReturn(incomingDataTransferResult); when(continuation.getObject()).thenReturn(future); when(continuationProvider.getContinuation()).thenReturn(continuation); when(messageContext.get(any())).thenReturn(continuationProvider); when(webServiceContext.getMessageContext()).thenReturn(messageContext); motownCentralSystemService.setContext(webServiceContext); } @Test public void dataTransferAcceptedVerifyResponse() throws InterruptedException, ExecutionException { prepareDataTransfer(IncomingDataTransferResultStatus.ACCEPTED); DataTransferRequest request = new DataTransferRequest(); DataTransferResponse response = motownCentralSystemService.dataTransfer(request, CHARGING_STATION_ID.getId()); assertEquals(DataTransferStatus.ACCEPTED, response.getStatus()); } @Test public void dataTransferRejectedVerifyResponse() throws InterruptedException, ExecutionException { prepareDataTransfer(IncomingDataTransferResultStatus.REJECTED); DataTransferRequest request = new DataTransferRequest(); DataTransferResponse response = motownCentralSystemService.dataTransfer(request, CHARGING_STATION_ID.getId()); assertEquals(DataTransferStatus.REJECTED, response.getStatus()); } @Test public void statusNotificationVerifyResponse() { StatusNotificationRequest request = new StatusNotificationRequest(); request.setStatus(ChargePointStatus.AVAILABLE); StatusNotificationResponse response = motownCentralSystemService.statusNotification(request, CHARGING_STATION_ID.getId()); assertNotNull(response); } @Test public void statusNotificationVerifyServiceCall() { StatusNotificationRequest request = new StatusNotificationRequest(); request.setStatus(ChargePointStatus.FAULTED); request.setVendorId(CHARGING_STATION_VENDOR); request.setConnectorId(EVSE_ID.getNumberedId()); request.setErrorCode(ChargePointErrorCode.GROUND_FAILURE); request.setInfo(STATUS_NOTIFICATION_ERROR_INFO); request.setTimestamp(FIVE_MINUTES_AGO); request.setVendorErrorCode(STATUS_NOTIFICATION_VENDOR_ERROR_CODE); motownCentralSystemService.statusNotification(request, CHARGING_STATION_ID.getId()); verify(domainService).statusNotification(CHARGING_STATION_ID, EVSE_ID, ChargePointErrorCode.GROUND_FAILURE.value(), ComponentStatus.FAULTED, STATUS_NOTIFICATION_ERROR_INFO, FIVE_MINUTES_AGO, CHARGING_STATION_VENDOR, STATUS_NOTIFICATION_VENDOR_ERROR_CODE, OCPPS15_ADD_ON_IDENTITY); } @Test public void stopTransactionVerifyResponse() { StopTransactionRequest request = new StopTransactionRequest(); request.setIdTag(IDENTIFYING_TOKEN.getToken()); StopTransactionResponse response = motownCentralSystemService.stopTransaction(request, CHARGING_STATION_ID.getId()); assertNotNull(response); } @Test public void stopTransactionVerifyServiceCall() { StopTransactionRequest request = new StopTransactionRequest(); request.setIdTag(IDENTIFYING_TOKEN.getToken()); request.setMeterStop(METER_STOP); request.setTimestamp(FIVE_MINUTES_AGO); request.setTransactionId(TRANSACTION_NUMBER); request.getTransactionData().addAll(TRANSACTION_DATA); motownCentralSystemService.stopTransaction(request, CHARGING_STATION_ID.getId()); verify(domainService).stopTransaction(eq(CHARGING_STATION_ID), eq(new NumberedTransactionId(CHARGING_STATION_ID, PROTOCOL_IDENTIFIER, TRANSACTION_NUMBER)), eq(IDENTIFYING_TOKEN), eq(METER_STOP), eq(FIVE_MINUTES_AGO), anyListOf(MeterValue.class), eq(OCPPS15_ADD_ON_IDENTITY)); } @Test public void stopTransactionWithoutIdTag() { StopTransactionRequest request = new StopTransactionRequest(); request.setIdTag(null); request.setMeterStop(METER_STOP); request.setTimestamp(FIVE_MINUTES_AGO); request.setTransactionId(TRANSACTION_NUMBER); request.getTransactionData().addAll(TRANSACTION_DATA); motownCentralSystemService.stopTransaction(request, CHARGING_STATION_ID.getId()); verify(domainService).stopTransaction(eq(CHARGING_STATION_ID), eq(new NumberedTransactionId(CHARGING_STATION_ID, PROTOCOL_IDENTIFIER, TRANSACTION_NUMBER)), eq(EMPTY_IDENTIFYING_TOKEN), eq(METER_STOP), eq(FIVE_MINUTES_AGO), anyListOf(MeterValue.class), eq(OCPPS15_ADD_ON_IDENTITY)); } @Test public void bootNotificationNoAddressVerifyResponse() { when(soapHeaderReader.getChargingStationAddress(any(MessageContext.class))).thenReturn(""); BootNotificationRequest request = new BootNotificationRequest(); BootNotificationResponse response = motownCentralSystemService.bootNotification(request, CHARGING_STATION_ID.getId()); assertEquals(response.getStatus(), RegistrationStatus.REJECTED); assertNotNull(response.getCurrentTime()); assertNotNull(response.getHeartbeatInterval()); } @Test public void bootNotificationAcceptedVerifyResponse() { BootNotificationRequest request = new BootNotificationRequest(); Date now = new Date(); BootChargingStationResult result = new BootChargingStationResult(true, HEARTBEAT_INTERVAL, now); when(domainService.bootChargingStation(any(ChargingStationId.class), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), any(AddOnIdentity.class))).thenReturn(result); BootNotificationResponse response = motownCentralSystemService.bootNotification(request, CHARGING_STATION_ID.getId()); assertEquals(response.getStatus(), RegistrationStatus.ACCEPTED); assertEquals(response.getCurrentTime(), now); assertEquals(response.getHeartbeatInterval(), HEARTBEAT_INTERVAL.intValue()); } @Test public void bootNotificationRejectedVerifyResponse() { BootNotificationRequest request = new BootNotificationRequest(); Date now = new Date(); BootChargingStationResult result = new BootChargingStationResult(false, HEARTBEAT_INTERVAL, now); when(domainService.bootChargingStation(any(ChargingStationId.class), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), any(AddOnIdentity.class))).thenReturn(result); BootNotificationResponse response = motownCentralSystemService.bootNotification(request, CHARGING_STATION_ID.getId()); assertEquals(response.getStatus(), RegistrationStatus.REJECTED); assertEquals(response.getCurrentTime(), now); assertEquals(response.getHeartbeatInterval(), HEARTBEAT_INTERVAL.intValue()); } @Test public void bootNotificationVerifyServiceCall() { BootNotificationRequest request = new BootNotificationRequest(); request.setChargePointVendor(CHARGING_STATION_VENDOR); request.setChargePointModel(CHARGING_STATION_MODEL); request.setChargePointSerialNumber(CHARGING_STATION_SERIAL_NUMBER); request.setChargeBoxSerialNumber(CHARGE_BOX_SERIAL_NUMBER); request.setFirmwareVersion(CHARGING_STATION_FIRMWARE_VERSION); request.setIccid(CHARGING_STATION_ICCID); request.setImsi(CHARGING_STATION_IMSI); request.setMeterType(CHARGING_STATION_METER_TYPE); request.setMeterSerialNumber(CHARGING_STATION_METER_SERIAL_NUMBER); Date now = new Date(); BootChargingStationResult result = new BootChargingStationResult(true, HEARTBEAT_INTERVAL, now); when(domainService.bootChargingStation(any(ChargingStationId.class), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), any(AddOnIdentity.class))).thenReturn(result); motownCentralSystemService.bootNotification(request, CHARGING_STATION_ID.getId()); verify(domainService).bootChargingStation(CHARGING_STATION_ID, LOCALHOST, CHARGING_STATION_VENDOR, CHARGING_STATION_MODEL, PROTOCOL_IDENTIFIER, CHARGING_STATION_SERIAL_NUMBER, CHARGE_BOX_SERIAL_NUMBER, CHARGING_STATION_FIRMWARE_VERSION, CHARGING_STATION_ICCID, CHARGING_STATION_IMSI, CHARGING_STATION_METER_TYPE, CHARGING_STATION_METER_SERIAL_NUMBER, OCPPS15_ADD_ON_IDENTITY); } @Test public void heartBeatVerifyResponse() { HeartbeatRequest request = new HeartbeatRequest(); HeartbeatResponse response = motownCentralSystemService.heartbeat(request, CHARGING_STATION_ID.getId()); assertNotNull(response); assertNotNull(response.getCurrentTime()); } @Test public void heartBeatVerifyServiceCall() { HeartbeatRequest request = new HeartbeatRequest(); motownCentralSystemService.heartbeat(request, CHARGING_STATION_ID.getId()); verify(domainService).heartbeat(CHARGING_STATION_ID, OCPPS15_ADD_ON_IDENTITY); } @Test public void meterValuesVerifyResponse() { MeterValuesRequest request = new MeterValuesRequest(); request.setTransactionId(TRANSACTION_NUMBER); MeterValuesResponse response = motownCentralSystemService.meterValues(request, CHARGING_STATION_ID.getId()); assertNotNull(response); } @Test public void meterValuesVerifyServiceCall() { MeterValuesRequest request = new MeterValuesRequest(); request.setConnectorId(EVSE_ID.getNumberedId()); request.setTransactionId(TRANSACTION_NUMBER); List<io.motown.ocpp.v15.soap.centralsystem.schema.MeterValue> meterValuesSoap = getMeterValuesSoap(4); request.getValues().addAll(meterValuesSoap); List<io.motown.domain.api.chargingstation.MeterValue> expectedMeterValuesList = new ArrayList<>(); for (io.motown.ocpp.v15.soap.centralsystem.schema.MeterValue mv : meterValuesSoap) { for (io.motown.ocpp.v15.soap.centralsystem.schema.MeterValue.Value value : mv.getValue()) { expectedMeterValuesList.add(new io.motown.domain.api.chargingstation.MeterValue(mv.getTimestamp(), value.getValue())); } } motownCentralSystemService.meterValues(request, CHARGING_STATION_ID.getId()); verify(domainService).meterValues(CHARGING_STATION_ID, TRANSACTION_ID, EVSE_ID, expectedMeterValuesList, OCPPS15_ADD_ON_IDENTITY); } @Test public void diagnosticsStatusNotificationVerifyResponse() { DiagnosticsStatusNotificationRequest request = new DiagnosticsStatusNotificationRequest(); DiagnosticsStatusNotificationResponse response = motownCentralSystemService.diagnosticsStatusNotification(request, CHARGING_STATION_ID.getId()); assertNotNull(response); } @Test public void diagnosticsStatusNotificationUploadedVerifyServiceCall() { DiagnosticsStatusNotificationRequest request = new DiagnosticsStatusNotificationRequest(); request.setStatus(DiagnosticsStatus.UPLOADED); motownCentralSystemService.diagnosticsStatusNotification(request, CHARGING_STATION_ID.getId()); verify(domainService).diagnosticsUploadStatusUpdate(CHARGING_STATION_ID, true, OCPPS15_ADD_ON_IDENTITY); } @Test public void diagnosticsStatusNotificationUploadFailedVerifyServiceCall() { DiagnosticsStatusNotificationRequest request = new DiagnosticsStatusNotificationRequest(); request.setStatus(DiagnosticsStatus.UPLOAD_FAILED); motownCentralSystemService.diagnosticsStatusNotification(request, CHARGING_STATION_ID.getId()); verify(domainService).diagnosticsUploadStatusUpdate(CHARGING_STATION_ID, false, OCPPS15_ADD_ON_IDENTITY); } //TODO test authorize @Test public void firmwareStatusNotificationVerifyResponse() { FirmwareStatusNotificationRequest request = new FirmwareStatusNotificationRequest(); FirmwareStatusNotificationResponse response = motownCentralSystemService.firmwareStatusNotification(request, CHARGING_STATION_ID.getId()); assertNotNull(response); } @Test public void firmwareStatusNotificationInstalledVerifyServiceCall() { FirmwareStatusNotificationRequest request = new FirmwareStatusNotificationRequest(); request.setStatus(FirmwareStatus.INSTALLED); motownCentralSystemService.firmwareStatusNotification(request, CHARGING_STATION_ID.getId()); verify(domainService).firmwareStatusUpdate(CHARGING_STATION_ID, io.motown.domain.api.chargingstation.FirmwareStatus.INSTALLED, OCPPS15_ADD_ON_IDENTITY); } @Test public void firmwareStatusNotificationInstallFailedVerifyServiceCall() { FirmwareStatusNotificationRequest request = new FirmwareStatusNotificationRequest(); request.setStatus(FirmwareStatus.INSTALLATION_FAILED); motownCentralSystemService.firmwareStatusNotification(request, CHARGING_STATION_ID.getId()); verify(domainService).firmwareStatusUpdate(CHARGING_STATION_ID, io.motown.domain.api.chargingstation.FirmwareStatus.INSTALLATION_FAILED, OCPPS15_ADD_ON_IDENTITY); } @Test public void firmwareStatusNotificationDownloadedVerifyServiceCall() { FirmwareStatusNotificationRequest request = new FirmwareStatusNotificationRequest(); request.setStatus(FirmwareStatus.DOWNLOADED); motownCentralSystemService.firmwareStatusNotification(request, CHARGING_STATION_ID.getId()); verify(domainService).firmwareStatusUpdate(CHARGING_STATION_ID, io.motown.domain.api.chargingstation.FirmwareStatus.DOWNLOADED, OCPPS15_ADD_ON_IDENTITY); } @Test public void firmwareStatusNotificationDownloadFailedVerifyServiceCall() { FirmwareStatusNotificationRequest request = new FirmwareStatusNotificationRequest(); request.setStatus(FirmwareStatus.DOWNLOAD_FAILED); motownCentralSystemService.firmwareStatusNotification(request, CHARGING_STATION_ID.getId()); verify(domainService).firmwareStatusUpdate(CHARGING_STATION_ID, io.motown.domain.api.chargingstation.FirmwareStatus.DOWNLOAD_FAILED, OCPPS15_ADD_ON_IDENTITY); } //TODO write tests for startTransaction with FutureEventCallback // // @Test // public void startTransactionVerifyResponse() { // StartTransactionRequest request = new StartTransactionRequest(); // request.setConnectorId(EVSE_ID.getNumberedId()); // request.setIdTag(IDENTIFYING_TOKEN.getToken()); // // StartTransactionResponse response = motownCentralSystemService.startTransaction(request, CHARGING_STATION_ID.getId()); // // assertNotNull(response.getIdTagInfo()); // assertNotNull(response.getTransactionId()); // } // // @Test // public void startTransactionVerifyServiceCall() { // StartTransactionRequest request = new StartTransactionRequest(); // request.setConnectorId(EVSE_ID.getNumberedId()); // request.setIdTag(IDENTIFYING_TOKEN.getToken()); // request.setMeterStart(METER_START); // request.setTimestamp(TWO_MINUTES_AGO); // FutureEventCallback mockFutureCallback = mock(FutureEventCallback.class); // // motownCentralSystemService.startTransaction(request, CHARGING_STATION_ID.getId()); // // verify(domainService).startTransaction(CHARGING_STATION_ID, EVSE_ID, IDENTIFYING_TOKEN, mockFutureCallback, OCPPS15_ADD_ON_IDENTITY); // verify(domainService).startTransaction(CHARGING_STATION_ID, EVSE_ID, IDENTIFYING_TOKEN, METER_START, TWO_MINUTES_AGO, null, PROTOCOL_IDENTIFIER, OCPPS15_ADD_ON_IDENTITY); // } // // @Test // public void startTransactionWithReservationVerifyServiceCall() { // StartTransactionRequest request = new StartTransactionRequest(); // request.setConnectorId(EVSE_ID.getNumberedId()); // request.setIdTag(IDENTIFYING_TOKEN.getToken()); // request.setMeterStart(METER_START); // request.setTimestamp(TWO_MINUTES_AGO); // request.setReservationId(RESERVATION_ID.getNumber()); // // motownCentralSystemService.startTransaction(request, CHARGING_STATION_ID.getId()); // // verify(domainService).startTransactionNoAuthorize(CHARGING_STATION_ID, EVSE_ID, IDENTIFYING_TOKEN, METER_START, TWO_MINUTES_AGO, RESERVATION_ID, PROTOCOL_IDENTIFIER, OCPPS15_ADD_ON_IDENTITY); // } }
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))
import { Component, OnInit } from '@angular/core'; import { InterventionService } from 'app/Core/intervention/intervention.service'; import { PanneService } from 'app/Core/panne/panne.service'; import { Intervention } from 'app/Core/intervention/intervention.model'; import { MatDialog } from '@angular/material/dialog'; import {MatSnackBarModule, MatSnackBar} from '@angular/material/snack-bar'; import { AddeditInterventionComponent } from '../addedit-intervention/addedit-intervention.component'; import { DatePipe } from '@angular/common'; import { Panne } from 'app/Core/panne/panne.model'; import * as moment from 'moment'; import { User } from 'app/components/_models/user'; import { Role } from 'app/components/_models/role'; import { AuthenticationService } from 'app/components/_services/authentication.service'; @Component({ selector: 'app-list-intervention', templateUrl: './list-intervention.component.html', styleUrls: ['./list-intervention.component.css'], providers: [DatePipe] }) export class ListInterventionComponent implements OnInit { user: User; constructor( public interventionservice: InterventionService, public panneService: PanneService, private dialog:MatDialog, private _snack:MatSnackBar, private authenticationService: AuthenticationService, ) { this.authenticationService.currentUser.subscribe(x => this.user = x); } intervention:Intervention; panne: Panne; interventionsachevee: Intervention[]; interventionsnonachevee: Intervention[] n:number; ngOnInit(): void { this.getInterventionsAchevee(); this.getInterventionsNonAchevee(); } getInterventionsAchevee(){ this.interventionservice.getInterventionAchevee().subscribe( data=>{ this.interventionsachevee=data as Intervention[]; },error=>{ console.log(error) } ) } getInterventionsNonAchevee(){ this.interventionservice.getInterventionNonAchevee().subscribe( data=>{ this.interventionsnonachevee=data as Intervention[]; },error=>{ console.log(error) } ) } openComponentForPost(id_panne){ this.interventionservice.initializeFormForPost(id_panne); this.dialog.open(AddeditInterventionComponent).afterClosed().subscribe(res => { this.getInterventionsAchevee(); }); } openComponentForUpdate(Intervention: Intervention) { this.interventionservice.initializeFormForEdit(Intervention); this.dialog.open(AddeditInterventionComponent).afterClosed().subscribe(res => { this.getInterventionsAchevee(); }); } onDelete(id_intervention){ if (confirm("Vous êtes sûr de vouloir supprimer cette intervention")) { this.interventionservice.deleteIntervention(id_intervention).subscribe(data=>{ this._snack.open("Suppression réussi",'X',{ verticalPosition: 'top', duration: 2000, panelClass:'snack-supp' }); this.getInterventionsAchevee(); },error=>{ console.log(error); }); } this.getInterventionsAchevee(); } ValiderIntervention(intervention){ if (confirm("Vous êtes sûr de vouloir valider cette intervention ?")) { intervention.dateFin=moment().format('DD/MM/yyyy'); intervention.etatIntervention="Achevée"; this.interventionservice.initializeFormForEdit(intervention); this.interventionservice.putIntervention().subscribe(data=>{ this._snack.open("intervention validée",'x',{ verticalPosition: 'top', duration: 2000, panelClass: 'snack-' }); this.getInterventionsAchevee(); this.getInterventionsNonAchevee(); }, error=>{ console.log(error); }); this.panneService.getPanneById(intervention.id_panne).subscribe(data=> { this.panne=data as Panne; this.panne.etat_panne="réparée"; console.log("+++++"+this.panne.etat_panne); this.panneService.initializeFormForEdit(this.panne); this.panneService.putPanne().subscribe(data=>{ this._snack.open("panne réparée",'x',{ verticalPosition: 'top', duration: 2000, panelClass: 'snack-' }); }); this.panneService.getPanne(); }, error=>{ console.log(error); }); } this.getInterventionsAchevee(); } echecIntervention(intervention) { if (confirm("Vous êtes sûr de vouloir déclarer l'échec de cette intervention et la création d'une nouvelle intervention ?")) { intervention.dateFin=moment().format('DD/MM/yyyy'); console.log( intervention.dateFin); intervention.etatIntervention="Achevée sans succés"; this.interventionservice.initializeFormForPost(intervention.id_panne); this.dialog.open(AddeditInterventionComponent).afterClosed().subscribe(res => { this.getInterventionsAchevee(); }); } } prolongerIntervention(intervention){ if (confirm("Vous êtes sûr de vouloir prolonger la durée de cette intervention par 1 jour ?")) { intervention.duree = +intervention.duree+1; this.interventionservice.initializeFormForEdit(intervention); this.interventionservice.putIntervention().subscribe(data=>{ this._snack.open("Durée de l'intervention est prolongée par 1 jour",'x',{ verticalPosition: 'top', duration: 2000, panelClass: 'snack-' }); this.getInterventionsNonAchevee(); }, error=>{ console.log(error); }); } } get isAdmin() { return this.user && this.user.role === Role.Admin; } get isUser() { return this.user && this.user.role === Role.User; } }
import oci class ServiceCatalogClientCompositeOperations(object): def __init__(self, service_catalog_client): """ Constructor for ServiceCatalogClientCompositeOperations. :param service_catalog_client: The service catalog client instance. :type service_catalog_client: oci.service_catalog.ServiceCatalogClient """ self.service_catalog_client = service_catalog_client def perform_and_wait_for_state(self, operation_name, operation_params, expected_state, waiter_timeout): """ Perform the specified operation using the service catalog client and wait for the resource to enter the expected state. :param operation_name: The name of the operation to be performed. :type operation_name: str :param operation_params: Parameters required for the operation. :type operation_params: dict :param expected_state: The state that the resource is expected to enter after the operation. :type expected_state: str :param waiter_timeout: The maximum time to wait for the resource to enter the expected state. :type waiter_timeout: int :return: None :raises: TimeoutError if the resource does not enter the expected state within the specified timeout. """ # Perform the operation using the service catalog client # For example: # result = self.service_catalog_client.perform_operation(operation_name, operation_params) # Use a waiter to wait for the resource to enter the expected state # For example: # waiter = oci.waiter.StateWaiter(self.service_catalog_client, 'resource_id', expected_state) # waiter.wait_for_state(timeout=waiter_timeout) # Check if the resource entered the expected state within the timeout # If not, raise a TimeoutError # For example: # if not resource_in_expected_state: # raise TimeoutError("Resource did not enter the expected state within the specified timeout")
class tierRegistry { static isIgnored(type) { // Omit these tier types from the website, as they're ugly and mostly useless. return ( type === "variantTypes" || // variantTypes indicates when a morpheme is a spelling variant, free variant, etc. type === "hn" || // hn, "homophone number", indicates which of multiple look-alike morphemes it is. type === "glsAppend" || type === "msa" // msa is the part of speech ); } static decodeType(type) { /* // English UI text: switch(type) { case "txt": return "morpheme (text)"; case "cf": return "morpheme (citation form)"; case "gls": return "morpheme gloss" case "msa": return "part of speech"; default: return type; } */ // Spanish UI text: switch (type) { case "txt": return "Morfema (texto)"; case "cf": return "Morfema (forma típico)"; case "gls": return "Glosa de morfema"; case "msa": return "Parte del habla"; case "words": return "Palabra"; case "free": return "Frase"; default: return type; } } constructor(isoDict) { this.tierIDs = {}; // for internal bookkeeping this.jsonTierIDs = {}; // format that should be written to file this.nextTierIDnum = 1; this.isoDict = isoDict; } decodeLang(lang) { const desiredName = "Native name"; // or we might want to use "ISO language name" const lcLang = lang.toLowerCase(); // ignore capitalization when decoding // Override the usual iso-based decoding for some language codes switch (lang) { // case "flex-language-name-here": return "desired-decoded-name-here"; case "con-Latn-EC": return "A'ingae (Borman)"; case "con-Latn-EC-x-dureno": return "A'ingae (Dureno)"; case "defaultLang": return "defaultLang"; // for Spanish UI text: case "en": return "Inglés"; default: // fall through } // if lang is an iso code, decode it if (this.isoDict.hasOwnProperty(lcLang)) { return this.isoDict[lcLang][desiredName]; } // if lang starts with a (three-letter or two-letter) iso code, decode it const firstThreeLetters = lcLang.substr(0, 3); if (this.isoDict.hasOwnProperty(firstThreeLetters)) { return this.isoDict[firstThreeLetters][desiredName]; } const firstTwoLetters = lcLang.substr(0, 2); if (this.isoDict.hasOwnProperty(firstTwoLetters)) { return this.isoDict[firstTwoLetters][desiredName]; } // as a last resort, return without decoding return lang; } getTierName(lang, type) { /* // English UI text: return decodeLang(lang) + " " + decodeType(type); */ // Spanish UI text: return tierRegistry.decodeType(type) + " " + this.decodeLang(lang).toLowerCase(); } getTiersJson() { return this.jsonTierIDs; } // if this is a new, non-ignored tier, register its ID and include it in metadata // if the tier is ignored, return null; else return its ID // used global vars: tierIDs, jsonOut.metadata["tier IDs"], nextTierIDnum maybeRegisterTier(lang, type, isSubdivided) { if (tierRegistry.isIgnored(type)) { return null; } if (!this.tierIDs.hasOwnProperty(lang)) { this.tierIDs[lang] = {}; } if (!this.tierIDs[lang].hasOwnProperty(type)) { const tierID = "T" + (this.nextTierIDnum++).toString(); this.tierIDs[lang][type] = tierID; this.jsonTierIDs[tierID] = { name: this.getTierName(lang, type), subdivided: isSubdivided, }; } return this.tierIDs[lang][type]; } } module.exports = { tierRegistry: tierRegistry };
<filename>src/core/PollingKeeper.h #pragma once #include <map> #include <Poco/Mutex.h> #include "core/DevicePoller.h" #include "core/PollableDevice.h" namespace BeeeOn { /** * @brief PollingKeeper takes care of devices that are being polled. * It cancels all polled devices it manages upon request or destruction * to avoid leaking unstopped polled devices. */ class PollingKeeper { public: PollingKeeper(); /** * @brief Cancel all registered pollable devices. */ ~PollingKeeper(); /** * @brief Configure DevicePoller to use. */ void setDevicePoller(DevicePoller::Ptr poller); /** * @brief Register the given device and schedule it into * the underlying poller. */ void schedule(PollableDevice::Ptr device); /** * @brief Cancel polling of the device represented by the * given ID and unregister it. */ void cancel(const DeviceID &id); /** * @brief Cancel all registered pollable devices. */ void cancelAll(); /** * @brief Lookup a device the PollingKeeper takes care of. */ PollableDevice::Ptr lookup(const DeviceID &id) const; private: std::map<DeviceID, PollableDevice::Ptr> m_polled; DevicePoller::Ptr m_devicePoller; mutable Poco::FastMutex m_lock; }; }
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete python manage.py makemigrations python manage.py migrate python manage.py load_regions python manage.py load_vaccins_regions python manage.py load_countries python manage.py load_vaccins_hospitIncidReg
<reponame>victor-aguilars/kibana_api<filename>lib/kibana_api/v7/client.rb require_relative 'actions' module KibanaAPI module V7 class Client include HttpStatusCodes include ApiExceptions include Actions::UserActions include Actions::SavedObjectActions include Actions::SpaceActions include Actions::IndexPatternActions include Actions::DashboardActions include Actions::VisualizationActions attr_reader :api_key def initialize @api_key = KibanaAPI.configuration.api_key end private def client Faraday.new(KibanaAPI.configuration.api_host) do |client| client.request :url_encoded client.adapter Faraday.default_adapter # Default Kibana API Headers client.headers['kbn-xsrf'] = "true" client.headers['Authorization'] = "ApiKey #{api_key}" client.headers['Content-Type'] = "application/json;charset=UTF-8" end end def request(http_method:, endpoint:, params: {}) response = client.public_send(http_method, endpoint, params) parsed_response = Oj.load(response.body) return parsed_response if response_successful?(response) raise error_class(response), "Code: #{response.status}, response: #{response.body}" end def error_class(response) case response.status when HTTP_BAD_REQUEST_CODE BadRequestError when HTTP_UNAUTHORIZED_CODE UnauthorizedError when HTTP_FORBIDDEN_CODE ForbiddenError when HTTP_NOT_FOUND_CODE NotFoundError when HTTP_UNPROCESSABLE_ENTITY_CODE UnprocessableEntityError else ApiError end end def response_successful?(response) response.status == HTTP_OK_CODE end end end end
import matplotlib.pyplot as plt import numpy as np # Step 1: Generate 10 random data points in 2D space num_points = 10 x_coords = np.random.randint(0, 100, num_points) y_coords = np.random.randint(0, 100, num_points) # Step 2: Create a scatter plot of the generated data points plt.scatter(x_coords, y_coords) plt.title('Random Data Points') plt.xlabel('X') plt.ylabel('Y') # Step 3: Calculate the Euclidean distance between each pair of data points for i in range(num_points): for j in range(i + 1, num_points): point1 = (x_coords[i], y_coords[i]) point2 = (x_coords[j], y_coords[j]) distance = np.linalg.norm(np.array(point1) - np.array(point2)) # Step 4: Print the coordinates of each pair of points and their corresponding Euclidean distance print(f"Distance between {point1} and {point2}: {distance:.2f}") # Display the scatter plot plt.show()
<filename>src/ukf.cpp #include "ukf.h" #include "Eigen/Dense" #include <iostream> #include "tools.h" #include<math.h> using Eigen::MatrixXd; using Eigen::VectorXd; /**f * Initializes Unscented Kalman filter */ //namespace plt = matplotlibcpp; UKF::UKF() { is_initialized_ = false; use_laser_ = true; // if this is false, laser measurements will be ignored (except during init) use_radar_ = true; // if this is false, radar measurements will be ignored (except during init) x_ = VectorXd(5); // initial state vector x_.fill(0); P_ = MatrixXd(5, 5); // initial covariance matrix Q_ = MatrixXd(2,2); // Process Noise Covariance std_a_ = 2; //ms-1 // Process noise standard deviation of longitudinal acceleration in m/s^2 // Process noise standard deviation of yaw acceleration in rad/s^2 std_yawdd_ = 0.3; // rad/s^2 vary Normalised Innovation Squared std_laspx_ = 0.15; // Laser measurement noise standard deviation position1 in m std_laspy_ = 0.15; // Laser measurement noise standard deviation position2 in m std_radr_ = 0.3; // Radar measurement noise standard deviation radius in m std_radphi_ = 0.03; // Radar measurement noise standard deviation angle in rad std_radrd_ = 0.3; // Radar measurement noise standard deviation radius change in m/s n_aug_ = 7; n_x_ = 5 ; lambda_ = 3 - n_x_ ; n_z_ = 3 ; time_us_ = 0; previous_timestamp_ = 0.0; X_sig = MatrixXd(5, 15); X_sig.fill(0.0); dt = 0; S_R = MatrixXd(3 , 3); S_R.fill(0); // RADAR Measurement Covariance S_L = MatrixXd(2,2); S_L.fill(0); // LIDAR Measurement Covariance weights = VectorXd(2* n_aug_ +1) ; cycle = 0; } UKF::~UKF() {} void UKF::ProcessMeasurement(MeasurementPackage meas_package) { if(!is_initialized_) { if(use_laser_ == true && meas_package.sensor_type_ == MeasurementPackage::LASER) { // Update with Laser Measurements VectorXd inter = meas_package.raw_measurements_ ; x_(0) = inter(0); x_(1) = inter(1); } else if(use_radar_ == true && meas_package.sensor_type_ == MeasurementPackage::RADAR) { // Update with Radar measurements double rho = meas_package.raw_measurements_(0); double phi = meas_package.raw_measurements_(1); double rhodot = meas_package.raw_measurements_(2); x_(0) = rho * cos(phi) ; x_(1) = rho * sin(phi) ; double vx = rhodot * cos(phi); double vy = rhodot * sin(phi); x_(2) = sqrt(vx*vx + vy*vy); x_(3) = 0; x_(4) = 0; } P_ = MatrixXd::Identity(n_x_, n_x_); // Covariance matrix set to Identity is_initialized_ = true; cycle = 0; previous_timestamp_ = meas_package.timestamp_ ; Q_ << std_a_ , 0, 0 , std_yawdd_ ; std::cout << std::endl; std::cout << "1 $$$$$$$$$$$$$$$$$$$$$$ Initialization Done! $$$$$$$$$$$$$$$$$$$$$$" << std::endl; std::cout << std::endl << std::endl; return ; } dt = (meas_package.timestamp_ - previous_timestamp_)/1000000.0 ; previous_timestamp_ = meas_package.timestamp_ ; std::cout << "$$$$$$$$$$$$$$$$$$$$$$$$$$ CYCLE : " << cycle << " $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" << std::endl; cycle++; Prediction(dt); // Sigma points generated , augmented , mapped and x_ and P_ is triangulated . // If next meas is LIDAR or RADAR meas Update with the state and Covariance using Kalman Gain if(cycle >= 497){ std::cout << "********** PLOT HERE ? ******************" << std::endl; //plt::plot(NIS_R_vec); //plt::savefig("NIS_R_vec.pdf"); std::cout << "NIS_R_vec "<<std::endl ; for(int i =0 ; i < NIS_R_vec.size() ; ++i) { std::cout << NIS_R_vec[i] <<std::endl; } } if(use_laser_ == true && meas_package.sensor_type_ == MeasurementPackage::LASER) { UpdateLidar(meas_package); } else if(use_radar_ == true && meas_package.sensor_type_ == MeasurementPackage::RADAR) { UpdateRadar(meas_package); } } void UKF::Prediction(double delta_t) { std::cout << "$$$$$$$$$$$$$$$$$$$$$$$ PREDICTION $$$$$$$$$$$$$$$$$$$$$$$$$$" << std::endl; std::cout << std::endl; VectorXd x_aug_ = VectorXd(n_aug_); x_aug_.head(n_x_) = x_ ; x_aug_(5) = 0 ; x_aug_(6) = 0 ; MatrixXd P_aug = MatrixXd(n_aug_, n_aug_); P_aug.topLeftCorner(n_x_ , n_x_) = P_; P_aug(5,5) = std_a_ * std_a_; P_aug(6,6) = std_yawdd_ * std_yawdd_ ; MatrixXd A = MatrixXd(n_aug_ , n_aug_); A = P_aug.llt().matrixL(); // CHOLESKY DECOMPOSITION returning a PSD matrix MatrixXd Xsig_aug_ = MatrixXd(7 , 15); lambda_ = 3 - n_x_; Xsig_aug_.col(0) = x_aug_ ; for(int i =0 ; i < n_aug_ ; ++i) { Xsig_aug_.col(i + 1) = x_aug_ + sqrt(lambda_ + n_aug_)* A.col(i) ; Xsig_aug_.col(i + n_aug_ + 1) = x_aug_ - sqrt(lambda_ + n_aug_)* A.col(i); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // PREDICTION // // MAPPING THROUGH A NON LINEAR PROCESS // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// for(int i =0 ; i < 2*n_aug_ +1 ; ++i) { double px = Xsig_aug_.col(i)[0]; double py = Xsig_aug_.col(i)[1]; double v = Xsig_aug_.col(i)[2]; double yaw = Xsig_aug_.col(i)[3]; double yaw_rate = Xsig_aug_.col(i)[4]; double acc_noise = Xsig_aug_.col(i)[5]; double yawrate_noise = Xsig_aug_.col(i)[6]; double px_m; double py_m; double v_m; double yaw_m; double yaw_rate_m; if(fabs(yaw_rate) > 0.001 ) { px_m = px + ((v/yaw_rate)*( sin(yaw + yaw_rate*dt) - sin(yaw) ) ) + ((1/2)*(dt*dt)* cos(yaw)*acc_noise); py_m = py + ((v/yaw_rate) * (-cos(yaw + yaw_rate*dt) + cos(yaw) )) + ((1/2)*(dt*dt)* cos(yaw)*acc_noise); v_m = v + 0 + dt*acc_noise; yaw_m = yaw + yaw_rate*dt+ (1/2)*(dt*dt)*yawrate_noise; yaw_rate_m = yaw_rate + 0 + dt*yawrate_noise; } else { px_m = px + (v*cos(yaw)*dt) + ((1/2)*(dt*dt)* cos(yaw)*acc_noise); py_m = py + (v*cos(yaw)*dt) + ((1/2)*(dt*dt)* cos(yaw)*acc_noise); v_m = v + 0 + dt*acc_noise; yaw_m = yaw + 0 + (1/2)*(dt*dt)*yawrate_noise; yaw_rate_m = yaw_rate + 0 + dt*yawrate_noise; } X_sig(0 , i) = px_m; X_sig(1 , i) = py_m; X_sig(2 , i) = v_m; X_sig(3 , i) = yaw_m; X_sig(4 , i) = yaw_rate_m; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////// TRIANGULATE MEAN AND COVARIANCE //////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// for(int i =0 ; i < 2*n_aug_+1 ; ++i) { if(i == 0) { weights(i) = lambda_/(lambda_ + n_aug_); } else { weights(i) = 1/(2*(lambda_ + n_aug_)); } } x_.fill(0.0); for(int j= 0 ; j < 2*n_aug_ +1 ; ++j) { x_ = x_ + weights(j)*X_sig.col(j); } P_.fill(0.0); for(int k = 0 ; k < 2*n_aug_+1 ; ++k) { VectorXd x_diff = X_sig.col(k) - x_ ; while(x_diff(3) > M_PI) { x_diff(3) -= 2.*M_PI ; } while(x_diff(3) < -M_PI){ x_diff(3) += 2.*M_PI ; } P_ = P_ + weights(k)*(x_diff)* x_diff.transpose() ; } } void UKF::UpdateLidar(MeasurementPackage meas_package) { std::cout << "################ UPDATING WITH LIDAR MEASUREMENTS ##################"<< std::endl << std::endl; VectorXd inter_ = meas_package.raw_measurements_ ; VectorXd z_ = VectorXd(2); z_(0) = inter_(0); z_(1) = inter_(1); MatrixXd Z_sig = MatrixXd(2 , 2*n_aug_+1); for(int i = 0 ; i < 2*n_aug_+1 ; ++i) { Z_sig.col(i)(0) = X_sig.col(i)(0); Z_sig.col(i)(1) = X_sig.col(i)(1); } /////////// MEAN PREDICTED MEASUREMENT ///////////////// VectorXd z_pred = VectorXd(2); lambda_ = 3 - n_x_; z_pred.fill(0.0); for(int i =0 ; i < 2*n_aug_+1 ; ++i) { if(i == 0) { weights(i) = lambda_/(lambda_ + n_aug_); } else { weights(i) = 1/(2*(lambda_ + n_aug_)); } } for(int i = 0 ; i< 2 * n_aug_ +1 ; ++i){ z_pred = z_pred + weights(i) * Z_sig.col(i); } /////////// MEASUREMENT COVARIANCE MATRIX /////////////// VectorXd z_diff = VectorXd(2); for(int i =0 ; i < 2*n_aug_+1 ; ++i) { if(i == 0) { weights(i) = lambda_/(lambda_ + n_aug_); } else { weights(i) = 1/(2*(lambda_ + n_aug_)); } } for(int i =0 ; i < 2*n_aug_+ 1 ; ++i) { z_diff = Z_sig.col(i) - z_pred ; S_L = S_L + weights(i)* z_diff * z_diff.transpose(); } MatrixXd R = MatrixXd(2 , 2); R << std_laspx_*std_laspx_ , 0 , 0, std_laspy_*std_laspy_ ; S_L = S_L + R ; MatrixXd T = MatrixXd(5,2); T.fill(0.0); VectorXd x_diff = VectorXd(n_x_); for(int i = 0 ; i < 2* n_aug_ +1 ; ++i) { x_diff = X_sig.col(i) - x_ ; while(x_diff(3) > M_PI) x_diff(3) -= 2.*M_PI; while(x_diff(3) < M_PI) x_diff(3) += 2.*M_PI; z_diff = Z_sig.col(i) - z_pred ; T = T + weights(i) * x_diff * z_diff.transpose(); } MatrixXd K = MatrixXd(n_x_ , n_x_); K.fill(0.0); K = T * S_L.inverse(); double NIS_val_RADAR = z_diff.transpose() * S_L.inverse() * z_diff ; NIS_L_vec.push_back(NIS_val_RADAR); x_ = x_ + K * (z_ - z_pred); // z_ -> SENSOR MEASUREMENT z_pred -> PREDICTED MEASUREMETN P_ = P_ - K * S_L * K.transpose(); } void UKF::UpdateRadar(MeasurementPackage meas_package) { std::cout << "$$$$$$$$$$$$ UPDATING WITH RADAR MEASUREMENTS $$$$$$$$$$$$$$$" << std::endl; VectorXd z = meas_package.raw_measurements_; int n_z = 3; MatrixXd Zsig = MatrixXd(n_z, 2 * n_aug_ + 1); /// MAP points into measurement space for (int i = 0; i < 2 * n_aug_ + 1; i++) { double p_x = X_sig(0, i); double p_y = X_sig(1, i); double v = X_sig(2, i); double yaw = X_sig(3, i); double v1 = cos(yaw)*v; double v2 = sin(yaw)*v; Zsig(0, i) = sqrt(p_x*p_x + p_y*p_y); Zsig(1, i) = atan2(p_y, p_x); Zsig(2, i) = (p_x*v1 + p_y*v2) / sqrt(p_x*p_x + p_y*p_y); } //mean predicted measurement VectorXd z_pred = VectorXd(n_z); for(int i =0 ; i < 2*n_aug_+1 ; ++i) { if(i == 0) { weights(i) = lambda_/(lambda_ + n_aug_); } else { weights(i) = 1/(2*(lambda_ + n_aug_)); } } z_pred.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; i++) { z_pred = z_pred + weights(i) * Zsig.col(i); } // MEASUREMENT COVARINCE matrix S_R.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; i++) { VectorXd z_diff = Zsig.col(i) - z_pred; while (z_diff(1)> M_PI) z_diff(1) -= 2.*M_PI; while (z_diff(1)<-M_PI) z_diff(1) += 2.*M_PI; S_R = S_R + weights(i) * z_diff * z_diff.transpose(); } MatrixXd R = MatrixXd(n_z, n_z); R << std_radr_*std_radr_, 0, 0, 0, std_radphi_*std_radphi_, 0, 0, 0, std_radrd_*std_radrd_; S_R = S_R + R; MatrixXd Tc = MatrixXd(n_x_, n_z); Tc.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; i++) { VectorXd z_diff = Zsig.col(i) - z_pred; while (z_diff(1)> M_PI) z_diff(1) -= 2.*M_PI; while (z_diff(1)<-M_PI) z_diff(1) += 2.*M_PI; VectorXd x_diff = X_sig.col(i) - x_; while (x_diff(3)> M_PI) x_diff(3) -= 2.*M_PI; while (x_diff(3)<-M_PI) x_diff(3) += 2.*M_PI; Tc = Tc + weights(i) * x_diff * z_diff.transpose(); } MatrixXd K = Tc * S_R.inverse(); VectorXd z_diff = z - z_pred; //angle normalization while (z_diff(1)> M_PI) z_diff(1) -= 2.*M_PI; while (z_diff(1)<-M_PI) z_diff(1) += 2.*M_PI; //calculate NIS double NIS_value_RADAR = z_diff.transpose() * S_R.inverse() * z_diff; NIS_R_vec.push_back(NIS_value_RADAR); // k length at kth cycle //update state mean and covariance matrix x_ = x_ + K * z_diff; P_ = P_ - K*S_R*K.transpose(); }
// Define the PhotoToolboxDelegate protocol public protocol PhotoToolboxDelegate: AnyObject { func canceledEditing() } // Implement the PhotoToolbox class public class PhotoToolbox { /** Presents the UI for editing a photo. - Parameter photo: The UIImage to be edited. - Parameter presentingViewController: The UIViewController calling this method. Note that the presentingViewController MUST conform to the PhotoToolboxDelegate protocol. */ static public func editPhoto(_ photo: UIImage, presentingViewController: UIViewController) { // Check if the presentingViewController conforms to the PhotoToolboxDelegate protocol guard let delegate = presentingViewController as? PhotoToolboxDelegate else { fatalError("The presentingViewController must conform to the PhotoToolboxDelegate protocol") } // Present the photo editing UI and handle the editing process // If editing is canceled, call the canceledEditing method on the delegate delegate.canceledEditing() } }
def findClosestPair(arr1, arr2): min_diff = float("inf") min_pair = (0,0) i, j = 0, 0 while (i < len(arr1) and j < len(arr2)): current_diff = abs(arr1[i] - arr2[j]) if current_diff < min_diff: min_diff = current_diff min_pair = (arr1[i], arr2[j]) if arr1[i] < arr2[j]: i += 1 else: j += 1 return min_pair
<gh_stars>1-10 package com.elasticsearch.cloud.monitor.metric.common.monitor.kmon.config; import java.util.Map; import com.google.common.collect.Maps; import static com.elasticsearch.cloud.monitor.sdk.sink.SlsMonitorSink.CONFIG_ACCESS_KEY; import static com.elasticsearch.cloud.monitor.sdk.sink.SlsMonitorSink.CONFIG_ACCESS_SECRET; import static com.elasticsearch.cloud.monitor.sdk.sink.SlsMonitorSink.CONFIG_END_POINT; import static com.elasticsearch.cloud.monitor.sdk.sink.SlsMonitorSink.CONFIG_LOG_STORE; import static com.elasticsearch.cloud.monitor.sdk.sink.SlsMonitorSink.CONFIG_REPORT_SWITCH; import static com.elasticsearch.cloud.monitor.sdk.sink.SlsMonitorSink.CONFIG_SLS_PROJECT; /** * @author xiaoping * @date 2019/12/2 */ public class SlsConfigMapBuilder { private Map<String, String> sinkConfMap = Maps.newHashMap(); public SlsConfigMapBuilder reportEnable(boolean enable) { sinkConfMap.put(CONFIG_REPORT_SWITCH, String.valueOf(enable)); return this; } public SlsConfigMapBuilder endpoint(String endpoint) { sinkConfMap.put(CONFIG_END_POINT, endpoint); return this; } public SlsConfigMapBuilder project(String project) { sinkConfMap.put(CONFIG_SLS_PROJECT, project); return this; } public SlsConfigMapBuilder logstore(String logstore) { sinkConfMap.put(CONFIG_LOG_STORE, logstore); return this; } public SlsConfigMapBuilder accesskey(String accesskey) { sinkConfMap.put(CONFIG_ACCESS_KEY, accesskey); return this; } public SlsConfigMapBuilder accesssecret(String accesssecret) { sinkConfMap.put(CONFIG_ACCESS_SECRET, accesssecret); return this; } public Map<String, String> build() { return sinkConfMap; } }
<reponame>xiaohuobulai/gmall package com.atguigu.gmall.pms.vo; import com.atguigu.gmall.pms.entity.AttrEntity; import com.atguigu.gmall.pms.entity.AttrGroupEntity; import lombok.Data; import java.util.List; @Data public class GroupVo extends AttrGroupEntity { private List<AttrEntity> attrEntities; }
//-------------------------------------------------------------------------------------- // File: SoftParticles10.1.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTgui.h" #include "DXUTsettingsdlg.h" #include "DXUTcamera.h" #include "SDKmisc.h" #include "SDKmesh.h" #include "resource.h" #define MAX_PARTICLES 500 struct PARTICLE_VERTEX { D3DXVECTOR3 Pos; D3DXVECTOR3 Vel; float Life; float Size; }; //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- CModelViewerCamera g_Camera; // A model viewing camera CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs CD3DSettingsDlg g_D3DSettingsDlg; // Device settings dialog CDXUTDialog g_HUD; // manages the 3D UI CDXUTDialog g_SampleUI; // dialog for sample specific controls PARTICLE_VERTEX* g_pCPUParticles = NULL; DWORD* g_pCPUParticleIndices = NULL; float* g_pParticleDepthArray = NULL; CDXUTSDKMesh g_ObjectMesh; CDXUTSDKMesh g_SkyMesh; ID3DX10Font* g_pFont10 = NULL; ID3DX10Sprite* g_pSprite10 = NULL; CDXUTTextHelper* g_pTxtHelper = NULL; ID3D10Effect* g_pEffect10 = NULL; ID3D10InputLayout* g_pSceneVertexLayout = NULL; ID3D10InputLayout* g_pParticleVertexLayout = NULL; ID3D10Texture2D* g_pDepthStencilTexture = NULL; ID3D10DepthStencilView* g_pDepthStencilDSV = NULL; ID3D10ShaderResourceView* g_pDepthStencilSRV = NULL; ID3D10Buffer* g_pParticleVB = NULL; ID3D10Buffer* g_pParticleIB = NULL; ID3D10ShaderResourceView* g_pParticleTexRV = NULL; ID3D10Texture3D* g_pNoiseVolume = NULL; ID3D10ShaderResourceView* g_pNoiseVolumeRV = NULL; ID3D10Texture2D* g_pColorGradTexture = NULL; ID3D10ShaderResourceView* g_pColorGradTexRV = NULL; ID3D10EffectTechnique* g_pRenderScene = NULL; ID3D10EffectTechnique* g_pRenderSky = NULL; ID3D10EffectTechnique* g_pRenderBillboardParticlesHard = NULL; ID3D10EffectTechnique* g_pRenderBillboardParticlesODepth = NULL; ID3D10EffectTechnique* g_pRenderBillboardParticlesSoft = NULL; ID3D10EffectTechnique* g_pRenderVolumeParticlesHard = NULL; ID3D10EffectTechnique* g_pRenderVolumeParticlesSoft = NULL; ID3D10EffectTechnique* g_pRenderBillboardParticlesODepthSoft = NULL; ID3D10EffectTechnique* g_pRenderVolumeParticlesSoftMSAA = NULL; ID3D10EffectTechnique* g_pRenderVolumeParticlesHardMSAA = NULL; ID3D10EffectTechnique* g_pRenderBillboardParticlesSoftMSAA = NULL; ID3D10EffectTechnique* g_pRenderBillboardParticlesODepthSoftMSAA = NULL; ID3D10EffectMatrixVariable* g_pmWorldViewProj = NULL; ID3D10EffectMatrixVariable* g_pmWorldView = NULL; ID3D10EffectMatrixVariable* g_pmWorld = NULL; ID3D10EffectMatrixVariable* g_pmInvView = NULL; ID3D10EffectMatrixVariable* g_pmInvProj = NULL; ID3D10EffectScalarVariable* g_pfFadeDistance = NULL; ID3D10EffectScalarVariable* g_pfSizeZScale = NULL; ID3D10EffectVectorVariable* g_pvViewLightDir1 = NULL; ID3D10EffectVectorVariable* g_pvViewLightDir2 = NULL; ID3D10EffectVectorVariable* g_pvWorldLightDir1 = NULL; ID3D10EffectVectorVariable* g_pvWorldLightDir2 = NULL; ID3D10EffectVectorVariable* g_pvEyePt = NULL; ID3D10EffectVectorVariable* g_pvViewDir = NULL; ID3D10EffectVectorVariable* g_pvOctaveOffsets = NULL; ID3D10EffectVectorVariable* g_pvScreenSize = NULL; ID3D10EffectShaderResourceVariable* g_pDiffuseTex = NULL; ID3D10EffectShaderResourceVariable* g_pNormalTex = NULL; ID3D10EffectShaderResourceVariable* g_pColorGradient = NULL; ID3D10EffectShaderResourceVariable* g_pVolumeDiffTex = NULL; ID3D10EffectShaderResourceVariable* g_pVolumeNormTex = NULL; ID3D10EffectShaderResourceVariable* g_pDepthTex = NULL; ID3D10EffectShaderResourceVariable* g_pDepthMSAATex = NULL; INT g_iWidth = 640; INT g_iHeight = 480; INT g_iSampleCount = 1; enum PARTICLE_TECHNIQUE { PT_VOLUME_SOFT = 0x0, PT_VOLUME_HARD, PT_BILLBOARD_ODEPTHSOFT, PT_BILLBOARD_ODEPTH, PT_BILLBOARD_SOFT, PT_BILLBOARD_HARD }; float g_fFadeDistance = 1.0f; float g_fParticleLifeSpan = 5.0f; float g_fEmitRate = 0.015f; float g_ParticleVel = 3.0f; float g_fParticleMaxSize = 1.25f; float g_fParticleMinSize = 1.0f; bool g_bAnimateParticles = true; PARTICLE_TECHNIQUE g_ParticleTechnique = PT_VOLUME_SOFT; D3DXVECTOR3 g_vLightDir1 = D3DXVECTOR3(1.705f,5.557f,-9.380f); D3DXVECTOR3 g_vLightDir2 = D3DXVECTOR3(-5.947f,-5.342f,-5.733f); //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- #define IDC_STATIC -1 #define IDC_TOGGLEFULLSCREEN 1 #define IDC_TOGGLEREF 3 #define IDC_CHANGEDEVICE 4 #define IDC_TECHNIQUE 5 #define IDC_TOGGLEWARP 6 //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ); LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ); void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ); void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ); bool CALLBACK IsD3D10DeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); HRESULT CALLBACK OnD3D10CreateDevice( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); HRESULT CALLBACK OnD3D10SwapChainResized( ID3D10Device* pd3dDevice, IDXGISwapChain *pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void CALLBACK OnD3D10SwapChainReleasing( void* pUserContext ); void CALLBACK OnD3D10DestroyDevice( void* pUserContext ); void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ); void InitApp(); void RenderText(); HRESULT CreateParticleBuffers(ID3D10Device* pd3dDevice); HRESULT CreateNoiseVolume( ID3D10Device* pd3dDevice, UINT VolumeSize ); void SortParticleBuffer( D3DXVECTOR3 vEye, D3DXVECTOR3 vDir ); void AdvanceParticles( ID3D10Device* pd3dDevice, double fTime, float fTimeDelta ); void UpdateParticleBuffers( ID3D10Device* pd3dDevice ); //-------------------------------------------------------------------------------------- // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. //-------------------------------------------------------------------------------------- int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // Disable gamma correction on this sample DXUTSetIsInGammaCorrectMode( false ); // DXUT will create and use the best device (either D3D9 or D3D10) // that is available on the system depending on which D3D callbacks are set below // Set DXUT callbacks DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackKeyboard( KeyboardProc ); DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackD3D10DeviceAcceptable( IsD3D10DeviceAcceptable ); DXUTSetCallbackD3D10DeviceCreated( OnD3D10CreateDevice ); DXUTSetCallbackD3D10SwapChainResized( OnD3D10SwapChainResized ); DXUTSetCallbackD3D10SwapChainReleasing( OnD3D10SwapChainReleasing ); DXUTSetCallbackD3D10DeviceDestroyed( OnD3D10DestroyDevice ); DXUTSetCallbackD3D10FrameRender( OnD3D10FrameRender ); InitApp(); DXUTInit( true, true, NULL ); // Parse the command line, show msgboxes on error, no extra command line params DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen DXUTCreateWindow( L"SoftParticles10.1" ); DXUTCreateDevice( true, 640, 480 ); DXUTMainLoop(); // Enter into the DXUT render loop } //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- void InitApp() { g_D3DSettingsDlg.Init( &g_DialogResourceManager ); g_HUD.Init( &g_DialogResourceManager ); g_SampleUI.Init( &g_DialogResourceManager ); g_HUD.SetCallback( OnGUIEvent ); int iY = 10; g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22 ); g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2 ); g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 35, iY += 24, 125, 22, VK_F3 ); g_HUD.AddButton( IDC_TOGGLEWARP, L"Toggle WARP (F4)", 35, iY += 24, 125, 22, VK_F4 ); g_SampleUI.SetCallback( OnGUIEvent ); iY = 10; CDXUTComboBox* pComboBox = NULL; g_SampleUI.AddStatic( IDC_STATIC, L"(T)echnique", 0, 0, 105, 25 ); g_SampleUI.AddComboBox( IDC_TECHNIQUE, 0, 25, 140, 24, 'T', false, &pComboBox ); if( pComboBox ) pComboBox->SetDropHeight( 80 ); pComboBox->AddItem( L"Volume Soft", (void*)PT_VOLUME_SOFT ); pComboBox->AddItem( L"Volume Hard", (void*)PT_VOLUME_HARD ); pComboBox->AddItem( L"Depth Sprites Soft", (void*)PT_BILLBOARD_ODEPTHSOFT ); pComboBox->AddItem( L"Depth Sprites Hard", (void*)PT_BILLBOARD_ODEPTH ); pComboBox->AddItem( L"Billboard Soft", (void*)PT_BILLBOARD_SOFT ); pComboBox->AddItem( L"Billboard Hard", (void*)PT_BILLBOARD_HARD ); } //-------------------------------------------------------------------------------------- // Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { // For the first device created if its a REF device, optionally display a warning dialog box static bool s_bFirstTime = true; if( s_bFirstTime ) { s_bFirstTime = false; if( (DXUT_D3D9_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF) || (DXUT_D3D10_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d10.DriverType == D3D10_DRIVER_TYPE_REFERENCE) ) DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver ); } pDeviceSettings->d3d10.SyncInterval = 0; return true; } static int iFrame = 0; //-------------------------------------------------------------------------------------- // Handle updates to the scene. This is called regardless of which D3D API is used //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) { // Update the camera's position based on user input g_Camera.FrameMove( fElapsedTime ); D3DXVECTOR3 vEye = *g_Camera.GetEyePt(); D3DXVECTOR3 vDir = *g_Camera.GetLookAtPt() - vEye; D3DXVec3Normalize( &vDir, &vDir ); ID3D10Device* pd3dDevice = DXUTGetD3D10Device(); AdvanceParticles( pd3dDevice, fTime, fElapsedTime ); SortParticleBuffer( vEye, vDir ); UpdateParticleBuffers( pd3dDevice ); // Update the movement of the noise octaves D3DXVECTOR4 OctaveOffsets[4]; for( int i=0; i<4; i++ ) { OctaveOffsets[i].x = -(float)(fTime*0.05); OctaveOffsets[i].y = 0; OctaveOffsets[i].z = 0; OctaveOffsets[i].w = 0; } g_pvOctaveOffsets->SetFloatVectorArray( (float*)OctaveOffsets, 0, 4 ); } //-------------------------------------------------------------------------------------- // Handle messages to the application //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { // Pass messages to dialog resource manager calls so GUI state is updated correctly *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass messages to settings dialog if its active if( g_D3DSettingsDlg.IsActive() ) { g_D3DSettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam ); return 0; } // Give the dialogs a chance to handle the message first *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; *pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass all remaining windows messages to camera so it can respond to user input g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam ); return 0; } //-------------------------------------------------------------------------------------- // Handle key presses //-------------------------------------------------------------------------------------- void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) { } //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ) { switch( nControlID ) { case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break; case IDC_TOGGLEREF: DXUTToggleREF(); break; case IDC_CHANGEDEVICE: g_D3DSettingsDlg.SetActive( !g_D3DSettingsDlg.IsActive() ); break; case IDC_TOGGLEWARP: DXUTToggleWARP(); break; case IDC_TECHNIQUE: { CDXUTComboBox* pComboBox = (CDXUTComboBox*)pControl; g_ParticleTechnique = (PARTICLE_TECHNIQUE)(int)PtrToInt(pComboBox->GetSelectedData()); } break; } } //-------------------------------------------------------------------------------------- // Reject any D3D10 devices that aren't acceptable by returning false //-------------------------------------------------------------------------------------- bool CALLBACK IsD3D10DeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) { return true; } //-------------------------------------------------------------------------------------- // Create any D3D10 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D10CreateDevice( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC *pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; ID3D10Device1* pd3dDevice1 = DXUTGetD3D10Device1(); V_RETURN( g_DialogResourceManager.OnD3D10CreateDevice( pd3dDevice ) ); V_RETURN( g_D3DSettingsDlg.OnD3D10CreateDevice( pd3dDevice ) ); V_RETURN( D3DX10CreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &g_pFont10 ) ); V_RETURN( D3DX10CreateSprite( pd3dDevice, 512, &g_pSprite10 ) ); g_pTxtHelper = new CDXUTTextHelper( NULL, NULL, g_pFont10, g_pSprite10, 15 ); // Read the D3DX effect file WCHAR str[MAX_PATH]; V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"SoftParticles.fx" ) ); DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) // Set the D3D10_SHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags |= D3D10_SHADER_DEBUG; #endif if( NULL == pd3dDevice1 ) { V_RETURN( D3DX10CreateEffectFromFile( str, NULL, NULL, "fx_4_0", dwShaderFlags, 0, pd3dDevice, NULL, NULL, &g_pEffect10, NULL, NULL ) ); } else { V_RETURN( D3DX10CreateEffectFromFile( str, NULL, NULL, "fx_4_1", dwShaderFlags, 0, pd3dDevice, NULL, NULL, &g_pEffect10, NULL, NULL ) ); } // Obtain the technique handles g_pRenderScene = g_pEffect10->GetTechniqueByName( "RenderScene" ); g_pRenderSky = g_pEffect10->GetTechniqueByName( "RenderSky" ); g_pRenderBillboardParticlesHard = g_pEffect10->GetTechniqueByName( "RenderBillboardParticles_Hard" ); g_pRenderBillboardParticlesODepth = g_pEffect10->GetTechniqueByName( "RenderBillboardParticles_ODepth" ); g_pRenderBillboardParticlesSoft = g_pEffect10->GetTechniqueByName( "RenderBillboardParticles_Soft" ); g_pRenderBillboardParticlesODepthSoft = g_pEffect10->GetTechniqueByName( "RenderBillboardParticles_ODepthSoft" ); g_pRenderVolumeParticlesHard = g_pEffect10->GetTechniqueByName( "RenderVolumeParticles_Hard" ); g_pRenderVolumeParticlesSoft = g_pEffect10->GetTechniqueByName( "RenderVolumeParticles_Soft" ); g_pRenderVolumeParticlesSoftMSAA = g_pEffect10->GetTechniqueByName( "RenderVolumeParticles_Soft_MSAA" ); g_pRenderVolumeParticlesHardMSAA = g_pEffect10->GetTechniqueByName( "RenderVolumeParticles_Hard_MSAA" ); g_pRenderBillboardParticlesSoftMSAA = g_pEffect10->GetTechniqueByName( "RenderBillboardParticles_Soft_MSAA" ); g_pRenderBillboardParticlesODepthSoftMSAA = g_pEffect10->GetTechniqueByName( "RenderBillboardParticles_ODepthSoft_MSAA" ); // Obtain the parameter handles g_pmWorldViewProj = g_pEffect10->GetVariableByName( "g_mWorldViewProj" )->AsMatrix(); g_pmWorldView = g_pEffect10->GetVariableByName( "g_mWorldView" )->AsMatrix(); g_pmWorld = g_pEffect10->GetVariableByName( "g_mWorld" )->AsMatrix(); g_pmInvView = g_pEffect10->GetVariableByName( "g_mInvView" )->AsMatrix(); g_pmInvProj = g_pEffect10->GetVariableByName( "g_mInvProj" )->AsMatrix(); g_pfFadeDistance = g_pEffect10->GetVariableByName( "g_fFadeDistance" )->AsScalar(); g_pfSizeZScale = g_pEffect10->GetVariableByName( "g_fSizeZScale" )->AsScalar(); g_pvViewLightDir1 = g_pEffect10->GetVariableByName( "g_vViewLightDir1" )->AsVector(); g_pvViewLightDir2 = g_pEffect10->GetVariableByName( "g_vViewLightDir2" )->AsVector(); g_pvWorldLightDir1 = g_pEffect10->GetVariableByName( "g_vWorldLightDir1" )->AsVector(); g_pvWorldLightDir2 = g_pEffect10->GetVariableByName( "g_vWorldLightDir2" )->AsVector(); g_pvEyePt = g_pEffect10->GetVariableByName( "g_vEyePt" )->AsVector(); g_pvViewDir = g_pEffect10->GetVariableByName( "g_vViewDir" )->AsVector(); g_pvOctaveOffsets = g_pEffect10->GetVariableByName( "g_OctaveOffsets" )->AsVector(); g_pvScreenSize = g_pEffect10->GetVariableByName( "g_vScreenSize" )->AsVector(); g_pDiffuseTex = g_pEffect10->GetVariableByName( "g_txDiffuse" )->AsShaderResource(); g_pNormalTex = g_pEffect10->GetVariableByName( "g_txNormal" )->AsShaderResource(); g_pColorGradient = g_pEffect10->GetVariableByName( "g_txColorGradient" )->AsShaderResource(); g_pVolumeDiffTex = g_pEffect10->GetVariableByName( "g_txVolumeDiff" )->AsShaderResource(); g_pVolumeNormTex = g_pEffect10->GetVariableByName( "g_txVolumeNorm" )->AsShaderResource(); g_pDepthTex = g_pEffect10->GetVariableByName( "g_txDepth" )->AsShaderResource(); g_pDepthMSAATex = g_pEffect10->GetVariableByName( "g_txDepthMSAA" )->AsShaderResource(); // Create our vertex input layouts const D3D10_INPUT_ELEMENT_DESC scenelayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 32, D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; D3D10_PASS_DESC PassDesc; g_pRenderScene->GetPassByIndex( 0 )->GetDesc( &PassDesc ); V_RETURN( pd3dDevice->CreateInputLayout( scenelayout, sizeof(scenelayout)/sizeof(scenelayout[0]), PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pSceneVertexLayout ) ); const D3D10_INPUT_ELEMENT_DESC particlelayout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "VELOCITY", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "LIFE", 0, DXGI_FORMAT_R32_FLOAT, 0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "SIZE", 0, DXGI_FORMAT_R32_FLOAT, 0, 28, D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; g_pRenderBillboardParticlesHard->GetPassByIndex( 0 )->GetDesc( &PassDesc ); V_RETURN( pd3dDevice->CreateInputLayout( particlelayout, sizeof(particlelayout)/sizeof(scenelayout[0]), PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pParticleVertexLayout ) ); // Load meshes V_RETURN( g_ObjectMesh.Create( pd3dDevice, L"SoftParticles\\TankScene.sdkmesh", true ) ); V_RETURN( g_SkyMesh.Create( pd3dDevice, L"SoftParticles\\desertsky.sdkmesh", true ) ); // Create the particles V_RETURN( CreateParticleBuffers( pd3dDevice ) ); // Create the noise volume V_RETURN( CreateNoiseVolume( pd3dDevice, 32 ) ); // Load the Particle Texture V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"SoftParticles\\smokevol1.dds" ) ); V_RETURN( D3DX10CreateShaderResourceViewFromFile( pd3dDevice, str, NULL, NULL, &g_pParticleTexRV, NULL ) ); V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"SoftParticles\\colorgradient.dds" ) ); V_RETURN( D3DX10CreateShaderResourceViewFromFile( pd3dDevice, str, NULL, NULL, &g_pColorGradTexRV, NULL ) ); // Setup the camera's view parameters D3DXVECTOR3 vecEye(2,1,-10); D3DXVECTOR3 vecAt (2,1,0); g_Camera.SetViewParams( &vecEye, &vecAt ); g_Camera.SetRadius( 10.0f, 1.0f, 20.0f ); g_pfFadeDistance->SetFloat( g_fFadeDistance ); // Enable/Disable MSAA settings from the settings dialog based on whether we have dx10.1 // support or not. g_D3DSettingsDlg.GetDialogControl()->GetComboBox( DXUTSETTINGSDLG_D3D10_MULTISAMPLE_COUNT )->SetEnabled( NULL != pd3dDevice1 ); g_D3DSettingsDlg.GetDialogControl()->GetComboBox( DXUTSETTINGSDLG_D3D10_MULTISAMPLE_QUALITY )->SetEnabled( NULL != pd3dDevice1 ); g_D3DSettingsDlg.GetDialogControl()->GetStatic( DXUTSETTINGSDLG_D3D10_MULTISAMPLE_COUNT_LABEL )->SetEnabled( NULL != pd3dDevice1 ); g_D3DSettingsDlg.GetDialogControl()->GetStatic( DXUTSETTINGSDLG_D3D10_MULTISAMPLE_QUALITY_LABEL )->SetEnabled( NULL != pd3dDevice1 ); return S_OK; } //-------------------------------------------------------------------------------------- // Create any D3D10 resources that depend on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D10SwapChainResized( ID3D10Device* pd3dDevice, IDXGISwapChain *pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { ID3D10Device1* pd3dDevice1 = DXUTGetD3D10Device1(); HRESULT hr = S_OK; V_RETURN( g_DialogResourceManager.OnD3D10ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) ); V_RETURN( g_D3DSettingsDlg.OnD3D10ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) ); // Setup the camera's projection parameters float fNearPlane = 0.1f; float fFarPlane = 150.0f; float fAspectRatio = pBackBufferSurfaceDesc->Width / (FLOAT)pBackBufferSurfaceDesc->Height; g_Camera.SetProjParams( 54.43f*(D3DX_PI/180.0f), fAspectRatio, fNearPlane, fFarPlane ); g_Camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height ); g_Camera.SetButtonMasks( 0, MOUSE_WHEEL, MOUSE_RIGHT_BUTTON | MOUSE_LEFT_BUTTON ); // Set the effect variable g_pfSizeZScale->SetFloat( 1.0f/(fFarPlane - fNearPlane) ); g_HUD.SetLocation( pBackBufferSurfaceDesc->Width-170, 0 ); g_HUD.SetSize( 170, 170 ); g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width-170, pBackBufferSurfaceDesc->Height-200 ); g_SampleUI.SetSize( 170, 200 ); // Create a new Depth-Stencil texture to replace the DXUT created one D3D10_TEXTURE2D_DESC descDepth; descDepth.Width = pBackBufferSurfaceDesc->Width; descDepth.Height = pBackBufferSurfaceDesc->Height; descDepth.MipLevels = 1; descDepth.ArraySize = 1; descDepth.Format = DXGI_FORMAT_R32_TYPELESS; // Use a typeless type here so that it can be both depth-stencil and shader resource. // This will fail if we try a format like D32_FLOAT descDepth.SampleDesc = pBackBufferSurfaceDesc->SampleDesc; descDepth.Usage = D3D10_USAGE_DEFAULT; descDepth.BindFlags = D3D10_BIND_DEPTH_STENCIL | D3D10_BIND_SHADER_RESOURCE; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; V_RETURN( pd3dDevice->CreateTexture2D( &descDepth, NULL, &g_pDepthStencilTexture ) ); // Create the depth stencil view D3D10_DEPTH_STENCIL_VIEW_DESC descDSV; if( 1 == descDepth.SampleDesc.Count ) { descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D; } else { descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2DMS; } descDSV.Format = DXGI_FORMAT_D32_FLOAT; // Make the view see this as D32_FLOAT instead of typeless descDSV.Texture2D.MipSlice = 0; V_RETURN( pd3dDevice->CreateDepthStencilView( g_pDepthStencilTexture, &descDSV, &g_pDepthStencilDSV ) ); // Create the shader resource view if( 1 == descDepth.SampleDesc.Count ) { D3D10_SHADER_RESOURCE_VIEW_DESC descSRV; descSRV.Format = DXGI_FORMAT_R32_FLOAT; // Make the shaders see this as R32_FLOAT instead of typeless descSRV.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D; descSRV.Texture2D.MipLevels = 1; descSRV.Texture2D.MostDetailedMip = 0; V_RETURN( pd3dDevice->CreateShaderResourceView( g_pDepthStencilTexture, &descSRV, &g_pDepthStencilSRV ) ); } else if( NULL != pd3dDevice1 ) { D3D10_SHADER_RESOURCE_VIEW_DESC1 descSRV1; ID3D10ShaderResourceView1* pSRView1 = NULL; descSRV1.Format = DXGI_FORMAT_R32_FLOAT; descSRV1.ViewDimension = D3D10_1_SRV_DIMENSION_TEXTURE2DMS; V_RETURN( pd3dDevice1->CreateShaderResourceView1( g_pDepthStencilTexture, &descSRV1, &pSRView1 ) ); // Get the original shader resource view interface from the dx10.1 interface V_RETURN( pSRView1->QueryInterface( __uuidof( ID3D10ShaderResourceView ), (LPVOID*)&g_pDepthStencilSRV ) ); pSRView1->Release(); } else { // Inconsistent state, we are trying to use MSAA with a device that does not support dx10.1 V_RETURN( E_FAIL ); } g_iWidth = pBackBufferSurfaceDesc->Width; g_iHeight = pBackBufferSurfaceDesc->Height; g_iSampleCount = pBackBufferSurfaceDesc->SampleDesc.Count; return hr; } //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { float ClearColor[4] = { 0.0, 0.0, 0.0, 0.0 }; ID3D10RenderTargetView* pRTV = DXUTGetD3D10RenderTargetView(); pd3dDevice->ClearRenderTargetView( pRTV, ClearColor); pd3dDevice->ClearDepthStencilView( g_pDepthStencilDSV, D3D10_CLEAR_DEPTH, 1.0, 0); pd3dDevice->OMSetRenderTargets( 1, &pRTV, g_pDepthStencilDSV ); // If the settings dialog is being shown, then // render it instead of rendering the app's scene if( g_D3DSettingsDlg.IsActive() ) { g_D3DSettingsDlg.OnRender( fElapsedTime ); return; } // Get the projection & view matrix from the camera class D3DXMATRIX mWorld; D3DXMATRIX mView; D3DXMATRIX mProj; D3DXMATRIX mInvView; D3DXMATRIX mInvProj; D3DXMatrixIdentity( &mWorld ); mProj = *g_Camera.GetProjMatrix(); mView = *g_Camera.GetViewMatrix(); D3DXMATRIX mWorldViewProj = mWorld*mView*mProj; D3DXMATRIX mWorldView = mWorld*mView; D3DXMatrixInverse( &mInvView, NULL, &mView ); D3DXMatrixInverse( &mInvProj, NULL, &mProj); D3DXVECTOR4 vViewLightDir1; D3DXVECTOR4 vWorldLightDir1; D3DXVECTOR4 vViewLightDir2; D3DXVECTOR4 vWorldLightDir2; D3DXVec3Normalize( (D3DXVECTOR3*)&vWorldLightDir1, &g_vLightDir1 ); D3DXVec3TransformNormal( (D3DXVECTOR3*)&vViewLightDir1, &g_vLightDir1, &mView ); D3DXVec3Normalize( (D3DXVECTOR3*)&vViewLightDir1, (D3DXVECTOR3*)&vViewLightDir1 ); D3DXVec3Normalize( (D3DXVECTOR3*)&vWorldLightDir2, &g_vLightDir2 ); D3DXVec3TransformNormal( (D3DXVECTOR3*)&vViewLightDir2, &g_vLightDir2, &mView ); D3DXVec3Normalize( (D3DXVECTOR3*)&vViewLightDir2, (D3DXVECTOR3*)&vViewLightDir2 ); D3DXVECTOR3 viewDir = *g_Camera.GetLookAtPt() - *g_Camera.GetEyePt(); D3DXVec3Normalize( &viewDir, &viewDir ); D3DXVECTOR3 vec3 = *g_Camera.GetEyePt(); D3DXVECTOR4 vEyePt; vEyePt.x = vec3.x; vEyePt.y = vec3.y; vEyePt.z = vec3.z; FLOAT fScreenSize[ 2 ] = { (FLOAT)g_iWidth, (FLOAT)g_iHeight }; g_pmWorldViewProj->SetMatrix( (float*)&mWorldViewProj ); g_pmWorldView->SetMatrix( (float*)&mWorldView ); g_pmWorld->SetMatrix( (float*)&mWorld ); g_pmInvView->SetMatrix( (float*)&mInvView ); g_pmInvProj->SetMatrix( (float*)&mInvProj ); g_pvViewLightDir1->SetFloatVector( (float*)&vViewLightDir1 ); g_pvWorldLightDir1->SetFloatVector( (float*)&vWorldLightDir1); g_pvViewLightDir2->SetFloatVector( (float*)&vViewLightDir2 ); g_pvWorldLightDir2->SetFloatVector( (float*)&vWorldLightDir2); g_pvViewDir->SetFloatVector( (float*)&viewDir ); g_pvEyePt->SetFloatVector( (float*)&vEyePt ); g_pvScreenSize->SetFloatVector( fScreenSize ); // Render the scene pd3dDevice->IASetInputLayout( g_pSceneVertexLayout ); g_SkyMesh.Render( pd3dDevice, g_pRenderSky, g_pDiffuseTex ); g_ObjectMesh.Render( pd3dDevice, g_pRenderScene, g_pDiffuseTex, g_pNormalTex ); ID3D10EffectTechnique* pParticleTech = NULL; if( 1 == g_iSampleCount ) { switch( g_ParticleTechnique ) { case PT_BILLBOARD_HARD: pParticleTech = g_pRenderBillboardParticlesHard; break; case PT_BILLBOARD_ODEPTH: pParticleTech = g_pRenderBillboardParticlesODepth; break; case PT_BILLBOARD_SOFT: pParticleTech = g_pRenderBillboardParticlesSoft; break; case PT_BILLBOARD_ODEPTHSOFT: pParticleTech = g_pRenderBillboardParticlesODepthSoft; break; case PT_VOLUME_HARD: pParticleTech = g_pRenderVolumeParticlesHard; break; case PT_VOLUME_SOFT: pParticleTech = g_pRenderVolumeParticlesSoft; break; }; } else { switch( g_ParticleTechnique ) { case PT_BILLBOARD_HARD: pParticleTech = g_pRenderBillboardParticlesHard; break; case PT_BILLBOARD_ODEPTH: pParticleTech = g_pRenderBillboardParticlesODepth; break; case PT_BILLBOARD_SOFT: pParticleTech = g_pRenderBillboardParticlesSoftMSAA; break; case PT_BILLBOARD_ODEPTHSOFT: pParticleTech = g_pRenderBillboardParticlesODepthSoftMSAA; break; case PT_VOLUME_HARD: pParticleTech = g_pRenderVolumeParticlesHardMSAA; break; case PT_VOLUME_SOFT: pParticleTech = g_pRenderVolumeParticlesSoftMSAA; break; }; } if( PT_BILLBOARD_HARD != g_ParticleTechnique && PT_BILLBOARD_ODEPTH != g_ParticleTechnique ) { // Unbind the depth stencil texture from the device pd3dDevice->OMSetRenderTargets( 1, &pRTV, NULL ); // Bind it instead as a shader resource view if( 1 == g_iSampleCount ) { g_pDepthTex->SetResource( g_pDepthStencilSRV ); } else { g_pDepthMSAATex->SetResource( g_pDepthStencilSRV ); } } // Render the particles pd3dDevice->IASetInputLayout( g_pParticleVertexLayout ); ID3D10Buffer *pBuffers[1] = { g_pParticleVB }; UINT stride[1] = { sizeof(PARTICLE_VERTEX) }; UINT offset[1] = { 0 }; pd3dDevice->IASetVertexBuffers( 0, 1, pBuffers, stride, offset ); pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_POINTLIST ); pd3dDevice->IASetIndexBuffer( g_pParticleIB, DXGI_FORMAT_R32_UINT, 0 ); if( PT_VOLUME_HARD == g_ParticleTechnique || PT_VOLUME_SOFT == g_ParticleTechnique ) { g_pVolumeDiffTex->SetResource( g_pNoiseVolumeRV ); g_pVolumeNormTex->SetResource( NULL ); } else { g_pVolumeDiffTex->SetResource( g_pParticleTexRV ); } g_pColorGradient->SetResource( g_pColorGradTexRV ); D3D10_TECHNIQUE_DESC techDesc; pParticleTech->GetDesc( &techDesc ); for( UINT p = 0; p < techDesc.Passes; ++p ) { pParticleTech->GetPassByIndex( p )->Apply(0); pd3dDevice->DrawIndexed( MAX_PARTICLES, 0, 0 ); } // unbind the depth from the resource so we can set it as depth next time around ID3D10ShaderResourceView* Nulls[2] = {NULL,NULL}; pd3dDevice->PSSetShaderResources( 0, 2, Nulls ); DXUT_BeginPerfEvent( DXUT_PERFEVENTCOLOR, L"HUD / Stats" ); RenderText(); g_HUD.OnRender( fElapsedTime ); g_SampleUI.OnRender( fElapsedTime ); DXUT_EndPerfEvent(); } //-------------------------------------------------------------------------------------- // Render the help and statistics text //-------------------------------------------------------------------------------------- void RenderText() { g_pTxtHelper->Begin(); g_pTxtHelper->SetInsertionPos( 2, 0 ); g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) ); g_pTxtHelper->DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) ); g_pTxtHelper->DrawTextLine( DXUTGetDeviceStats() ); g_pTxtHelper->End(); } //-------------------------------------------------------------------------------------- // Release D3D10 resources created in OnD3D10ResizedSwapChain //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10SwapChainReleasing( void* pUserContext ) { g_DialogResourceManager.OnD3D10ReleasingSwapChain(); SAFE_RELEASE( g_pDepthStencilTexture ); SAFE_RELEASE( g_pDepthStencilDSV ); SAFE_RELEASE( g_pDepthStencilSRV ); } //-------------------------------------------------------------------------------------- // Release D3D10 resources created in OnD3D10CreateDevice //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10DestroyDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D10DestroyDevice(); g_D3DSettingsDlg.OnD3D10DestroyDevice(); DXUTGetGlobalResourceCache().OnDestroyDevice(); SAFE_RELEASE( g_pFont10 ); SAFE_RELEASE( g_pSprite10 ); SAFE_DELETE( g_pTxtHelper ); SAFE_RELEASE( g_pEffect10 ); SAFE_RELEASE( g_pSceneVertexLayout ); SAFE_RELEASE( g_pParticleVertexLayout ); SAFE_RELEASE( g_pParticleVB ); SAFE_RELEASE( g_pParticleIB ); SAFE_RELEASE( g_pParticleTexRV ); SAFE_RELEASE( g_pNoiseVolume ); SAFE_RELEASE( g_pNoiseVolumeRV ); SAFE_RELEASE( g_pColorGradTexRV ); g_ObjectMesh.Destroy(); g_SkyMesh.Destroy(); SAFE_DELETE_ARRAY( g_pCPUParticles ); SAFE_DELETE_ARRAY( g_pCPUParticleIndices ); SAFE_DELETE_ARRAY( g_pParticleDepthArray ); } //-------------------------------------------------------------------------------------- float RPercent() { float ret = (float)((rand()%20000) - 10000 ); return ret/10000.0f; } //-------------------------------------------------------------------------------------- void EmitParticle( PARTICLE_VERTEX* pParticle ) { pParticle->Pos.x = 0.0f; pParticle->Pos.y = 0.7f; pParticle->Pos.z = 3.0f; pParticle->Vel.x = 1.0f; pParticle->Vel.y = 0.3f*RPercent(); pParticle->Vel.z = 0.3f*RPercent(); D3DXVec3Normalize( &pParticle->Vel, &pParticle->Vel ); pParticle->Vel *= g_ParticleVel; pParticle->Life = 0.0f; pParticle->Size = 0.0f; } //-------------------------------------------------------------------------------------- // Create a VB for particles //-------------------------------------------------------------------------------------- HRESULT CreateParticleBuffers( ID3D10Device* pd3dDevice ) { HRESULT hr = S_OK; D3D10_BUFFER_DESC vbdesc; vbdesc.BindFlags = D3D10_BIND_VERTEX_BUFFER; vbdesc.ByteWidth = MAX_PARTICLES*sizeof(PARTICLE_VERTEX); vbdesc.CPUAccessFlags = 0; vbdesc.MiscFlags = 0; vbdesc.Usage = D3D10_USAGE_DEFAULT; V_RETURN( pd3dDevice->CreateBuffer( &vbdesc, NULL, &g_pParticleVB ) ); vbdesc.BindFlags = D3D10_BIND_INDEX_BUFFER; vbdesc.ByteWidth = MAX_PARTICLES*sizeof(DWORD); V_RETURN( pd3dDevice->CreateBuffer( &vbdesc, NULL, &g_pParticleIB ) ); g_pCPUParticles = new PARTICLE_VERTEX[ MAX_PARTICLES ]; if( !g_pCPUParticles ) return E_OUTOFMEMORY; for( UINT i=0; i<MAX_PARTICLES; i++ ) { g_pCPUParticles[i].Life = -1; //kill all particles } g_pCPUParticleIndices = new DWORD[ MAX_PARTICLES ]; if( !g_pCPUParticleIndices ) return E_OUTOFMEMORY; g_pParticleDepthArray = new float[ MAX_PARTICLES ]; if( !g_pParticleDepthArray ) return E_OUTOFMEMORY; return hr; } struct CHAR4 { char x,y,z,w; }; //-------------------------------------------------------------------------------------- float GetDensity( int x, int y, int z, CHAR4* pTexels, UINT VolumeSize ) { if( x < 0 ) x += VolumeSize; if( y < 0 ) y += VolumeSize; if( z < 0 ) z += VolumeSize; x = x%VolumeSize; y = y%VolumeSize; z = z%VolumeSize; int index = x + y*VolumeSize + z*VolumeSize*VolumeSize; return (float)pTexels[index].w / 128.0f; } void SetNormal( D3DXVECTOR3 Normal, int x, int y, int z, CHAR4* pTexels, UINT VolumeSize ) { if( x < 0 ) x += VolumeSize; if( y < 0 ) y += VolumeSize; if( z < 0 ) z += VolumeSize; x = x%VolumeSize; y = y%VolumeSize; z = z%VolumeSize; int index = x + y*VolumeSize + z*VolumeSize*VolumeSize; pTexels[index].x = (char)(Normal.x * 128.0f); pTexels[index].y = (char)(Normal.y * 128.0f); pTexels[index].z = (char)(Normal.z * 128.0f); } //-------------------------------------------------------------------------------------- // Create and blur a noise volume texture //-------------------------------------------------------------------------------------- HRESULT CreateNoiseVolume( ID3D10Device* pd3dDevice, UINT VolumeSize ) { HRESULT hr = S_OK; D3D10_SUBRESOURCE_DATA InitData; InitData.pSysMem = new CHAR4[ VolumeSize*VolumeSize*VolumeSize ]; InitData.SysMemPitch = VolumeSize*sizeof(CHAR4); InitData.SysMemSlicePitch = VolumeSize*VolumeSize*sizeof(CHAR4); // Gen a bunch of random values CHAR4* pData = (CHAR4*)InitData.pSysMem; for( UINT i=0; i<VolumeSize*VolumeSize*VolumeSize; i++ ) { pData[i].w = (char)(RPercent() * 128.0f); } // Generate normals from the density gradient float heightAdjust = 0.5f; D3DXVECTOR3 Normal; D3DXVECTOR3 DensityGradient; for( UINT z=0; z<VolumeSize; z++ ) { for( UINT y=0; y<VolumeSize; y++ ) { for( UINT x=0; x<VolumeSize; x++ ) { DensityGradient.x = GetDensity( x+1, y, z, pData, VolumeSize ) - GetDensity( x-1, y, z, pData, VolumeSize )/heightAdjust; DensityGradient.y = GetDensity( x, y+1, z, pData, VolumeSize ) - GetDensity( x, y-1, z, pData, VolumeSize )/heightAdjust; DensityGradient.z = GetDensity( x, y, z+1, pData, VolumeSize ) - GetDensity( x, y, z-1, pData, VolumeSize )/heightAdjust; D3DXVec3Normalize( &Normal, &DensityGradient ); SetNormal( Normal, x,y,z, pData, VolumeSize ); } } } D3D10_TEXTURE3D_DESC desc; desc.BindFlags = D3D10_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; desc.Depth = desc.Height = desc.Width = VolumeSize; desc.Format = DXGI_FORMAT_R8G8B8A8_SNORM; desc.MipLevels = 1; desc.MiscFlags = 0; desc.Usage = D3D10_USAGE_IMMUTABLE; V_RETURN( pd3dDevice->CreateTexture3D( &desc, &InitData, &g_pNoiseVolume ) ); D3D10_SHADER_RESOURCE_VIEW_DESC SRVDesc; ZeroMemory( &SRVDesc, sizeof(SRVDesc) ); SRVDesc.Format = desc.Format; SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE3D; SRVDesc.Texture3D.MipLevels = desc.MipLevels; SRVDesc.Texture3D.MostDetailedMip = 0; V_RETURN(pd3dDevice->CreateShaderResourceView( g_pNoiseVolume, &SRVDesc, &g_pNoiseVolumeRV )); SAFE_DELETE_ARRAY( InitData.pSysMem ); return hr; } //-------------------------------------------------------------------------------------- // Update the particle VB using UpdateSubresource //-------------------------------------------------------------------------------------- void QuickDepthSort(DWORD* indices, float* depths, int lo, int hi) { // lo is the lower index, hi is the upper index // of the region of array a that is to be sorted int i=lo, j=hi; float h; int index; float x=depths[(lo+hi)/2]; // partition do { while (depths[i] > x) i++; while (depths[j] < x) j--; if (i<=j) { h=depths[i]; depths[i]=depths[j]; depths[j]=h; index = indices[i]; indices[i] = indices[j]; indices[j] = index; i++; j--; } } while (i<=j); // recursion if (lo<j) QuickDepthSort(indices, depths, lo, j); if (i<hi) QuickDepthSort(indices, depths, i, hi); } //-------------------------------------------------------------------------------------- // Sort the particle buffer //-------------------------------------------------------------------------------------- void SortParticleBuffer( D3DXVECTOR3 vEye, D3DXVECTOR3 vDir ) { if( !g_pParticleDepthArray || !g_pCPUParticleIndices ) return; // assume vDir is normalized D3DXVECTOR3 vToParticle; //init indices and depths for( UINT i=0; i<MAX_PARTICLES; i++ ) { g_pCPUParticleIndices[i] = i; vToParticle = g_pCPUParticles[i].Pos - vEye; g_pParticleDepthArray[i] = D3DXVec3Dot( &vDir, &vToParticle ); } // Sort QuickDepthSort(g_pCPUParticleIndices, g_pParticleDepthArray, 0, MAX_PARTICLES-1); } //-------------------------------------------------------------------------------------- // Create a VB for particles //-------------------------------------------------------------------------------------- void AdvanceParticles( ID3D10Device* pd3dDevice, double fTime, float fTimeDelta ) { //emit new particles static double fLastEmitTime = 0; static UINT iLastParticleEmitted = 0; if( !g_bAnimateParticles ) { fLastEmitTime = fTime; return; } float fEmitRate = g_fEmitRate; float fParticleMaxSize = g_fParticleMaxSize; float fParticleMinSize = g_fParticleMinSize; if( PT_VOLUME_HARD == g_ParticleTechnique || PT_VOLUME_SOFT == g_ParticleTechnique ) { fEmitRate *= 3.0f; //emit 1/3 less particles if we're doing volume fParticleMaxSize *= 1.5f; //1.5x the max radius fParticleMinSize *= 1.5f; //1.5x the min radius } UINT NumParticlesToEmit = (UINT)( (fTime - fLastEmitTime)/fEmitRate ); if( NumParticlesToEmit > 0 ) { for( UINT i=0; i<NumParticlesToEmit; i++ ) { EmitParticle( &g_pCPUParticles[iLastParticleEmitted] ); iLastParticleEmitted = (iLastParticleEmitted+1) % MAX_PARTICLES; } fLastEmitTime = fTime; } D3DXVECTOR3 vel; float lifeSq = 0; for( UINT i=0; i<MAX_PARTICLES; i++ ) { if( g_pCPUParticles[i].Life > -1 ) { // squared velocity falloff lifeSq = g_pCPUParticles[i].Life*g_pCPUParticles[i].Life; // Slow down by 50% as we age vel = g_pCPUParticles[i].Vel * (1 - 0.5f*lifeSq); vel.y += 0.5f; //(add some to the up direction, becuase of buoyancy) g_pCPUParticles[i].Pos += vel*fTimeDelta; g_pCPUParticles[i].Life += fTimeDelta/g_fParticleLifeSpan; g_pCPUParticles[i].Size = fParticleMinSize + (fParticleMaxSize-fParticleMinSize) * g_pCPUParticles[i].Life; if( g_pCPUParticles[i].Life > 0.99f ) g_pCPUParticles[i].Life = -1; } } } //-------------------------------------------------------------------------------------- // Update the particle VB using UpdateSubresource //-------------------------------------------------------------------------------------- void UpdateParticleBuffers( ID3D10Device* pd3dDevice ) { pd3dDevice->UpdateSubresource( g_pParticleVB, NULL, NULL, g_pCPUParticles, 0, 0 ); pd3dDevice->UpdateSubresource( g_pParticleIB, NULL, NULL, g_pCPUParticleIndices, 0, 0 ); }
#!/usr/bin/env bash # cmake add_custom_command is stateless, we have to use a script instead if [ "$#" -ne 1 ]; then echo "Illegal number of parameters" exit -1 else CMAKE_SOURCE_DIR=$1 fi cmake -DBOOTSTRAP_DEPS=on ${CMAKE_SOURCE_DIR} && \ make all install && \ cmake -DBOOTSTRAP_DEPS=off ${CMAKE_SOURCE_DIR}
package com.dfire.zerodb.http; import com.dfire.zerodb.common.ProxyNode; import java.util.List; public class GetProxiesResponse { private boolean success; private List<ProxyNode> proxyNodes; public GetProxiesResponse(boolean success, List<ProxyNode> proxyNodes) { this.success = success; this.proxyNodes = proxyNodes; } public boolean isSuccess() { return success; } public List<ProxyNode> getProxyNodes() { return proxyNodes; } }
#!/usr/bin/env sh /home/zhecao/caffe//build/tools/caffe train --solver=pose_solver.prototxt --gpu=$1 --weights=../../../model/vgg/VGG_ILSVRC_19_layers.caffemodel 2>&1 | tee ./output.txt
package org.multibit.hd.ui.views.wizards.welcome.restore_wallet; import com.google.common.base.Optional; import com.google.common.base.Strings; import net.miginfocom.swing.MigLayout; import org.multibit.commons.utils.Dates; import org.multibit.hd.brit.core.seed_phrase.Bip39SeedPhraseGenerator; import org.multibit.hd.brit.core.seed_phrase.SeedPhraseGenerator; import org.multibit.hd.ui.events.view.ViewEvents; import org.multibit.hd.ui.languages.MessageKey; import org.multibit.hd.ui.views.components.Components; import org.multibit.hd.ui.views.components.ModelAndView; import org.multibit.hd.ui.views.components.Panels; import org.multibit.hd.ui.views.components.enter_seed_phrase.EnterSeedPhraseModel; import org.multibit.hd.ui.views.components.enter_seed_phrase.EnterSeedPhraseView; import org.multibit.hd.ui.views.components.panels.PanelDecorator; import org.multibit.hd.ui.views.fonts.AwesomeIcon; import org.multibit.hd.ui.views.wizards.AbstractWizard; import org.multibit.hd.ui.views.wizards.AbstractWizardPanelView; import org.multibit.hd.ui.views.wizards.WizardButton; import org.multibit.hd.ui.views.wizards.welcome.WelcomeWizardModel; import javax.swing.*; import java.util.List; /** * <p>Wizard to provide the following to UI:</p> * <ul> * <li>Restore wallet from seed phrase and timestamp</li> * </ul> * * @since 0.0.1 * */ public class RestoreWalletSeedPhrasePanelView extends AbstractWizardPanelView<WelcomeWizardModel, List<String>> { private ModelAndView<EnterSeedPhraseModel, EnterSeedPhraseView> enterSeedPhraseMaV; private SeedPhraseGenerator generator = new Bip39SeedPhraseGenerator(); /** * @param wizard The wizard managing the states * @param panelName The panel name to filter events from components */ public RestoreWalletSeedPhrasePanelView(AbstractWizard<WelcomeWizardModel> wizard, String panelName) { super(wizard, panelName, AwesomeIcon.KEY, MessageKey.RESTORE_WALLET_SEED_PHRASE_TITLE); } @Override public void newPanelModel() { // Do not ask for timestamp until necessary enterSeedPhraseMaV = Components.newEnterSeedPhraseMaV(getPanelName(), false, true); setPanelModel(enterSeedPhraseMaV.getModel().getValue()); getWizardModel().setRestoreWalletEnterSeedPhraseModel(enterSeedPhraseMaV.getModel()); // Register components registerComponents(enterSeedPhraseMaV); } @Override public void initialiseContent(JPanel contentPanel) { contentPanel.setLayout(new MigLayout( Panels.migLayout("fill,insets 0,hidemode 1"), "[]", // Column constraints "[][]" // Row constraints )); contentPanel.add(Panels.newRestoreFromSeedPhrase(), "wrap"); contentPanel.add(enterSeedPhraseMaV.getView().newComponentPanel(), "wrap"); } @Override protected void initialiseButtons(AbstractWizard<WelcomeWizardModel> wizard) { PanelDecorator.addExitCancelPreviousNext(this, wizard); } @Override public void afterShow() { enterSeedPhraseMaV.getView().requestInitialFocus(); } @Override public void updateFromComponentModels(Optional componentModel) { // Fire the decision events ViewEvents.fireWizardButtonEnabledEvent(getPanelName(), WizardButton.NEXT, isNextEnabled()); // Fire "seed phrase verification" event ViewEvents.fireVerificationStatusChangedEvent(getPanelName() + ".seedphrase", isNextEnabled()); } /** * @return True if the "next" button should be enabled */ private boolean isNextEnabled() { // Get the user data String timestamp = enterSeedPhraseMaV.getModel().getSeedTimestamp(); List<String> seedPhrase = enterSeedPhraseMaV.getModel().getSeedPhrase(); // Attempt to parse the timestamp if present boolean timestampIsValid = false; if (Strings.isNullOrEmpty(timestamp)) { // User has not entered any timestamp so assume it's lost timestampIsValid = true; } else { try { Dates.parseSeedTimestamp(timestamp); timestampIsValid = true; } catch (IllegalArgumentException e) { // Do nothing } } // Perform a more comprehensive test on the seed phrase boolean seedPhraseIsValid = generator.isValid(seedPhrase); return timestampIsValid && seedPhraseIsValid; } }
#!/usr/bin/env bash # Switches ngnix configurations based on input # Define Variables INPUT=$1 CONFIG_STORE_PATH="../nginx-configs" NGINX_CONFIG_PATH="/etc/nginx/sites-available/default" # replace config and restart nginx if [ -f $CONFIG_STORE_PATH/$INPUT ]; then sudo cp $CONFIG_STORE_PATH/$INPUT $NGINX_CONFIG_PATH sudo service nginx restart else echo "configuration: $CONFIG_STORE_PATH/$INPUT does not exist." fi
self.importScripts('../scripts/analytics-helper.js'); let CACHE_NAME = "static-cache"; let urlsToCache = [ "../index.html", "../styles/style.css", "../styles/grid.css", "../scripts/MTLLoader.js", "../scripts/OBJLoader.js", "../scripts/artList.js", "../assets/3d-model.mtl", "../assets/3d-model.obj", "../assets/camera_para.dat", "../assets/27348 ARt Basingstoke map - flyer.jpg", "../assets/Studentbb copy.jpg", "../assets/Maddie1 copy.jpg", "../assets/All_Our_Own_Crafts copy.jpg", "../assets/iPad_1 2 copy.jpg", "../assets/Scream_iPad copy.jpg", "../assets/When_Robots_Attack_-_Proteus copy.jpg", "../assets/Emily_Mcbrayne 3 copy.jpg", "../assets/Student1a copy.jpg", "../assets/Annabel1 copy.jpg", "../assets/ThatGallery copy.jpg", "../assets/Students copy.jpg", "../assets/Student2a copy.jpg", "../assets/Studentdd_ copy.jpg", "../assets/BasingstokeArtClass copy.jpg", "../assets/Lissie_ 2 copy.jpg", "../assets/Studentcc_ copy.jpg", "../assets/Willis_Museum.jpg", "../assets/Helena_iPad copy.jpg", "../assets/Lillian-_Let's_Make_A_Deal 2 copy.jpg", "../assets/Viable copy.jpg" ]; self.addEventListener("install", function(event) { event.waitUntil( caches.open(CACHE_NAME).then(function(cache) { return cache.addAll(urlsToCache); }) ); event.waitUntil( sendAnalyticsEvent('appinstall', 'ar') ); }); addEventListener("fetch", function(event) { console.log(event.request); event.respondWith( caches.match(event.request).then(function(response) { if (response) { return response; // if valid response is found in cache return it } else { return fetch(event.request) //fetch from internet .then(function(res) { return caches.open(CACHE_NAME).then(function(cache) { cache.put(event.request.url, res.clone()); //save the response for future return res; // return the fetched data }); }) .catch(function(err) { // fallback mechanism return caches .open(CACHE_CONTAINING_ERROR_MESSAGES) .then(function(cache) { return cache.match("/offline.html"); }); }); } }) ); });
package controlapi import ( "crypto/x509" "encoding/pem" "github.com/docker/swarmkit/api" "github.com/docker/swarmkit/manager/state/raft/membership" "github.com/docker/swarmkit/manager/state/store" "github.com/docker/swarmkit/protobuf/ptypes" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/codes" ) func validateNodeSpec(spec *api.NodeSpec) error { if spec == nil { return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } return nil } // GetNode returns a Node given a NodeID. // - Returns `InvalidArgument` if NodeID is not provided. // - Returns `NotFound` if the Node is not found. func (s *Server) GetNode(ctx context.Context, request *api.GetNodeRequest) (*api.GetNodeResponse, error) { if request.NodeID == "" { return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } var node *api.Node s.store.View(func(tx store.ReadTx) { node = store.GetNode(tx, request.NodeID) }) if node == nil { return nil, grpc.Errorf(codes.NotFound, "node %s not found", request.NodeID) } if s.raft != nil { memberlist := s.raft.GetMemberlist() for _, member := range memberlist { if member.NodeID == node.ID { node.ManagerStatus = &api.ManagerStatus{ RaftID: member.RaftID, Addr: member.Addr, Leader: member.Status.Leader, Reachability: member.Status.Reachability, } break } } } return &api.GetNodeResponse{ Node: node, }, nil } func filterNodes(candidates []*api.Node, filters ...func(*api.Node) bool) []*api.Node { result := []*api.Node{} for _, c := range candidates { match := true for _, f := range filters { if !f(c) { match = false break } } if match { result = append(result, c) } } return result } // ListNodes returns a list of all nodes. func (s *Server) ListNodes(ctx context.Context, request *api.ListNodesRequest) (*api.ListNodesResponse, error) { var ( nodes []*api.Node err error ) s.store.View(func(tx store.ReadTx) { switch { case request.Filters != nil && len(request.Filters.Names) > 0: nodes, err = store.FindNodes(tx, buildFilters(store.ByName, request.Filters.Names)) case request.Filters != nil && len(request.Filters.NamePrefixes) > 0: nodes, err = store.FindNodes(tx, buildFilters(store.ByNamePrefix, request.Filters.NamePrefixes)) case request.Filters != nil && len(request.Filters.IDPrefixes) > 0: nodes, err = store.FindNodes(tx, buildFilters(store.ByIDPrefix, request.Filters.IDPrefixes)) case request.Filters != nil && len(request.Filters.Roles) > 0: filters := make([]store.By, 0, len(request.Filters.Roles)) for _, v := range request.Filters.Roles { filters = append(filters, store.ByRole(v)) } nodes, err = store.FindNodes(tx, store.Or(filters...)) case request.Filters != nil && len(request.Filters.Memberships) > 0: filters := make([]store.By, 0, len(request.Filters.Memberships)) for _, v := range request.Filters.Memberships { filters = append(filters, store.ByMembership(v)) } nodes, err = store.FindNodes(tx, store.Or(filters...)) default: nodes, err = store.FindNodes(tx, store.All) } }) if err != nil { return nil, err } if request.Filters != nil { nodes = filterNodes(nodes, func(e *api.Node) bool { if len(request.Filters.Names) == 0 { return true } if e.Description == nil { return false } return filterContains(e.Description.Hostname, request.Filters.Names) }, func(e *api.Node) bool { if len(request.Filters.NamePrefixes) == 0 { return true } if e.Description == nil { return false } return filterContainsPrefix(e.Description.Hostname, request.Filters.NamePrefixes) }, func(e *api.Node) bool { return filterContainsPrefix(e.ID, request.Filters.IDPrefixes) }, func(e *api.Node) bool { if len(request.Filters.Labels) == 0 { return true } if e.Description == nil { return false } return filterMatchLabels(e.Description.Engine.Labels, request.Filters.Labels) }, func(e *api.Node) bool { if len(request.Filters.Roles) == 0 { return true } for _, c := range request.Filters.Roles { if c == e.Spec.Role { return true } } return false }, func(e *api.Node) bool { if len(request.Filters.Memberships) == 0 { return true } for _, c := range request.Filters.Memberships { if c == e.Spec.Membership { return true } } return false }, ) } // Add in manager information on nodes that are managers if s.raft != nil { memberlist := s.raft.GetMemberlist() for _, node := range nodes { for _, member := range memberlist { if member.NodeID == node.ID { node.ManagerStatus = &api.ManagerStatus{ RaftID: member.RaftID, Addr: member.Addr, Leader: member.Status.Leader, Reachability: member.Status.Reachability, } break } } } } return &api.ListNodesResponse{ Nodes: nodes, }, nil } // UpdateNode updates a Node referenced by NodeID with the given NodeSpec. // - Returns `NotFound` if the Node is not found. // - Returns `InvalidArgument` if the NodeSpec is malformed. // - Returns an error if the update fails. func (s *Server) UpdateNode(ctx context.Context, request *api.UpdateNodeRequest) (*api.UpdateNodeResponse, error) { if request.NodeID == "" || request.NodeVersion == nil { return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } if err := validateNodeSpec(request.Spec); err != nil { return nil, err } var ( node *api.Node member *membership.Member demote bool ) err := s.store.Update(func(tx store.Tx) error { node = store.GetNode(tx, request.NodeID) if node == nil { return nil } // Demotion sanity checks. if node.Spec.Role == api.NodeRoleManager && request.Spec.Role == api.NodeRoleWorker { demote = true // Check for manager entries in Store. managers, err := store.FindNodes(tx, store.ByRole(api.NodeRoleManager)) if err != nil { return grpc.Errorf(codes.Internal, "internal store error: %v", err) } if len(managers) == 1 && managers[0].ID == node.ID { return grpc.Errorf(codes.FailedPrecondition, "attempting to demote the last manager of the swarm") } // Check for node in memberlist if member = s.raft.GetMemberByNodeID(request.NodeID); member == nil { return grpc.Errorf(codes.NotFound, "can't find manager in raft memberlist") } // Quorum safeguard if !s.raft.CanRemoveMember(member.RaftID) { return grpc.Errorf(codes.FailedPrecondition, "can't remove member from the raft: this would result in a loss of quorum") } } node.Meta.Version = *request.NodeVersion node.Spec = *request.Spec.Copy() return store.UpdateNode(tx, node) }) if err != nil { return nil, err } if node == nil { return nil, grpc.Errorf(codes.NotFound, "node %s not found", request.NodeID) } if demote && s.raft != nil { // TODO(abronan): the remove can potentially fail and leave the node with // an incorrect role (worker rather than manager), we need to reconcile the // memberlist with the desired state rather than attempting to remove the // member once. if err := s.raft.RemoveMember(ctx, member.RaftID); err != nil { return nil, grpc.Errorf(codes.Internal, "cannot demote manager to worker: %v", err) } } return &api.UpdateNodeResponse{ Node: node, }, nil } // RemoveNode removes a Node referenced by NodeID with the given NodeSpec. // - Returns NotFound if the Node is not found. // - Returns FailedPrecondition if the Node has manager role (and is part of the memberlist) or is not shut down. // - Returns InvalidArgument if NodeID or NodeVersion is not valid. // - Returns an error if the delete fails. func (s *Server) RemoveNode(ctx context.Context, request *api.RemoveNodeRequest) (*api.RemoveNodeResponse, error) { if request.NodeID == "" { return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } err := s.store.Update(func(tx store.Tx) error { node := store.GetNode(tx, request.NodeID) if node == nil { return grpc.Errorf(codes.NotFound, "node %s not found", request.NodeID) } if node.Spec.Role == api.NodeRoleManager { if s.raft == nil { return grpc.Errorf(codes.FailedPrecondition, "node %s is a manager but cannot access node information from the raft memberlist", request.NodeID) } if member := s.raft.GetMemberByNodeID(request.NodeID); member != nil { return grpc.Errorf(codes.FailedPrecondition, "node %s is a cluster manager and is a member of the raft cluster. It must be demoted to worker before removal", request.NodeID) } } if !request.Force && node.Status.State == api.NodeStatus_READY { return grpc.Errorf(codes.FailedPrecondition, "node %s is not down and can't be removed", request.NodeID) } // lookup the cluster clusters, err := store.FindClusters(tx, store.ByName("default")) if err != nil { return err } if len(clusters) != 1 { return grpc.Errorf(codes.Internal, "could not fetch cluster object") } cluster := clusters[0] removedNode := &api.RemovedNode{ID: node.ID} // Set an expiry time for this RemovedNode if a certificate // exists and can be parsed. if len(node.Certificate.Certificate) != 0 { certBlock, _ := pem.Decode(node.Certificate.Certificate) if certBlock != nil { X509Cert, err := x509.ParseCertificate(certBlock.Bytes) if err == nil && !X509Cert.NotAfter.IsZero() { expiry, err := ptypes.TimestampProto(X509Cert.NotAfter) if err == nil { removedNode.Expiry = expiry } } } } cluster.RemovedNodes = append(cluster.RemovedNodes, removedNode) if err := store.UpdateCluster(tx, cluster); err != nil { return err } return store.DeleteNode(tx, request.NodeID) }) if err != nil { return nil, err } return &api.RemoveNodeResponse{}, nil }
# This software is licensed under the MIT "Expat" License. # # Copyright (c) 2016: Oliver Schulz. BASIC_BUILD_OPTS="\ --fail-on-missing \ --enable-shared \ --enable-soversion \ " ADDITIONAL_BUILD_OPTS="\ -DGEANT4_BUILD_MULTITHREADED=OFF \ -DGEANT4_USE_GDML=ON \ -DGEANT4_USE_QT=ON \ -DGEANT4_USE_XM=ON \ -DGEANT4_USE_OPENGL_X11=ON \ -DGEANT4_USE_RAYTRACER_X11=ON \ -DGEANT4_INSTALL_DATA=ON \ -DGEANT4_INSTALL_EXAMPLES=ON \ -DGEANT4_USE_SYSTEM_EXPAT=ON \ -DGEANT4_USE_SYSTEM_ZLIB=ON \ " CLHEP_PREFIX=`(clhep-config --prefix | sed 's/\"//g') 2> /dev/null` if [ -n "${CLHEP_PREFIX}" ] ; then echo "INFO: `clhep-config --version` available, will use it for Geant4 installation." BASIC_BUILD_OPTS="${BASIC_BUILD_OPTS} -DGEANT4_USE_SYSTEM_CLHEP=ON -DCLHEP_ROOT_DIR=${CLHEP_PREFIX}" else BASIC_BUILD_OPTS="${BASIC_BUILD_OPTS} -DGEANT4_USE_SYSTEM_CLHEP=OFF" fi DEFAULT_BUILD_OPTS=`echo ${BASIC_BUILD_OPTS} ${ADDITIONAL_BUILD_OPTS}` download_url() { # Note: Currently using plain HTTP, as the SSL cert of geant4.cern.ch is expired. local PKG_VERSION="${1}" \ && local PKG_VERSION_MAJOR=$(echo "${PKG_VERSION}" | cut -d '.' -f 1) \ && local PKG_VERSION_MINOR=$(echo "${PKG_VERSION}" | cut -d '.' -f 2) \ && local PKG_VERSION_MINOR=$(test "${PKG_VERSION_MAJOR}" -ge 10 && seq -f "%02g" "${PKG_VERSION_MINOR}" "${PKG_VERSION_MINOR}" || echo "${PKG_VERSION_MINOR}") \ && local PKG_VERSION_PATCH=$(echo "${PKG_VERSION}" | cut -d '.' -f 3) \ && local PKG_VERSION_PATCH=$(seq -f "%02g" "${PKG_VERSION_PATCH}" "${PKG_VERSION_PATCH}") \ && local PKG_VERSION_DNL="${PKG_VERSION_MAJOR}.${PKG_VERSION_MINOR}" \ && local PKG_VERSION_DNL=$(test "${PKG_VERSION_PATCH}" -ne 0 && echo "${PKG_VERSION_DNL}.p${PKG_VERSION_PATCH}" || echo "${PKG_VERSION_DNL}") \ && echo "http://geant4.cern.ch/support/source/geant4.${PKG_VERSION_DNL}.tar.gz" } pkg_install() { DOWNLOAD_URL=`download_url "${PACKAGE_VERSION}"` echo "INFO: Download URL: \"${DOWNLOAD_URL}\"." >&2 mkdir src build curl -L "${DOWNLOAD_URL}" | tar --strip-components 1 -C src --strip=1 -x -z cd build cmake \ -DCMAKE_INSTALL_PREFIX="${INSTALL_PREFIX}" \ ${DEFAULT_BUILD_OPTS} \ ../src time make -j"$(nproc)" install } pkg_env_vars() { export LD_LIBRARY_PATH="" . "${INSTALL_PREFIX}/bin/geant4.sh" cat <<-EOF PATH="${INSTALL_PREFIX}/bin:\$PATH" LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:\$LD_LIBRARY_PATH" EOF G4_DATA_VARS="$(echo `env|grep -o '^G4.*DATA='|sed 's/=//' | sort`)" env|grep '^G4.*DATA='|sort cat <<-EOF export PATH LD_LIBRARY_PATH ${G4_DATA_VARS} EOF }
# shellcheck shell=bash subcmd() { local flag_{list,show}='no' for arg; do case "$arg" in --list) shift; flag_list='yes' ;; --show) shift; flag_show='yes' ;; esac done local module="$1" if [ "$flag_list" = 'yes' ]; then for file in "$DOTMGR_ROOT_DIR/lib/modules/"*; do file="${file##*/}" file="${file%.sh}" printf '%s ' "$file" done; unset file printf '\n' return fi if [ -z "$module" ]; then util.die 'Name of module stage cannot be empty' fi if [ -f "$DOTMGR_ROOT_DIR/lib/modules/$module.sh" ]; then if [ "$flag_show" = 'yes' ]; then printf '%s\n' "$(<"$DOTMGR_ROOT_DIR/lib/modules/$module.sh")" else source "$DOTMGR_ROOT_DIR/lib/modules/$module.sh" "$@" fi else printf '%s\n' "Module '$module' not found" fi }
package org.bf2.cos.fleetshard.api; import java.util.List; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class OperatorSelectorTest { public static final List<Operator> OPERATORS = List.of( new Operator("1", "camel", "1.0.0"), new Operator("2", "camel", "1.1.0"), new Operator("3", "camel", "1.9.0"), new Operator("4", "camel", "2.0.0"), new Operator("5", "strimzi", "1.9.0"), new Operator("6", "strimzi", "2.0.0")); @Test void assignOperator() { Assertions.assertThat(new OperatorSelector("2", "camel", "[1.0.0,2.0.0)").assign(OPERATORS)) .isPresent() .get() .hasFieldOrPropertyWithValue("type", "camel") .hasFieldOrPropertyWithValue("version", "1.1.0"); Assertions.assertThat(new OperatorSelector("camel", "[1.0.0,2.0.0)").assign(OPERATORS)) .isPresent() .get() .hasFieldOrPropertyWithValue("type", "camel") .hasFieldOrPropertyWithValue("version", "1.9.0"); assertThatThrownBy(() -> new OperatorSelector("5", "camel", "[1.0.0,2.0.0)").assign(OPERATORS)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The given operator id does not match the operator selector type"); assertThatThrownBy(() -> new OperatorSelector("4", "camel", "[1.0.0,2.0.0)").assign(OPERATORS)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The given operator id is outside the operator selector range"); } @Test void availableOperator() { Assertions.assertThat(new OperatorSelector("strimzi", "[1.0.0,2.0.0)").available(OPERATORS)) .isPresent() .get() .hasFieldOrPropertyWithValue("type", "strimzi") .hasFieldOrPropertyWithValue("version", "1.9.0"); Assertions.assertThat(new OperatorSelector("camel", "[1.0.0,2.0.0)").available(OPERATORS)) .isPresent() .get() .hasFieldOrPropertyWithValue("type", "camel") .hasFieldOrPropertyWithValue("version", "1.9.0"); Assertions.assertThat(new OperatorSelector("camel", "(1.0.0,1.8.9)").available(OPERATORS)) .isPresent() .get() .hasFieldOrPropertyWithValue("type", "camel") .hasFieldOrPropertyWithValue("version", "1.1.0"); } }
<reponame>ckpt/backend-services package main import ( "encoding/json" "errors" "net/http" "sort" "strconv" "github.com/ckpt/backend-services/tournaments" "github.com/m4rw3r/uuid" "github.com/zenazn/goji/web" ) func createNewTournament(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") info := new(tournaments.Info) decoder := json.NewDecoder(r.Body) if err := decoder.Decode(info); err != nil { return &appError{err, "Invalid JSON", 400} } nTournament, err := tournaments.NewTournament(*info) if err != nil { return &appError{err, "Failed to create new tournament", 500} } w.Header().Set("Location", "/tournaments/"+nTournament.UUID.String()) w.WriteHeader(201) return nil } func listAllTournaments(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") tournamentList, err := tournaments.AllTournaments() if err != nil { return &appError{err, "Cant load tournaments", 500} } encoder := json.NewEncoder(w) encoder.Encode(tournamentList) return nil } func getTournament(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") uuid, err := uuid.FromString(c.URLParams["uuid"]) tournament, err := tournaments.TournamentByUUID(uuid) if err != nil { return &appError{err, "Cant find tournament", 404} } encoder := json.NewEncoder(w) encoder.Encode(tournament) return nil } func updateTournamentInfo(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") uuid, err := uuid.FromString(c.URLParams["uuid"]) tournament, err := tournaments.TournamentByUUID(uuid) if err != nil { return &appError{err, "Cant find tournament", 404} } tempInfo := new(tournaments.Info) decoder := json.NewDecoder(r.Body) if err := decoder.Decode(tempInfo); err != nil { return &appError{err, "Invalid JSON", 400} } if err := tournament.UpdateInfo(*tempInfo); err != nil { return &appError{err, "Failed to update tournament info", 500} } w.WriteHeader(204) return nil } func setTournamentPlayed(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") uuid, err := uuid.FromString(c.URLParams["uuid"]) tournament, err := tournaments.TournamentByUUID(uuid) if err != nil { return &appError{err, "Cant find tournament", 404} } tempInfo := make(map[string]bool) decoder := json.NewDecoder(r.Body) if err := decoder.Decode(&tempInfo); err != nil { return &appError{err, "Invalid JSON", 400} } if err := tournament.SetPlayed(tempInfo["played"]); err != nil { return &appError{err, "Failed to update tournament played status", 500} } w.WriteHeader(204) return nil } func setTournamentResult(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") tID, err := uuid.FromString(c.URLParams["uuid"]) tournament, err := tournaments.TournamentByUUID(tID) if err != nil { return &appError{err, "Cant find tournament", 404} } type Result struct { Result []uuid.UUID } resultData := new(Result) decoder := json.NewDecoder(r.Body) if err := decoder.Decode(resultData); err != nil { return &appError{err, "Invalid JSON", 400} } if err := tournament.SetResult(resultData.Result); err != nil { return &appError{err, "Failed to update tournament result", 500} } w.WriteHeader(204) return nil } func setTournamentBountyHunters(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") tID, err := uuid.FromString(c.URLParams["uuid"]) tournament, err := tournaments.TournamentByUUID(tID) if err != nil { return &appError{err, "Cant find tournament", 404} } bhData := make(map[uuid.UUID][]uuid.UUID) decoder := json.NewDecoder(r.Body) if err := decoder.Decode(&bhData); err != nil { return &appError{err, "Invalid JSON", 400} } if err := tournament.SetBountyHunters(bhData); err != nil { return &appError{err, "Failed to update tournament bounty hunters", 500} } w.WriteHeader(204) return nil } func addTournamentNoShow(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") tID, err := uuid.FromString(c.URLParams["uuid"]) tournament, err := tournaments.TournamentByUUID(tID) if err != nil { return &appError{err, "Cant find tournament", 404} } absenteeData := new(tournaments.Absentee) decoder := json.NewDecoder(r.Body) if err := decoder.Decode(absenteeData); err != nil { return &appError{err, "Invalid JSON", 400} } if !c.Env["authIsAdmin"].(bool) || absenteeData.Player.IsZero() { absenteeData.Player = c.Env["authPlayer"].(uuid.UUID) } if err := tournament.AddNoShow(absenteeData.Player, absenteeData.Reason); err != nil { return &appError{err, "Failed to set absentee for tournament", 500} } w.WriteHeader(204) return nil } func removeTournamentNoShow(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") tID, err := uuid.FromString(c.URLParams["uuid"]) tournament, err := tournaments.TournamentByUUID(tID) if err != nil { return &appError{err, "Cant find tournament", 404} } pID, err := uuid.FromString(c.URLParams["playeruuid"]) if !c.Env["authIsAdmin"].(bool) && pID != c.Env["authPlayer"].(uuid.UUID) { return &appError{errors.New("Unauthorized"), "Must be given player or admin to remove absentee", 403} } if err := tournament.RemoveNoShow(pID); err != nil { return &appError{err, "Failed to remove absentee for tournament", 500} } w.WriteHeader(204) return nil } func getTournamentResult(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") tID, err := uuid.FromString(c.URLParams["uuid"]) tournament, err := tournaments.TournamentByUUID(tID) if err != nil { return &appError{err, "Cant find tournament", 404} } encoder := json.NewEncoder(w) encoder.Encode(tournament.Result) return nil } func listAllSeasons(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") allTournaments, err := tournaments.AllTournaments() if err != nil { return &appError{err, "Cant load tournaments", 404} } seasonList := allTournaments.Seasons() sort.Ints(seasonList) encoder := json.NewEncoder(w) encoder.Encode(map[string][]int{"seasons": seasonList}) return nil } func listTournamentsBySeason(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") season, err := strconv.Atoi(c.URLParams["year"]) tList, err := tournaments.TournamentsBySeason(season) if err != nil { return &appError{err, "Cant find tournaments", 404} } encoder := json.NewEncoder(w) encoder.Encode(map[string][]*tournaments.Tournament{"tournaments": tList}) return nil } func getSeasonStandings(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") season, _ := strconv.Atoi(c.URLParams["year"]) sortedStandings := tournaments.SeasonStandings(season) encoder := json.NewEncoder(w) encoder.Encode(sortedStandings) return nil } func getSeasonStats(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") season, _ := strconv.Atoi(c.URLParams["year"]) seasonStats := tournaments.SeasonStats([]int{season}) encoder := json.NewEncoder(w) encoder.Encode(seasonStats) return nil } func getSeasonTitles(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") season, _ := strconv.Atoi(c.URLParams["year"]) seasonTitles := tournaments.Titles([]int{season}) encoder := json.NewEncoder(w) encoder.Encode(seasonTitles) return nil } func getTotalStandings(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") tList, err := tournaments.AllTournaments() if err != nil { return &appError{err, "Cant find tournaments", 404} } seasons := tList.Seasons() totalStandings := tournaments.TotalStandings(seasons) encoder := json.NewEncoder(w) encoder.Encode(totalStandings) return nil } func getTotalStats(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") tList, err := tournaments.AllTournaments() if err != nil { return &appError{err, "Cant find tournaments", 404} } seasons := tList.Seasons() fullStats := tournaments.SeasonStats(seasons) encoder := json.NewEncoder(w) encoder.Encode(fullStats) return nil } func getTotalTitles(c web.C, w http.ResponseWriter, r *http.Request) *appError { w.Header().Set("Content-Type", "application/json; charset=utf-8") tList, err := tournaments.AllTournaments() if err != nil { return &appError{err, "Cant find tournaments", 404} } seasons := tList.Seasons() allTitles := tournaments.Titles(seasons) encoder := json.NewEncoder(w) encoder.Encode(allTitles) return nil }
:<<!EOF! #-------------------------------------------------------------------- DllRelyTest_bit=$1 DllRelyTest_dlllib=$2 DllRelyTest_debugRelease=$3 DllRelyTest_allSame=$4 "$CLOUD_REBUILD" DllRelyTest $DllRelyTest_bit $DllRelyTest_dlllib $DllRelyTest_debugRelease $DllRelyTest_allSame !EOF! #-------------------------------------------------------------------- CSystem_bit=$1 CSystem_dlllib=$2 CSystem_debugRelease=$3 CSystem_allSame=$4 "$CLOUD_REBUILD" CSystem $CSystem_bit $CSystem_dlllib $CSystem_debugRelease $CSystem_allSame #-------------------------------------------------------------------- SQLite_bit=$1 SQLite_dlllib=$2 SQLite_debugRelease=$3 SQLite_allSame=$4 "$CLOUD_REBUILD" SQLite $SQLite_bit $SQLite_dlllib $SQLite_debugRelease $SQLite_allSame #-------------------------------------------------------------------- ReadWriteMutex_bit=$1 ReadWriteMutex_dlllib=$2 ReadWriteMutex_debugRelease=$3 ReadWriteMutex_allSame=$4 "$CLOUD_REBUILD" ReadWriteMutex $ReadWriteMutex_bit $ReadWriteMutex_dlllib $ReadWriteMutex_debugRelease $ReadWriteMutex_allSame
#!/bin/zsh if ! git describe --tags 2>&- ; then count=$(git rev-list --count HEAD 2>&- ) commit=$(git describe --tags --always 2>&- ) ret=$? if [ "$ret" -eq 0 ]; then buildno="0.1.0-alpha.$(date +%Y%m%d).$count.$commit" echo "$buildno" else echo "ERROR $(basename $0)" >&2 exit $ret fi fi
/* **** Notes Sort //*/ # define CALEND # define CAR # include "../../../incl/config.h" signed(__cdecl cals_order_events(cals_roll_t(*argp))) { auto cals_event_t *ev; auto time_t t; auto signed i,r; if(!argp) return(0x00); ev = (*(CLI_INDEX+(R(event,*argp)))); if(!ev) return(0x00); if(!(*(CLI_DI+(R(event,*ev))))) return(0x00); if(!(*(CLI_DI+(R(event,**(CLI_DI+(R(event,*ev)))))))) *(CLI_LEAD+(R(event,*argp))) = (ev); else *(CLI_SI+(R(event,**(CLI_DI+(R(event,**(CLI_DI+(R(event,*ev))))))))) = (ev); *(CLI_SI+(R(event,**(CLI_DI+(R(event,*ev)))))) = (*(CLI_SI+(R(event,*ev)))); *(CLI_SI+(R(event,*ev))) = (*(CLI_DI+(R(event,*ev)))); if(!(*(CLI_SI+(R(event,**(CLI_SI+(R(event,*ev)))))))) *(CLI_BASE+(R(event,*argp))) = (*(CLI_SI+(R(event,*ev)))); else *(CLI_DI+(R(event,**(CLI_SI+(R(event,**(CLI_SI+(R(event,*ev))))))))) = (*(CLI_SI+(R(event,*ev)))); *(CLI_DI+(R(event,*ev))) = (*(CLI_DI+(R(event,**(CLI_SI+(R(event,*ev))))))); *(CLI_DI+(R(event,**(CLI_SI+(R(event,*ev)))))) = (ev); *(CLI_OFFSET+(R(event,*argp))) = (*(CLI_SI+(R(event,*ev)))); *(CLI_INDEX+(R(event,*argp))) = (*(CLI_SI+(R(event,*ev)))); return(0x01); }
#! /bin/sh # echo "1: $1 2: $2 3: $3" >> $HOME/debug_mscore-to-eps.sh # 1: /home/jf/git-repositories/jf/baldr/songbook/modules/library-update/songs/Zum-Tanze-da-geht-ein-Maedel/piano/piano.mscx # 2: # 3: # one page: # piano.eps # two pages: # piano_1.eps # piano_2.eps # Auf-der-Mauer: 1 page # Swing-low: 1 page # Zum-Tanze-da-geht-ein-Maedel: 2 pages _eps() { local EPS=$(echo "$1" | sed "s#.mscx#_$2.eps#") echo "Test file" > "$EPS" } if [ -n "$1" ] && [ "$1" != '--help' ]; then _eps "$1" 1 _eps "$1" 2 exit 0 else exit 1 fi
plantApp.controller('findPlantCtrl', function ($scope, ngMaterial) { console.log('contact with mainCtrl') } )
import { showNotification } from "../helpers" export default class RailsImportmap { constructor() {} pin() { const message = 'Pin one or more packages to Rails importmap. Separate package names with a blank space.' nova.workspace.showInputPanel(message, { label: 'Packages', placeholder: 'lodash local-time react@17.0.1', prompt: 'Pin' }, packages => this.pin_or_unpin(packages, { method: 'pin' })) } unpin() { const message = 'Unpin one or more packages from Rails importmap. Separate package names with a blank space.' nova.workspace.showInputPanel(message, { label: 'Packages', placeholder: 'lodash local-time react@17.0.1', prompt: 'Unpin' }, packages => this.pin_or_unpin(packages, { method: 'unpin' })) } // Private pin_or_unpin(packages, options) { const process = new Process('usr/bin/env', { cwd: nova.workspace.path, args: ['bin/importmap', options.method, ...packages.split(' ')], stdio: ['ignore', 'pipe', 'pipe'], }) let str = "" process.onStdout((output) => { str += output.trim() }) process.onStderr(output => { str += output.trim() }) process.onDidExit((status) => { console.log(`Importmap ${options.method} command exited with status:`, status) if (status === 0) { if (str.includes("Couldn't find any packages")) { console.warn(`Couldn't find packages:`, packages) nova.workspace.showWarningMessage(`Couldn't find the specified packages. Check out for typos or other reference errors.`) } else { console.log(`Successfully ${options.method}ned packages:`, packages) showNotification( `rails-importmap-${options.method}`, `Successfully ${options.method}ned packages`, false, `The specified packages have been ${options.method}ned to the project. Check out config/importmap.rb for more information.` ) } } else { console.error(`Importmap ${options.method} command exited with error:`, str) nova.workspace.showErrorMessage(`Something went wrong with the importmap ${options.method} command. Check out the Extension Console for more information.`) } }) process.start() } }
<reponame>JoshEliYang/PriceTag package cn.springmvc.controller; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import cn.springmvc.model.Equipment; import cn.springmvc.service.EquService; import com.springmvc.utils.HttpUtils; @Scope("prototype") @Controller @RequestMapping("/equs") public class EquController { @Autowired private EquService equService; @ResponseBody @RequestMapping(method = RequestMethod.GET) public Map<String, Object> getEquCheckByShopId() { List<Equipment> lists = null; try { lists = equService.getAllEquipments(); } catch (Exception ex) { ex.printStackTrace(); return HttpUtils.generateResponse("1", "服务器内部错误", null); } return HttpUtils.generateResponse("0", "请求成功", lists); } }
#!/bin/sh set -ex DIR=${PWD} # the configure must be run once beforehand cd "$1" # build benchmark binary # assuming the configure has set up the NDK and SDK correctly bazel build -c opt \ --config=android_arm \ --cxxopt='--std=c++11' \ --copt=-DTFLITE_PROFILING_ENABLED \ tensorflow/lite/tools/benchmark:benchmark_model cd ${DIR} cp "$1/bazel-bin/tensorflow/lite/tools/benchmark/benchmark_model" "$2"
#!/bin/bash # read-multiple: read multiple values from keyboard echo -n "Enter one or more values > " read var1 var2 var3 var4 var5 echo "var1 = '$var1'" echo "var2 = '$var2'" echo "var3 = '$var3'" echo "var4 = '$var4'" echo "var5 = '$var5'"
#standardSQL SELECT * FROM `public-data-finance.crypto_tezos.transaction_operations` WHERE status = 'applied' ORDER BY amount DESC LIMIT 1000
<reponame>timonus/UIImageAnimatedGIF // // SceneDelegate.h // UIImageViewAnimatedGIFTestBed // // Created by <NAME> on 12/28/19. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface SceneDelegate : UIResponder <UIWindowSceneDelegate> @property (strong, nonatomic) UIWindow * window; @end
#!/bin/bash APP_MAIN=com.webank.webase.front.Application CURRENT_DIR=`pwd` CONF_DIR=${CURRENT_DIR}/conf SERVER_PORT=$(cat $CONF_DIR/application.yml| grep "port" | awk '{print $2}'| sed 's/\r//') if [ ${SERVER_PORT}"" = "" ];then echo "$CONF_DIR/application.yml server port has not been configured" exit -1 fi processPid=0 checkProcess(){ server_pid=`ps aux | grep java | grep $APP_MAIN | awk '{print $2}'` port_pid=`netstat -anp 2>&1|grep ":$SERVER_PORT "|awk '{printf $7}'|cut -d/ -f1` if [ -n "$port_pid" ]; then if [[ $server_pid =~ $port_pid ]]; then processPid=$port_pid else processPid=0 fi else processPid=0 fi } status(){ checkProcess echo "===============================================================================================" if [ $processPid -ne 0 ]; then echo "Server $APP_MAIN Port $SERVER_PORT is running PID($processPid)" echo "===============================================================================================" else echo "Server $APP_MAIN Port $SERVER_PORT is not running" echo "===============================================================================================" fi } status
from svg import Svg import codecs MARGIN_X=20 MARGIN_Y=60 MAGNIFICATION = 500 MIN_D = 1 MAX_D = 4 DIMMEST_MAG = 6 BRIGHTEST_MAG = -1.5 LABEL_OFFSET_X = 4 LABEL_OFFSET_Y = 3 FONT_SIZE=16 FONT_COLOUR='#167ac6' TITLE_SIZE=16 TITLE_COLOUR='#000' COORDS_SIZE=12 COORDS_COLOUR='#000' STAR_COLOUR='#000' CURVE_WIDTH = 0.1 CURVE_COLOUR = '#000' class Diagram: def __init__(self, title, area, star_data_list): self.title = title self.area = area self.star_data_list = star_data_list self.curves = [] self.border_min_x = self.border_min_y = self.border_max_x = self.border_max_y = None def add_curve(self, curve_points): self.curves.append(curve_points) def _mag_to_d(self, m): mag_range = DIMMEST_MAG - BRIGHTEST_MAG m_score = (DIMMEST_MAG - m) / mag_range r_range = MAX_D - MIN_D return MIN_D + m_score * r_range def _invert_and_offset(self, x, y): return x + MARGIN_X, (self.star_data_list.max_y - y) + MARGIN_Y def render_svg(self, outfile): svg = Svg() # add stars first for star_data in self.star_data_list.data: x, y = self._invert_and_offset(star_data.x, star_data.y) svg.circle(x, y, self._mag_to_d(star_data.mag), STAR_COLOUR) # next add labels for star_data in self.star_data_list.data: if star_data.label: x, y = self._invert_and_offset(star_data.x, star_data.y) d = self._mag_to_d(star_data.mag) svg.text(x + LABEL_OFFSET_X + d/2, y + LABEL_OFFSET_Y, star_data.label, FONT_COLOUR, FONT_SIZE) # next add curves for curve_points in self.curves: svg.curve([self._invert_and_offset(cp[0], cp[1]) for cp in curve_points], CURVE_WIDTH, CURVE_COLOUR) # title center_x = self.star_data_list.max_x/2 + MARGIN_X svg.text(center_x, MARGIN_Y/2, self.title, TITLE_COLOUR, TITLE_SIZE, 'middle', 'underline') # coords chart_bottom_y = self.star_data_list.max_y + MARGIN_Y svg.text(center_x, chart_bottom_y + MARGIN_Y/2, "Right Ascension: {}-{}".format(self.area.ra_min, self.area.ra_max), COORDS_COLOUR, COORDS_SIZE, 'middle') svg.text(center_x, chart_bottom_y + MARGIN_Y/2 + COORDS_SIZE, "Declination: {}-{}".format(self.area.dec_min, self.area.dec_max), COORDS_COLOUR, COORDS_SIZE, 'middle') codecs.open(outfile, 'w', 'utf-8').writelines(svg.to_list())
import matplotlib.pyplot as plt # Set the x-axis to a list of strings for each month. x_axis = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] # Set the y-axis to a list of floats as the total fare in US dollars accumulated for each month. y_axis = [10.02, 23.24, 39.20, 35.42, 32.34, 27.04, 43.82, 10.56, 11.85, 27.90,
declare module "notification" { /** * 从未读通知队列中取出指定位置的通知 * @param index 要获取通知的下标 */ export function getMsg(index: number): object /** * 按照获取规则取出通知数组 * @param select_mode select_mode 为选择类型,可用值为:“NotRead”,“HeaveRead”,“SelectAll” */ export function getMsgs(select_mode: string): object /** * 添加新的通知到 js 通知队列中 * @param msg_obj 要发送的通知对象 */ export function pushMsg(msg_obj: object): boolean /** * 从通知队列中删除指定id对象 * @param id 要删除通知对象的ID */ export function deleteMsg(id: number): boolean /** * 删除通知队列所有通知 */ export function deleteAll(): void /** * 获取通知队列中通知数量 * @param select_mode select_mode 为选择类型,可用值为:“NotRead”,“HeaveRead”,“SelectAll” */ export function getCount(select_mode: string): number /** * 设置排序模式 * @param mode SordMode 排序模式,可用值为:“TimeMode”,“PriorityMode” */ export function setSortMode(mode: string): boolean /** * 将指定通知标记为已读 * @param id 要更新通知对象的 ID */ export function updateMsgReadStatus(id: number): boolean /** * 提供page注册通知监听函数 */ export function onNotification(callback: Function): boolean /** * page注销监听函数 */ export function offNotification(callback: Function): boolean }
import 'babel-polyfill'; import CellGrid from './CellGrid.js'; const seedInput = document.getElementById('seed'); const ruleInput = document.getElementById('ruleNum'); const cellSizeInput = document.getElementById('cellSize'); const canvasSizeInput = document.getElementById('canvasSize'); const canvas = document.getElementById('canvas'); const genButton = document.getElementById('generate'); const ctx = canvas.getContext("2d"); let options = {}; genButton.addEventListener('click', (e) => { // set up options object options.seedString = seedInput.value || "a"; options.ruleNum = ruleInput.value || "90"; options.cellSize = cellSizeInput.value || "2"; options.canvasSize = canvasSizeInput.value || "500"; options.canvasColors = {empty: "#eeeeee", filled: "green"}; let grid = new CellGrid(options); grid.drawGrid(canvas, ctx); return false; });
/* jshint esversion: 6 */ /*tslint:disabled*/ window.Test3 = (function () { "use strict"; let tools = window.Tools, content = document.getElementById("content"), flagCounter = 0, firstRun = true, timeouts = [], guessOrder = [ 'Laos', 'Bhutan', 'Serbia', 'Sweden', 'Serbia', 'Bhutan', 'Laos', 'Serbia', 'Sweden' ], uniqueCountryNames = [ 'Sweden', 'Laos', 'Bhutan', 'Serbia' ], nineFlagNames = [ 'Serbia', 'Sweden', 'Sweden', 'Laos', 'Serbia', 'Bhutan', 'Bhutan', 'Laos', 'Serbia' ], flagDivs = [ '<div class="swe-horizontal" ></div><div class="swe-vertical"></div>', '<div class="laos-stripe" ></div><div class="laos-circle"></div>', `<div class="bhutan-bottom-triangle"></div> <img src="img/flags/flag_dragon_bhutan.svg" alt="Dragon" class="bhutan-dragon">`, `<div class="serbia-midle-stripe"></div><div class="serbia-bottom-stripe"></div> <img src="img/flags/Flag_of_Serbia_coat_of_arms.svg" alt="Double headed eagle" class="serbia-eagle">` ]; let flagObj = { country: NaN, id: NaN, flagHtml: NaN, flagDiv: NaN, hiddenDiv: '<div class="hidden-flag"></div>', flagDivHandle: NaN, countryFlagHtmlToElement: function (flagHtml) { let div = document.createElement('div'); div.id = "flag-" + this.id; div.className = 'flag-75x50 ' + this.country.toLowerCase(); div.innerHTML = flagHtml; return div; }, init: function (country, flagDiv, id) { this.country = country; this.flagDiv = flagDiv; this.id = id; this.flagHtml = this.countryFlagHtmlToElement(flagDiv); }, drawFlag: function (rootDivHandle) { rootDivHandle.appendChild(this.flagHtml); this.addDelayedEventListener(); }, resetFlag: function () { this.flagHtml = this.countryFlagHtmlToElement(this.flagDiv); }, hideFlag: function () { this.flagHandle = document.getElementById("flag-" + this.id); this.flagHandle.innerHTML = this.hiddenDiv; }, addDelayedEventListener: function () { let thatId = this.id, thatFlagDiv = this.flagDiv, thatCountry = this.country, timerId; timerId = setTimeout(function () { let flagHandle = document.getElementById("flag-" + thatId); flagHandle.addEventListener("click", function() { flagHandle.innerHTML = thatFlagDiv; checkOrder(thatCountry); }); }, 5000); timeouts.push(timerId); } }; let flagObjects = []; for (let ix = 0; ix < nineFlagNames.length; ix += 1) { let flagIx = uniqueCountryNames.indexOf(nineFlagNames[ix]); flagObjects[ix] = Object.create(flagObj); flagObjects[ix].init( uniqueCountryNames[flagIx], flagDivs[flagIx], ix ); } function showResult(isLast) { let pContent = "", h1 = "Minnestestet är slut!"; if (isLast) { h1 = "Grattis till samtliga rätt!"; } tools.cleanContent(); pContent = "Antal poäng: " + window.Test.partialScore; tools.createHeader(h1, pContent); tools.addButton(window.Test4.startTest, "Nästa test >>"); } function checkOrder(country) { if (country === guessOrder[flagCounter]) { flagCounter += 1; window.Test.partialScore+= 1; if (flagCounter === guessOrder.length) { showResult(true); } } else { showResult(false); } } function drawAllFlags() { let flagsContainerDiv = document.createElement("div"); flagsContainerDiv.className = "flags-container "; content.appendChild(flagsContainerDiv); flagObjects.forEach(flag => { flag.drawFlag(flagsContainerDiv); }); } function hideFlags() { let timerId; timerId = setTimeout(function () { flagObjects.forEach(flag => { flag.hideFlag(); }); }, 5000); timeouts.push(timerId); } function showGuessOrder() { let timerId; timerId = setTimeout(function () { let ol = document.createElement("ol"); ol.innerText = "Flaggornas clickorder:"; guessOrder.forEach( function(element, ix) { let li = document.createElement("li"); li.innerText = guessOrder[ix]; ol.appendChild(li); }); content.appendChild(ol); }, 5000); timeouts.push(timerId); } function memoryTest() { tools.cleanContent(); tools.createHeader("Gissa flaggornas ordning", " "); drawAllFlags(); hideFlags(); showGuessOrder(); } function startTest() { let h1 = "Minne", pContent = `Detta är ett litet minnes-test som kollar hur bra bildminne man har. Testet börjar med att 9 flaggor visas under 5 sekunder. Därefter döljs de och en numrerad lista men namnen på de nio flaggorna visas upp i stället. Du skall nu klicka på rätt ruta där motsvarande flagga ligger, i rätt ordning. Varje rätt svar ger 1 poäng. Varje fel svar ger inga poäng. När du är beredd klickar du på start-knappen.`; tools.cleanContent(); flagCounter = 0; if (firstRun) { window.Test.totalScore += window.Test.partialScore; window.Test.currentTest = 3; firstRun = false; } else { for (let i = 0; i < timeouts.length; i++) { clearTimeout(timeouts[i]); } timeouts = []; flagObjects.forEach(flag => { flag.resetFlag(); }); } console.log("score: " + window.Test.totalScore); window.Test.partialScore = 0; tools.createHeader(h1, pContent); tools.addButton(memoryTest, "Starta minnestestet!"); } return { startTest: startTest }; })();
<filename>spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosNotificationServerListUpdater.java package com.alibaba.cloud.nacos.ribbon; import java.util.Date; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.listener.Event; import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.listener.NamingEvent; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.config.DynamicIntProperty; import com.netflix.loadbalancer.ServerListUpdater; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A server list updater for the * {@link com.netflix.loadbalancer.DynamicServerListLoadBalancer} that utilizes nacos's * event listener to trigger LB cache updates. * <p> * Note that when a cache refreshed notification is received, the actual update on the * serverList is done on a separate scheduler as the notification is delivered on an * namingService thread. * <p> * Learn from {@link com.netflix.niws.loadbalancer.EurekaNotificationServerListUpdater} * and {@link com.netflix.loadbalancer.PollingServerListUpdater},thanks. * * @author <NAME> * @author gaowei */ public class NacosNotificationServerListUpdater implements ServerListUpdater { private static final Logger logger = LoggerFactory .getLogger(NacosNotificationServerListUpdater.class); private static long LISTOFSERVERS_CACHE_UPDATE_DELAY = 1000; // msecs; private static int LISTOFSERVERS_CACHE_REPEAT_INTERVAL = 30 * 1000; // msecs; private static class LazyHolder { private final static String CORE_THREAD = "NacosNotificationServerListUpdater.ThreadPoolSize"; private final static String QUEUE_SIZE = "NacosNotificationServerListUpdater.queueSize"; private final static LazyHolder SINGLETON = new LazyHolder(); private final DynamicIntProperty poolSizeProp = new DynamicIntProperty( CORE_THREAD, 2); private final DynamicIntProperty queueSizeProp = new DynamicIntProperty( QUEUE_SIZE, 1000); private final ThreadPoolExecutor defaultServerListUpdateExecutor; private final ScheduledThreadPoolExecutor timedServerListRefreshExecutor; private final Thread shutdownThread; private LazyHolder() { int corePoolSize = getCorePoolSize(); defaultServerListUpdateExecutor = new ThreadPoolExecutor(corePoolSize, corePoolSize * 5, 0, TimeUnit.NANOSECONDS, new ArrayBlockingQueue<Runnable>(queueSizeProp.get()), new ThreadFactoryBuilder().setNameFormat( "NacosNotificationServerListUpdater-defaultServerListUpdateExecutor-%d") .setDaemon(true).build()); ThreadFactory factory = (new ThreadFactoryBuilder()).setNameFormat( "NacosNotificationServerListUpdater-timedServerListRefreshExecutor-%d") .setDaemon(true).build(); timedServerListRefreshExecutor = new ScheduledThreadPoolExecutor(corePoolSize, factory); poolSizeProp.addCallback(new Runnable() { @Override public void run() { int corePoolSize = getCorePoolSize(); defaultServerListUpdateExecutor.setCorePoolSize(corePoolSize); defaultServerListUpdateExecutor.setMaximumPoolSize(corePoolSize * 5); timedServerListRefreshExecutor.setCorePoolSize(corePoolSize); } }); shutdownThread = new Thread(new Runnable() { @Override public void run() { logger.info( "Shutting down the Executor for NacosNotificationServerListUpdater"); try { defaultServerListUpdateExecutor.shutdown(); timedServerListRefreshExecutor.shutdown(); Runtime.getRuntime().removeShutdownHook(shutdownThread); } catch (Exception e) { // this can happen in the middle of a real shutdown, and that's // ok. } } }); Runtime.getRuntime().addShutdownHook(shutdownThread); } private int getCorePoolSize() { int propSize = poolSizeProp.get(); if (propSize > 0) { return propSize; } return 2; // default } } public static ExecutorService getDefaultRefreshExecutor() { return LazyHolder.SINGLETON.defaultServerListUpdateExecutor; } public static ScheduledThreadPoolExecutor getTimedRefreshExecutor() { return LazyHolder.SINGLETON.timedServerListRefreshExecutor; } private final AtomicBoolean updateQueued = new AtomicBoolean(false); private final AtomicBoolean isActive = new AtomicBoolean(false); private final AtomicLong lastUpdated = new AtomicLong(System.currentTimeMillis()); private final ExecutorService refreshExecutor; private final NacosDiscoveryProperties nacosDiscoveryProperties; private final IClientConfig clientConfig; private volatile EventListener nacosEventListener; private volatile ScheduledFuture<?> scheduledFuture; private final long initialDelayMs; private final long refreshIntervalMs; public NacosNotificationServerListUpdater( NacosDiscoveryProperties nacosDiscoveryProperties, IClientConfig config) { this(nacosDiscoveryProperties, config, getDefaultRefreshExecutor(), LISTOFSERVERS_CACHE_UPDATE_DELAY, getRefreshIntervalMs(config)); } public NacosNotificationServerListUpdater( NacosDiscoveryProperties nacosDiscoveryProperties, IClientConfig clientConfig, ExecutorService refreshExecutor, final long initialDelayMs, final long refreshIntervalMs) { this.nacosDiscoveryProperties = nacosDiscoveryProperties; this.clientConfig = clientConfig; this.refreshExecutor = refreshExecutor; this.initialDelayMs = initialDelayMs; this.refreshIntervalMs = refreshIntervalMs; } @Override public synchronized void start(final UpdateAction updateAction) { if (isActive.compareAndSet(false, true)) { NamingService namingService = nacosDiscoveryProperties .namingServiceInstance(); this.nacosEventListener = new EventListener() { @Override public void onEvent(Event event) { if (event instanceof NamingEvent) { if (!updateQueued.compareAndSet(false, true)) { // if an update is // already queued logger.info( "an update action is already queued, returning as no-op"); return; } logger.info( "Trigger Nacos change event and received a message ,serviceName:{}", ((NamingEvent) event).getServiceName()); if (!refreshExecutor.isShutdown()) { try { refreshExecutor.submit(new Runnable() { @Override public void run() { try { updateAction.doUpdate(); lastUpdated.set(System.currentTimeMillis()); } catch (Exception e) { logger.warn("Failed to update serverList", e); } finally { updateQueued.set(false); } } }); // fire and forget } catch (Exception e) { logger.warn( "Error submitting update task to executor, skipping one round of updates", e); updateQueued.set(false); // if submit fails, need to reset // updateQueued to false } } else { logger.debug( "stopping NacosNotificationServerListUpdater, as refreshExecutor has been shut down"); stop(); } } } }; try { namingService.subscribe(clientConfig.getClientName(), nacosEventListener); } catch (NacosException e) { logger.warn( "Error submitting update task to executor, skipping one round of updates", e); updateQueued.set(false); // if submit fails, need to reset updateQueued to // false } scheduledFuture = getTimedRefreshExecutor() .scheduleWithFixedDelay(new Runnable() { @Override public void run() { if (!isActive.get()) { if (scheduledFuture != null) { scheduledFuture.cancel(true); } return; } if (!updateQueued.compareAndSet(false, true)) { // if an // update is // already // queued logger.info( "an update action is already queued, returning as no-op"); return; } try { updateAction.doUpdate(); lastUpdated.set(System.currentTimeMillis()); } catch (Exception e) { logger.warn("Failed one update cycle", e); } finally { updateQueued.set(false); } } }, initialDelayMs, refreshIntervalMs, TimeUnit.MILLISECONDS); } else { logger.info("Already active, no-op"); } } @Override public synchronized void stop() { if (isActive.compareAndSet(true, false)) { NamingService namingService = nacosDiscoveryProperties .namingServiceInstance(); if (namingService != null) { try { namingService.unsubscribe(clientConfig.getClientName(), nacosEventListener); } catch (NacosException e) { e.printStackTrace(); } } if (scheduledFuture != null) { scheduledFuture.cancel(true); } } else { logger.info("Not currently active, no-op"); } } @Override public String getLastUpdate() { return new Date(lastUpdated.get()).toString(); } @Override public long getDurationSinceLastUpdateMs() { return System.currentTimeMillis() - lastUpdated.get(); } @Override public int getNumberMissedCycles() { if (!isActive.get()) { return 0; } return (int) ((int) (System.currentTimeMillis() - lastUpdated.get()) / refreshIntervalMs); } @Override public int getCoreThreads() { if (isActive.get()) { if (refreshExecutor != null && refreshExecutor instanceof ThreadPoolExecutor) { return ((ThreadPoolExecutor) refreshExecutor).getCorePoolSize(); } } return 0; } private static long getRefreshIntervalMs(IClientConfig clientConfig) { return clientConfig.get(CommonClientConfigKey.ServerListRefreshInterval, LISTOFSERVERS_CACHE_REPEAT_INTERVAL); } }
<reponame>stephanboersma/my-prototype // Source: https://gist.github.com/whitlockjc/9363016 export const rgbaToHex = (rgba) => { var inParts = rgba.substring(rgba.indexOf('(')).split(','), r = parseInt(trim(inParts[0].substring(1)), 10), g = parseInt(trim(inParts[1]), 10), b = parseInt(trim(inParts[2]), 10), a = parseFloat( trim(inParts[3].substring(0, inParts[3].length - 1)) ).toFixed(2); var outParts = [ r.toString(16), g.toString(16), b.toString(16), Math.round(a * 255) .toString(16) .substring(0, 2), ]; // Pad single-digit output values outParts.forEach(function (part, i) { if (part.length === 1) { outParts[i] = '0' + part; } }); return '#' + outParts.join(''); }; const trim = (str) => { return str.replace(/^\s+|\s+$/gm, ''); };
-- MySQL dump 10.13 Distrib 5.5.47, for debian-linux-gnu (x86_64) -- -- Host: alpha.ineqbench.me Database: ineq_bench -- ------------------------------------------------------ -- Server version 5.5.46-0ubuntu0.14.04.2 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `BENEFIT_TOTALS` -- DROP TABLE IF EXISTS `BENEFIT_TOTALS`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `BENEFIT_TOTALS` ( `GENDER` varchar(45) DEFAULT NULL, `BENEFITS` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `CAR_AVAILABILITY` -- DROP TABLE IF EXISTS `CAR_AVAILABILITY`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `CAR_AVAILABILITY` ( `DATA_ZONE` varchar(11) DEFAULT NULL, `SEX` varchar(45) DEFAULT NULL, `AGE` varchar(45) DEFAULT NULL, `ALL_PEOPLE` int(11) DEFAULT NULL, `NO_CAR` int(11) DEFAULT NULL, `ONE_CAR` int(11) DEFAULT NULL, `TWO_MORE` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `ETHNIC_GROUP` -- DROP TABLE IF EXISTS `ETHNIC_GROUP`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ETHNIC_GROUP` ( `POSTCODE` varchar(25) DEFAULT NULL, `SEX` varchar(25) DEFAULT NULL, `AGE` varchar(25) DEFAULT NULL, `ALL_PEOPLE` int(11) DEFAULT NULL, `WHITE_TOTAL` int(11) DEFAULT NULL, `WHITE_SCOTTISH` int(11) DEFAULT NULL, `WHITE_OTHER_BRITISH` int(11) DEFAULT NULL, `WHITE_IRISH` int(11) DEFAULT NULL, `WHITE_TRAVELLER` int(11) DEFAULT NULL, `WHITE_POLISH` int(11) DEFAULT NULL, `WHITE_OTHER_WHITE` int(11) DEFAULT NULL, `MIXED_ETHNIC_GROUPS` int(11) DEFAULT NULL, `ASIAN_TOTAL` int(11) DEFAULT NULL, `ASIAN_PAKISTANI` int(11) DEFAULT NULL, `ASIAN_INDIAN` int(11) DEFAULT NULL, `ASIAN_BANGLADESHI` int(11) DEFAULT NULL, `ASIAN_CHINESE` int(11) DEFAULT NULL, `ASIAN_OTHER` int(11) DEFAULT NULL, `AFRICAN_TOTAL` int(11) DEFAULT NULL, `AFRICAN` int(11) DEFAULT NULL, `AFRICAN_OTHER` int(11) DEFAULT NULL, `CARIBBEAN_TOTAL` int(11) DEFAULT NULL, `CARIBBEAN_BRITISH` int(11) DEFAULT NULL, `CARIBBEAN_BLACK` int(11) DEFAULT NULL, `CARIBBEAN_OTHER` int(11) DEFAULT NULL, `OTHER_TOTAL` int(11) DEFAULT NULL, `OTHER_ARAB` int(11) DEFAULT NULL, `OTHER_OTHER` int(11) DEFAULT NULL, KEY `ETHNIC_GROUP_POSTCODE_INDEX` (`POSTCODE`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `FUEL_POVERTY` -- DROP TABLE IF EXISTS `FUEL_POVERTY`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `FUEL_POVERTY` ( `DATA_ZONE` varchar(11) DEFAULT NULL, `HEATING_CONDITION` varchar(45) DEFAULT NULL, `OCCUPANCY_RATING` varchar(45) DEFAULT NULL, `ALL_PEOPLE_IN_HOUSEHOLDS` int(11) DEFAULT NULL, `0-15` int(11) DEFAULT NULL, `16-24` int(11) DEFAULT NULL, `25-34` int(11) DEFAULT NULL, `35-49` int(11) DEFAULT NULL, `50-64` int(11) DEFAULT NULL, `65_PLUS` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `GEOGRAPHY_LOOKUP` -- DROP TABLE IF EXISTS `GEOGRAPHY_LOOKUP`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `GEOGRAPHY_LOOKUP` ( `Postcode` varchar(10) DEFAULT NULL, `Datazone` varchar(11) DEFAULT NULL, `Datazone_pop` int(11) DEFAULT NULL, `IZ2011_Code` varchar(11) DEFAULT NULL, `IZ2011_Name` varchar(45) DEFAULT NULL, `Local_Authority_Code` int(11) DEFAULT NULL, `Local_Authority_Name` varchar(45) DEFAULT NULL, `CHP_Code` varchar(11) DEFAULT NULL, `CHP_Name` varchar(100) DEFAULT NULL, `HB_Code` varchar(11) DEFAULT NULL, `HB_Name` varchar(45) DEFAULT NULL, `Locality` varchar(45) DEFAULT NULL, `LHP_Code` int(11) DEFAULT NULL, KEY `GEOGRAPHY_INDEX` (`Locality`), KEY `GEOGRAPHY_LOOKUP_POSTCODE_INDEX` (`Postcode`), KEY `GEOGRAPHY_LOOKUP_DATAZONE_INDEX` (`Datazone`), KEY `LOOKUP_POSTCODE_INDEX` (`Postcode`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `INCOME_SUPPORT` -- DROP TABLE IF EXISTS `INCOME_SUPPORT`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `INCOME_SUPPORT` ( `SEX` varchar(15) DEFAULT NULL, `TOTAL` double DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `IN_WORK_BENEFITS` -- DROP TABLE IF EXISTS `IN_WORK_BENEFITS`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `IN_WORK_BENEFITS` ( `Age` varchar(20) DEFAULT NULL, `Males:` int(11) DEFAULT NULL, `Females:` int(11) DEFAULT NULL, `All People:` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `LOCALITY_POPULATION` -- DROP TABLE IF EXISTS `LOCALITY_POPULATION`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `LOCALITY_POPULATION` ( `AREA` varchar(25) DEFAULT NULL, `POPULATION` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `LONE_PARENTS_WITH_DEPENDANT_CHILDREN` -- DROP TABLE IF EXISTS `LONE_PARENTS_WITH_DEPENDANT_CHILDREN`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `LONE_PARENTS_WITH_DEPENDANT_CHILDREN` ( `SEX` varchar(25) DEFAULT NULL, `TOTAL` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `LONG_TERM_CONDITIONS` -- DROP TABLE IF EXISTS `LONG_TERM_CONDITIONS`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `LONG_TERM_CONDITIONS` ( `DATA_ZONE` varchar(11) DEFAULT NULL, `AGE` varchar(45) DEFAULT NULL, `TOTAL` int(11) DEFAULT NULL, `SEVERE` int(11) DEFAULT NULL, `MILD` int(11) DEFAULT NULL, `NO_CONDITION` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `LONG_TERM_HEALTH_CONDITION` -- DROP TABLE IF EXISTS `LONG_TERM_HEALTH_CONDITION`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `LONG_TERM_HEALTH_CONDITION` ( `DATA_ZONE` varchar(11) NOT NULL, `ALL_PEOPLE` int(11) DEFAULT NULL, `NO_CONDITION` int(11) DEFAULT NULL, `SOME_CONDITION` int(11) DEFAULT NULL, `DEAFNESS` int(11) DEFAULT NULL, `BLINDNESS` int(11) DEFAULT NULL, `LEARNING_DISABILITY` int(11) DEFAULT NULL, `LEARNING_DIFICULTY` int(11) DEFAULT NULL, `DEVELOPMENT_DISORDER` int(11) DEFAULT NULL, `PHYSICAL_DISORDER` int(11) DEFAULT NULL, `MENTAL_CONDITION` int(11) DEFAULT NULL, `OTHER` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `POP_AGE_PERCENT` -- DROP TABLE IF EXISTS `POP_AGE_PERCENT`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `POP_AGE_PERCENT` ( `AGE` int(11) DEFAULT NULL, `PERCENT` double DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `POP_GENDER_PERCENT` -- DROP TABLE IF EXISTS `POP_GENDER_PERCENT`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `POP_GENDER_PERCENT` ( `GENDER` varchar(45) DEFAULT NULL, `PERCENT` double DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `QUALIFICATIONS` -- DROP TABLE IF EXISTS `QUALIFICATIONS`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `QUALIFICATIONS` ( `DATA_ZONE` varchar(11) DEFAULT NULL, `SEX` varchar(45) DEFAULT NULL, `AGE` varchar(45) DEFAULT NULL, `TOTAL_PEOPLE` int(11) DEFAULT NULL, `NO_QUALIFICATIONS` int(11) DEFAULT NULL, `LEVEL_1` int(11) DEFAULT NULL, `LEVEL_2` int(11) DEFAULT NULL, `LEVEL_3` int(11) DEFAULT NULL, `LEVEL_4_PLUS` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `SCHOOL_DISTANCE` -- DROP TABLE IF EXISTS `SCHOOL_DISTANCE`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `SCHOOL_DISTANCE` ( `DATA_ZONE` varchar(11) DEFAULT NULL, `TOTAL` int(11) DEFAULT NULL, `HOMESCHOOLED` int(11) DEFAULT NULL, `LESS_2KM` int(11) DEFAULT NULL, `2KM-5KM` int(11) DEFAULT NULL, `5KM-10KM` int(11) DEFAULT NULL, `10KM-20KM` int(11) DEFAULT NULL, `20KM-30KM` int(11) DEFAULT NULL, `30KM-40KM` int(11) DEFAULT NULL, `40KM-60KM` int(11) DEFAULT NULL, `60KM_PLUS` int(11) DEFAULT NULL, `OTHER` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `SIMD_LOCAL_QUINTILES` -- DROP TABLE IF EXISTS `SIMD_LOCAL_QUINTILES`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `SIMD_LOCAL_QUINTILES` ( `QUINTILE` int(11) DEFAULT NULL, `AnnandaleEskdale` varchar(45) DEFAULT NULL, `Nithsdale` varchar(45) DEFAULT NULL, `Stewartry` varchar(45) DEFAULT NULL, `Wigtownshire` varchar(45) DEFAULT NULL, `DumfriesGalloway` varchar(45) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `SIMD_NATIONAL_QUINTILES` -- DROP TABLE IF EXISTS `SIMD_NATIONAL_QUINTILES`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `SIMD_NATIONAL_QUINTILES` ( `QUINTILE` int(11) DEFAULT NULL, `Annandale & Eskdale` varchar(45) DEFAULT NULL, `Nithsdale` varchar(45) DEFAULT NULL, `Stewartry` varchar(45) DEFAULT NULL, `Wigtownshire` varchar(45) DEFAULT NULL, `Dumfries & Galloway` varchar(45) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `TAX_BAND` -- DROP TABLE IF EXISTS `TAX_BAND`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `TAX_BAND` ( `POST_CODE` varchar(10) NOT NULL, `A` int(11) DEFAULT NULL, `B` int(11) DEFAULT NULL, `C` int(11) DEFAULT NULL, `D` int(11) DEFAULT NULL, `E` int(11) DEFAULT NULL, `F` int(11) DEFAULT NULL, `G` int(11) DEFAULT NULL, `H` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `UNEMPLOYED` -- DROP TABLE IF EXISTS `UNEMPLOYED`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `UNEMPLOYED` ( `DATA_ZONE` varchar(11) DEFAULT NULL, `TOTAL` int(11) DEFAULT NULL, `PART_TIME` int(11) DEFAULT NULL, `FULL_TIME` int(11) DEFAULT NULL, `SELF_EMPLOYED` int(11) DEFAULT NULL, `UNEMPLOYED` int(11) DEFAULT NULL, `STUDENT` int(11) DEFAULT NULL, `RETIRED` int(11) DEFAULT NULL, `INACTIVE_STUDENT` int(11) DEFAULT NULL, `HOMEMAKER` int(11) DEFAULT NULL, `SICK` int(11) DEFAULT NULL, `OTHER` int(11) DEFAULT NULL, `16_24` int(11) DEFAULT NULL, `50-74` int(11) DEFAULT NULL, `NEVER_WORKED` int(11) DEFAULT NULL, `LONG_TERM_UNEMPLOYED` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `UNPAID_CARE` -- DROP TABLE IF EXISTS `UNPAID_CARE`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `UNPAID_CARE` ( `DATA_ZONE` varchar(11) DEFAULT NULL, `TOTAL` int(11) DEFAULT NULL, `SEVERE_DISABILITY` int(11) DEFAULT NULL, `MILD_DISABILITY` int(11) DEFAULT NULL, `NO_DISABILITY` int(11) DEFAULT NULL, `SEVERE_DISABILITY_16-64` int(11) DEFAULT NULL, `MILD_DISABILITY_16-64` int(11) DEFAULT NULL, `NO_DISABILITY_16-64` int(11) DEFAULT NULL, `HEALTH_VERY_GOOD` int(11) DEFAULT NULL, `HEALTH_GOOD` int(11) DEFAULT NULL, `HEALTH_FAIR` int(11) DEFAULT NULL, `HEALTH_BAD` int(11) DEFAULT NULL, `HEALTH_VERY_BAD` int(11) DEFAULT NULL, `NO_UNPAID_CARE` int(11) DEFAULT NULL, `1-19_HOURS_CARE` int(11) DEFAULT NULL, `20-49_HOURS_CARE` int(11) DEFAULT NULL, `50_PLUS_HOURS_CARE` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2016-02-25 13:36:33
import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity'; import { createReducer, on } from '@ngrx/store'; import * as LandsPileCardsActions from './lands-pile-cards.actions'; import { LandsPileCardsEntity } from './lands-pile-cards.models'; export const LANDS_PILE_CARDS_FEATURE_KEY = 'landsPileCards'; export interface LandsPileCardsState extends EntityState<LandsPileCardsEntity> { selectedId?: string; initialized: boolean; loaded: boolean; errorMsg?: string; } export interface LandsPileCardsPartialState { readonly [LANDS_PILE_CARDS_FEATURE_KEY]: LandsPileCardsState; } export const landsPileCardsAdapter: EntityAdapter<LandsPileCardsEntity> = createEntityAdapter<LandsPileCardsEntity>(); export const initialLandsPileCardsState: LandsPileCardsState = landsPileCardsAdapter.getInitialState( { // set initial required properties initialized: false, loaded: false, } ); export const landsPileCardsReducer = createReducer( initialLandsPileCardsState, on(LandsPileCardsActions.initLandsPileCardsNewGame, (state) => ({ ...state, initialized: false, })), on(LandsPileCardsActions.initLandsPileCardsSavedGame, (state) => ({ ...state, loaded: false, errorMsg: undefined, })), on( LandsPileCardsActions.loadLandsPileCardsSuccess, (state, { landsPileCards }) => landsPileCardsAdapter.setAll(landsPileCards, { ...state, loaded: true }) ), on(LandsPileCardsActions.loadLandsPileCardsFailure, (state, { error }) => ({ ...state, errorMsg: error, })), on( LandsPileCardsActions.setLandsPileCardsInitialized, (state, { landsPileCards }) => landsPileCardsAdapter.setAll(landsPileCards, { ...state, initialized: true, }) ), on(LandsPileCardsActions.setLandsPileCardsError, (state, { error }) => ({ ...state, errorMsg: error, })), on(LandsPileCardsActions.selectLandsPileCard, (state, { id }) => ({ ...state, selectedId: id, })), on(LandsPileCardsActions.removeLandsPileCard, (state, { id }) => landsPileCardsAdapter.removeOne(id, state) ) );
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { MatDialogModule } from '@angular/material/dialog'; import { SharedDialogModule } from '../shared-dialog/shared-dialog.module'; import { InformationDialogComponent } from './components/information-dialog/information-dialog.component'; @NgModule({ declarations: [InformationDialogComponent], imports: [CommonModule, MatDialogModule, SharedDialogModule], }) export class InformationDialogModule {}
def first_last(arr) new_arr = [] new_arr << arr.first new_arr << arr.last return new_arr end
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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.springframework.http.codec.multipart; import java.util.Collections; import java.util.Map; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.core.ResolvableType; import org.springframework.core.codec.Hints; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.core.io.buffer.PooledDataBuffer; import org.springframework.http.MediaType; import org.springframework.http.ReactiveHttpOutputMessage; import org.springframework.http.codec.HttpMessageWriter; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * {@link HttpMessageWriter} for writing {@link PartEvent} objects. Useful for * server-side proxies, that relay multipart requests to others services. * * @author <NAME> * @since 6.0 * @see PartEvent */ public class PartEventHttpMessageWriter extends MultipartWriterSupport implements HttpMessageWriter<PartEvent> { public PartEventHttpMessageWriter() { super(Collections.singletonList(MediaType.MULTIPART_FORM_DATA)); } @Override public boolean canWrite(ResolvableType elementType, @Nullable MediaType mediaType) { if (PartEvent.class.isAssignableFrom(elementType.toClass())) { if (mediaType == null) { return true; } for (MediaType supportedMediaType : getWritableMediaTypes()) { if (supportedMediaType.isCompatibleWith(mediaType)) { return true; } } } return false; } @Override public Mono<Void> write(Publisher<? extends PartEvent> partDataStream, ResolvableType elementType, @Nullable MediaType mediaType, ReactiveHttpOutputMessage outputMessage, Map<String, Object> hints) { byte[] boundary = generateMultipartBoundary(); mediaType = getMultipartMediaType(mediaType, boundary); outputMessage.getHeaders().setContentType(mediaType); if (logger.isDebugEnabled()) { logger.debug(Hints.getLogPrefix(hints) + "Encoding Publisher<PartEvent>"); } Flux<DataBuffer> body = Flux.from(partDataStream) .windowUntil(PartEvent::isLast) .concatMap(partData -> partData.switchOnFirst((signal, flux) -> { if (signal.hasValue()) { PartEvent value = signal.get(); Assert.state(value != null, "Null value"); return encodePartData(boundary, outputMessage.bufferFactory(), value, flux); } else { return flux.cast(DataBuffer.class); } })) .concatWith(generateLastLine(boundary, outputMessage.bufferFactory())) .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release); if (logger.isDebugEnabled()) { body = body.doOnNext(buffer -> Hints.touchDataBuffer(buffer, hints, logger)); } return outputMessage.writeWith(body); } private Flux<DataBuffer> encodePartData(byte[] boundary, DataBufferFactory bufferFactory, PartEvent first, Flux<? extends PartEvent> flux) { return Flux.concat( generateBoundaryLine(boundary, bufferFactory), generatePartHeaders(first.headers(), bufferFactory), flux.map(PartEvent::content), generateNewLine(bufferFactory)); } }
import { PassportStrategy } from '@nestjs/passport'; import { Strategy, ExtractJwt } from 'passport-jwt'; import { Injectable, UnauthorizedException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { UsersRepository } from './users.repository'; import { User } from './entities/user.entity'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor(@InjectRepository(UsersRepository) private userRepository: UsersRepository) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: process.env.JWT_SECRET, }); } async validate(payload: any): Promise<User> { const user = await this.userRepository.findOne(payload.id); if (!user) throw new UnauthorizedException(); delete user.password; delete user.salt; return user; } }
#!/bin/bash set -e cd $( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) time PLAINTEXT_PASSPHRASE=$BORG_PASSPHRASE BORG_NAME=VPNTECH_BORG ./compiler.sh rm -rf ../../../bin/VPNTECH_BORG mv dist/VPNTECH_BORG ../../../bin
<gh_stars>1-10 import * as NS from '../../namespace'; import { combineReducers } from 'redux'; import { ReducersMap } from 'shared/types/redux'; import communicationReducer from './communication'; import dataReducer from './data'; import uiReducer from './ui'; export default combineReducers<NS.IReduxState>({ communication: communicationReducer, data: dataReducer, ui: uiReducer, } as ReducersMap<NS.IReduxState>);
package com.comandulli.engine.panoramic.playback.entity.playback; import com.comandulli.engine.panoramic.playback.engine.core.Engine; import com.comandulli.engine.panoramic.playback.engine.core.Entity; import com.comandulli.engine.panoramic.playback.engine.core.Time; import com.comandulli.engine.panoramic.playback.engine.core.Transform; import com.comandulli.engine.panoramic.playback.engine.math.Quaternion; import com.comandulli.engine.panoramic.playback.engine.math.Vector3; import com.comandulli.engine.panoramic.playback.engine.render.camera.Camera; import com.comandulli.engine.panoramic.playback.engine.render.material.Material; import com.comandulli.engine.panoramic.playback.engine.render.renderer.MeshRenderer; import android.media.MediaPlayer; public class SeekControl extends Entity { private final Camera camera; private final MediaPlayer player; private final Subtitle subs; private static final float MIN_ANGLE = -38.0f; private static final float MAX_ANGLE = 38.0f; private static final float ANGLE_LENGTH = 76.0f; private static final float MIN_HEIGHT = 30.0f; private static final float MAX_HEIGHT = 35.0f; private boolean isInFocus; private float timemark; private Entity pivot; private final PlaybackControls controls; private final int mesh; // MESH_STATUS private final int shader; // SHADER_COLOR public SeekControl(String name, MediaPlayer player, Camera camera, PlaybackControls controls, Subtitle subs, int mesh, int shader) { super(name); this.camera = camera; this.player = player; this.controls = controls; this.subs = subs; this.mesh = mesh; this.shader = shader; } @Override public void start() { Entity marker = new Entity("Start"); marker.addComponent(new MeshRenderer(mesh, new Material(shader))); marker.transform.rotation = new Quaternion(0.0f, (float) Math.toRadians(180.0f), 0.0f); marker.transform.scale = Vector3.scaled(Vector3.SCALE_ONE, 0.1f); marker.transform.position = new Vector3(0.0f, 0.7f, 8.8f); pivot = new Entity("Pivot"); pivot.transform.rotation = new Quaternion(0.0f, (float) Math.toRadians(MAX_ANGLE), 0.0f); pivot.transform.position = new Vector3(0.0f, -6.0f, 0.2f); marker.transform.parent = pivot.transform; Engine.getScene().addEntity(marker); super.start(); pivot.transform.parent = this.transform.parent; } @Override public void update() { super.update(); int duration; float progress; try { duration = player.getDuration(); progress = (float) player.getCurrentPosition() / duration; } catch (IllegalStateException e) { return; } float currentAngle = MAX_ANGLE - progress * ANGLE_LENGTH; pivot.transform.rotation = new Quaternion(0.0f, (float) Math.toRadians(currentAngle), 0.0f); Vector3 euler = camera.entity.transform.rotation.getEulerVector(); float height = (float) Math.toDegrees(euler.x); float angle = (float) Math.toDegrees(euler.y - pivot.transform.parent.getWorldRotation().getEulerVector().y); if (height > MIN_HEIGHT && height < MAX_HEIGHT) { if (angle > MIN_ANGLE && angle < MAX_ANGLE) { controls.currentAlpha = 1.0f; if (!isInFocus) { isInFocus = true; timemark = Time.time; } if (Time.time > timemark + 1.0f) { float t = (MAX_ANGLE - angle) / ANGLE_LENGTH; float pos = duration * t; player.seekTo((int) pos); timemark = Time.time; if (subs != null) { subs.init(pos / 1000.0f); } } } else { isInFocus = false; } } else { isInFocus = false; } } }
<reponame>mvaliev/gp2s-pncc import Vue from 'vue' import * as sinon from 'sinon' import BaseForm from '@/components/App/Protein/registration_system_ext/BaseForm' import ConcentrationType from '@/components/App/ConcentrationType' import DialogsService from '@/services/DialogsService' const sandbox = sinon.sandbox.create() describe('Protein/registration_system_ext/BaseForm.vue', () => { let vm = null const DATA = { projectSlugOrId: 'project-1', protein: { id: 1, slug: 'protein-label', label: 'Protein label', purificationId: '333', tubeLabel: 'T333', concentration: { concentrationType: ConcentrationType.Concentration, concentrationFactor: '0.2', isDilutedOrConcentrated: true } } } beforeEach(() => { const Constructor = Vue.extend(BaseForm) vm = new Constructor({ propsData: { protein: DATA.protein, projectId: DATA.projectSlugOrId, template: {} } }) vm = vm.$mount() }) afterEach(() => { sandbox.restore() vm.$destroy() vm = null }) it('should update state for Protein registration system validation call', done => { Vue.nextTick().then(() => { let proteinId = '123' vm.validatePurificationId(proteinId, () => {}) vm.validatePurificationId(null) expect(vm.proteinIdValidationState).to.be.equal('invalid') vm.validPurificationIds = [proteinId] vm.validatePurificationId(proteinId) expect(vm.proteinIdValidationState).to.be.equal('correct') vm.proteinIdValidationState = 'unknown' vm.validPurificationIds = [] vm.validatePurificationId(proteinId) expect(vm.proteinIdValidationState).to.be.equal('processing') }).then(() => { vm.callProteinRegistrationSystem = sandbox.spy() vm.validatePurificationId('123', () => {}) return Vue.nextTick() }).then(() => { expect(vm.callProteinRegistrationSystem).to.have.been.calledOnce }).then(done, done) }) describe('proteinRegistrationSystemPurError', () => { it('calls setProteinRegistrationSystemError with the one received', () => { // given const expected = 'error message' const spy = sandbox.spy(vm, 'setProteinRegistrationSystemError') // when vm.handleProteinRegistrationSystemError({message: expected}) // then expect(spy).to.have.been.calledWith(expected) }) }) describe('proteinRegistrationSystemPurInvalid', () => { it('calls setProteinRegistrationSystemError with the one received', () => { // given const expected = 'Invalid PUR ID' const spy = sandbox.spy(vm, 'setProteinRegistrationSystemError') // when vm.handleProteinRegistrationSystemError({purId: 11111}) // then expect(spy).to.have.been.calledWith(expected) }) }) describe('proteinRegistrationSystemPurLoaded', () => { it('calls setProteinRegistrationSystemError with the one received', () => { // given const spy = sandbox.spy(vm, 'setProteinRegistrationSystemError') // when vm.proteinRegistrationSystemPurLoaded(123) // then expect(spy).to.have.been.calledWith(null) }) }) describe('setProteinRegistrationSystemError', () => { it('sets errors.purificationId to the given error', () => { // given const expected = 1337 // when vm.setProteinRegistrationSystemError(expected) // then expect(vm.errors.purificationId).to.be.equal(expected) }) }) describe('displayNoMolecularWeightInRegistrationSystemDialog', () => { it('should not be called from purHasNoMolecularWeight when purId doesn\'t match', () => { // given vm.protein = {purificationId: 'some-value'} const spy = sandbox.stub(vm, 'displayNoMolecularWeightInRegistrationSystemDialog') // when vm.$events.$emit('purHasNoMolecularWeight', 'different-value') // then spy.should.not.have.been.called }) it('should be called from purHasNoMolecularWeight when purId matches', () => { // given const purId = 1337 vm.protein = {purificationId: 1337} const spy = sandbox.stub(vm, 'displayNoMolecularWeightInRegistrationSystemDialog') // when vm.$events.$emit('purHasNoMolecularWeight', purId) // then spy.should.have.been.called }) it('should call DialogService.showConfirmationDialog', () => { // given const spy = sandbox.stub(DialogsService, 'showConfirmDialog').resolves() sandbox.stub(vm, 'showMolecularWeightError') // when vm.displayNoMolecularWeightInRegistrationSystemDialog() // then spy.should.have.been.called }) it('should call showMolecularWeightError after dialog finishes', async () => { // given sandbox.stub(DialogsService, 'showConfirmDialog').resolves() const spy = sandbox.stub(vm, 'showMolecularWeightError') // when await vm.displayNoMolecularWeightInRegistrationSystemDialog() // then spy.should.have.been.called }) }) })
#ifndef WALLET_H #define WALLET_H #include <iostream> #include <vector> #include <string> #include <chrono> #include <utility> using namespace std::rel_ops; using std::vector; using std::ostream; using std::string; using namespace std::chrono; using ll = long long; using ull = unsigned long long; // OPERATION class Operation { private: ll balance_after; time_point<system_clock> timestamp; public: Operation(ll balance); ll getUnits() const; bool operator==(const Operation &o2) const; bool operator<(const Operation &o2) const; friend ostream& operator<<(ostream& os, const Operation &o0); }; // WALLET class Wallet { private: template<typename T> Wallet(T t); const static ll max_BajtekCoin_amount; static ll BajtekCoin_amount; ll balance; vector<Operation> history; bool can_create_B(ll balance); public: Wallet(); Wallet(int starting_balance_B); explicit Wallet(const char * starting_balance_text); explicit Wallet(const string & starting_balance_text); Wallet(Wallet &&w2); Wallet(Wallet &&w1, Wallet &&w2); static Wallet fromBinary(const char * binaryStartingBalance); static Wallet fromBinary(const string & binaryStartingBalance); Wallet(Wallet &w1) = delete; ~Wallet(); Wallet & operator=(Wallet &w2) = delete; Wallet & operator=(Wallet &&w2); Wallet & operator+=(Wallet &w2); Wallet & operator+=(Wallet &&w2); friend Wallet && operator+(Wallet &&w1, Wallet &&w2); friend Wallet && operator+(Wallet &&w1, Wallet &w2); Wallet & operator*=(int x); friend Wallet && operator*(int x, Wallet &&w); friend Wallet && operator*(Wallet &&w1, int x); friend Wallet && operator*(int x, Wallet &w); friend Wallet && operator*(Wallet &w1, int x); Wallet & operator-=(Wallet &w2); Wallet & operator-=(Wallet &&w2); friend Wallet && operator-(Wallet &&w1, Wallet &&w2); friend Wallet && operator-(Wallet &&w1, Wallet &w2); friend bool operator== (const Wallet &&w1, const Wallet &&w2); friend bool operator== (const Wallet &&w1, const Wallet &w2); friend bool operator== (const Wallet &&w, ll x); friend bool operator== (const Wallet &w1, const Wallet &&w2); friend bool operator== (const Wallet &w1, const Wallet &w2); friend bool operator== (const Wallet &w, ll x); friend bool operator== (ll x, const Wallet &w); friend bool operator== (ll x, const Wallet &&w); friend bool operator< (const Wallet &&w1, const Wallet &&w2); friend bool operator< (const Wallet &&w1, const Wallet &w2); friend bool operator< (const Wallet &&w, ll x); friend bool operator< (const Wallet &w1, const Wallet &&w2); friend bool operator< (const Wallet &w1, const Wallet &w2); friend bool operator< (const Wallet &w, ll x); friend bool operator< (ll x, const Wallet &w); friend bool operator< (ll x, const Wallet &&w); friend ostream & operator<<(ostream& os, const Wallet &w0); ll getUnits() const; ull opSize() const; Operation & operator[] (size_t i) const; }; const Wallet & Empty(); #endif
#!/bin/bash # @Author: Jeremiah Marks # @Date: 2015-02-03 23:29:02 # @Last Modified by: Jeremiah Marks # @Last Modified time: 2015-02-04 01:37:09 # An application that I did a long time ago asked that I write a # script in either bash or python that checks the status of a server # and if it is down emails to a notification address. # What I did then does not bear being seen, it was one of the worst # pieces of code I think that I have ever written. # This is that attempt, except in bash. I hope that this is actually worth sharing! # I am using the solution found at # http://stackoverflow.com/a/8937694/492549 # as a jumping off point LOGFILE=~/nsslog.txt ANOTHERLOGFILE=~/thislogfile.txt addresses=( 192.168.1.110 192.168.168.1 google.com ) TOADDRESS="jeremiah@jlmarks.org" FROMADDRESS="jeremiah.l.marks@gmail.com" SUBJECT="I think that I have tried sagan times tonight." BODY=" This is the body of this message. Oh my joy if I see it" # setips() # { # ip_addr=192.168.1.110 # ip_addr2=192.168.112.2 # } echotest() { ping -c1 -W1 $ip_addr || echo 'server is down' ping -c1 -W1 $ip_addr2 || echo 'server2 is down' } sendmessage(){ rm ~/thismessage.txt touch ~/thismessage.txt chmod 777 ~/thismessage.txt echo "To: $TOADDRESS" >> ~/thismessage.txt echo "From: $FROMADDRESS" >> ~/thismessage.txt echo "Subject: $SUBJECT" >> ~/thismessage.txt echo "$BODY" >> ~/thismessage.txt ssmtp jeremiah@jlmarks.org < ~/thismessage.txt } echofunction(){ #This function will accept the ip address of a server and state if it is up or not echo "\n\nNew File attempt\n\n" >> LOGFILE ping -c1 -W1 $1 >> LOGFILE || echo "\n\n$1 is down\n\n" } modulerizedsendmessage(){ # this function requires four variables rm ~/thismessage.txt touch ~/thismessage.txt chmod 777 ~/thismessage.txt echo "To: $1" >> ~/thismessage.txt echo "From: $2" >> ~/thismessage.txt echo "Subject: $3" >> ~/thismessage.txt createmessage $4 #This is the ip address of the server # echo "$4" >> ~/thismessage.txt } createmessage(){ #this function requires the ipaddress that failed and the location of the file to save it to dtstamp=$(date +%c) echo $dtstamp message="At $dtstamp server $1 was down." echo " $message" >> ~/thismessage.txt } ipisup(){ ping -c1 -W1 $1 >> LOGFILE } # setips(){ # addresses=( "192.168.1.110" "192.168.168.1" ) # } recordServerSatus(){ dtstamp=$(date +%c) echo "At $dtstamp server $1 was $2" >> $ANOTHERLOGFILE } testips(){ for i in "${addresses[@]}" do ipisup $i && recordServerSatus $i up || recordServerSatus $i down done } #setips testips #ipisup $ip_addr && echo "Server 1 is up" || echo "That server is not up" #ipisup $ip_addr2 && echo "Server 2 is up" || echo "server two is down" #echotest #modulerizedsendmessage $TOADDRESS $FROMADDRESS "$SUBJECT" $ip_addr #echofunction $ip_addr #echofunction $ip_addr2 #createmessage #sendmessage
<gh_stars>0 package com.example.admin.courseforum; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.provider.Settings; import android.view.LayoutInflater; import android.view.View; import android.widget.*; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import static com.example.admin.courseforum.questions.inflater; import static com.example.admin.courseforum.questions.lin; import static com.example.admin.courseforum.questions.rel; import static com.example.admin.courseforum.questions.usrID; public class ViewQuestion extends Activity { int Voted; String username, usr, answer; EditText body; int q_id, q_id_vote; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.viewquestion); Bundle extras = getIntent().getExtras(); // ((TextView)findViewById(R.id.body)).setText(extras.getString("title")); ((TextView)findViewById(R.id.answeredBy)).setText(extras.getString("user")); ((TextView)findViewById(R.id.qTitle)).setText(extras.getString("question")); //((TextView)findViewById(R.id.votesText)).setText(Integer.toString(extras.getInt("votes"))); checkVote(); listAnswers(extras.getInt("question_id"), false, -1); } @SuppressLint("StaticFieldLeak") public void updateVote(View v){ ContentValues params = new ContentValues(); Bundle extras = getIntent().getExtras(); if (getIntent().getStringExtra("user") != null) { usr = extras.getString("user"); } if (getIntent().getStringExtra("question_id") != null) { q_id_vote = extras.getInt("question_id"); } params.put("user",usr); params.put("question_id",q_id_vote); @SuppressLint("StaticFieldLeak") AsyncHTTPPost asyncHTTPPost = new AsyncHTTPPost("http://lamp.ms.wits.ac.za/~s1619336/updateVote.php?output=" + Integer.toString(Voted), params) { @Override protected void onPostExecute(String output) { } }; asyncHTTPPost.execute(); checkVote(); asyncHTTPPost = new AsyncHTTPPost("http://lamp.ms.wits.ac.za/~s1619336/getVotesQ.php?qid=" + extras.getInt("id"), params) { @Override protected void onPostExecute(String output) { try { JSONArray j = new JSONArray(output); int i = j.getJSONObject(0).getInt("Votes"); ((TextView) findViewById(R.id.votesText)).setText(Integer.toString(i)); } catch (JSONException e){ e.printStackTrace(); } } }; asyncHTTPPost.execute(); listAnswers(extras.getInt("id"), false, -1); } public void checkVote(){ ContentValues params = new ContentValues(); params.put("", ""); Bundle extras = getIntent().getExtras(); @SuppressLint("StaticFieldLeak") AsyncHTTPPost asyncHTTPPost = new AsyncHTTPPost("http://lamp.ms.wits.ac.za/~s1619336/checkVoteQ.php?userid=" + extras.getInt("userID") + "&qid=" + extras.getInt("id"), params) { @Override protected void onPostExecute(String output) { try { JSONArray arr = new JSONArray(output); Voted = arr.getJSONObject(0).getInt("Voted"); if (Voted==1){ ImageView img = (ImageView)findViewById(R.id.votedImage); img.setImageDrawable(getResources().getDrawable(R.drawable.filled)); } else { ImageView img = (ImageView)findViewById(R.id.votedImage); img.setImageDrawable(getResources().getDrawable(R.drawable.unfilled)); } } catch (JSONException e){ e.printStackTrace(); } } }; asyncHTTPPost.execute(); } @Override public void onBackPressed() { Bundle extras = getIntent().getExtras(); //questions.refreshScrollView(questions.lin, questions.inflater , extras.getInt("userID"), questions.rel); //questions.refreshScrollView(); super.onBackPressed(); } public void listAnswers(int question, final Boolean clicked, final int aidclicked){ ContentValues params = new ContentValues(); params.put("question_id", question); @SuppressLint("StaticFieldLeak") AsyncHTTPPost asyncHTTPPost = new AsyncHTTPPost("http://lamp.ms.wits.ac.za/~s1619336/answerlist.php", params) { @Override protected void onPostExecute(String output) { LinearLayout l = (LinearLayout) findViewById(R.id.answerLinLayout); l.removeAllViews(); Toast.makeText(getBaseContext(), output, Toast.LENGTH_LONG); try { JSONArray arr = new JSONArray(output); for (int i = 0; i < arr.length(); i++) { RelativeLayout rl = (RelativeLayout) getLayoutInflater().inflate(R.layout.answerlayout, null); JSONObject j = arr.getJSONObject(i); int aid = j.getInt("ANSWER_ID"); updateAnswerVote((ImageView)rl.findViewById(R.id.votedimg), aid, getResources().getDrawable(R.drawable.filled), getResources().getDrawable(R.drawable.unfilled), clicked, aidclicked, (TextView)rl.findViewById(R.id.voteText)); String user = j.getString("USER_NAME"); String ans = j.getString("ANSWER"); // int correct = j.getInt("Correct"); //int votes = j.getInt("Votes"); TextView t = ((TextView)rl.findViewById(R.id.answeredBy)); t.setText(user); t = ((TextView)rl.findViewById(R.id.fullanswer)); t.setText(ans); t = ((TextView)rl.findViewById(R.id.voteText)); // t.setText(Integer.toString(votes)); rl.findViewById(R.id.votedimg).setTag(aid); /*if (correct == 1){ rl.findViewById(R.id.correctimg).setVisibility(View.VISIBLE); } else{ rl.findViewById(R.id.correctimg).setVisibility(View.INVISIBLE); } */ l.addView(rl); } } catch(JSONException e){ e.printStackTrace(); } } }; asyncHTTPPost.execute(); } @SuppressLint("StaticFieldLeak") public void checkAnswerVotes(final ImageView img, int aid, final Drawable d1, final Drawable d2, final TextView t){ ContentValues params = new ContentValues(); params.put("", ""); Bundle extras = getIntent().getExtras(); @SuppressLint("StaticFieldLeak") AsyncHTTPPost asyncHTTPPost = new AsyncHTTPPost("http://lamp.ms.wits.ac.za/~s1619336/checkVoteA.php?userid=" + extras.getInt("userID") + "&aid=" + aid, params) { @Override protected void onPostExecute(String output) { try { JSONArray arr = new JSONArray(output); if (arr.getJSONObject(0).getInt("Voted") == 1){ img.setImageDrawable(d1); } else { img.setImageDrawable(d2); } } catch (JSONException e){ e.printStackTrace(); } } }; asyncHTTPPost.execute(); asyncHTTPPost = new AsyncHTTPPost("http://lamp.ms.wits.ac.za/~s1619336/getVotesA.php?aid=" + aid, params) { @Override protected void onPostExecute(String output) { try { JSONArray arr = new JSONArray(output); t.setText(arr.getJSONObject(0).getString("Votes")); } catch (JSONException e){ e.printStackTrace(); } } }; asyncHTTPPost.execute(); } public void updateAnswerVote(final ImageView img, int aid, Drawable d1, Drawable d2, Boolean clicked, int aidclicked, TextView t){ if (clicked) { if (aid == aidclicked) { ContentValues params = new ContentValues(); params.put("", ""); Bundle extras = getIntent().getExtras(); @SuppressLint("StaticFieldLeak") AsyncHTTPPost asyncHTTPPost = new AsyncHTTPPost("http://lamp.ms.wits.ac.za/~s1619336/updateAnswerVote.php?&userid=" + extras.getInt("userID") + "&aid=" + aid, params) { @Override protected void onPostExecute(String output) { Toast.makeText(getBaseContext(), output, Toast.LENGTH_SHORT); } }; asyncHTTPPost.execute(); //Runs query to insert/delete vote } } checkAnswerVotes(img, aid, d1, d2, t); } public void doList(View v) { Bundle extras = getIntent().getExtras(); int q = extras.getInt("question_id"); listAnswers(q, false, Integer.parseInt(v.getTag().toString())); } public void process(String output){ System.out.println(output); try { JSONArray arr = new JSONArray(output); lin.removeAllViews(); for (int i = 0; i < arr.length(); i++) { RelativeLayout rl = (RelativeLayout) inflater.inflate(R.layout.questionlayout, rel); JSONObject j = arr.getJSONObject(i); answer = j.getString("ANSWER"); ContentValues params = new ContentValues(); params.put("answer",answer); lin.addView(rl); } } catch(JSONException e){ e.printStackTrace(); } } public void postAnswer(View v){ AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); final View dView = inflater.inflate(R.layout.answerdialogue, null); final EditText e = (EditText) dView.findViewById(R.id.answerEdit); Bundle extras = getIntent().getExtras(); username = extras.getString("user"); q_id = extras.getInt("question_id"); builder.setTitle("Enter your answer"); builder.setView(dView); builder.setPositiveButton("Post answer", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ContentValues params = new ContentValues(); params.put("user", username); params.put("answer",e.getText().toString()); params.put("question_id",q_id); @SuppressLint("StaticFieldLeak") AsyncHTTPPost asyncHTTPPost = new AsyncHTTPPost("http://lamp.ms.wits.ac.za/~s1619336/newanswer.php", params) { @Override protected void onPostExecute(String output) { Bundle extras = getIntent().getExtras(); listAnswers(extras.getInt("question_id"), false, -1); } }; asyncHTTPPost.execute(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog d = builder.create(); d.show(); } }
<gh_stars>0 export const ResumeType = ({ subtitle, maintitle }) => { return ( <div> <span className='color-subtitle text-capitalize fs-xl-14 p-medium'>{subtitle}</span> <h4 className='fs-xl-36 fs-md-36 p-bold color-lightn text-capitalize my-2'> {maintitle} </h4> </div> ) }
#!/bin/bash # This script is intended to be run by Travis CI. If running elsewhere, invoke # it with: TRAVIS_PULL_REQUEST=false [path to script] # shellcheck disable=SC1090 source "$(dirname "$0")"/../pattern-ci/scripts/resources.sh check_swift() { swift -version } build_microservices() { echo "Building leaderboards microservice" swift build --package-path containers/leaderboards echo "Building shop microservice" swift build --package-path containers/shop echo "Building users microservice" swift build --package-path containers/users } main(){ if ! check_swift; then echo "Swift not found." test_failed "$0" elif ! build_microservices; then echo "Building with swift failed." test_failed "$0" else test_passed "$0" fi } main
#!/bin/bash #SBATCH -J Act_maxsig_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=6000 #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/sequence_tagging/arg_min/PE-my.py maxsig 315 sgd 2 0.17450118307727136 0.011682744040013505 he_uniform 0.3
#!/bin/bash for file in $(find ./workers/process/ -type f -not -name "_*.py"); do base_filename=$(basename -- "$file") filename_json="${base_filename%.*}.json" if [ ! -f "./rest/process_definitions/$filename_json" ] then wget -P ./rest/process_definitions/ https://raw.githubusercontent.com/Open-EO/openeo-processes/0.4.2/$filename_json --no-clobber fi done
import { Component, OnInit } from '@angular/core'; import { NgForm } from '@angular/forms'; import { Router } from '@angular/router'; import { Store, select } from '@ngrx/store'; import * as fromUsers from './state'; import { State } from '../state/app.state'; import { unmaskUserName, maskUserName } from './state/user.actions'; import { AuthService } from './auth.service'; import { Observable, Subscription } from 'rxjs'; import { take } from 'rxjs/operators'; @Component({ templateUrl: './login.component.html', styleUrls: ['./login.component.css'], }) export class LoginComponent implements OnInit { public pageTitle = 'Log In'; public maskUserName$: Observable<boolean>; private sub: Subscription; constructor( private authService: AuthService, private router: Router, private store: Store<State> ) {} ngOnInit(): void { this.maskUserName$ = this.store .pipe(select(fromUsers.selectMaskUserName)); } cancel(): void { this.router.navigate(['welcome']); } checkChanged(): void { this.maskUserName$ .pipe(take(1)) .subscribe((isMasked: boolean) => { if (isMasked) { this.store.dispatch(unmaskUserName()); } else { this.store.dispatch(maskUserName()); } }); } login(loginForm: NgForm): void { if (loginForm && loginForm.valid) { const userName = loginForm.form.value.userName; const password = <PASSWORD>Form.form.value.password; this.authService.login(userName, password); if (this.authService.redirectUrl) { this.router.navigateByUrl(this.authService.redirectUrl); } else { this.router.navigate(['/products']); } } } }
<reponame>cssagogo/pikadeck pikaDeck.search = {}; (function() { "use strict"; this.init = function() { this.getSimpleData('types'); this.getSimpleData('subtypes'); this.getSimpleData('supertypes'); this.getSets(); }; this.getParams = function () { var data = $('#pika_filters').serializeArray(); if (data && data.length > 0) { var newData = {}; for (var i = 0; i < data.length; i++) { // TODO: This is a specific hack for the card N. if (data[i].name === 'name' && data[i].value === 'N') { newData[data[i].name] = '"' + data[i].value + '"'; continue; } if (newData[data[i].name]) { newData[data[i].name] = newData[data[i].name] + '|' + data[i].value; continue; } if (data[i].value) { newData[data[i].name] = data[i].value; } } newData = $.param(newData, true); return newData; } return null; }; this.getSets = function () { // Else get new data... $.ajax({ dataType: 'json', url: pikaDeck.apiPath + 'sets', success: function(data) { // Show latest set first... if (data && data.sets && data.sets.length > 0) { data.sets.reverse(); } pikaDeck.store.push('sets', pikaDeck.getLookupTable(data.sets, 'code')); pikaDeck.store.push('tournamentSets', pikaDeck.getTournamentSets(data.sets)); pikaDeck.store.push('setsData', data.sets); }, error: function(xhr, status, error) { console.log([xhr, status, error]); } }); }; this.getSimpleData = function (endpoint) { // TODO: Consider checking localStore and load into memory store if it exists and not out of date. //If exists in localstore... // var data = store.get(endpoint) || []; // if (data[endpoint] && data[endpoint].length > 0) { // // pikaDeck.store.push(endpoint, data[endpoint]); // return; // // } $.ajax({ dataType: 'json', url: pikaDeck.apiPath + endpoint, success: function(data) { // TODO: Consider saving to localStore. pikaDeck.store.push(endpoint, data[endpoint]); }, error: function(xhr, status, error) { console.log([xhr, status, error]); } }); }; this.getTypeOptions = function (data) { if (data && data.length > 0) { var items = []; for (var i = 0; i < data.length; i++) { items.push('<option value="' + data[i] + '">' + data[i] + '</option>'); } return items.join(''); } return null; }; this.drawSets = function (data) { var items = _getSetOptions(data); $('#poke_set').html(items).select2({ placeholder: 'Select a set', allowClear: true, templateResult: _getSelect2SetOptions, templateSelection: _getSelect2SetOptions }); $(document).trigger('set.draw_done'); }; this.drawTypes = function (items) { items = pikaDeck.search.getTypeOptions(items); $('#poke_type').html(items).select2({ placeholder: 'Select a Type', allowClear: true }); $(document).trigger('types.draw_done'); }; this.drawSubtypes = function (items) { items = pikaDeck.search.getTypeOptions(items); $('#poke_subtype').html(items).select2({ placeholder: 'Select a Subtype', allowClear: true }); $(document).trigger('subtypes.draw_done'); }; this.drawSupertypes = function (items) { items = pikaDeck.search.getTypeOptions(items); $('#poke_supertype').html(items).select2({ placeholder: 'Select a Supertype', allowClear: true }); $(document).trigger('supertypes.draw_done'); }; this.drawQuerySet = function (setCode) { $('#poke_set').val(setCode).trigger('change'); }; this.drawQueryTypes = function (types) { $('#poke_type').val(types).trigger('change'); }; this.drawQuerySubtype = function (subtype) { $('#poke_subtype').val(subtype).trigger('change'); }; this.drawQuerySupertype = function (supertype) { $('#poke_supertype').val(supertype).trigger('change'); }; this.drawSearchOptionsCount = function (query) { var queryCount = Object.keys(query).length; if (queryCount === 1 && !query.name && !query.list || queryCount >= 2) { //var count = (query.name || query.list) ? queryCount - 1 : queryCount; $('#search_options_count').html('!'); } else { $('#search_options_count').html(''); } }; var _getSelect2SetOptions = function(state) { if (!state.id) { return state.text; } var baseUrl = 'https://images.pokemontcg.io'; var html = $( '<span class="img-set">' + '<span><img src="' + baseUrl + '/' + state.element.value.toLowerCase() + '/symbol.png" /></span> ' + state.text + '</span>' ); return html; }; var _getSetOptions = function (data) { var items = []; $.each(data, function(key, val) { items.push('<option value="' + val.code + '">' + val.name + ' (' + val.ptcgoCode + ')</option>'); }); return items.join(''); }; }).apply(pikaDeck.search);
<reponame>kawanet/binjson /** * @see https://github.com/kawanet/binjson */ import type {binjson} from "../types/binjson"; import {hBinary} from "./h-binary"; import {hBuffer} from "./h-buffer"; import {hDate, hNull, hRegExp, hUndefined} from "./h-misc"; import {hString, hStringBuffer, hStringNative, hStringPureJS} from "./h-string"; import {hArrayBegin, hArrayEnd} from "./h-array"; import {hArrayBuffer, hArrayBufferView} from "./h-typedarray"; import {hBigInt, hDouble, hInt32, hNumber0} from "./h-number"; import {hFalse, hTrue} from "./h-boolean"; import {hObjectBegin, hObjectEnd} from "./h-object"; import {ReadDriver} from "./read-driver"; export const handlers: binjson.Handlers = { Buffer: hBuffer, Date: hDate, RegExp: hRegExp, StringPureJS: hStringPureJS, StringBuffer: hStringBuffer, StringNative: hStringNative, Undefined: hUndefined, }; /** * default router for `decode()`. */ const initDefault = () => { const driver = new ReadDriver(); driver.add([ hArrayBegin, hArrayBuffer, hArrayBufferView, hArrayEnd, hBigInt, hBinary, hBuffer, hDouble, hDate, hFalse, hInt32, hNull, hNumber0, hObjectBegin, hObjectEnd, hRegExp, hString, hTrue, hUndefined, ]); return driver; }; export const defaultReader = initDefault();