repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
amreo/lungo
result.go
package lungo import ( "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "github.com/256dpi/lungo/bsonkit" ) // ErrNoDocuments is returned by SingleResult if not document has been found. // The value is the same as mongo.ErrNoDocuments and can be used interchangeably. var ErrNoDocuments = mongo.ErrNoDocuments var _ ISingleResult = &SingleResult{} // SingleResult wraps a result to be mongo compatible. type SingleResult struct { doc bsonkit.Doc err error } // Decode implements the ISingleResult.Decode method. func (r *SingleResult) Decode(out interface{}) error { // check error if r.err != nil { return r.err } // check document if r.doc == nil { return ErrNoDocuments } // decode document return bsonkit.Decode(r.doc, out) } // DecodeBytes implements the ISingleResult.DecodeBytes method. func (r *SingleResult) DecodeBytes() (bson.Raw, error) { // check error if r.err != nil { return nil, r.err } // check document if r.doc == nil { return nil, ErrNoDocuments } // marshal document return bson.Marshal(r.doc) } // Err implements the ISingleResult.Err method. func (r *SingleResult) Err() error { // check error if r.err != nil { return r.err } // check document if r.doc == nil { return ErrNoDocuments } return nil }
MichaelLangbein/jsonix
scripts/src/main/javascript/org/hisrc/jsonix/Jsonix/Util/NumberUtils.js
<filename>scripts/src/main/javascript/org/hisrc/jsonix/Jsonix/Util/NumberUtils.js<gh_stars>100-1000 Jsonix.Util.NumberUtils = { isInteger : function(value) { return Jsonix.Util.Type.isNumber(value) && ((value % 1) === 0); } };
syntheticgio/fda-hive
hive/html/oldjs/seq.js
<gh_stars>0 /* * ::718604! * * Copyright(C) November 20, 2014 U.S. Food and Drug Administration * Authors: Dr. <NAME> (1), Dr. <NAME> (2), et al * Affiliation: Food and Drug Administration (1), George Washington University (2) * * All rights Reserved. * * The MIT License (MIT) * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /****************************************************** * * Sequence data manipulation routines * ******************************************************/ var gSeq_Parsing=""; var gSeq_dirListDest=""; var gSeq_dirInfo=""; var gSeq_dirSingleSel=0; var gSeq_fastaInfo=""; var gSeq_fileListPrepend=""; function vSeq_compiledVioseq(container, txt) { alert(txt+" reads were read from sequence file."); gSeq_Parsing=""; vDir_listPath(container,"","vDir_listDirContent",1); } function vSeq_fastaInfo(seqfile, prfx) { if (seqfile.indexOf("--")==0)seqfile=cookieGet("vSeq_selected_"+seqfile.substring(2)); var ccmd=protectFields('-verbose 0 -wrap 60 -cnt 100 -print len=1 -fSeq '+prfx+seqfile+' 0 128 '); var t=""; t+="<table class='QP_tbl' style='position:relative; left:-100px; background-color:#FFFFFF;' width='100%'>"; t+="<tr><th style='border:1px dotted #4282B1;' width='100%'><img border=0 height=16 width=48 src='img/dna.gif'>"+seqfile+"<img border=0 height=16 width=48 src='img/dna.gif'><a style='float:right;' href='#' onclick='javascript:vis(\"floatDiv\",\"sectHid\")'>&times;</a></th></tr>"; t+="<tr><td style='border:1px dotted #4282B1;' width='100%'><div style='overflow: auto; height: 200px; width: 100%; padding: 0px;' id='preFastaInfo' >fasta</div></td></tr>" t+="</table>"; gObjectSet("floatDiv",gMoX,gMoY,t,"show","-","-"); gObject("floatDiv").className="sectVis"; linkCmd("viotools&raw=1&exec="+ccmd,"preFastaInfo","-"); setTimeout("vis(\"floatDiv\",\"sectHid\")",10000); } /* function vSeq_vioinfoDownloaded (container, text) { var o=document.forms[gVDir_formName].elements[container]; if( o ){o.value=text; return ;} o=gObject(container); if(o)o.innerHTML=text; } function vSeq_vioinfoUpload (pathcontainer,infocontainer) { if(!gSeq_dirInfo || !gSeq_dirInfo.length)return; var o=document.forms[gVDir_formName].elements[infocontainer]; if( !o || !o.value || o.value.length==0)return ; url="?cmd=infoSet&file="+document.forms[gVDir_formName].elements[pathcontainer].value+"vioinfo.html&info="+protectFields(o.value); //alert(url); ajaxDynaRequestAction(url,false); } */ function vSeq_dirListItemClicked(dirtxt,container, callback, isdir) { var inf=dirtxt.split(":"); var dir=inf[0]; if(!isdir){ if(dir.indexOf(".vioseq")!=-1) { //if(gSeq_dirSingleSel || !(gVDir_concatMode) )document.forms[gVDir_formName].elements[gSeq_dirListDest].value=""; var ls=document.forms[gVDir_formName].elements[gSeq_dirListDest].value.split("; "); var isin=0, allbut=""; for ( var li=0 ; li<ls.length; ++li ){ if(ls[li]==dir )isin=1; // this field was in the list //else { if(allbut.length>0)allbut+="; "; allbut+=ls[li]; //} } //if(isin) document.forms[gVDir_formName].elements[gSeq_dirListDest].value=allbut; //else { if(!isin){ if(allbut.length>0)allbut+="; "; allbut+=dir; } document.forms[gVDir_formName].elements[gSeq_dirListDest].value=allbut; //} cookieSet("vSeq_selected_"+gSeq_dirListDest,allbut); return dir; } if(gSeq_Parsing.length) { alert("the file "+gSeq_Parsing+" is being parsed now\nPlease wait for it to finish"); return; } var rval=confirm("The file "+dir+" has not been parsed yet\nCompilation may take sime time\nDo you want to compile it now?"); if(!rval)return ; gSeq_Parsing=dir; linkCmd("viotools&raw=1&exec="+protectFields("-verbose 0 -fParse %QUERY%"+dir),container,vSeq_compiledVioseq); } if(isdir){ linkCmd("dirList&raw=1&path="+dir, container, callback); //if(gSeq_dirInfo && gSeq_dirInfo.length)linkCmd("infoGet&raw=1&file="+dir+"vioinfo.html", gSeq_dirInfo, vSeq_vioinfoDownloaded); } return dir; } function vSeq_size(idim) { var SZ=""; if(idim>=10000){idim=idim/1000; SZ="K";} if(idim>=10000){idim/=1000; SZ="M";} if(idim>=10000){idim/=1000; SZ="G";} idim=parseInt(idim); if((""+idim).length>=4)idim=parseInt(idim/1000)+","+(idim+"").substring(1); idim+=SZ; return idim; } function vSeq_dirListItemText(isdir, itmtxt, txt, curdir) { var inf=itmtxt.split(":"); var itm=inf[0]; var idim=vSeq_size((inf.length>1) ? parseInt(inf[1]) : 0); var sdim=(inf.length>1) ? ";&nbsp;<img border=0 height=12 width=24 src='img/dna.gif'>" : ""; if(isdir)return "-"; if(itm.indexOf(".vioseq")!=-1){ //var ccmd=protectFields('-verbose 0 -cnt 100 -print len=1 -fSeq %QUERY%'+curdir+itm); //sdim="&nbsp;<a href=\"javascript:linkSelf('viotools&raw=1&exec="+ccmd+"','new');\" >"+sdim+"</a>"; //var idim=parseInt(sdim); t="<img border=0 src='img/ok.gif' height=12 >&nbsp;"+itm + "&nbsp;&nbsp<small>["+idim+"]</small>"; //if(!gSeq_dirSingleSel)t+="&nbsp;<img border=0 src='img/plus.gif' height=12 ></a>"; if(gSeq_fastaInfo && gSeq_fastaInfo.length!=0)t+="&nbsp;<a href=\"javascript:"+gSeq_fastaInfo+"('"+curdir+itm+"','%QUERY%');\" >"+sdim+"</a>"; return t; } var extpos=itm.lastIndexOf("."); var fnd=(extpos!=-1) ? itm.substring(0,extpos+1) : ""; if(extpos!=-1){ var isfound= txt.indexOf(fnd+"vioseq")==-1 ? 0 : 1 ; if(!isfound) return "<img border=0 src='img/process.gif' height=12 >&nbsp;"+itm; } return "";//<img border=0 src='ok.gif' height=12 >&nbsp;"+fnd+"vioseq"; } function vSeq_onChangeQrySub(e) { if(!e)e=event; var container=e.srcElement.name; cookieSet("vSeq_selected_"+container,e.srcElement.value); } function vSeq_loadedAvailableFiles(container, txt) { if(gSeq_fileListPrepend.length) txt=gSeq_fileListPrepend+txt; var vrr=txt.split("\n"); var defval=document.forms[gVDir_formName].elements[container].value; var arrt=vrr[0].split("|"); var selt="<table><tr><td>"; selt+="<select class='inputEditable' name='"+container+"' onchange='vSeq_onChangeQrySub()' >"; for ( var im=0; im<arrt.length; ++im) { var inf=arrt[im].split(":"); var flnm=inf[0]; var dim= (inf.length>1) ? " // "+vSeq_size(inf[1])+"" : ""; selt+="<option value='"+flnm+"' "+((defval==flnm) ? "selected" : "") +">"+flnm+dim+"</option>"; } selt+="</select>"; selt+="</td><td>"; if(flnm.indexOf("vioseq")!=-1)selt+="<a href=\"javascript:gSeq_fastaInfo('--subject','%SUBJECT%');\" ><img border=0 height=12 width=24 src='img/dna.gif'></a>"; selt+="</td></tr></table>"; gObject(container+"_layer").innerHTML=selt; }
CalledByThe4ire/liga-bank
tasks/browsersync.js
'use strict'; // Start watch with browserSync module.exports = { build: 4, name: 'browserSync:watch', run(done) { if (!this.isDev || !process.env.WATCH) return done(); const browserSync = require('browser-sync').create(); const files = this.paths.slashNormalize(this.paths.dist('**', '*.*')); browserSync.init({ server: this.paths._dist, port: process.env.PORT || 3000, tunnel: process.env.TUNNEL || false, snippetOptions: { rule: { match: /<\/body>/i } } }); this.store.watch = true; return browserSync.watch(files).on('change', browserSync.reload); } };
deniscostadsc/playground
solutions/beecrowd/1589/1589.cpp
#include <cstdint> #include <cstdio> int main() { int16_t n, r1, r2; scanf("%d", &n); while (n--) { scanf("%d %d", &r1, &r2); printf("%d\n", r1 + r2); } return 0; }
cloudfoundry-incubator/cf-networking
src/code.cloudfoundry.org/service-discovery-controller/routes/fakes/address_table.go
<filename>src/code.cloudfoundry.org/service-discovery-controller/routes/fakes/address_table.go // Code generated by counterfeiter. DO NOT EDIT. package fakes import ( "sync" "code.cloudfoundry.org/service-discovery-controller/routes" ) type AddressTable struct { GetAllAddressesStub func() map[string][]string getAllAddressesMutex sync.RWMutex getAllAddressesArgsForCall []struct { } getAllAddressesReturns struct { result1 map[string][]string } getAllAddressesReturnsOnCall map[int]struct { result1 map[string][]string } IsWarmStub func() bool isWarmMutex sync.RWMutex isWarmArgsForCall []struct { } isWarmReturns struct { result1 bool } isWarmReturnsOnCall map[int]struct { result1 bool } LookupStub func(string) []string lookupMutex sync.RWMutex lookupArgsForCall []struct { arg1 string } lookupReturns struct { result1 []string } lookupReturnsOnCall map[int]struct { result1 []string } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *AddressTable) GetAllAddresses() map[string][]string { fake.getAllAddressesMutex.Lock() ret, specificReturn := fake.getAllAddressesReturnsOnCall[len(fake.getAllAddressesArgsForCall)] fake.getAllAddressesArgsForCall = append(fake.getAllAddressesArgsForCall, struct { }{}) stub := fake.GetAllAddressesStub fakeReturns := fake.getAllAddressesReturns fake.recordInvocation("GetAllAddresses", []interface{}{}) fake.getAllAddressesMutex.Unlock() if stub != nil { return stub() } if specificReturn { return ret.result1 } return fakeReturns.result1 } func (fake *AddressTable) GetAllAddressesCallCount() int { fake.getAllAddressesMutex.RLock() defer fake.getAllAddressesMutex.RUnlock() return len(fake.getAllAddressesArgsForCall) } func (fake *AddressTable) GetAllAddressesCalls(stub func() map[string][]string) { fake.getAllAddressesMutex.Lock() defer fake.getAllAddressesMutex.Unlock() fake.GetAllAddressesStub = stub } func (fake *AddressTable) GetAllAddressesReturns(result1 map[string][]string) { fake.getAllAddressesMutex.Lock() defer fake.getAllAddressesMutex.Unlock() fake.GetAllAddressesStub = nil fake.getAllAddressesReturns = struct { result1 map[string][]string }{result1} } func (fake *AddressTable) GetAllAddressesReturnsOnCall(i int, result1 map[string][]string) { fake.getAllAddressesMutex.Lock() defer fake.getAllAddressesMutex.Unlock() fake.GetAllAddressesStub = nil if fake.getAllAddressesReturnsOnCall == nil { fake.getAllAddressesReturnsOnCall = make(map[int]struct { result1 map[string][]string }) } fake.getAllAddressesReturnsOnCall[i] = struct { result1 map[string][]string }{result1} } func (fake *AddressTable) IsWarm() bool { fake.isWarmMutex.Lock() ret, specificReturn := fake.isWarmReturnsOnCall[len(fake.isWarmArgsForCall)] fake.isWarmArgsForCall = append(fake.isWarmArgsForCall, struct { }{}) stub := fake.IsWarmStub fakeReturns := fake.isWarmReturns fake.recordInvocation("IsWarm", []interface{}{}) fake.isWarmMutex.Unlock() if stub != nil { return stub() } if specificReturn { return ret.result1 } return fakeReturns.result1 } func (fake *AddressTable) IsWarmCallCount() int { fake.isWarmMutex.RLock() defer fake.isWarmMutex.RUnlock() return len(fake.isWarmArgsForCall) } func (fake *AddressTable) IsWarmCalls(stub func() bool) { fake.isWarmMutex.Lock() defer fake.isWarmMutex.Unlock() fake.IsWarmStub = stub } func (fake *AddressTable) IsWarmReturns(result1 bool) { fake.isWarmMutex.Lock() defer fake.isWarmMutex.Unlock() fake.IsWarmStub = nil fake.isWarmReturns = struct { result1 bool }{result1} } func (fake *AddressTable) IsWarmReturnsOnCall(i int, result1 bool) { fake.isWarmMutex.Lock() defer fake.isWarmMutex.Unlock() fake.IsWarmStub = nil if fake.isWarmReturnsOnCall == nil { fake.isWarmReturnsOnCall = make(map[int]struct { result1 bool }) } fake.isWarmReturnsOnCall[i] = struct { result1 bool }{result1} } func (fake *AddressTable) Lookup(arg1 string) []string { fake.lookupMutex.Lock() ret, specificReturn := fake.lookupReturnsOnCall[len(fake.lookupArgsForCall)] fake.lookupArgsForCall = append(fake.lookupArgsForCall, struct { arg1 string }{arg1}) stub := fake.LookupStub fakeReturns := fake.lookupReturns fake.recordInvocation("Lookup", []interface{}{arg1}) fake.lookupMutex.Unlock() if stub != nil { return stub(arg1) } if specificReturn { return ret.result1 } return fakeReturns.result1 } func (fake *AddressTable) LookupCallCount() int { fake.lookupMutex.RLock() defer fake.lookupMutex.RUnlock() return len(fake.lookupArgsForCall) } func (fake *AddressTable) LookupCalls(stub func(string) []string) { fake.lookupMutex.Lock() defer fake.lookupMutex.Unlock() fake.LookupStub = stub } func (fake *AddressTable) LookupArgsForCall(i int) string { fake.lookupMutex.RLock() defer fake.lookupMutex.RUnlock() argsForCall := fake.lookupArgsForCall[i] return argsForCall.arg1 } func (fake *AddressTable) LookupReturns(result1 []string) { fake.lookupMutex.Lock() defer fake.lookupMutex.Unlock() fake.LookupStub = nil fake.lookupReturns = struct { result1 []string }{result1} } func (fake *AddressTable) LookupReturnsOnCall(i int, result1 []string) { fake.lookupMutex.Lock() defer fake.lookupMutex.Unlock() fake.LookupStub = nil if fake.lookupReturnsOnCall == nil { fake.lookupReturnsOnCall = make(map[int]struct { result1 []string }) } fake.lookupReturnsOnCall[i] = struct { result1 []string }{result1} } func (fake *AddressTable) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.getAllAddressesMutex.RLock() defer fake.getAllAddressesMutex.RUnlock() fake.isWarmMutex.RLock() defer fake.isWarmMutex.RUnlock() fake.lookupMutex.RLock() defer fake.lookupMutex.RUnlock() copiedInvocations := map[string][][]interface{}{} for key, value := range fake.invocations { copiedInvocations[key] = value } return copiedInvocations } func (fake *AddressTable) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { fake.invocations = map[string][][]interface{}{} } if fake.invocations[key] == nil { fake.invocations[key] = [][]interface{}{} } fake.invocations[key] = append(fake.invocations[key], args) } var _ routes.AddressTable = new(AddressTable)
hjc851/SourceCodePlagiarismDetectionDataset
Variant Programs/1/1-3/history/OperatorContest.java
package history; import looked.DayCaretaker; import provider.Grower; public class OperatorContest extends history.SpectaclePrecedent implements java.lang.Comparable<OperatorContest> { public static final java.lang.String JohnPart = "CAN_START"; public provider.Grower manager = null; public OperatorContest(double chance, String dope, Grower proprietor) { this.again = chance; this.scoop = dope; this.manager = proprietor; } public synchronized void mechanismSummit() { looked.DayCaretaker.placeWeek(this.again); this.manager.proceedingsTheOpposes(); } public static final java.lang.String WantingDoneThing = "WILL_FINISH_OBJECT"; public synchronized String toString() { return "owner: " + manager + " info: " + scoop + " chrono: " + again; } public synchronized int compareTo(OperatorContest factors) { if (this.again < factors.again) return 1; else if (this.again == factors.again) return 0; else return -1; } }
kifferltd/open-mika
vm-cmp/awt/rudolph/java5/org/apache/harmony/awt/wtk/GraphicsFactory.java
/* * 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. */ /** * @author <NAME>, <NAME>, <NAME> * @version $Revision$ */ package org.apache.harmony.awt.wtk; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.peer.FontPeer; import org.apache.harmony.awt.gl.MultiRectArea; import org.apache.harmony.awt.gl.font.FontManager; import android.graphics.Canvas; import android.graphics.Paint; /** * GraphicsFactory interface defines methods for Graphics2D * and font stuff instances factories. */ public interface GraphicsFactory { static final FontMetrics cacheFM[] = new FontMetrics[10]; /** * This method creates Graphics2D instance for specified native window. * * @param win Native window to draw * @param translateX Translation along X axis * @param translateY Translation along Y axis * @param clip Clipping area for a new Graphics2D instance * @return New Graphics2D instance for specified native window * @deprecated */ @Deprecated Graphics2D getGraphics2D(NativeWindow win, int translateX, int translateY, MultiRectArea clip); /** * This method creates Graphics2D instance for specified native window. * * @param win Native window to draw * @param translateX Translation along X axis * @param translateY Translation along Y axis * @param width Width of drawing area * @param height Height of drawing area * @return New Graphics2D instance for specified native window */ Graphics2D getGraphics2D(NativeWindow win, int translateX, int translateY, int width, int height); // ???AWT: not standard harmony Graphics2D getGraphics2D(Canvas c, Paint p); /** * Creates instance of GraphicsEnvironment for specified WindowFactory * * @param wf WindowFactory * @return New instance of GraphicsEnvironment */ GraphicsEnvironment createGraphicsEnvironment(WindowFactory wf); // Font methods FontMetrics getFontMetrics(Font font); FontManager getFontManager(); FontPeer getFontPeer(Font font); Font embedFont(String fontFilePath); }
mehulagg/gitlab-codesanbox
ee/app/assets/javascripts/vue_shared/security_reports/store/state.js
export default () => ({ blobPath: { head: null, base: null, }, sourceBranch: null, canReadVulnerabilityFeedback: false, vulnerabilityFeedbackPath: null, vulnerabilityFeedbackHelpPath: null, createVulnerabilityFeedbackIssuePath: null, createVulnerabilityFeedbackMergeRequestPath: null, createVulnerabilityFeedbackDismissalPath: null, pipelineId: null, containerScanning: { paths: { head: null, base: null, diffEndpoint: null, }, isLoading: false, hasError: false, newIssues: [], resolvedIssues: [], baseReportOutofDate: false, hasBaseReport: false, }, dast: { paths: { head: null, base: null, diffEndpoint: null, }, isLoading: false, hasError: false, newIssues: [], resolvedIssues: [], baseReportOutofDate: false, hasBaseReport: false, scans: [], }, coverageFuzzing: { paths: { head: null, base: null, diffEndpoint: null, }, isLoading: false, hasError: false, newIssues: [], resolvedIssues: [], allIssues: [], baseReportOutofDate: false, hasBaseReport: false, }, dependencyScanning: { paths: { head: null, base: null, diffEndpoint: null, }, isLoading: false, hasError: false, newIssues: [], resolvedIssues: [], allIssues: [], baseReportOutofDate: false, hasBaseReport: false, }, secretScanning: { paths: { head: null, base: null, diffEndpoint: null, }, isLoading: false, hasError: false, newIssues: [], resolvedIssues: [], allIssues: [], baseReportOutofDate: false, hasBaseReport: false, }, modal: { title: null, learnMoreUrl: null, vulnerability: { isDismissed: false, hasIssue: false, hasMergeRequest: false, }, isShowingDeleteButtons: false, isCommentingOnDismissal: false, error: null, }, isCreatingIssue: false, isDismissingVulnerability: false, isCreatingMergeRequest: false, });
minigame-network/core
src/me/chasertw123/minigames/core/utils/items/AbstractItem.java
<reponame>minigame-network/core package me.chasertw123.minigames.core.utils.items; import me.chasertw123.minigames.core.user.User; import org.bukkit.inventory.ItemStack; /** * Created by Chase on 9/2/2017. */ public class AbstractItem { private User pp; private int slot; private ItemStack itemStack; private AbstractAction action; public AbstractItem(ItemStack itemStack, User pp, int slot, AbstractAction action) { this.itemStack = itemStack; this.pp = pp; this.slot = slot; this.action = action; pp.getAbstractItems().put(slot, this); pp.getPlayer().getInventory().setItem(slot, itemStack); } public ItemStack getItemStack() { return itemStack; } public int getSlot() { return slot; } public AbstractAction getAction() { return action; } public interface AbstractAction { void interact(InteractType interactType); } public enum InteractType { LEFT, RIGHT, OTHER } }
kaizer04/Telerik-Academy-2013-2014
JS/Operators-Expressions-Homework/Operators-Expressions-Homework/Task2/scripts.js
<reponame>kaizer04/Telerik-Academy-2013-2014 // 02. Write a boolean expression that checks for given integer if it can be divided (without remainder) by 7 and 5 in the same time. var number = 36; console.log(((number % 7 == 0) && (number % 5 == 0)) ? "The number divides by 7 and 5" : "The number is not divide by 7 and 5");
hainguyen81/nlh4j
modules/core/src/test/java/org/nlh4j/core/text/numberinwords/i18n/en/TestNumberInWordsProcessor.java
/* * @(#)TestNumberInWordsProcessor.java 1.0 Oct 5, 2016 * Copyright 2016 by GNU Lesser General Public License (LGPL). All rights reserved. */ package org.nlh4j.core.text.numberinwords.i18n.en; import java.io.Serializable; import org.junit.Test; /** * Test class of {@link NumberInWordsProcessor} * * @author <NAME> (<EMAIL>) * */ public final class TestNumberInWordsProcessor implements Serializable { /** * serialVersionUID */ private static final long serialVersionUID = 1L; /** * Test {@link NumberInWordsProcessor} */ @Test public static void numberInEnglishWords() { NumberInWordsProcessor processor = new NumberInWordsProcessor(); long[] values = new long[] { 0, 4, 10, 12, 100, 108, 299, 1000, 1003, 2040, 45213, 100000, 100005, 100010, 202020, 202022, 999999, 1000000, 1000001, 10000000, 10000007, 99999999, Long.MAX_VALUE, Long.MIN_VALUE }; String[] strValues = new String[] { "0001.2", "3.141592", "11.00" }; for (long val : values) { System.out.println(val + " = " + processor.getName(val)); } for (String strVal : strValues) { System.out.println(strVal + " = " + processor.getName(strVal)); } // generate a very big number... StringBuilder bigNumber = new StringBuilder(); for (int d = 0; d < 66; d++) { bigNumber.append((char) ((Math.random() * 10) + '0')); } bigNumber.append("."); for (int d = 0; d < 26; d++) { bigNumber.append((char) ((Math.random() * 10) + '0')); } System.out.println(bigNumber.toString() + " = " + processor.getName(bigNumber.toString())); } }
undefinedhuman/OpEngIneX
engine/src/de/undefinedhuman/engine/opengl/shader/uniforms/UniformDirectional.java
package de.undefinedhuman.engine.opengl.shader.uniforms; import de.undefinedhuman.engine.light.DirectionalLight; public class UniformDirectional extends UniformArray { private UniformFloat intensity; private UniformVector3 direction; private UniformVector3 color; public UniformDirectional(String name) { super.setUniforms(intensity = new UniformFloat(name + ".intensity"), direction = new UniformVector3(name + ".direction"), color = new UniformVector3(name + ".color")); } public void loadUniforms(DirectionalLight directionalLight) { this.intensity.loadValue(directionalLight.getIntensity()); this.direction.loadValue(directionalLight.getDirection()); this.color.loadValue(directionalLight.getColor()); } }
arifC/kyma
components/helm-broker/internal/helm/automock/helm_delete_installer.go
// Code generated by mockery v1.0.0 package automock import chart "k8s.io/helm/pkg/proto/hapi/chart" import helm "k8s.io/helm/pkg/helm" import mock "github.com/stretchr/testify/mock" import services "k8s.io/helm/pkg/proto/hapi/services" // HelmDeleteInstaller is an autogenerated mock type for the HelmDeleteInstaller type type HelmDeleteInstaller struct { mock.Mock } // DeleteRelease provides a mock function with given fields: rlsName, opts func (_m *HelmDeleteInstaller) DeleteRelease(rlsName string, opts ...helm.DeleteOption) (*services.UninstallReleaseResponse, error) { _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] } var _ca []interface{} _ca = append(_ca, rlsName) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *services.UninstallReleaseResponse if rf, ok := ret.Get(0).(func(string, ...helm.DeleteOption) *services.UninstallReleaseResponse); ok { r0 = rf(rlsName, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*services.UninstallReleaseResponse) } } var r1 error if rf, ok := ret.Get(1).(func(string, ...helm.DeleteOption) error); ok { r1 = rf(rlsName, opts...) } else { r1 = ret.Error(1) } return r0, r1 } // InstallReleaseFromChart provides a mock function with given fields: _a0, ns, opts func (_m *HelmDeleteInstaller) InstallReleaseFromChart(_a0 *chart.Chart, ns string, opts ...helm.InstallOption) (*services.InstallReleaseResponse, error) { _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] } var _ca []interface{} _ca = append(_ca, _a0, ns) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *services.InstallReleaseResponse if rf, ok := ret.Get(0).(func(*chart.Chart, string, ...helm.InstallOption) *services.InstallReleaseResponse); ok { r0 = rf(_a0, ns, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*services.InstallReleaseResponse) } } var r1 error if rf, ok := ret.Get(1).(func(*chart.Chart, string, ...helm.InstallOption) error); ok { r1 = rf(_a0, ns, opts...) } else { r1 = ret.Error(1) } return r0, r1 }
lixinjian/20170615
ds365-android-commons/src/com/ds365/commons/json/PageParams.java
<filename>ds365-android-commons/src/com/ds365/commons/json/PageParams.java package com.ds365.commons.json; import java.io.Serializable; /** * * @Title: PageVo.java * @Package com.ds365.erp.wms.common.web.vo * @Description: (pageVO) * @author Gavin * @date 2015-1-23 下午4:08:05 * @version V1.0 */ public class PageParams implements Serializable { /** * */ private static final long serialVersionUID = 8715602092889027725L; public PageParams(){ } public PageParams(int start,int limit){ this.start=start; this.limit=limit; } /** * 起始页 */ private int start; /** * 页面大小 */ private int limit; public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } }
noorbeast/blender
intern/cycles/bvh/bvh_multi.h
/* * Copyright 2020, Blender Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __BVH_MULTI_H__ #define __BVH_MULTI_H__ #include "bvh/bvh.h" #include "bvh/bvh_params.h" CCL_NAMESPACE_BEGIN class BVHMulti : public BVH { public: vector<BVH *> sub_bvhs; protected: friend class BVH; BVHMulti(const BVHParams &params, const vector<Geometry *> &geometry, const vector<Object *> &objects); virtual ~BVHMulti(); }; CCL_NAMESPACE_END #endif /* __BVH_MULTI_H__ */
pikesley/skellington
spec/sinatra/app/public_spec.rb
module Skellington describe CLI do let :subject do described_class.new end it 'generates placeholders for static files' do subject.generate 'dummy-app' expect(File).to exist 'dummy_app/public/js/dummy_app.js' expect(File).to exist 'dummy_app/public/assets/favicon.ico' end end end
cactacea/backend
core/src/test/scala/io/github/cactacea/backend/core/domain/repositories/UserChannelsRepositorySpec.scala
package io.github.cactacea.backend.core.domain.repositories import io.github.cactacea.backend.core.domain.enums.{ChannelPrivacyType, MessageType} import io.github.cactacea.backend.core.helpers.specs.RepositorySpec import io.github.cactacea.backend.core.util.exceptions.CactaceaException import io.github.cactacea.backend.core.util.responses.CactaceaErrors.{UserNotFound, UserNotJoined, ChannelAlreadyHidden, ChannelNotHidden, InvalidUserIdError} class UserChannelsRepositorySpec extends RepositorySpec { feature("findOrCreate") { scenario("should return a channel") { forOne(userGen, userGen) { (s, a) => // preparing val sessionId = await(createUser(s.userName)).id.sessionId val userId = await(createUser(a.userName)).id // result // create a channel val result = await(userChannelsRepository.findOrCreate(userId, sessionId)) assert(result.message.isEmpty) assert(result.userCount == 2L) // find a channel val result2 = await(userChannelsRepository.findOrCreate(userId, sessionId)) assert(result2.message.isEmpty) assert(result2.userCount == 2L) } } scenario("should return exception if session id and user id is same.") { forOne(userGen) { (s) => // preparing val sessionId = await(createUser(s.userName)).id.sessionId // result assert(intercept[CactaceaException] { await(userChannelsRepository.findOrCreate(sessionId.userId, sessionId)) }.error == InvalidUserIdError) } } scenario("should return exception if user is blocked.") { forOne(userGen, userGen) { (s, a) => // preparing val sessionId = await(createUser(s.userName)).id.sessionId val userId = await(createUser(a.userName)).id await(blocksRepository.create(sessionId.userId, userId.sessionId)) // result assert(intercept[CactaceaException] { await(userChannelsRepository.findOrCreate(userId, sessionId)) }.error == UserNotFound) } } } feature("delete") { scenario("should hide a channel") { forOne(userGen, channelGen, messageTextGen) { (a, g, m) => // preparing val sessionId = await(createUser(a.userName)).id.sessionId val channelId = await(channelsRepository.create(g.name, g.invitationOnly, g.privacyType, g.authorityType, sessionId)) val message = await(messagesRepository.createText(channelId, m, sessionId)) // result val result1 = await(userChannelsRepository.find(None, 0, 1, false, sessionId)).headOption assert(result1.exists(_.id == channelId)) assert(result1.exists(_.message.exists(_.id == message.id))) await(userChannelsRepository.delete(channelId, sessionId)) val result2 = await(userChannelsRepository.find(None, 0, 1, true, sessionId)).headOption assert(result2.exists(_.id == channelId)) assert(result2.exists(_.message.isEmpty)) } } scenario("should return exception if do not join.") { forOne(userGen, userGen, channelGen) { (s, a, g) => // preparing val sessionId = await(createUser(s.userName)).id.sessionId val userId = await(createUser(a.userName)).id val channelId = await(channelsRepository.create(g.name, g.invitationOnly, g.privacyType, g.authorityType, sessionId)) // result assert(intercept[CactaceaException] { await(userChannelsRepository.delete(channelId, userId.sessionId)) }.error == UserNotJoined) } } } feature("find") { scenario("should return an user`s channels") { forOne(userGen, userGen, messageTextGen, channel20SeqGen) { (s, a1, m, g) => val sessionId = await(createUser(s.userName)).id.sessionId val userId1 = await(createUser(a1.userName)).id val channels = g.map({g => val channelId = await(channelsRepository.create(g.name, g.invitationOnly, ChannelPrivacyType.everyone, g.authorityType, sessionId)) await(channelUsersRepository.create(userId1, channelId, sessionId)) await(messagesRepository.createText(channelId, m, sessionId)) g.copy(id = channelId) }).reverse // page1 found val result1 = await(userChannelsRepository.find(userId1, None, 0, 10, sessionId)) assert(result1.size == 10) result1.zipWithIndex.map { case (r, i) => assert(r.id == channels(i).id) assert(r.message.exists(_.channelId == channels(i).id)) assert(r.message.exists(_.message.getOrElse("") == m)) assert(r.message.exists(_.messageType == MessageType.text)) assert(r.message.exists(_.userCount == 2)) assert(r.message.exists(_.readUserCount == 0)) } // page2 found val size1 = result1.size val result2 = await(userChannelsRepository.find(userId1, result1.lastOption.flatMap(_.next), 0, 10, sessionId)) assert(result2.size == 10) result2.zipWithIndex.map { case (r, i) => assert(r.id == channels(i + size1).id) assert(r.message.exists(_.channelId == channels(i + size1).id)) assert(r.message.exists(_.message.exists(_ == m))) assert(r.message.exists(_.messageType == MessageType.text)) assert(r.message.exists(_.userCount == 2)) assert(r.message.exists(_.readUserCount == 0)) } // page3 not found val result3 = await(userChannelsRepository.find(userId1, result2.lastOption.flatMap(_.next), 0, 10, sessionId)) assert(result3.size == 0) } } scenario("should return error if session id and user id is same.") { forOne(userGen, channelGen) { (s, g) => // preparing val sessionId = await(createUser(s.userName)).id.sessionId await(channelsRepository.create(g.name, g.invitationOnly, g.privacyType, g.authorityType, sessionId)) // result assert(intercept[CactaceaException] { await(userChannelsRepository.find(sessionId.userId, None, 0, 10, sessionId)) }.error == InvalidUserIdError) } } scenario("should return error when user is blocked.") { forOne(userGen, userGen, channelGen) { (s, a, g) => // preparing val sessionId = await(createUser(s.userName)).id.sessionId val userId = await(createUser(a.userName)).id await(blocksRepository.create(sessionId.userId, userId.sessionId)) await(channelsRepository.create(g.name, g.invitationOnly, g.privacyType, g.authorityType, sessionId)) // result assert(intercept[CactaceaException] { await(userChannelsRepository.find(userId, None, 0, 10, sessionId)) }.error == UserNotFound) } } } feature("find session's channels") { scenario("should return channels") { forOne(userGen, messageTextGen, channel20SeqGen) { (s, m, g) => val sessionId = await(createUser(s.userName)).id.sessionId val channels = g.map({g => val channelId = await(channelsRepository.create(g.name, g.invitationOnly, ChannelPrivacyType.everyone, g.authorityType, sessionId)) await(messagesRepository.createText(channelId, m, sessionId)) g.copy(id = channelId) }).reverse // page1 found val result1 = await(userChannelsRepository.find(None, 0, 10, false, sessionId)) assert(result1.size == 10) result1.zipWithIndex.map { case (r, i) => assert(r.id == channels(i).id) assert(r.message.exists(_.channelId == channels(i).id)) assert(r.message.exists(_.message.getOrElse("") == m)) assert(r.message.exists(_.messageType == MessageType.text)) assert(r.message.exists(_.userCount == 1)) assert(r.message.exists(_.readUserCount == 0)) } // page2 found val size1 = result1.size val result2 = await(userChannelsRepository.find(result1.lastOption.flatMap(_.next), 0, 10, false, sessionId)) assert(result2.size == 10) result2.zipWithIndex.map { case (r, i) => assert(r.id == channels(i + size1).id) assert(r.message.exists(_.channelId == channels(i + size1).id)) assert(r.message.exists(_.message.exists(_ == m))) assert(r.message.exists(_.messageType == MessageType.text)) assert(r.message.exists(_.userCount == 1)) assert(r.message.exists(_.readUserCount == 0)) } // page3 not found val result3 = await(userChannelsRepository.find(result2.lastOption.flatMap(_.next), 0, 10, false, sessionId)) assert(result3.size == 0) } } } feature("show") { scenario("should show a channel") { forOne(userGen, channelGen) { (a, g) => // preparing val sessionId = await(createUser(a.userName)).id.sessionId val channelId = await(channelsRepository.create(g.name, g.invitationOnly, g.privacyType, g.authorityType, sessionId)) await(userChannelsRepository.delete(channelId, sessionId)) await(userChannelsRepository.show(channelId, sessionId)) // result val result = await(userChannelsRepository.find(None, 0, 1, false, sessionId)).headOption assert(result.exists(_.id == channelId)) } } scenario("should return exception if do not join.") { forOne(userGen, userGen, channelGen) { (s, a, g) => // preparing val sessionId = await(createUser(s.userName)).id.sessionId val userId = await(createUser(a.userName)).id val channelId = await(channelsRepository.create(g.name, g.invitationOnly, g.privacyType, g.authorityType, sessionId)) // result assert(intercept[CactaceaException] { await(userChannelsRepository.show(channelId, userId.sessionId)) }.error == UserNotJoined) } } scenario("should return exception if a channel is already shown") { forOne(userGen, channelGen) { (a, g) => // preparing val sessionId = await(createUser(a.userName)).id.sessionId val channelId = await(channelsRepository.create(g.name, g.invitationOnly, g.privacyType, g.authorityType, sessionId)) // result assert(intercept[CactaceaException] { await(userChannelsRepository.show(channelId, sessionId)) }.error == ChannelNotHidden) } } } feature("hide") { scenario("should hide a channel") { forOne(userGen, channelGen) { (a, g) => // preparing val sessionId = await(createUser(a.userName)).id.sessionId val channelId = await(channelsRepository.create(g.name, g.invitationOnly, g.privacyType, g.authorityType, sessionId)) await(userChannelsRepository.hide(channelId, sessionId)) // result val result = await(userChannelsRepository.find(None, 0, 1, true, sessionId)).headOption assert(result.exists(_.id == channelId)) } } scenario("should return exception if do not join.") { forOne(userGen, userGen, channelGen) { (s, a, g) => // preparing val sessionId = await(createUser(s.userName)).id.sessionId val userId = await(createUser(a.userName)).id val channelId = await(channelsRepository.create(g.name, g.invitationOnly, g.privacyType, g.authorityType, sessionId)) // result assert(intercept[CactaceaException] { await(userChannelsRepository.hide(channelId, userId.sessionId)) }.error == UserNotJoined) } } scenario("should return exception if a channel is already hidden") { forOne(userGen, channelGen) { (a, g) => // preparing val sessionId = await(createUser(a.userName)).id.sessionId val channelId = await(channelsRepository.create(g.name, g.invitationOnly, g.privacyType, g.authorityType, sessionId)) await(userChannelsRepository.hide(channelId, sessionId)) // result assert(intercept[CactaceaException] { await(userChannelsRepository.hide(channelId, sessionId)) }.error == ChannelAlreadyHidden) } } } }
artanikin/budget
db/migrate/20190802120342_add_owner_at_to_document.rb
class AddOwnerAtToDocument < ActiveRecord::Migration[5.1] def change add_column :documents, :owner_id, :integer add_column :documents, :owner_type, :string end end
dukefirehawk/infinispan
object-filter/src/main/java/org/infinispan/objectfilter/impl/predicateindex/package-info.java
/** * An efficient index for boolean expressions. * * @author <EMAIL> * @since 7.0 * * @api.private */ package org.infinispan.objectfilter.impl.predicateindex;
iootclab/openjdk
openjdk11/test/hotspot/jtreg/runtime/SharedArchiveFile/SASymbolTableTestAgent.java
<reponame>iootclab/openjdk /* * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import sun.jvm.hotspot.memory.SymbolTable; import sun.jvm.hotspot.oops.Symbol; import sun.jvm.hotspot.runtime.VM; import sun.jvm.hotspot.tools.Tool; /** * This class is launched in a sub-process by the main test, * SASymbolTableTest.java. * * It uses SA to connect to another JVM process, whose PID is specified in args[]. * The purpose of the test is to validate that we can walk the SymbolTable * and CompactHashTable of the other process. Everything should work regardless * of whether the other process runs in CDS mode or not. * * Note: CompactHashTable is used only when CDS is enabled. */ public class SASymbolTableTestAgent extends Tool { public SASymbolTableTestAgent() { super(); } public static void main(String args[]) { SASymbolTableTestAgent tool = new SASymbolTableTestAgent(); tool.execute(args); } static String[] commonNames = { "java/lang/Object", "java/lang/String", "java/lang/Class", "java/lang/Cloneable", "java/lang/ClassLoader", "java/io/Serializable", "java/lang/System", "java/lang/Throwable", "java/lang/Error", "java/lang/ThreadDeath", "java/lang/Exception", "java/lang/RuntimeException", "java/lang/SecurityManager", "java/security/ProtectionDomain", "java/security/AccessControlContext", "java/security/SecureClassLoader", "java/lang/ClassNotFoundException", "java/lang/NoClassDefFoundError", "java/lang/LinkageError", "java/lang/ClassCastException", "java/lang/ArrayStoreException", "java/lang/VirtualMachineError", "java/lang/OutOfMemoryError", "java/lang/StackOverflowError", "java/lang/IllegalMonitorStateException", "java/lang/ref/Reference", "java/lang/ref/SoftReference", "java/lang/ref/WeakReference", "java/lang/ref/FinalReference", "java/lang/ref/PhantomReference", "java/lang/ref/Finalizer", "java/lang/Thread", "java/lang/ThreadGroup", "java/util/Properties", "java/lang/reflect/AccessibleObject", "java/lang/reflect/Field", "java/lang/reflect/Method", "java/lang/reflect/Constructor", "java/lang/invoke/MethodHandle", "java/lang/invoke/MemberName", "java/lang/invoke/MethodHandleNatives", "java/lang/invoke/MethodType", "java/lang/BootstrapMethodError", "java/lang/invoke/CallSite", "java/lang/invoke/ConstantCallSite", "java/lang/invoke/MutableCallSite", "java/lang/invoke/VolatileCallSite", "java/lang/StringBuffer", "java/lang/StringBuilder", "java/io/ByteArrayInputStream", "java/io/File", "java/net/URLClassLoader", "java/net/URL", "java/util/jar/Manifest", "java/security/CodeSource", }; static String[] badNames = { "java/lang/badbadbad", "java/io/badbadbadbad", "this*symbol*must*not*exist" }; public void run() { System.out.println("SASymbolTableTestAgent: starting"); try { VM vm = VM.getVM(); SymbolTable table = vm.getSymbolTable(); // (a) These are names that are likely to exist in the symbol table // of a JVM after start-up. They were taken from vmSymbols.hpp // during the middle of JDK9 development. // // The purpose is not to check that each name must exist (a future // version of JDK may not preload some of the classes). // // The purpose of this loops is to ensure that we check a lot of symbols, // so we will (most likely) hit on both VALUE_ONLY_BUCKET_TYPE and normal bucket type // in CompactHashTable.probe(). for (String n : commonNames) { Symbol s = table.probe(n); System.out.format("%-40s = %s\n", n, s); } System.out.println("======================================================================"); // (b) Also test a few strings that are known to not exist in the table. This will // both the compact table (if it exists) and the regular table to be walked. for (String n : badNames) { Symbol s = table.probe(n); System.out.format("%-40s = %s\n", n, s); } } catch (NullPointerException e) { System.out.println("connected too early -- please try again"); } } }
tizenorg/profile.ivi.smartdevicelink
SDL_Android/SmartDeviceLinkProxyAndroid/src/com/smartdevicelink/proxy/rpc/enums/TBTState.java
// // Copyright (c) 2013 Ford Motor Company // package com.smartdevicelink.proxy.rpc.enums; public enum TBTState { ROUTE_CANCELLED, DESTINATION_REACHED, ROUTE_UPDATE_MANUAL, OFF_ROUTE_UPDATE, OFF_ROUTE_DECLINED, ROUTE_ACCEPTED, ROUTE_REFUSED; public static TBTState valueForString(String value) { return valueOf(value); } }
SeraphRoy/PyPy-Functional
pypy/interpreter/unicodehelper.py
<gh_stars>1-10 from pypy.interpreter.error import OperationError from rpython.rlib.objectmodel import specialize from rpython.rlib import runicode from pypy.module._codecs import interp_codecs @specialize.memo() def decode_error_handler(space): # Fast version of the "strict" errors handler. def raise_unicode_exception_decode(errors, encoding, msg, s, startingpos, endingpos): raise OperationError(space.w_UnicodeDecodeError, space.newtuple([space.newtext(encoding), space.newbytes(s), space.newint(startingpos), space.newint(endingpos), space.newtext(msg)])) return raise_unicode_exception_decode @specialize.memo() def encode_error_handler(space): # Fast version of the "strict" errors handler. def raise_unicode_exception_encode(errors, encoding, msg, u, startingpos, endingpos): raise OperationError(space.w_UnicodeEncodeError, space.newtuple([space.newtext(encoding), space.newunicode(u), space.newint(startingpos), space.newint(endingpos), space.newtext(msg)])) return raise_unicode_exception_encode # ____________________________________________________________ def encode(space, w_data, encoding=None, errors='strict'): from pypy.objspace.std.unicodeobject import encode_object return encode_object(space, w_data, encoding, errors) # These functions take and return unwrapped rpython strings and unicodes def decode_unicode_escape(space, string): state = space.fromcache(interp_codecs.CodecState) unicodedata_handler = state.get_unicodedata_handler(space) result, consumed = runicode.str_decode_unicode_escape( string, len(string), "strict", final=True, errorhandler=decode_error_handler(space), unicodedata_handler=unicodedata_handler) return result def decode_raw_unicode_escape(space, string): result, consumed = runicode.str_decode_raw_unicode_escape( string, len(string), "strict", final=True, errorhandler=decode_error_handler(space)) return result def decode_utf8(space, string): # Surrogates are accepted and not treated specially at all. # If there happen to be two 3-bytes encoding a pair of surrogates, # you still get two surrogate unicode characters in the result. # These are the Python2 rules; Python3 differs. result, consumed = runicode.str_decode_utf_8( string, len(string), "strict", final=True, errorhandler=decode_error_handler(space), allow_surrogates=True) return result def encode_utf8(space, uni): # Note that this function never raises UnicodeEncodeError, # since surrogates are allowed, either paired or lone. # A paired surrogate is considered like the non-BMP character # it stands for. These are the Python2 rules; Python3 differs. return runicode.unicode_encode_utf_8( uni, len(uni), "strict", errorhandler=None, allow_surrogates=True)
arnaud-morvan/pyramid_oereb
pyramid_oereb/contrib/data_sources/standard/__init__.py
# -*- coding: utf-8 -*- import re from sqlalchemy.schema import CreateTable from sqlalchemy.dialects import postgresql def convert_camel_case_to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def convert_camel_case_to_text_form(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1 \2', name) return re.sub('([a-z0-9])([A-Z])', r'\1 \2', s1) def tables(base): return base.metadata.sorted_tables def create_schema_sql(schema_name): return 'CREATE SCHEMA IF NOT EXISTS {0};'.format(schema_name) def create_tables_sql(tables_to_create): """ Args: tables_to_create (list of sqlalchemy.schema.Table): The table objects from sqlalchemy. Returns: a string with the sql statement used to create the tables """ sqls = [] for table in tables_to_create: sqls.append( '{};\n'.format( str(CreateTable(table).compile(dialect=postgresql.dialect())).replace('DATETIME', 'timestamp') ) ) return ''.join(sqls) def create_sql(schema_name, tables_to_create): sqls = [ create_schema_sql(schema_name), create_tables_sql(tables_to_create) ] return '\n'.join(sqls)
saulo-alvarado/nimiogcs
nimiogcs-core/src/main/java/es/nimio/nimiogcs/jpa/entidades/operaciones/relaciones/RelacionOperacionSitio.java
package es.nimio.nimiogcs.jpa.entidades.operaciones.relaciones; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import es.nimio.nimiogcs.jpa.entidades.operaciones.Operacion; import es.nimio.nimiogcs.jpa.entidades.sistema.servidores.Servidor; /** * Relaciona una operación con un entorno */ @Entity @Access(AccessType.FIELD) @DiscriminatorValue(value = "SITIO") public class RelacionOperacionSitio extends RelacionOperacion { public RelacionOperacionSitio() { super(); } public RelacionOperacionSitio(Operacion operacion, Servidor sitio) { super(operacion); this.entorno = sitio; } // --------------------------------------------- // Estado // --------------------------------------------- @JoinColumn(name="DESTINO", nullable=false) @OneToOne(fetch=FetchType.EAGER) private Servidor entorno; // --------------------------------------------- // Lectura y escritura estado // --------------------------------------------- public Servidor getSitio() { return entorno; } public void setSitio(Servidor sitio) { this.entorno = sitio; } }
rneogns/simpleio
Library/Deps/MySQL/Include/template_utils.h
<reponame>rneogns/simpleio /* Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TEMPLATE_UTILS_INCLUDED #define TEMPLATE_UTILS_INCLUDED /** Clears a container, but deletes all objects that the elements point to first. @tparam Container of pointers. */ template<typename Container_type> void delete_container_pointers(Container_type &container) { typename Container_type::iterator it1= container.begin(); typename Container_type::iterator it2= container.end(); for (; it1 != it2; ++it1) { delete (*it1); } container.clear(); } /** Clears a container, but frees all objects that the elements point to first. @tparam Container of pointers. */ template<typename Container_type> void my_free_container_pointers(Container_type &container) { typename Container_type::iterator it1= container.begin(); typename Container_type::iterator it2= container.end(); for (; it1 != it2; ++it1) { my_free(*it1); } container.clear(); } /** Casts from one pointer type, to another, without using reinterpret_cast or C-style cast: foo *f; bar *b= pointer_cast<bar*>(f); This avoids having to do: foo *f; bar *b= static_cast<b*>(static_cast<void*>(f)); */ template<typename T> inline T pointer_cast(void *p) { return static_cast<T>(p); } template<typename T> inline const T pointer_cast(const void *p) { return static_cast<const T>(p); } /** Casts from one pointer type to another in a type hierarchy. In debug mode, we verify the cast is indeed legal. */ template<typename Target, typename Source> inline Target down_cast(Source arg) { DBUG_ASSERT(NULL != dynamic_cast<Target>(arg)); return static_cast<Target>(arg); } /** Sometimes the compiler insists that types be the same and does not do any implicit conversion. For example: Derived1 *a; Derived2 *b; // Derived1 and 2 are children classes of Base Base *x= cond ? a : b; // Error, need to force a cast. Use: Base *x= cond ? implicit_cast<Base*>(a) : implicit_cast<Base*>(b); static_cast would work too, but would be less safe (allows any pointer-to-pointer conversion, not only up-casts). */ template<typename To> inline To implicit_cast(To x) { return x; } #endif // TEMPLATE_UTILS_INCLUDED
pierotofy/rosettadrone
app/src/main/cpp/gstreamer-1.0/armv7/include/json-glib-1.0/json-glib/json-path.h
/* json-path.h - JSONPath implementation * * This file is part of JSON-GLib * Copyright © 2011 Intel Corp. * * This library 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 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * Author: * <NAME> <<EMAIL>> */ #ifndef __JSON_PATH_H__ #define __JSON_PATH_H__ #if !defined(__JSON_GLIB_INSIDE__) && !defined(JSON_COMPILATION) #error "Only <json-glib/json-glib.h> can be included directly." #endif #include <json-glib/json-types.h> G_BEGIN_DECLS #define JSON_TYPE_PATH (json_path_get_type ()) #define JSON_PATH(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), JSON_TYPE_PATH, JsonPath)) #define JSON_IS_PATH(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), JSON_TYPE_PATH)) /** * JSON_PATH_ERROR: * * Error domain for #JsonPath errors * * Since: 0.14 */ #define JSON_PATH_ERROR (json_path_error_quark ()) /** * JsonPathError: * @JSON_PATH_ERROR_INVALID_QUERY: Invalid query * * Error code enumeration for the %JSON_PATH_ERROR domain. * * Since: 0.14 */ typedef enum { JSON_PATH_ERROR_INVALID_QUERY } JsonPathError; /** * JsonPath: * * The `JsonPath` structure is an opaque object whose members cannot be * directly accessed except through the provided API. * * Since: 0.14 */ typedef struct _JsonPath JsonPath; /** * JsonPathClass: * * The `JsonPathClass` structure is an opaque object class whose members * cannot be directly accessed. * * Since: 0.14 */ typedef struct _JsonPathClass JsonPathClass; JSON_AVAILABLE_IN_1_0 GType json_path_get_type (void) G_GNUC_CONST; JSON_AVAILABLE_IN_1_0 GQuark json_path_error_quark (void); JSON_AVAILABLE_IN_1_0 JsonPath * json_path_new (void); JSON_AVAILABLE_IN_1_0 gboolean json_path_compile (JsonPath *path, const char *expression, GError **error); JSON_AVAILABLE_IN_1_0 JsonNode * json_path_match (JsonPath *path, JsonNode *root); JSON_AVAILABLE_IN_1_0 JsonNode * json_path_query (const char *expression, JsonNode *root, GError **error); #ifdef G_DEFINE_AUTOPTR_CLEANUP_FUNC G_DEFINE_AUTOPTR_CLEANUP_FUNC (JsonPath, g_object_unref) #endif G_END_DECLS #endif /* __JSON_PATH_H__ */
pppttl/TrackMyMarks
middlewares/course/getAllCoursesMW.js
var requireOption = require('../common').requireOption; /** * Get all the courses * put it on res.tpl */ module.exports = function (objectrepository) { var courseModel = requireOption(objectrepository, 'courseModel'); return function (req, res, next) { if (res.tpl.logToConsole) console.log('getAllCoursesMW'); courseModel.find({ _user: req.session.userid }, function (err, results) { if (err) { return next(new Error('Error getting courses')); } res.tpl.courses = results; return next(); }); }; };
spulec/pep8ify
pep8ify/fixes/fix_tabs.py
from __future__ import unicode_literals from lib2to3.fixer_base import BaseFix from lib2to3.pytree import Leaf from .utils import SPACES class FixTabs(BaseFix): ''' For new projects, spaces-only are strongly recommended over tabs. Most editors have features that make this easy to do. ''' def match(self, node): if node.prefix.count('\t') or (isinstance(node, Leaf) and node.value.count('\t')): return True return False def transform(self, node, results): new_prefix = node.prefix.replace('\t', SPACES) new_value = node.value.replace('\t', SPACES) if node.prefix != new_prefix or node.value != new_value: node.prefix = new_prefix node.value = new_value node.changed()
qwerlarlgus/JS-Basic
javascript_subway_path_precourse/src/utils/Dijkstra.js
<gh_stars>1-10 /* eslint-disable */ export default function Dijkstra() { const Node = { init: function (val, priority) { this.val = val; this.priority = priority; }, }; const PriorityQueue = { init: function () { this.values = []; }, enqueue: function (val, priority) { const newNode = Object.create(Node); newNode.init(val, priority); this.values.push(newNode); let idxOfNewNode = this.values.length - 1; while (idxOfNewNode > 0) { const idxOfParentNode = Math.floor((idxOfNewNode - 1) / 2); const parentNode = this.values[idxOfParentNode]; if (priority < parentNode.priority) { this.values[idxOfParentNode] = newNode; this.values[idxOfNewNode] = parentNode; idxOfNewNode = idxOfParentNode; continue; } break; } return this.values; }, dequeue: function () { if (this.values.length == 0) { return; } const dequeued = this.values.shift(); const lastItem = this.values.pop(); if (!lastItem) { return dequeued; } this.values.unshift(lastItem); let idxOfTarget = 0; while (true) { let idxOfLeftChild = idxOfTarget * 2 + 1; let idxOfRightChild = idxOfTarget * 2 + 2; let leftChild = this.values[idxOfLeftChild]; let rightChild = this.values[idxOfRightChild]; function swap(direction) { const idxOfChild = direction == 'left' ? idxOfLeftChild : idxOfRightChild; const child = direction == 'left' ? leftChild : rightChild; this.values[idxOfChild] = this.values[idxOfTarget]; this.values[idxOfTarget] = child; idxOfTarget = idxOfChild; } if (!leftChild) { return dequeued; } if (!rightChild) { if (leftChild.priority < lastItem.priority) { swap.call(this, 'left'); continue; } return dequeued; } if (leftChild.priority == rightChild.priority) { swap.call(this, 'left'); continue; } if ( leftChild.priority < rightChild.priority && leftChild.priority < lastItem.priority ) { swap.call(this, 'left'); continue; } if ( rightChild.priority < leftChild.priority && rightChild.priority < lastItem.priority ) { swap.call(this, 'right'); continue; } } }, }; const WeightedGraph = { init: function () { this.adjacencyList = {}; this.length = 0; }, addVertex: function (vertex) { if (!this.adjacencyList.hasOwnProperty(vertex)) { this.adjacencyList[vertex] = {}; this.length++; } }, addEdge: function (vertex1, vertex2, weight) { this.addVertex(vertex1); this.addVertex(vertex2); this.adjacencyList[vertex1][vertex2] = weight; this.adjacencyList[vertex2][vertex1] = weight; return this.adjacencyList; }, removeEdge: function (vertex1, vertex2) { if (!this.adjacencyList.hasOwnProperty(vertex1)) { return `There's no ${vertex1}`; } if (!this.adjacencyList.hasOwnProperty(vertex2)) { return `There's no ${vertex2}`; } function removeHelper(v1, v2) { if (!this.adjacencyList.hasOwnProperty(v1)) { return `There's no edge between ${v1} and ${v2}`; } delete this.adjacencyList[v1][v2]; if (Object.keys(this.adjacencyList[v1]).length == 0) { delete this.adjacencyList[v1]; } } removeHelper.call(this, vertex1, vertex2); removeHelper.call(this, vertex2, vertex1); return this.adjacencyList; }, removeVertex: function (vertex) { if (!this.adjacencyList.hasOwnProperty(vertex)) { return `There's no ${vertex}`; } const edges = this.adjacencyList[vertex]; for (const key in edges) { this.removeEdge(key, vertex); } return this.adjacencyList; }, findShortestRoute: function (start, end) { if (!start || !end) { throw Error('출발지와 도착지를 모두 입력해야 합니다.'); } const distance = {}; const previous = {}; const pq = Object.create(PriorityQueue); pq.init(); pq.enqueue(start, 0); const visited = {}; const hashOfVertex = this.adjacencyList; for (const vertexName in hashOfVertex) { const priority = vertexName == start ? 0 : Infinity; distance[vertexName] = priority; previous[vertexName] = null; } while (true) { let current = pq.dequeue(); if (!current?.val) { return; } current = current.val; if (current == end) { break; } const neighbors = hashOfVertex[current]; for (const vertexName in neighbors) { if (visited.hasOwnProperty(vertexName)) { continue; } const distFromStart = distance[current] + neighbors[vertexName]; if (distFromStart < distance[vertexName]) { pq.enqueue(vertexName, distFromStart); distance[vertexName] = distFromStart; previous[vertexName] = current; } } visited[current] = true; } let node = end; const route = []; while (node) { route.unshift(node); node = previous[node]; } return route; }, }; this.addEdge = (source, target, weight) => { WeightedGraph.addEdge(source, target, weight); }; this.findShortestPath = (source, target) => { return WeightedGraph.findShortestRoute(source, target); }; this.addVertex = (vertex) => { WeightedGraph.addVertex(vertex); }; WeightedGraph.init(); }
touxiong88/92_mediatek
packages/apps/iSMS/tests/src/com/hissage/tests/AcNotificationReceiverTest.java
package com.hissage.tests; import android.app.Instrumentation; import android.content.Context; import android.content.Intent; import android.test.InstrumentationTestCase; import com.mediatek.mms.ipmessage.IIpMessagePlugin; import com.mediatek.pluginmanager.PluginManager; import com.mediatek.imsp.ServiceManagerExt; import com.hissage.message.ip.NmsIpMessageConsts; import com.hissage.message.ip.NmsIpMessageConsts.NmsUpdateGroupAction; import com.hissage.message.ip.NmsIpMessageConsts.NmsSaveHistory; import com.hissage.message.ip.NmsIpMessageConsts.NmsIpMessageStatus; import com.hissage.service.NmsService; import com.hissage.contact.NmsContact; import com.hissage.util.data.NmsConsts; import java.util.List; public class AcNotificationReceiverTest extends InstrumentationTestCase { protected Instrumentation mInstrumentation; protected Context mContext; private ServiceManagerExt mServiceManagerExt; @Override protected void setUp() throws Exception { super.setUp(); mInstrumentation = getInstrumentation(); mContext = mInstrumentation.getTargetContext(); mServiceManagerExt = new ServiceManagerExt(mContext); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void test00EnableReceiver() throws Exception { mServiceManagerExt.startIpService(); } public void test01RestartAction() throws Exception { Intent intent = new Intent(); intent.setAction(NmsConsts.NmsIntentStrId.NMS_MMS_RESTART_ACTION); mContext.sendBroadcast(intent); } public void test02ServiceReady() throws Exception { Intent intent = new Intent(); intent.setAction(NmsIpMessageConsts.NMS_INTENT_SERVICE_READY); NmsService.getInstance().sendBroadcast(intent); } public void test03IMStatusAction() throws Exception { Intent intent = new Intent(); NmsContact nc = new NmsContact((short)1, 1, "test", "12345", "case", 1, 0, false); intent.putExtra(NmsIpMessageConsts.NmsImStatus.NMS_CONTACT_CURRENT_STATUS, nc); intent.setAction(NmsIpMessageConsts.NmsImStatus.NMS_IM_STATUS_ACTION); NmsService.getInstance().sendBroadcast(intent); } public void test04StatusAction() throws Exception { Intent intent = new Intent(); intent.putExtra(NmsIpMessageStatus.NMS_IP_MSG_RECD_ID, 1); intent.putExtra(NmsIpMessageStatus.NMS_IP_MSG_SYS_ID, 1); intent.setAction(NmsIpMessageConsts.NmsIpMessageStatus.NMS_MESSAGE_STATUS_ACTION); NmsService.getInstance().sendBroadcast(intent); } public void test05DownloadStatusAction() throws Exception { Intent intent = new Intent(); intent.setAction(NmsIpMessageConsts.NmsDownloadAttachStatus.NMS_DOWNLOAD_ATTACH_STATUS_ACTION); NmsService.getInstance().sendBroadcast(intent); } public void test06DownloadHistory() throws Exception { Intent intent = new Intent(); intent.putExtra(NmsSaveHistory.NMS_DOWNLOAD_HISTORY_DONE, -1); intent.setAction(NmsIpMessageConsts.NmsSaveHistory.NMS_ACTION_DOWNLOAD_HISTORY); NmsService.getInstance().sendBroadcast(intent); } public void test07UpdateGroup() throws Exception { Intent intent = new Intent(); intent.setAction(NmsIpMessageConsts.NmsUpdateGroupAction.NMS_UPDATE_GROUP); intent.putExtra(NmsUpdateGroupAction.NMS_UPDATE_GROUP, 51); intent.putExtra(NmsUpdateGroupAction.NMS_GROUP_ID, 2); NmsService.getInstance().sendBroadcast(intent); } public void test08UpdateContact() throws Exception { Intent intent = new Intent(); intent.setAction(NmsIpMessageConsts.NmsUpdateSystemContactAction.NMS_UPDATE_CONTACT); NmsService.getInstance().sendBroadcast(intent); } public void test09NewMessageAction() throws Exception { Intent intent = new Intent(); intent.setAction(NmsIpMessageConsts.NmsNewMessageAction.NMS_NEW_MESSAGE_ACTION); NmsService.getInstance().sendBroadcast(intent); } }
soulgoast/blog-repository
source_code/src/goodman/com/sun/corba/se/impl/orbutil/closure/Future.java
<reponame>soulgoast/blog-repository /* * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package goodman.com.sun.corba.se.impl.orbutil.closure; import com.sun.corba.se.spi.orbutil.closure.Closure ; public class Future implements Closure { private boolean evaluated ; private Closure closure ; private Object value ; public Future( Closure value ) { this.evaluated = false ; this.closure = (Closure)value ; this.value = null ; } public synchronized Object evaluate() { if (!evaluated) { evaluated = true ; value = closure.evaluate() ; } return value ; } }
mqlight/qpid-proton
proton-j/src/main/java/org/apache/qpid/proton/codec/DecoderImpl.java
<reponame>mqlight/qpid-proton /* * * 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.qpid.proton.codec; import org.apache.qpid.proton.amqp.Binary; import org.apache.qpid.proton.amqp.Decimal128; import org.apache.qpid.proton.amqp.Decimal32; import org.apache.qpid.proton.amqp.Decimal64; import org.apache.qpid.proton.amqp.DescribedType; import org.apache.qpid.proton.amqp.Symbol; import org.apache.qpid.proton.amqp.UnsignedByte; import org.apache.qpid.proton.amqp.UnsignedInteger; import org.apache.qpid.proton.amqp.UnsignedLong; import org.apache.qpid.proton.amqp.UnsignedShort; import java.lang.reflect.Array; import java.nio.ByteBuffer; import java.util.*; public class DecoderImpl implements ByteBufferDecoder { private ByteBuffer _buffer; private PrimitiveTypeEncoding[] _constructors = new PrimitiveTypeEncoding[256]; private Map<Object, DescribedTypeConstructor> _dynamicTypeConstructors = new HashMap<Object, DescribedTypeConstructor>(); public DecoderImpl() { } DecoderImpl(final ByteBuffer buffer) { _buffer = buffer; } TypeConstructor readConstructor() { int code = ((int)readRawByte()) & 0xff; if(code == EncodingCodes.DESCRIBED_TYPE_INDICATOR) { final Object descriptor = readObject(); TypeConstructor nestedEncoding = readConstructor(); DescribedTypeConstructor dtc = _dynamicTypeConstructors.get(descriptor); if(dtc == null) { dtc = new DescribedTypeConstructor() { public DescribedType newInstance(final Object described) { return new UnknownDescribedType(descriptor, described); } public Class getTypeClass() { return UnknownDescribedType.class; } }; register(descriptor, dtc); } return new DynamicTypeConstructor(dtc, nestedEncoding); } else { return _constructors[code]; } } public void register(final Object descriptor, final DescribedTypeConstructor dtc) { _dynamicTypeConstructors.put(descriptor, dtc); } private ClassCastException unexpectedType(final Object val, Class clazz) { return new ClassCastException("Unexpected type " + val.getClass().getName() + ". Expected " + clazz.getName() +"."); } public Boolean readBoolean() { return readBoolean(null); } public Boolean readBoolean(final Boolean defaultVal) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultVal; } else if(val instanceof Boolean) { return (Boolean) val; } throw unexpectedType(val, Boolean.class); } public boolean readBoolean(final boolean defaultVal) { TypeConstructor constructor = readConstructor(); if(constructor instanceof BooleanType.BooleanEncoding) { return ((BooleanType.BooleanEncoding)constructor).readPrimitiveValue(); } else { Object val = constructor.readValue(); if(val == null) { return defaultVal; } else { throw unexpectedType(val, Boolean.class); } } } public Byte readByte() { return readByte(null); } public Byte readByte(final Byte defaultVal) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultVal; } else if(val instanceof Byte) { return (Byte) val; } throw unexpectedType(val, Byte.class); } public byte readByte(final byte defaultVal) { TypeConstructor constructor = readConstructor(); if(constructor instanceof ByteType.ByteEncoding) { return ((ByteType.ByteEncoding)constructor).readPrimitiveValue(); } else { Object val = constructor.readValue(); if(val == null) { return defaultVal; } else { throw unexpectedType(val, Byte.class); } } } public Short readShort() { return readShort(null); } public Short readShort(final Short defaultVal) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultVal; } else if(val instanceof Short) { return (Short) val; } throw unexpectedType(val, Short.class); } public short readShort(final short defaultVal) { TypeConstructor constructor = readConstructor(); if(constructor instanceof ShortType.ShortEncoding) { return ((ShortType.ShortEncoding)constructor).readPrimitiveValue(); } else { Object val = constructor.readValue(); if(val == null) { return defaultVal; } else { throw unexpectedType(val, Short.class); } } } public Integer readInteger() { return readInteger(null); } public Integer readInteger(final Integer defaultVal) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultVal; } else if(val instanceof Integer) { return (Integer) val; } throw unexpectedType(val, Integer.class); } public int readInteger(final int defaultVal) { TypeConstructor constructor = readConstructor(); if(constructor instanceof IntegerType.IntegerEncoding) { return ((IntegerType.IntegerEncoding)constructor).readPrimitiveValue(); } else { Object val = constructor.readValue(); if(val == null) { return defaultVal; } else { throw unexpectedType(val, Integer.class); } } } public Long readLong() { return readLong(null); } public Long readLong(final Long defaultVal) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultVal; } else if(val instanceof Long) { return (Long) val; } throw unexpectedType(val, Long.class); } public long readLong(final long defaultVal) { TypeConstructor constructor = readConstructor(); if(constructor instanceof LongType.LongEncoding) { return ((LongType.LongEncoding)constructor).readPrimitiveValue(); } else { Object val = constructor.readValue(); if(val == null) { return defaultVal; } else { throw unexpectedType(val, Long.class); } } } public UnsignedByte readUnsignedByte() { return readUnsignedByte(null); } public UnsignedByte readUnsignedByte(final UnsignedByte defaultVal) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultVal; } else if(val instanceof UnsignedByte) { return (UnsignedByte) val; } throw unexpectedType(val, UnsignedByte.class); } public UnsignedShort readUnsignedShort() { return readUnsignedShort(null); } public UnsignedShort readUnsignedShort(final UnsignedShort defaultVal) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultVal; } else if(val instanceof UnsignedShort) { return (UnsignedShort) val; } throw unexpectedType(val, UnsignedShort.class); } public UnsignedInteger readUnsignedInteger() { return readUnsignedInteger(null); } public UnsignedInteger readUnsignedInteger(final UnsignedInteger defaultVal) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultVal; } else if(val instanceof UnsignedInteger) { return (UnsignedInteger) val; } throw unexpectedType(val, UnsignedInteger.class); } public UnsignedLong readUnsignedLong() { return readUnsignedLong(null); } public UnsignedLong readUnsignedLong(final UnsignedLong defaultVal) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultVal; } else if(val instanceof UnsignedLong) { return (UnsignedLong) val; } throw unexpectedType(val, UnsignedLong.class); } public Character readCharacter() { return readCharacter(null); } public Character readCharacter(final Character defaultVal) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultVal; } else if(val instanceof Character) { return (Character) val; } throw unexpectedType(val, Character.class); } public char readCharacter(final char defaultVal) { TypeConstructor constructor = readConstructor(); if(constructor instanceof CharacterType.CharacterEncoding) { return ((CharacterType.CharacterEncoding)constructor).readPrimitiveValue(); } else { Object val = constructor.readValue(); if(val == null) { return defaultVal; } else { throw unexpectedType(val, Character.class); } } } public Float readFloat() { return readFloat(null); } public Float readFloat(final Float defaultVal) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultVal; } else if(val instanceof Float) { return (Float) val; } throw unexpectedType(val, Float.class); } public float readFloat(final float defaultVal) { TypeConstructor constructor = readConstructor(); if(constructor instanceof FloatType.FloatEncoding) { return ((FloatType.FloatEncoding)constructor).readPrimitiveValue(); } else { Object val = constructor.readValue(); if(val == null) { return defaultVal; } else { throw unexpectedType(val, Float.class); } } } public Double readDouble() { return readDouble(null); } public Double readDouble(final Double defaultVal) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultVal; } else if(val instanceof Double) { return (Double) val; } throw unexpectedType(val, Double.class); } public double readDouble(final double defaultVal) { TypeConstructor constructor = readConstructor(); if(constructor instanceof DoubleType.DoubleEncoding) { return ((DoubleType.DoubleEncoding)constructor).readPrimitiveValue(); } else { Object val = constructor.readValue(); if(val == null) { return defaultVal; } else { throw unexpectedType(val, Double.class); } } } public UUID readUUID() { return readUUID(null); } public UUID readUUID(final UUID defaultVal) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultVal; } else if(val instanceof UUID) { return (UUID) val; } throw unexpectedType(val, UUID.class); } public Decimal32 readDecimal32() { return readDecimal32(null); } public Decimal32 readDecimal32(final Decimal32 defaultValue) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultValue; } else if(val instanceof Decimal32) { return (Decimal32) val; } throw unexpectedType(val, Decimal32.class); } public Decimal64 readDecimal64() { return readDecimal64(null); } public Decimal64 readDecimal64(final Decimal64 defaultValue) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultValue; } else if(val instanceof Decimal64) { return (Decimal64) val; } throw unexpectedType(val, Decimal64.class); } public Decimal128 readDecimal128() { return readDecimal128(null); } public Decimal128 readDecimal128(final Decimal128 defaultValue) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultValue; } else if(val instanceof Decimal128) { return (Decimal128) val; } throw unexpectedType(val, Decimal128.class); } public Date readTimestamp() { return readTimestamp(null); } public Date readTimestamp(final Date defaultValue) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultValue; } else if(val instanceof Date) { return (Date) val; } throw unexpectedType(val, Date.class); } public Binary readBinary() { return readBinary(null); } public Binary readBinary(final Binary defaultValue) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultValue; } else if(val instanceof Binary) { return (Binary) val; } throw unexpectedType(val, Binary.class); } public Symbol readSymbol() { return readSymbol(null); } public Symbol readSymbol(final Symbol defaultValue) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultValue; } else if(val instanceof Symbol) { return (Symbol) val; } throw unexpectedType(val, Symbol.class); } public String readString() { return readString(null); } public String readString(final String defaultValue) { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return defaultValue; } else if(val instanceof String) { return (String) val; } throw unexpectedType(val, String.class); } public List readList() { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return null; } else if(val instanceof List) { return (List) val; } throw unexpectedType(val, List.class); } public <T> void readList(final ListProcessor<T> processor) { //TODO. } public Map readMap() { TypeConstructor constructor = readConstructor(); Object val = constructor.readValue(); if(val == null) { return null; } else if(val instanceof Map) { return (Map) val; } throw unexpectedType(val, Map.class); } public <T> T[] readArray(final Class<T> clazz) { return null; //TODO. } public Object[] readArray() { return (Object[]) readConstructor().readValue(); } public boolean[] readBooleanArray() { return (boolean[]) ((ArrayType.ArrayEncoding)readConstructor()).readValueArray(); } public byte[] readByteArray() { return (byte[]) ((ArrayType.ArrayEncoding)readConstructor()).readValueArray(); } public short[] readShortArray() { return (short[]) ((ArrayType.ArrayEncoding)readConstructor()).readValueArray(); } public int[] readIntegerArray() { return (int[]) ((ArrayType.ArrayEncoding)readConstructor()).readValueArray(); } public long[] readLongArray() { return (long[]) ((ArrayType.ArrayEncoding)readConstructor()).readValueArray(); } public float[] readFloatArray() { return (float[]) ((ArrayType.ArrayEncoding)readConstructor()).readValueArray(); } public double[] readDoubleArray() { return (double[]) ((ArrayType.ArrayEncoding)readConstructor()).readValueArray(); } public char[] readCharacterArray() { return (char[]) ((ArrayType.ArrayEncoding)readConstructor()).readValueArray(); } public <T> T[] readMultiple(final Class<T> clazz) { Object val = readObject(); if(val == null) { return null; } else if(val.getClass().isArray()) { if(clazz.isAssignableFrom(val.getClass().getComponentType())) { return (T[]) val; } else { throw unexpectedType(val, Array.newInstance(clazz, 0).getClass()); } } else if(clazz.isAssignableFrom(val.getClass())) { T[] array = (T[]) Array.newInstance(clazz, 1); array[0] = (T) val; return array; } else { throw unexpectedType(val, Array.newInstance(clazz, 0).getClass()); } } public Object[] readMultiple() { Object val = readObject(); if(val == null) { return null; } else if(val.getClass().isArray()) { return (Object[]) val; } else { Object[] array = (Object[]) Array.newInstance(val.getClass(), 1); array[0] = val; return array; } } public byte[] readByteMultiple() { return new byte[0]; //TODO. } public short[] readShortMultiple() { return new short[0]; //TODO. } public int[] readIntegerMultiple() { return new int[0]; //TODO. } public long[] readLongMultiple() { return new long[0]; //TODO. } public float[] readFloatMultiple() { return new float[0]; //TODO. } public double[] readDoubleMultiple() { return new double[0]; //TODO. } public char[] readCharacterMultiple() { return new char[0]; //TODO. } public Object readObject() { TypeConstructor constructor = readConstructor(); if(constructor== null) { throw new DecodeException("Unknown constructor"); } return constructor instanceof ArrayType.ArrayEncoding ? ((ArrayType.ArrayEncoding)constructor).readValueArray() : constructor.readValue(); } public Object readObject(final Object defaultValue) { Object val = readObject(); return val == null ? defaultValue : val; } <V> void register(PrimitiveType<V> type) { Collection<? extends PrimitiveTypeEncoding<V>> encodings = type.getAllEncodings(); for(PrimitiveTypeEncoding<V> encoding : encodings) { _constructors[((int) encoding.getEncodingCode()) & 0xFF ] = encoding; } } byte readRawByte() { return _buffer.get(); } int readRawInt() { return _buffer.getInt(); } long readRawLong() { return _buffer.getLong(); } short readRawShort() { return _buffer.getShort(); } float readRawFloat() { return _buffer.getFloat(); } double readRawDouble() { return _buffer.getDouble(); } void readRaw(final byte[] data, final int offset, final int length) { _buffer.get(data, offset, length); } <V> V readRaw(TypeDecoder<V> decoder, int size) { V decode = decoder.decode((ByteBuffer) _buffer.slice().limit(size)); _buffer.position(_buffer.position()+size); return decode; } public void setByteBuffer(final ByteBuffer buffer) { _buffer = buffer; } interface TypeDecoder<V> { V decode(ByteBuffer buf); } private static class UnknownDescribedType implements DescribedType { private final Object _descriptor; private final Object _described; public UnknownDescribedType(final Object descriptor, final Object described) { _descriptor = descriptor; _described = described; } public Object getDescriptor() { return _descriptor; } public Object getDescribed() { return _described; } @Override public boolean equals(Object obj) { return obj instanceof DescribedType && _descriptor == null ? ((DescribedType) obj).getDescriptor() == null : _descriptor.equals(((DescribedType) obj).getDescriptor()) && _described == null ? ((DescribedType) obj).getDescribed() == null : _described.equals(((DescribedType) obj).getDescribed()); } } public int getByteBufferRemaining() { return _buffer.remaining(); } }
fortune/Hello-Shindig
extras/src/main/java/org/apache/shindig/extras/as/opensocial/model/MediaLink.java
<reponame>fortune/Hello-Shindig<filename>extras/src/main/java/org/apache/shindig/extras/as/opensocial/model/MediaLink.java /* * 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.shindig.extras.as.opensocial.model; import org.apache.shindig.protocol.model.Exportablebean; import org.apache.shindig.extras.as.core.model.MediaLinkImpl; import com.google.inject.ImplementedBy; /* * TODO: comment this class. */ /** * <p>MediaLink interface.</p> * */ @ImplementedBy(MediaLinkImpl.class) @Exportablebean public interface MediaLink { /** * Fields that represent the JSON elements. */ public static enum Field { TARGET("target"), TYPE("type"), WIDTH("width"), HEIGHT("height"), DURATION("duration"); /** * The name of the JSON element. */ private final String jsonString; /** * Constructs the field base for the JSON element. * * @param jsonString the name of the element */ private Field(String jsonString) { this.jsonString = jsonString; } /** * Returns the name of the JSON element. * * @return String the name of the JSON element */ public String toString() { return jsonString; } } /** * Returns the target of this MediaLink * * @return a target */ String getTarget(); /** * Sets the target for this MediaLink * * @param target a target linke */ void setTarget(String target); /** * Returns the type of the MediaLink * * @return a type */ String getType(); /** * Sets the type of the MediaLink * * @param type a type */ void setType(String type); /** * <p>getWidth</p> * * @return a {@link java.lang.String} object. */ String getWidth(); /** * Sets the Width of this mediaLink * * @param width a width */ void setWidth(String width); /** * Sets the Height of this mediaLink * * @return a height */ String getHeight(); /** * Sets the Height of this mediaLink * * @param height a height */ void setHeight(String height); /** * Returns the duration of this mediaLink * * @return a duration */ String getDuration(); /** * Sets the duration of this mediaLink * * @param duration a duration */ void setDuration(String duration); }
kishorevarma369/Competitive-Programming
testing/24.cpp
#include <bits/stdc++.h> using namespace std; void func() { int n; cin>>n; vector<int> v(n); for(int i=0;i<n;i++) cin>>v[i]; queue<int> q; sort(v.begin(), v.end()); q.push(v[0]); for (int i = 1; i < n; i++) { int now = q.front(); if (v[i] > now) q.pop(); q.push(v[i]); } cout<<q.size()<<'\n'; } int main() { int t; cin>>t; while(t--) func(); return 0; }
eloigrndl/mini-projet2
java/ch/epfl/cs107/play/game/areagame/actor/Interactor.java
<reponame>eloigrndl/mini-projet2 package ch.epfl.cs107.play.game.areagame.actor; import ch.epfl.cs107.play.math.DiscreteCoordinates; import java.util.List; /** * Models objects asking for interaction (i.e. can interact with some Interactable) * @see Interactable * This interface makes sense only in the "Area Context" with Actor contained into Area Cell */ public interface Interactor { /** * Un 'Interactor' occupe une liste de cellules * @return (List<DiscreteCoordinates>) */ List <DiscreteCoordinates> getCurrentCells(); /** * Les cellules dans le champ de vision de l'Interactor * @return (List<DiscreteCoordinates>) */ List<DiscreteCoordinates> getFieldOfViewCells(); /** * Self-explanatory. * @return (boolean) */ boolean wantsCellInteraction(); /** * Self-explanatory. * @return (boolean) */ boolean wantsViewInteraction(); /** * Method for an Interactor to interract with an Interactable * @param other Interactable with which we "work" */ void interactWith(Interactable other); }
libwifi/libwifi
src/libwifi/core/frame/frame.c
/* Copyright 2021 The libwifi Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "frame.h" #include "../../parse/misc/radiotap.h" #include "../misc/byteswap.h" #include "../radiotap/radiotap.h" #include <errno.h> #include <stdlib.h> #include <string.h> /* * Turn sniffed data into a libwifi_frame struct for use with other libwifi functions. * * Supported frames: * - Management Frames (Ordered) * - Management Frames (Unordered) * - Data Frames * - QoS Data Frames * - Control Frames */ int libwifi_get_wifi_frame(struct libwifi_frame *fi, const unsigned char *frame, size_t frame_len, int radiotap) { union libwifi_frame_header fh = {0}; size_t header_len = 0; size_t frame_data_len = frame_len; const unsigned char *frame_data = frame; if (radiotap) { struct libwifi_radiotap_info rtap_info = {0}; int ret = libwifi_parse_radiotap_info(&rtap_info, frame, frame_len); if (ret != 0) { return ret; } // Skip forward by the length of the radiotap header frame_data_len -= rtap_info.length; frame_data += rtap_info.length; // Remove the FCS from the end of the frame data, if present if (rtap_info.flags & IEEE80211_RADIOTAP_F_FCS) { fi->flags |= LIBWIFI_FLAGS_FCS_PRESENT; frame_data_len -= sizeof(uint32_t); // FCS is 4 bytes wide } } struct libwifi_frame_ctrl *frame_control = (struct libwifi_frame_ctrl *) frame_data; switch (frame_control->type) { case TYPE_DATA: switch (frame_control->subtype) { case SUBTYPE_DATA_QOS_DATA: case SUBTYPE_DATA_QOS_NULL: case SUBTYPE_DATA_QOS_DATA_CF_ACK: case SUBTYPE_DATA_QOS_DATA_CF_ACK_CF_POLL: case SUBTYPE_DATA_QOS_DATA_CF_POLL: case SUBTYPE_DATA_QOS_CF_ACK_CF_POLL: case SUBTYPE_DATA_QOS_CF_POLL: fi->flags |= LIBWIFI_FLAGS_IS_QOS; break; } if (fi->flags & LIBWIFI_FLAGS_IS_QOS) { header_len = sizeof(struct libwifi_data_qos_frame_header); } else { header_len = sizeof(struct libwifi_data_frame_header); } if (frame_data_len < header_len) { return -EINVAL; } if (fi->flags & LIBWIFI_FLAGS_IS_QOS) { memset(&fh.data_qos, 0, sizeof(struct libwifi_data_qos_frame_header)); memcpy(&fh.data_qos, frame_data, sizeof(struct libwifi_data_qos_frame_header)); } else { memset(&fh.data, 0, sizeof(struct libwifi_data_frame_header)); memcpy(&fh.data, frame_data, sizeof(struct libwifi_data_frame_header)); } break; case TYPE_MANAGEMENT: if (frame_control->flags.ordered) { fi->flags |= LIBWIFI_FLAGS_IS_ORDERED; header_len = sizeof(struct libwifi_mgmt_ordered_frame_header); if (frame_data_len < header_len) { return -EINVAL; } memcpy(&fh.mgmt_ordered, frame_data, header_len); } else { header_len = sizeof(struct libwifi_mgmt_unordered_frame_header); if (frame_data_len < header_len) { return -EINVAL; } memcpy(&fh.mgmt_unordered, frame_data, header_len); } break; case TYPE_CONTROL: header_len = sizeof(struct libwifi_ctrl_frame_header); if (frame_data_len < header_len) { return -EINVAL; } memcpy(&fh.ctrl, frame_data, sizeof(struct libwifi_ctrl_frame_header)); break; default: return -EINVAL; } fi->len = frame_data_len; fi->header = fh; fi->header_len = header_len; memcpy(&fi->frame_control, frame_control, sizeof(struct libwifi_frame_ctrl)); fi->body = malloc(fi->len - fi->header_len); if (fi->body == NULL) { return -ENOMEM; } memcpy(fi->body, frame_data + header_len, (fi->len - fi->header_len)); return 0; } void libwifi_free_wifi_frame(struct libwifi_frame *fi) { free(fi->body); }
ark100/multi-os-engine
moe/tools/moe.plugin.gradle/src/main/java/org/moe/gradle/options/PackagingOptions.java
<filename>moe/tools/moe.plugin.gradle/src/main/java/org/moe/gradle/options/PackagingOptions.java /* Copyright (C) 2016 Migeran Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.moe.gradle.options; import org.moe.gradle.anns.IgnoreUnused; import org.moe.gradle.anns.NotNull; import org.moe.gradle.utils.Require; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; public class PackagingOptions { @NotNull private List<String> excludes = new ArrayList<>(Arrays.asList( "LICENSE", "LICENSE.*", "META-INF/LICENSE", "META-INF/LICENSE.*", "NOTICE", "NOTICE.*", "META-INF/NOTICE", "META-INF/NOTICE.*", "**/.*")); @NotNull public List<String> getExcludes() { return Require.nonNull(excludes); } @IgnoreUnused public void setExcludes(@NotNull Collection<String> excludes) { this.excludes = new ArrayList<>(Require.nonNull(excludes)); } @NotNull @IgnoreUnused public PackagingOptions exclude(String... names) { excludes.addAll(Arrays.asList(Require.nonNull(names))); return this; } }
tlgs/dailyprogrammer
Python/easy/e312.py
# 25/04/2017 mapping = {'A': '4', 'B': '6', 'E': '3', 'I': '1', 'L': '1', 'M': '(V)', 'N': '(\\)', 'O': '0', 'S': '5', 'T': '7', 'V':'\\/', 'W': '`//'} def from_l33t(string): for k, v in mapping.items(): string = string.replace(v, k) return string[0].upper() + string[1:].lower() def to_l33t(string): return ''.join([c if c.upper() not in mapping else mapping[c.upper()] for c in string]).upper()
stonef13/grace-shopper
server/api/admin.js
<gh_stars>1-10 const router = require('express').Router() const isAuthorized = require('./gatekeeper') const {Product, Attribute} = require('../db/models') const {createAssociations, updateAssociations} = require('./utility') module.exports = router /** * POST a new product to the database, * requires administrative access * @param {Object} req.body - requires {name, price}, can accept {description, stock=0, imageUrl} */ router.post('/products', isAuthorized, async (req, res, next) => { try { if (req.user.type !== 'admin') { res.sendStatus(401) } else { const {name, price, description, stock, imageUrl} = req.body const newProduct = await Product.create({ name, price, description, stock, imageUrl }) await createAssociations(newProduct.id, req.body.attributes) res.json(newProduct) } } catch (err) { next(err) } }) /** * PUT new data onto an existing product by id, * requires administrative access * @param {Object} req.body - can accept {name, price, description, stock=0, imageUrl} and should pass in unchanged values */ router.put('/products/:id', isAuthorized, async (req, res, next) => { /* NOTE: PUT route contains minor bug: * Can update existing attribute * associations, but cannot add new ones */ try { const {name, price, description, stock, imageUrl} = req.body const [numberOfAffectedRows, affectedRows] = await Product.update( {name, price, description, stock, imageUrl}, { where: {id: req.params.id}, returning: true, plain: true } ) const updatedProduct = affectedRows console.log('attributes received: ', req.body.attributes) updateAssociations(updatedProduct.id, req.body.attributes) updatedProduct ? res.json(updatedProduct) : res.sendStatus(304) } catch (err) { console.log(err) next(err) } }) router.delete('/products/:id', isAuthorized, async (req, res, next) => { try { await Product.destroy({where: {id: req.params.id}}) res.sendStatus(204) } catch (err) { next(err) } })
LaudateCorpus1/go3mf
production/encoder_test.go
<gh_stars>10-100 // © Copyright 2021 HP Development Company, L.P. // SPDX-License Identifier: BSD-2-Clause package production import ( "testing" "github.com/go-test/deep" "github.com/hpinc/go3mf" "github.com/hpinc/go3mf/spec" ) func TestMarshalModel(t *testing.T) { components := &go3mf.Object{ AnyAttr: spec.AnyAttr{&ObjectAttr{UUID: "cb828680-8895-4e08-a1fc-be63e033df15"}}, ID: 20, Components: &go3mf.Components{Component: []*go3mf.Component{{ ObjectID: 8, AnyAttr: spec.AnyAttr{&ComponentAttr{ Path: "/3D/other.model", UUID: "cb828680-8895-4e08-a1fc-be63e033df16", }}}, }}, } m := &go3mf.Model{Path: "/3D/3dmodel.model", Build: go3mf.Build{ AnyAttr: spec.AnyAttr{&BuildAttr{UUID: "e9e25302-6428-402e-8633-cc95528d0ed3"}}, }} m.Resources = go3mf.Resources{Objects: []*go3mf.Object{components}} m.Build.Items = append(m.Build.Items, &go3mf.Item{ObjectID: 20, AnyAttr: spec.AnyAttr{&ItemAttr{UUID: "e9e25302-6428-402e-8633-cc95528d0ed2"}}, }, &go3mf.Item{ObjectID: 8, AnyAttr: spec.AnyAttr{&ItemAttr{ Path: "/3D/other.model", UUID: "e9e25302-6428-402e-8633-cc95528d0ed4", }}, }) m.Extensions = []go3mf.Extension{DefaultExtension} b, err := go3mf.MarshalModel(m) if err != nil { t.Errorf("production.MarshalModel() error = %v", err) return } newModel := new(go3mf.Model) newModel.Path = m.Path if err := go3mf.UnmarshalModel(b, newModel); err != nil { t.Errorf("production.MarshalModel() error decoding = %v, s = %s", err, string(b)) return } if diff := deep.Equal(m, newModel); diff != nil { t.Errorf("production.MarshalModel() = %v, s = %s", diff, string(b)) } }
malmil/frontend-components
src/components/Tabs/TabItem/TabItem.js
import * as React from 'react'; import PropTypes from 'prop-types'; export default class TabItem extends React.PureComponent { static propTypes = { /** @deprecated Teksten på arkfanen */ linkText: PropTypes.string, /** Teksten på arkfanen */ headerText: PropTypes.string, /** Unik identifikator av arkfanen */ itemKey: PropTypes.string, /** Ikon på arkfanen */ itemIcon: PropTypes.string, /** Teller på arkfanen */ itemCount: PropTypes.number, /** Overstyring av stiler */ className: PropTypes.string }; static defaultProps = { itemIcon: undefined }; render() { const { linkText, headerText, itemIcon, itemCount, itemKey, children, className, ...props } = this.props; return ( <div linkText={linkText} headerText={headerText} itemIcon={itemIcon} itemCount={itemCount} itemKey={itemKey} {...props} className={className} ></div> ); } }
Frezc/react-redux-project
src/maintain/containers/CompanyModal/index.js
<gh_stars>0 /** * Created by Frezc on 2016/11/16. */ import React, { PureComponent, PropTypes } from 'react'; import { connect } from 'react-redux'; import { easyGet, api, easyPost } from '../../../network'; import { Modal, message, Spin, Form, Input, Radio, Collapse } from 'antd'; const FormItem = Form.Item; const { Group: RadioGroup, Button: RadioButton } = Radio; const Panel = Collapse.Panel; import EasyImgUpload from '../../../components/EasyImgUpload'; import { closeCompanyModal } from '../../actions/common'; import auth from '../../configs/jwtAuth'; import { Link } from 'react-router'; import { formItemLayout } from '../../configs/constants'; import './style.scss'; class CompanyModal extends PureComponent { static propTypes = { visible: PropTypes.bool, id: PropTypes.number }; static defaultProps = { visible: false, id: -1 }; state = { loading: false, confirmLoading: false, data: {} }; handleSave = () => { const { form, id } = this.props; form.validateFields((err, values) => { if (!err) { this.setState({ confirmLoading: true }); easyPost(`${api.companies}/${id}`, values) .then(json => { message.success('保存成功'); }) .catch(() => { }) .then(() => this.setState({ confirmLoading: false })) } }); }; componentWillReceiveProps(nextProps) { if (nextProps.visible && nextProps.id > 0 && nextProps.id != this.props.id) { this.setState({ loading: true }); easyGet(`${api.companies}/${nextProps.id}`) .then(json => { this.setState({ data: json }); this.props.form.resetFields(); }) .catch(() => { }) .then(() => this.setState({ loading: false })) } } render() { const { visible, closeCompanyModal, form, id } = this.props; const { data, loading, confirmLoading } = this.state; const { name, url, address, logo, description, contact, contact_person } = data; const { getFieldDecorator } = form; const token = auth.getAuthSync().token; return ( <Modal title={`企业信息(id: ${id})`} visible={visible} onCancel={closeCompanyModal} wrapClassName="company-modal" okText="保存" onOk={this.handleSave} confirmLoading={confirmLoading} > <Spin spinning={loading}> <Form> <FormItem {...formItemLayout} label="名称" hasFeedback > <Input value={name} readOnly/> </FormItem> <FormItem {...formItemLayout} label="主页" hasFeedback > {getFieldDecorator('url', { initialValue: url })( <Input /> )} </FormItem> <FormItem {...formItemLayout} label="地址" hasFeedback > {getFieldDecorator('address', { rules: [{ required: true, message: '不能为空!' }], initialValue: address })( <Input /> )} </FormItem> <FormItem {...formItemLayout} label="联系人" hasFeedback > {getFieldDecorator('contact_person', { rules: [{ required: true, message: '不能为空!' }], initialValue: contact_person })( <Input /> )} </FormItem> <FormItem {...formItemLayout} label="联系方式" hasFeedback > {getFieldDecorator('contact', { rules: [{ required: true, message: '不能为空!' }], initialValue: contact })( <Input /> )} </FormItem> <FormItem {...formItemLayout} label="描述" hasFeedback > {getFieldDecorator('description', { initialValue: description })( <Input /> )} </FormItem> <FormItem {...formItemLayout} label="logo" > {getFieldDecorator('logo', { valuePropName: 'imgUrl', initialValue: logo })( <EasyImgUpload name="file" action={api.imgUpload} token={token} /> )} </FormItem> </Form> </Spin> <Collapse bordered={true}> <Panel header="其他" key="1"> <Link to={{ pathname: '/m/am/company', query: { company_id: id, status: 2 } }} target="_blank"> 查看该企业的认证信息 </Link> {','} <Link to={{ pathname: '/m/um/user_profiles', query: { company_id: id } }} target="_blank"> 查看该企业下的用户信息 </Link> {','} <Link to={{ pathname: '/m/um/jobs', query: { company_id: id } }} target="_blank"> 查看该企业下的岗位信息 </Link> </Panel> </Collapse> </Modal> ) } } function select(state, ownProps) { return state.companyModal; } export default connect(select, { closeCompanyModal })(Form.create()(CompanyModal));
abuasifkhan/pc-code
solved/r-t/the-unreal-tournament/unreal.cpp
<filename>solved/r-t/the-unreal-tournament/unreal.cpp #include <cstdio> #include <cstring> #include <vector> using namespace std; #define MAXI 1000 #define MAXJ 1000 #define EPS (1e-9) #define Zero(v) memset((v), 0, sizeof(v)) #define RFor(t,i,c) for(t::reverse_iterator i=(c).rbegin(); i!=(c).rend(); ++i) typedef vector<int> IV; typedef IV::iterator IVi; // // Big Integer // #define BIBAS 1000 #define BIDIG 3 #define BIFMT "%03d" struct BigInt { IV d; bool sgn; BigInt(int n=0) { if (n < 0) sgn = true, n = -n; else sgn = false; if (n < BIBAS) d.push_back(n); else while (n != 0) { d.push_back(n % BIBAS); n /= BIBAS; } } size_t len() const { return d.size(); } bool is_zero() const { return len() == 1 && d[0] == 0; } void flip() { sgn = !sgn; } BigInt neg() const { BigInt x = *this; x.flip(); return x; } void clean() { IVi i; for (i=d.end()-1; *i == 0 && i != d.begin(); i--); d.erase(i+1, d.end()); if (sgn && d.size() == 1 && d[0] == 0) sgn = false; } bool operator==(const BigInt &b) const { return sgn == b.sgn && d == b.d; } bool operator<(const BigInt &b) const { if (sgn != b.sgn) return sgn; if (len() != b.len()) return sgn ^ (len() < b.len()); for (int i = len() - 1; i >= 0; --i) if (d[i] != b.d[i]) return sgn ^ (d[i] < b.d[i]); return false; } BigInt &operator+=(const BigInt &b) { if (sgn != b.sgn) { (*this) -= b.neg(); return *this; } int s1 = len(), s2 = b.len(), s3 = max(s1, s2) + 1; IV res(s3); int c = 0; for (int i = 0; i < s3; ++i) { int sum = c; sum += i < s1 ? d[i] : 0; sum += i < s2 ? b.d[i] : 0; if (sum >= BIBAS) { c = sum / BIBAS; sum %= BIBAS; } else c = 0; res[i] = sum; } d = res; clean(); return *this; } BigInt &operator-=(const BigInt &_b) { if (sgn != _b.sgn) { (*this) += _b.neg(); return *this; } bool sbk = sgn; sgn = false; BigInt b = _b.sgn ? _b.neg() : _b; if (*this < b) { b -= *this; *this = sbk ? b : b.neg(); return *this; } int s1 = len(), s2 = b.len(), s3 = s1; IV res(s3); int c = 0; for (int i = 0; i < s3; ++i) { int sum = d[i] - (i < s2 ? b.d[i] : 0) - c; if (sum < 0) { sum += BIBAS; c = 1; } else c = 0; res[i] = sum; } d = res; sgn = sbk; clean(); return *this; } BigInt &operator*=(const BigInt &b) { int s1 = len(), s2 = b.len(), s3 = s1+s2; IV res(s3); int c = 0; for (int k=0; k < s3; ++k) { int sum = c; for (int i=max(0,k-s2+1), I=min(k+1, s1), j=k-i; i < I; ++i, --j) sum += d[i] * b.d[j]; if (sum >= BIBAS) { c = sum / BIBAS; sum %= BIBAS; } else c = 0; res[k] = sum; } d = res; sgn ^= b.sgn; clean(); return *this; } BigInt &short_div(int b) { for (int r = 0, i = len() - 1; i >= 0; --i) r = r*BIBAS + d[i], d[i] = r / b, r %= b; clean(); return *this; } BigInt &operator/=(const BigInt &b) { if (b.is_zero()) { int x=0; return *this=BigInt(x/x); } sgn ^= b.sgn; size_t l = len(), n = b.len(); if (n == 1) return short_div(b.d[0]); if (l < n || (l == n && d.back() < b.d.back())) return *this = BigInt(0); BigInt r(0); IV res(l); for (int i = l - 1; i >= 0; --i) { r.d.insert(r.d.begin(), d[i]); r.clean(); int x = r.len() >= n ? r.d[n-1] : 0; if (r.len() > n) x += BIBAS * r.d[n]; int q = x / b.d[n-1]; BigInt g = b; g *= BigInt(q); while (r < g) g -= b, --q; res[i] = q, r -= g; } d = res; clean(); return *this; } void print(bool nl = true) { if (sgn) putchar('-'); bool flg = true; RFor (IV, i, d) { if (flg) { printf("%d", *i); flg=false; } else printf(BIFMT, *i); } if (nl) putchar('\n'); } }; double p, q; int N; double P[MAXI + 1][MAXJ + 1]; bool vis[MAXI + 1][MAXJ + 1]; BigInt calls; BigInt fact[MAXI + MAXJ + 1]; void calc_p(int i, int j) { if (vis[i][j]) return; double &ans = P[i][j]; if (i == 0 && j == 0) ans = -1; else if (i == 0) ans = 1; else if (j == 0) ans = 0; else { calc_p(i - 1, j); calc_p(i, j - 1); ans = p*P[i-1][j] + q*P[i][j-1]; } vis[i][j] = true; } void calc_calls(int i, int j) { if (i == 0 && j == 0) { calls = 0; return; } calls = fact[i + j]; BigInt den = fact[i]; den *= fact[j]; calls /= den; calls *= 2; calls -= 2; } void prepare() { fact[0] = 1; for (int i = 1, I = MAXI + MAXJ; i <= I; ++i) { fact[i] = i; fact[i] *= fact[i - 1]; } } int main() { prepare(); bool first = true; while (true) { scanf("%lf %d", &p, &N); if (N == 0) break; q = 1 - p; if (first) first = false; else putchar('\n'); Zero(vis); while (N--) { int i, j; scanf("%d%d", &i, &j); calc_p(i, j); calc_calls(i, j); printf("%.5lf\n", P[i][j] + EPS); calls.print(); } } return 0; }
taulinger/bav4-nomigration
src/modules/commons/components/checkbox/Checkbox.js
import { html } from 'lit-html'; import { MvuElement } from '../../../MvuElement'; import css from './checkbox.css'; const Update_Disabled = 'update_disabled'; const Update_Checked = 'update_checked'; const Update_Title = 'update_title'; /** * Events: * - onToggle() * * Properties: * - `checked` * - `disabled` * - `title` * * * @class * @author alsturm * @author taulinger */ export class Checkbox extends MvuElement { constructor() { super({ checked: false, disabled: false, title: '' }); } /** * @override */ onInitialize() { this._onToggle = () => { }; this.addEventListener('click', (event) => { this._click(); event.stopPropagation(); }); this.addEventListener('keydown', (event) => { //handle Enter and Space events if (event.key === 'Enter' || event.key === ' ') { this._click(); event.preventDefault(); event.stopPropagation(); } }); } update(type, data, model) { switch (type) { case Update_Checked: return { ...model, checked: data }; case Update_Disabled: return { ...model, disabled: data }; case Update_Title: return { ...model, title: data }; } } /** * @override */ createView(model) { const { title, disabled, checked } = model; const onChange = (event) => { const checked = event.target.checked; this.signal(Update_Checked, checked); this.dispatchEvent(new CustomEvent('toggle', { detail: { checked: checked } })); this._onToggle(event); }; return html` <style>${css}</style> <input @change=${onChange} class="input" id="cbx" type="checkbox" style="display: none;" ?disabled=${disabled} .checked=${checked} /> <label title='${title}' class="ba-checkbox" > <span> <svg width="100%" height="100%" viewbox="0 0 12 9"> <polyline points="1 5 4 8 11 1"></polyline> </svg> </span> <span> <slot></slot> </span> </label> `; } static get tag() { return 'ba-checkbox'; } _click() { this._root.querySelector('#cbx').click(); } /** * @property {string} title='' - The title of the button */ set title(value) { this.signal(Update_Title, value); } get title() { return this.getModel().title; } /** * @property {boolean} disabled=false - Checkbox clickable? */ set disabled(value) { this.signal(Update_Disabled, value); } get disabled() { return this.getModel().disabled; } /** * @property {boolean} checked=false - Checkbox checked? */ set checked(value) { this.signal(Update_Checked, value); } get checked() { return this.getModel().checked; } /** * @property {function} onToggle - Callback function */ set onToggle(callback) { this._onToggle = callback; } get onToggle() { return this._onToggle; } }
Ahmedaltayyar/broadcast
node_modules/goodparts/test/fixtures/callback-return.pass.js
function foo(err, callback) { if (err) { return callback(err); } }
varijkapil13/atlaskit
packages/core/comment/src/styled/HeaderStyles.js
<reponame>varijkapil13/atlaskit<gh_stars>1-10 // @flow import styled from 'styled-components'; import { colors, gridSize } from '@atlaskit/theme'; const ThemeColor = { Restricted: { text: colors.N100A, }, }; export const BulletSpacer = styled.span` padding-right: ${gridSize() / 2}px; `; export const Restricted = styled.div` color: ${ThemeColor.Restricted.text}; display: flex; `; export const RestrictedIconWrapper = styled.span` margin-right: ${gridSize() / 2}px; `; RestrictedIconWrapper.displayName = 'RestrictedIconWrapper'; export const TopItem = styled.div` display: inline-block; margin-left: ${gridSize()}px; [dir='rtl'] & { margin-left: 0; margin-right: ${gridSize()}px; } &:first-child { margin-left: 0; [dir='rtl'] & { margin-right: 0; } } `; export const TopItemsContainer = styled.div` display: flex; `;
valentinvarbanov/software_engineering_2021
homework_03/07_gergana_roeva/hw03.py
from enum import Enum from math import sqrt class RelativePosition(Enum): NO_COMMON_POINTS = 1 TOUCHING = 2 INTERSECTING = 3 SAME = 4 class Point: def __init__(self, x, y): self.x = x self.y = y class Circle: def __init__(self, center, r): self.center = center self.r = r def same_center(self, other_circle): return (other_circle.center.x == self.center.x) and (other_circle.center.y == self.center.y) def distance(self, other_circle): return abs(sqrt((other_circle.center.x - self.center.x)**2 + (other_circle.center.y - self.center.y)**2)) def are_same(self, other_circle): if(abs(self.r - other_circle.r) == self.distance(other_circle)): return True if(abs(self.r - other_circle.r) > self.distance(other_circle)): return True return((other_circle.r == self.r) and self.same_center(other_circle)) def are_not_touching(self, other_circle): return(self.r + other_circle.r < self.distance(other_circle)) def are_touching(self, other_circle): return(self.r + other_circle.r == self.distance(other_circle)) def find_relative_position(self, other_circle): if(self.are_same(other_circle)): return RelativePosition.SAME if(self.are_touching(other_circle)): return RelativePosition.TOUCHING if(self.are_not_touching(other_circle)): return RelativePosition.NO_COMMON_POINTS return RelativePosition.INTERSECTING
alwyn/intellij-community
java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/PsiDocTagImpl.java
<reponame>alwyn/intellij-community /* * Copyright 2000-2012 JetBrains s.r.o. * * 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 com.intellij.psi.impl.source.javadoc; import com.intellij.lang.ASTNode; import com.intellij.psi.*; import com.intellij.psi.impl.PsiImplUtil; import com.intellij.psi.impl.source.Constants; import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry; import com.intellij.psi.impl.source.tree.ChildRole; import com.intellij.psi.impl.source.tree.CompositePsiElement; import com.intellij.psi.impl.source.tree.JavaDocElementType; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.javadoc.PsiDocTag; import com.intellij.psi.javadoc.PsiDocTagValue; import com.intellij.psi.tree.ChildRoleBase; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; public class PsiDocTagImpl extends CompositePsiElement implements PsiDocTag, Constants { private static final TokenSet TAG_VALUE_BIT_SET = TokenSet.create( DOC_TAG_VALUE_ELEMENT, DOC_METHOD_OR_FIELD_REF, DOC_PARAMETER_REF); private static final TokenSet VALUE_BIT_SET = TokenSet.orSet(TAG_VALUE_BIT_SET, TokenSet.create( DOC_TAG_VALUE_TOKEN, JAVA_CODE_REFERENCE, DOC_COMMENT_DATA, DOC_INLINE_TAG, DOC_REFERENCE_HOLDER)); public PsiDocTagImpl() { super(DOC_TAG); } @Override public PsiDocComment getContainingComment() { return (PsiDocComment)getParent(); } @Override public PsiElement getNameElement() { return findPsiChildByType(DOC_TAG_NAME); } @Override public PsiDocTagValue getValueElement() { return (PsiDocTagValue)findPsiChildByType(TAG_VALUE_BIT_SET); } @NotNull @Override public PsiElement[] getDataElements() { return getChildrenAsPsiElements(VALUE_BIT_SET, PsiElement.ARRAY_FACTORY); } @NotNull @Override public String getName() { if (getNameElement() == null) return ""; return getNameElement().getText().substring(1); } @Override public PsiElement setName(@NotNull String name) throws IncorrectOperationException { PsiImplUtil.setName(getNameElement(), name); return this; } @Override public int getChildRole(ASTNode child) { assert child.getTreeParent() == this : child.getTreeParent(); IElementType i = child.getElementType(); if (i == DOC_TAG_NAME) { return ChildRole.DOC_TAG_NAME; } else if (i == JavaDocElementType.DOC_COMMENT || i == DOC_INLINE_TAG) { return ChildRole.DOC_CONTENT; } else if (i == DOC_COMMENT_LEADING_ASTERISKS) { return ChildRole.DOC_COMMENT_ASTERISKS; } else if (TAG_VALUE_BIT_SET.contains(i)) { return ChildRole.DOC_TAG_VALUE; } else { return ChildRoleBase.NONE; } } @Override @NotNull public PsiReference[] getReferences() { return ReferenceProvidersRegistry.getReferencesFromProviders(this, PsiReferenceService.Hints.NO_HINTS); } @Override public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof JavaElementVisitor) { ((JavaElementVisitor)visitor).visitDocTag(this); } else { visitor.visitElement(this); } } public String toString() { return "PsiDocTag:" + getNameElement().getText(); } }
vrazdalovschi/kbcli
kbclient/payment_transaction/get_payment_by_transaction_id_responses.go
<reponame>vrazdalovschi/kbcli // Code generated by go-swagger; DO NOT EDIT. package payment_transaction // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/runtime" "github.com/killbill/kbcli/v2/kbcommon" strfmt "github.com/go-openapi/strfmt" kbmodel "github.com/killbill/kbcli/v2/kbmodel" ) // GetPaymentByTransactionIDReader is a Reader for the GetPaymentByTransactionID structure. type GetPaymentByTransactionIDReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *GetPaymentByTransactionIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewGetPaymentByTransactionIDOK() result.HttpResponse = response if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil default: errorResult := kbcommon.NewKillbillError(response.Code()) if err := consumer.Consume(response.Body(), &errorResult); err != nil && err != io.EOF { return nil, err } return nil, errorResult } } // NewGetPaymentByTransactionIDOK creates a GetPaymentByTransactionIDOK with default headers values func NewGetPaymentByTransactionIDOK() *GetPaymentByTransactionIDOK { return &GetPaymentByTransactionIDOK{} } /*GetPaymentByTransactionIDOK handles this case with default header values. successful operation */ type GetPaymentByTransactionIDOK struct { Payload *kbmodel.Payment HttpResponse runtime.ClientResponse } func (o *GetPaymentByTransactionIDOK) Error() string { return fmt.Sprintf("[GET /1.0/kb/paymentTransactions/{transactionId}][%d] getPaymentByTransactionIdOK %+v", 200, o.Payload) } func (o *GetPaymentByTransactionIDOK) GetPayload() *kbmodel.Payment { return o.Payload } func (o *GetPaymentByTransactionIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(kbmodel.Payment) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetPaymentByTransactionIDNotFound creates a GetPaymentByTransactionIDNotFound with default headers values func NewGetPaymentByTransactionIDNotFound() *GetPaymentByTransactionIDNotFound { return &GetPaymentByTransactionIDNotFound{} } /*GetPaymentByTransactionIDNotFound handles this case with default header values. Payment not found */ type GetPaymentByTransactionIDNotFound struct { HttpResponse runtime.ClientResponse } func (o *GetPaymentByTransactionIDNotFound) Error() string { return fmt.Sprintf("[GET /1.0/kb/paymentTransactions/{transactionId}][%d] getPaymentByTransactionIdNotFound ", 404) } func (o *GetPaymentByTransactionIDNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil }
matteoRondyUni/JBudget
src/main/java/it/unicam/cs/pa/jbudget/javaFX/input/JavaFXCategoryController.java
<filename>src/main/java/it/unicam/cs/pa/jbudget/javaFX/input/JavaFXCategoryController.java package it.unicam.cs.pa.jbudget.javaFX.input; import it.unicam.cs.pa.jbudget.controller.Controller; import it.unicam.cs.pa.jbudget.model.Category; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.stage.Stage; /** * La classe implementa l'interfaccia {@link JavaFXInputController} ed ha la responsabilita' di gestire * la Finestra per la creazione di una {@link Category}. * * @author <NAME> */ public class JavaFXCategoryController implements JavaFXInputController { private final Controller controller; @FXML TextField categoryName; @FXML TextField categoryDescription; @FXML Button categorySubmit; public JavaFXCategoryController(Controller controller) { this.controller = controller; } /** * Crea la {@link it.unicam.cs.pa.jbudget.model.Category} con i dati passati dall'Utente. * In caso di Errore viene visualizzata una Finestra di Dialogo. */ @Override @FXML public void submit() { try { controller.addCategory(getName(), getDescription()); cancel(); } catch (IllegalArgumentException exception) { errorWindow(ERROR_TITLE_ILLEGAL_ARGUMENT, exception.getMessage()); } } /** * {@inheritDoc} */ @Override @FXML public void cancel() { closeWindow((Stage) categorySubmit.getScene().getWindow()); } private String getName() { if (categoryName.getText().equals("")) throw new IllegalArgumentException(EXCEPTION_NAME_VOID); return categoryName.getText(); } private String getDescription() { return categoryDescription.getText(); } }
chenkuangfeng/framework
framework-mainframe/src/main/java/com/ubsoft/framework/mainframe/formbase/FormEngine.java
package com.ubsoft.framework.mainframe.formbase; import java.awt.Component; import java.awt.Container; import java.awt.GridBagConstraints; import java.awt.Insets; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.JInternalFrame; import javax.swing.JLabel; import com.ubsoft.framework.core.exception.ComException; import com.ubsoft.framework.mainframe.widgets.component.tree.XCheckBoxTree; import com.ubsoft.framework.mainframe.widgets.renderer.IRenderer; import com.ubsoft.framework.mainframe.widgets.renderer.MetaRegistry; import com.ubsoft.framework.mainframe.widgets.util.MessageBox; import com.ubsoft.framework.metadata.model.form.FormMeta; import com.ubsoft.framework.metadata.model.widget.WidgetMeta; import com.ubsoft.framework.metadata.model.widget.grid.GridCellMeta; import com.ubsoft.framework.metadata.model.widget.grid.GridMeta; import com.ubsoft.framework.metadata.model.widget.grid.GridRowMeta; import com.ubsoft.framework.metadata.model.widget.model.Align; import com.ubsoft.framework.metadata.model.widget.model.Layout; import com.ubsoft.framework.metadata.model.widget.tree.TreeMeta; public class FormEngine { private static Map<String, FormMeta> formMeta = new HashMap<String, FormMeta>(); private Map<String, Component> idmap = new HashMap<String, Component>(); /** * 根据配置对象生成界面 * * @param meta * @param cmp * @throws Exception */ public <T extends FormMeta> void rendererForm(FormMeta meta, Container cmp) throws Exception { if (cmp instanceof JInternalFrame) { JInternalFrame jif = (JInternalFrame) cmp; cmp = jif.getContentPane(); } WidgetMeta wgMeta = (WidgetMeta) meta; for (WidgetMeta child : wgMeta.getChildren()) { renderer(child, cmp); } } /** * 递归算法,绘制所有子控件。 * * @param meta * @param cmp * @param idMaps * @throws * @throws Exception */ private void renderer(WidgetMeta meta, Container cmp) throws Exception { Class<IRenderer> rendererClass = MetaRegistry.getRenderer(meta.getClass()); if (rendererClass == null) { throw new ComException(ComException.MIN_ERROR_CODE_FDM, meta.toString() + " 组件没有注册!"); } IRenderer cmpRenderer = null; // tree有两个控件,checkboxtree和jTree 通过checkbox属性来判断 if (meta instanceof TreeMeta) { TreeMeta treeMeta = (TreeMeta) meta; if (treeMeta.isCheckBox()) { cmpRenderer = new XCheckBoxTree(); } else { cmpRenderer = rendererClass.newInstance(); } } else { cmpRenderer = rendererClass.newInstance(); } Map<String, Object> params = new HashMap<String, Object>(); cmpRenderer.render(meta, cmp, params); if (cmpRenderer instanceof Container) { Container ctn = (Container) cmpRenderer; if (meta.getChildren() != null) { // swing 没有像html table行和列布局的组件,交给Panel内部处理; if (meta.getLayout() != null && meta.getLayout().equals(Layout.FORMLAYOUT)) { if (meta.getChildren() != null && meta.getChildren().size() == 1 && meta.getChildren().get(0) instanceof GridMeta) { GridMeta gridMeta = (GridMeta) meta.getChildren().get(0); rendererFormLayout(ctn, gridMeta); } else { throw new ComException(ComException.MIN_ERROR_CODE_FDM, meta.toString() + " FormLayout 必须只有一个GridMeta的子控件!"); } } else { for (WidgetMeta child : meta.getChildren()) { renderer(child, ctn); } } } } if (meta.getId() != null) { if (cmpRenderer instanceof Component) { if (!idmap.containsKey(meta.getId())) { idmap.put(meta.getId(), (Component) cmpRenderer); } else { MessageBox.showInfo(meta.getId()+"不能重复."); } } } } /** * formLayout 布局实现 * * @param cmp * @param gridMeta * @throws Exception */ public void rendererFormLayout(Container cmp, GridMeta gridMeta) throws Exception { int rowIndex = 1; List<WidgetMeta> rows = gridMeta.getChildren(); for (int r = 0; r < rows.size(); r++) { GridRowMeta rowMeta = (GridRowMeta) rows.get(r); List<WidgetMeta> cells = rowMeta.getChildren(); int colIndex = 1; for (int c = 0; c < cells.size(); c++) { GridCellMeta cellMeta = (GridCellMeta) cells.get(c); int colSpan = 1; if (cellMeta.getColSpan() != null) { colSpan = cellMeta.getColSpan(); } int rowSpan = 1; if (cellMeta.getRowSpan() != null) { rowSpan = cellMeta.getRowSpan(); } if (cellMeta.getChildren() != null && cellMeta.getChildren().size() == 1) { WidgetMeta cmpMeta = cellMeta.getChildren().get(0); String width = cellMeta.getWidth(); String height = cellMeta.getHeight(); String align = cellMeta.getAlign(); Class<IRenderer> rendererClass = MetaRegistry.getRenderer(cmpMeta.getClass()); if (rendererClass == null) { throw new ComException(ComException.MIN_ERROR_CODE_FDM, cmpMeta.toString() + " 组件没有注册!"); } IRenderer cmpRenderer = rendererClass.newInstance(); GridBagConstraints ctr = new GridBagConstraints(); Map<String, Object> params = new HashMap<String, Object>(); ctr.gridx = colIndex; ctr.gridy = rowIndex; ctr.gridwidth = colSpan; ctr.gridheight = rowSpan; ctr.insets = new Insets(2, 2, 2, 2); if (width == null) { ctr.weightx = 0; } else { if (width.indexOf("%") != -1) { width = width.replaceAll("%", ""); ctr.weightx = Integer.parseInt(width); } } if (height == null) { ctr.weighty = 0; } else { if (height.indexOf("%") != -1) { height = height.replaceAll("%", ""); ctr.weighty = Integer.parseInt(height); } } if (align != null) { if (align.equals(Align.LEFT)) { ctr.anchor = GridBagConstraints.WEST; } else if (align.equals(Align.RIGHT)) { ctr.anchor = GridBagConstraints.EAST; } else if (align.equals(Align.TOP)) { ctr.anchor = GridBagConstraints.NORTH; } else if (align.equals(Align.TOPLEFT)) { ctr.anchor = GridBagConstraints.NORTHWEST; } else if (align.equals(Align.TOPRIGHT)) { ctr.anchor = GridBagConstraints.NORTHEAST; } else if (align.equals(Align.BOTTOM)) { ctr.anchor = GridBagConstraints.SOUTH; } else if (align.equals(Align.BOTTOMRIGHT)) { ctr.anchor = GridBagConstraints.SOUTHEAST; } else if (align.equals(Align.BOTTOMLEFT)) { ctr.anchor = GridBagConstraints.SOUTHWEST; } else { ctr.anchor = GridBagConstraints.WEST; } } ctr.fill = GridBagConstraints.HORIZONTAL; params.put("ctr", ctr); cmpRenderer.render(cmpMeta, cmp, params); if (cmpMeta.getId() != null) { if (cmpRenderer instanceof Component) { idmap.put(cmpMeta.getId(), (Component) cmpRenderer); } } // cmp.add((Component) cmpRenderer, ctr); if (cmpMeta.getChildren() != null) { for (WidgetMeta child : cmpMeta.getChildren()) { if (cmpRenderer instanceof Container) { renderer(child, (Container) cmpRenderer); } } } } else { throw new ComException(ComException.MIN_ERROR_CODE_FDM, cellMeta.toString() + " GridCellMeta 必须切只有一个子控件!"); } colIndex += colSpan; } // 增加一行 rowIndex++; } GridBagConstraints ctr = new GridBagConstraints(); ctr.gridx = 1; ctr.gridy = rowIndex; // ctr.gridwidth = 10; // ctr.gridheight = rowSpan; // ctr.insets = new Insets(2, 2, 2, 2); ctr.weighty = 1; JLabel footerPanel = new JLabel(); cmp.add(footerPanel, ctr); } /** * 根据Id获取控件 * * @param id * @return */ public Component getComponent(String id) { return idmap.get(id); } public FormMeta getFormMeta(String id) { return formMeta.get(id); } public FormMeta putFormMeta(String id, FormMeta meta) { return formMeta.put(id, meta); } }
vladislav-horbatiuk/ossim
include/ossim/base/ossimMatrixProperty.h
//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: <NAME> (<EMAIL>) // //************************************************************************* // $Id: ossimMatrixProperty.h 17074 2010-04-14 18:49:11Z dburken $ #ifndef ossimMatrixProperty_HEADER #define ossimMatrixProperty_HEADER #include <vector> #include <ossim/base/ossimProperty.h> class OSSIMDLLEXPORT ossimMatrixProperty : public ossimProperty { public: ossimMatrixProperty(const ossimString& name=ossimString(""), const std::vector<double>& values = std::vector<double>(), int numberOfRows = 0, int numberOfColumns = 0); ossimMatrixProperty(const ossimMatrixProperty& rhs); virtual ~ossimMatrixProperty(); virtual ossimObject* dup()const; virtual const ossimProperty& assign(const ossimProperty& rhs); virtual bool setValue(const ossimString& value); virtual void valueToString(ossimString& valueResult)const; void resize(int numberOfRows, int numberOfColumns); double& operator ()(int rowIdx, int colIdx); const double& operator()(int rowIdx, int colIdx)const; int getNumberOfRows()const; int getNumberOfCols()const; void clearConstraints(); /*! * If any of the constraints are set to something < 0 then it means there * isn't a constraint for that value. So if you give a min value of -1 * and a max value of 10 then the column can grow from 10 downto 0. */ void setColConstraints(int minNumberOfColumns, int maxNumberOfColumns); /*! * If any of the contraints are set to something < 0 then it means there * isn't a constraint for that value. So if you give a min value of -1 * and a max value of 10 then the row can grow from 10 downto 0. */ void setRowConstraints(int minNumberOfRows, int maxNumberOfRows); void getColConstraints(int& minNumberOfColumns, int& maxNumberOfColumns) const; void getRowConstraints(int& minNumberOfRows, int& maxNumberOfRows) const; void normalize(); void zero(); protected: std::vector< std::vector<double> > theValueArray; int theMinNumberOfCols; int theMaxNumberOfCols; int theMinNumberOfRows; int theMaxNumberOfRows; double density()const; TYPE_DATA }; #endif
HongZhaoHua/jstarcraft-dataset
src/main/java/com/jstarcraft/crawler/book/ireader/IreaderBook.java
package com.jstarcraft.crawler.book.ireader; /** * 掌阅书籍 * * 书籍信息:https://www.ireader.com.cn/index.php?ca=bookdetail.index&pca=channel.index&bid={id} * 书籍评论:https://www.ireader.com.cn/index.php?ca=Sns_Topic.Index&pca=bookdetail.index&cid=book_{id}&page={page} * 章节列表:https://www.ireader.com.cn/index.php?ca=Chapter.List&ajax=1&bid={id}&page={page}&pageSize={size} * 章节内容:https://www.ireader.com.cn/index.php?ca=Chapter.Content&bid={id}&cid=1 * * @author Birdy * */ public class IreaderBook { }
mdhillmancmcl/TheWorldAvatar-CMCL-Fork
JPS_VIRTUALSENSOR/src/test/java/uk/ac/cam/cares/jps/virtualsensor/agents/test/WeatherAgentTest.java
package uk.ac.cam.cares.jps.virtualsensor.agents.test; import org.json.JSONObject; import junit.framework.TestCase; import uk.ac.cam.cares.jps.base.discovery.AgentCaller; import uk.ac.cam.cares.jps.virtualsensor.agents.WeatherAgent; import uk.ac.cam.cares.jps.virtualsensor.objects.WeatherStation; import uk.ac.cam.cares.jps.virtualsensor.sparql.DispSimSparql; public class WeatherAgentTest extends TestCase { /** * You must have a weather station called http://www.theworldavatar.com/ontology/ontostation/OntoStation.owl#weatherstation1 * instantiated in the triple store to run this test */ public void testUpdateWeatherStationWithAPI() { WeatherStation ws = new WeatherStation(); String stationiri = "http://www.theworldavatar.com/ontology/ontostation/OntoStation.owl#weatherstation1"; ws.setStationiri(stationiri); ws.setXcoord(114); ws.setYcoord(22.47); ws.setTimestamp(0); WeatherAgent wa = new WeatherAgent(); wa.updateWeatherStationWithAPI(ws); } /** * This will query for weather stations within the scope defined by the region class */ public void testWeatherAgentCall() { JSONObject jo = new JSONObject(); jo.put(DispSimSparql.SimKey, "http://www.theworldavatar.com/kb/ontodispersionsim/OntoDispersionSim.owl#sim5"); AgentCaller.executeGetWithJsonParameter("JPS_VIRTUALSENSOR/WeatherAgent", jo.toString()); } }
cider/cider
Godeps/_workspace/src/github.com/meeko/go-meeko/meeko/transports/inproc/rpc/messages_upstream.go
<reponame>cider/cider<filename>Godeps/_workspace/src/github.com/meeko/go-meeko/meeko/transports/inproc/rpc/messages_upstream.go // Copyright (c) 2013 The go-meeko AUTHORS // // Use of this source code is governed by The MIT License // that can be found in the LICENSE file. package rpc import ( // Stdlib "bytes" "encoding/binary" // Meeko client client "github.com/meeko/go-meeko/meeko/services/rpc" "github.com/meeko/go-meeko/meeko/utils/codecs" ) // rpc.Request ----------------------------------------------------------------- type rpcRequest struct { t *Transport cmd client.CallCmd args []byte } func newRPCRequest(t *Transport, cmd client.CallCmd) (*rpcRequest, error) { var argsBuffer bytes.Buffer if err := codecs.MessagePack.Encode(&argsBuffer, cmd.Args()); err != nil { return nil, err } return &rpcRequest{ t: t, cmd: cmd, args: argsBuffer.Bytes(), }, nil } func (msg *rpcRequest) Sender() []byte { return []byte(msg.t.identity) } func (msg *rpcRequest) Id() []byte { var idBuffer bytes.Buffer binary.Write(&idBuffer, binary.BigEndian, msg.cmd.RequestId()) return idBuffer.Bytes() } func (msg *rpcRequest) Method() []byte { return []byte(msg.cmd.Method()) } func (msg *rpcRequest) Args() []byte { return msg.args } func (msg *rpcRequest) StdoutTag() []byte { var tagBuffer bytes.Buffer if tag := msg.cmd.StdoutTag(); tag != nil { binary.Write(&tagBuffer, binary.BigEndian, *tag) } return tagBuffer.Bytes() } func (msg *rpcRequest) StderrTag() []byte { var tagBuffer bytes.Buffer if tag := msg.cmd.StderrTag(); tag != nil { binary.Write(&tagBuffer, binary.BigEndian, *tag) } return tagBuffer.Bytes() } func (msg *rpcRequest) Reject(code byte, reason string) error { msg.t.replyCh <- &rejectedCallReply{msg.cmd.RequestId(), code, []byte(reason)} return nil } // rpc.Interrupt --------------------------------------------------------------- type rpcInterrupt struct { sender []byte targetRequestId []byte } func newRPCInterrupt(sender string, targetRequestId client.RequestID) *rpcInterrupt { var idBuffer bytes.Buffer binary.Write(&idBuffer, binary.BigEndian, targetRequestId) return &rpcInterrupt{ sender: []byte(sender), targetRequestId: idBuffer.Bytes(), } } func (msg *rpcInterrupt) Sender() []byte { return msg.sender } func (msg *rpcInterrupt) TargetRequestId() []byte { return msg.targetRequestId } // rpc.Progress ---------------------------------------------------------------- type rpcProgress struct { sender []byte receiver []byte targetRequestId []byte } func (progress *rpcProgress) Sender() []byte { return progress.sender } func (progress *rpcProgress) Receiver() []byte { return progress.receiver } func (progress *rpcProgress) TargetRequestId() []byte { return progress.targetRequestId } // rpc.StreamFrame ------------------------------------------------------------- type rpcStreamFrame struct { sender []byte receiver []byte targetStreamTag []byte body []byte } func (frame *rpcStreamFrame) Sender() []byte { return frame.sender } func (frame *rpcStreamFrame) Receiver() []byte { return frame.receiver } func (frame *rpcStreamFrame) TargetStreamTag() []byte { return frame.targetStreamTag } func (frame *rpcStreamFrame) Body() []byte { return frame.body } // rpc.Reply ------------------------------------------------------------------- type rpcReply struct { sender []byte receiver []byte targetRequestId []byte returnCode []byte returnValue []byte } func (rep *rpcReply) Sender() []byte { return rep.sender } func (rep *rpcReply) Receiver() []byte { return rep.receiver } func (rep *rpcReply) TargetRequestId() []byte { return rep.targetRequestId } func (rep *rpcReply) ReturnCode() []byte { return rep.returnCode } func (rep *rpcReply) ReturnValue() []byte { return rep.returnValue }
Komanawa-Solutions-Ltd/SLMACC-2020-CSRA
Storylines/storyline_runs/run_random_suite.py
<reponame>Komanawa-Solutions-Ltd/SLMACC-2020-CSRA """ Author: <NAME> Created: 24/02/2021 10:46 AM """ import os import ksl_env import glob import numpy as np import pandas as pd import gc import netCDF4 as nc import psutil import itertools from Climate_Shocks.climate_shocks_env import temp_storyline_dir from Storylines.generate_random_storylines import generate_random_suite from BS_work.IID.IID import run_IID from Pasture_Growth_Modelling.full_pgr_model_mp import run_full_model_mp, default_pasture_growth_dir, pgm_log_dir, \ default_mode_sites from Pasture_Growth_Modelling.full_model_implementation import add_pasture_growth_anaomoly_to_nc from Storylines.storyline_evaluation.storyline_eval_support import get_pgr_prob_baseline_stiched random_pg_dir = os.path.join(default_pasture_growth_dir, 'random') random_sl_dir = os.path.join(temp_storyline_dir, 'random') gdrive_outdir = os.path.join(ksl_env.slmmac_dir, 'random_stories_prob') for d, tnm in itertools.product([random_pg_dir, random_sl_dir], ['_bad_irr', '_good_irr']): if not os.path.exists(f'{d}{tnm}'): os.makedirs(f'{d}{tnm}') if not os.path.exists(gdrive_outdir): os.makedirs(gdrive_outdir) def make_1_year_storylines(bad_irr=True): """ :param bad_irr: bool if True then create irrigation from 50-99th percentile if False 1-50th percentile :return: """ if bad_irr: tnm = '_bad_irr' else: tnm = '_good_irr' n = 70000 # based on an arbirary 4 day run length over easter storylines = generate_random_suite(n, use_default_seed=True, save=False, return_story=True, bad_irr=bad_irr) # run IID iid_prob = run_IID(story_dict={f'rsl-{k:06d}': v for k, v in enumerate(storylines)}, verbose=False, irr_prob_from_zero=False, add_irr_prob=True) iid_prob.set_index('ID', inplace=True) iid_prob.rename(columns={'log10_prob': 'log10_prob_irrigated'}, inplace=True) temp = run_IID(story_dict={f'rsl-{k:06d}': v for k, v in enumerate(storylines)}, verbose=False, irr_prob_from_zero=False, add_irr_prob=False).set_index('ID') iid_prob.loc[:, 'log10_prob_dryland'] = temp.loc[:, 'log10_prob'] iid_prob.reset_index(inplace=True) iid_prob.to_hdf(os.path.join(f'{random_pg_dir}{tnm}', 'IID_probs_1yr.hdf'), 'prob', mode='w') # save locally iid_prob.to_hdf(os.path.join(gdrive_outdir, f'IID_probs_1yr{tnm}.hdf'), 'prob', mode='w') # save on gdrive # save non-zero probability stories for sl, (i, p) in zip(storylines, iid_prob.log10_prob_irrigated.to_dict().items()): if not np.isfinite(p): continue name = f'rsl-{i:06d}' sl.to_csv(os.path.join(f'{random_sl_dir}{tnm}', f'{name}.csv')) def run_1year_basgra(bad_irr=True): """ :param bad_irr: bool if True then create irrigation from 50-99th percentile if False 1-50th percentile :return: """ if bad_irr: tnm = '_bad_irr' else: tnm = '_good_irr' run_stories = glob.glob(os.path.join(f'{random_sl_dir}{tnm}', 'rsl-*.csv')) outdirs = [f'{random_pg_dir}{tnm}' for e in run_stories] run_full_model_mp( storyline_path_mult=run_stories, outdir_mult=outdirs, nsims_mult=100, log_path=os.path.join(pgm_log_dir, 'random'), description_mult='random 1 year storylines, see Storylines/generate_random_storylines.py and ' 'Storylines/storyline_runs/run_random_suite.py for details', padock_rest_mult=False, save_daily_mult=False, verbose=False, #mode_sites_mult=default_mode_sites, mode_sites_mult=(('dryland', 'oxford'), ), #todo DADB just to re-run dryland only! re_run=False # and additional safety ) def create_1y_pg_data(bad_irr=True): """ :param bad_irr: bool if True then create irrigation from 50-99th percentile if False 1-50th percentile :return: """ if bad_irr: tnm = '_bad_irr' tp = 'bad' else: tp = 'good' tnm = '_good_irr' # Autumn Drought Cumulative-rest-50-75-eyrewell-irrigated.nc data = pd.read_hdf(os.path.join(f'{random_pg_dir}{tnm}', 'IID_probs_1yr.hdf'), 'prob') assert isinstance(data, pd.DataFrame) for site, mode in default_mode_sites: key = f'{mode}-{site}' data.loc[:, f'{key}_pg_yr1'] = np.nan data.loc[:, f'{key}_pgra_yr1'] = np.nan for i, idv in data.loc[:, ['ID']].itertuples(True, None): if i % 1000 == 0: print(f'starting to read sim {i} for site: {site} and mode: {mode}') p = os.path.join(f'{random_pg_dir}{tnm}', f'{idv}-{key}.nc') if not os.path.exists(p): continue nc_data = nc.Dataset(p) data.loc[i, f'{key}_pgra_yr1'] = np.array(nc_data.variables['m_PGRA_cum'][-1, :]).mean() temp = np.array(nc_data.variables['m_PGR']) temp *= np.array([31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30])[:, np.newaxis] temp = temp.sum(axis=0).mean() data.loc[i, f'{key}_pg_yr1'] = temp nc_data.close() data.loc[:, 'irr_type'] = tp data.to_hdf(os.path.join(f'{random_pg_dir}{tnm}', f'IID_probs_pg_1y{tnm}.hdf'), 'prob', mode='w') data.to_hdf(os.path.join(gdrive_outdir, f'IID_probs_pg_1y{tnm}.hdf'), 'prob', mode='w') def get_1yr_data(bad_irr=True, good_irr=True): """ get the 1 year data :param bad_irr: bool if True return the data from the worse than median irrigation restriction suite :param good_irr: bool if True return the data from the better than median irrigation restriction suite :return: """ assert any([bad_irr, good_irr]) good, bad = None, None if bad_irr: bad = pd.read_hdf(os.path.join(gdrive_outdir, f'IID_probs_pg_1y_bad_irr.hdf'), 'prob') if good_irr: good = pd.read_hdf(os.path.join(gdrive_outdir, f'IID_probs_pg_1y_good_irr.hdf'), 'prob') return pd.concat([good, bad]) def create_nyr_suite(nyr, use_default_seed=True, save_to_gdrive=True): """ :param nyr: number of years long, options are: [2, 3, 4, 5, 6, 7, 8, 9, 10, 15] :param use_default_seed: bool if true then use the default seed to keep reproducability :param save_to_gdrive: bool if True then save to the google drive :return: """ print(f'nyear: {nyr}') assert isinstance(nyr, int) n = int(2.5e8) if nyr>5: n = int(2.5e7) data_1y = get_1yr_data(bad_irr=True, good_irr=True) assert isinstance(data_1y, pd.DataFrame) data_1y = data_1y.dropna() default_seeds = { 2: 471121, 3: 44383, 4: 80942, 5: 464015, 6: 246731, 7: 229599, 8: 182848, 9: 310694, 10: 367013, 15: 458445 } if use_default_seed: seed = default_seeds[nyr] else: seed = np.random.randint(1, 500000) mem = psutil.virtual_memory().available - 3e9 # leave 3 gb spare total_mem_needed = np.zeros(1).nbytes * n * nyr * 4 chunks = int(np.ceil(total_mem_needed / mem)) * 5 print(f'running in {chunks} chunks') chunk_size = int(np.ceil(n / chunks)) for mode, site in default_mode_sites: print('making dataframe') outdata = pd.DataFrame(index=range(n), columns=['log10_prob_dryland', 'log10_prob_irrigated', f'{site}-{mode}_pgra_yr{nyr}', f'{site}-{mode}_pg_yr{nyr}' ], dtype=np.float32) print(outdata.dtypes) print('/n', mode, site) key = f'{site}-{mode}' np.random.seed(seed) temp_p = 10**data_1y.loc[:, f'log10_prob_{mode}'] p = temp_p/temp_p.sum() idxs = np.random.choice( np.arange(len(data_1y), dtype=np.uint32), size=(n * nyr), p=p ).reshape((n, nyr)) for c in range(chunks): print(f'chunk: {c}') start_idx = chunk_size * c end_idx = chunk_size * (c + 1) cs = chunk_size if c == chunks - 1: end_idx = n cs = end_idx - start_idx print('getting prob_dry') prob = data_1y[f'log10_prob_dryland'].values[idxs[start_idx:end_idx]] # note that I have changed the probability to be log10(probaility) outdata.loc[start_idx:end_idx - 1, f'log10_prob_dryland'] = prob.sum(axis=1).astype(np.float32) print('getting prob_irr') prob = data_1y[f'log10_prob_irrigated'].values[idxs[start_idx:end_idx]] # note that I have changed the probability to be log10(probaility) outdata.loc[start_idx:end_idx - 1, f'log10_prob_irrigated'] = prob.sum(axis=1).astype(np.float32) print('getting pgra') pga = data_1y[f'{key}_pgra_yr1'].values[idxs[start_idx:end_idx]].reshape(cs, nyr) outdata.loc[start_idx:end_idx - 1, f'{key}_pgra_yr{nyr}'] = pga.sum(axis=1).astype(np.float32) print('getting pg') pga = data_1y[f'{key}_pg_yr1'].values[idxs[start_idx:end_idx]].reshape(cs, nyr) outdata.loc[start_idx:end_idx - 1, f'{key}_pg_yr{nyr}'] = pga.sum(axis=1).astype(np.float32) if not use_default_seed: print('recording indexes') for n in range(nyr): outdata.loc[:, f'scen_{n + 1}'] = idxs[:, n] print(outdata.values.nbytes * 1e-9, f'gb for {mode} - {site}') print(outdata.dtypes) print(f'saving {mode} - {site} to local drive') outpath = os.path.join(os.path.dirname(random_pg_dir), 'nyr', f'IID_probs_pg_{nyr}y_{site}-{mode}.npy') if not os.path.exists(os.path.dirname(outpath)): os.makedirs(os.path.dirname(outpath)) np.save(outpath, outdata.values) with open(outpath.replace('.npy', '.csv'), 'w') as f: f.write(','.join(outdata.columns)) if save_to_gdrive: print(f'saving {mode} - {site} to google drive') outpath = os.path.join(gdrive_outdir, f'IID_probs_pg_{nyr}y_{site}-{mode}.npy') np.save(outpath, outdata.values) with open(outpath.replace('.npy', '.csv'), 'w') as f: f.write(','.join(outdata.columns)) print(f'finished {mode} - {site}') gc.collect() def get_nyr_suite(nyr, site, mode): outpath = os.path.join(os.path.dirname(random_pg_dir), 'nyr', f'IID_probs_pg_{nyr}y_{site}-{mode}.npy') out = np.load(outpath) out = pd.DataFrame(out, columns=pd.read_csv(outpath.replace('.npy', '.csv')).columns) return out """ timeit_test(r'C:/Users/dumon/python_projects/SLMACC-2020-CSRA/Storylines/storyline_runs/run_random_suite.py', ('make_1_year_storylines', # 16 stories 0.366s # 'run_1year_basgra', # 16 stories (full logical on dickie), 100 reals of 1 yr sim: 89.17002 seconds 'create_1y_pg_data', # 16 stories 0.197s ), n=100) # 90s per 16 stories. Memory: 10mb/16 stories, 1mb/16 stories in cloud based on my math the 1yr suite should be c. 4-5gb in size in the cloud and c. 40-50gb on disk. """ def fix_old_1yr_runs(base_dir, change_storyline_time=False): paths = glob.glob(os.path.join(base_dir, '*.nc')) pl = len(paths) for i, p in enumerate(paths): if i % 1000 == 0: print(f'{i} of {pl}') if change_storyline_time: data = nc.Dataset(p, mode='a') # change years data.variables['m_year'][:] = np.array([2025, 2025, 2025, 2025, 2025, 2025, 2026, 2026, 2026, 2026, 2026, 2026]) - 1 # add some metadata that a change happened in the description data.description = data.description + (' storyline changed with fix_old_1yr_runs to ' 'shift storyline start to july 2024 from 2025') # fix storyline data.storyline = [e.replace('2025', '2024').replace('2026', '2025') for e in data.storyline] data.close() # re-run add pgra add_pasture_growth_anaomoly_to_nc(p) if __name__ == '__main__': #todo re-run dryland, should be good to go once I fix the baseline stuff # todo check all re-runs!!!! # todo do I need to re-run with new ibasal? t = input('are you sure you want to run this, it takes 8 days to run basgra y/n') if t != 'y': raise ValueError('stopped re-running') # only run next line of code once as this fixes a mistake from previously #todo re-run all of these once baseline is sorted works!, need to do for all runs and then add to the readme file. #fix_old_1yr_runs(r"D:\mh_unbacked\SLMACC_2020\pasture_growth_sims\random_bad_irr", False) #fix_old_1yr_runs(r"D:\mh_unbacked\SLMACC_2020\pasture_growth_sims\random_good_irr", False) import time t = time.time() make_1_year_storylines(bad_irr=True) run_1year_basgra(bad_irr=True) create_1y_pg_data(bad_irr=True) make_1_year_storylines(bad_irr=False) run_1year_basgra(bad_irr=False) create_1y_pg_data(bad_irr=False) print((time.time() - t) / 60, 'minutes to run 2.5e8 sims') t = time.time() # todo remake these after checking the above # create_nyr_suite(2, True, False) # create_nyr_suite(3, True, False) # create_nyr_suite(5, True, False) # create_nyr_suite(10, True, False) print((time.time() - t) / 60, 'minutes to run 2.5e8 sims') pass
osidorkin85/nno
backend/watchdir/src/test/java/net/n2oapp/watchdir/WatchDir2Test.java
package net.n2oapp.watchdir; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.Assert.*; import static org.junit.Assert.assertFalse; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import static org.mockito.Mockito.verify; /** * @author iryabov * @since 04.12.2015 */ public class WatchDir2Test { private final static String TEST_DIR = getTestFolder(); private Path path = Paths.get(TEST_DIR + "test.txt"); private WatchDir watchDir; private FileChangeListener listener = mock(FileChangeListener.class); private static String getTestFolder() { StringBuilder customTestPath = new StringBuilder(); customTestPath.append(System.getProperty("user.home")); customTestPath.append(File.separator); customTestPath.append(WatchDirTest.class.getSimpleName()); customTestPath.append(File.separator); return customTestPath.toString(); } @Before public void setUpClass() throws Exception { File testDir = new File(TEST_DIR); if (testDir.exists()) { FileUtils.forceDelete(testDir); } assertTrue(testDir.mkdirs()); reset(listener); watchDir = new WatchDir(Paths.get(TEST_DIR), false, listener); } @After public void tearDownClass() throws Exception { watchDir.stop(); File testDir = new File(TEST_DIR); if (testDir.exists()) { FileUtils.forceDelete(testDir); } assertFalse(testDir.exists()); } /** * проверить, что было событие на создание и только */ @Test @Ignore public void testEventOnCreate() throws Exception { watchDir.start(); FileUtils.touch(new File(path.toString())); verify(listener, timeout(200).atLeast(1)).fileCreated(eq(path)); verify(listener, never()).fileModified(any(Path.class)); verify(listener, never()).fileDeleted(any(Path.class)); watchDir.stop(); } /** * проверить, что было событие на изменение и только * */ @Test @Ignore public void testEventOnChange() throws Exception { FileUtils.touch(new File(path.toString())); watchDir.start(); FileUtils.write(new File(path.toString()), "test"); verify(listener, timeout(200).atLeast(1)).fileModified(eq(path)); verify(listener, never()).fileCreated(any(Path.class)); verify(listener, never()).fileDeleted(any(Path.class)); watchDir.stop(); } /** * проверить, что было событие удаления * */ @Test @Ignore public void testEventOnDelete() throws Exception { FileUtils.touch(new File(path.toString())); watchDir.start(); assertTrue(new File(path.toString()).delete()); verify(listener, timeout(200).atLeast(1)).fileDeleted(eq(path)); verify(listener, never()).fileCreated(any(Path.class)); //side effect. Иногда Watcher сначала шлет modified, а потом deleted. Исключить не получилось. // verify(listener, timeout(200).atLeast(1)).fileModified(eq(path)); watchDir.stop(); } @Test @Ignore public void testChangeDir() throws Exception { String dir = TEST_DIR + "dir" + File.separator; //создание пустой папки reset(listener); watchDir.start(); FileUtils.forceMkdir(new File(dir)); verify(listener, timeout(200).atLeast(1)).fileCreated(eq(Paths.get(dir))); verify(listener, never()).fileModified(any(Path.class)); verify(listener, never()).fileDeleted(any(Path.class)); watchDir.stop(); //удаление пустой папки reset(listener); watchDir.start(); FileUtils.forceDelete(new File(dir)); verify(listener, timeout(200).atLeast(1)).fileDeleted(eq(Paths.get(dir))); verify(listener, never()).fileModified(any(Path.class)); verify(listener, never()).fileCreated(any(Path.class)); watchDir.stop(); //создание папки с файлом reset(listener); watchDir.start(); FileUtils.forceMkdir(new File(dir)); FileUtils.touch(new File(dir + "file.txt")); verify(listener, timeout(200).atLeast(1)).fileCreated(eq(Paths.get(dir))); verify(listener, never()).fileModified(any(Path.class)); verify(listener, never()).fileDeleted(any(Path.class)); watchDir.stop(); //удаление папки с файлом reset(listener); watchDir.start(); FileUtils.forceDelete(new File(dir)); verify(listener, timeout(200).never()).fileCreated(any(Path.class)); verify(listener, never()).fileModified(any(Path.class)); verify(listener, timeout(200).atLeast(1)).fileDeleted(eq(Paths.get(dir))); watchDir.stop(); } @Test @Ignore public void testCreateChangeDelete() throws Exception { watchDir.start(); FileUtils.touch(new File(path.toString())); FileUtils.write(new File(path.toString()), "test"); FileUtils.write(new File(path.toString()), "test2"); FileUtils.forceDelete(new File(path.toString())); verify(listener, timeout(200).atLeast(1)).fileCreated(eq(path)); verify(listener, atLeast(1)).fileDeleted(eq(path)); verify(listener, never()).fileModified(any(Path.class)); watchDir.stop(); } }
1iyiwei/deform2d
Wml/Include/WmlIntrLin3Con3.h
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2004. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #ifndef WMLINTRLIN3CON3_H #define WMLINTRLIN3CON3_H #include "WmlCone3.h" #include "WmlLine3.h" namespace Wml { // The cone is assumed to have an acute angle between cone axis and cone edge. // The return value is 'true' if and only if there is an intersection. If // there is an intersection, the number of intersections is stored in // riQuantity. // It is possible half the line is entirely on the cone surface. In this // case, the riQuantity is set to -1 and akPoint[] values are unassigned (the // ray of intersection is V+(t*Dot(D,A))*D where V is the cone vertex, D is // the line direction, and t >= 0. template <class Real> WML_ITEM bool FindIntersection (const Line3<Real>& rkLine, const Cone3<Real>& rkCone, int& riQuantity, Vector3<Real> akPoint[2]); } #endif
ivanceras/orm
src/test/java/com/ivanceras/db/sample/DefaultDAOInstanceProvider.java
<reponame>ivanceras/orm package com.ivanceras.db.sample; import com.ivanceras.db.shared.DAO; import com.ivanceras.db.api.DAOFactory; import com.ivanceras.db.shared.exception.DAOInstanceFactoryException; public class DefaultDAOInstanceProvider implements DAOFactory{ @Override @SuppressWarnings("unchecked") public <T> T getInstance(Class<? extends DAO> daoClass) throws DAOInstanceFactoryException{ if(daoClass.equals(DAO_Product.class)){ return (T)new DAO_Product(); } else if(daoClass.equals(DAO_ProductAvailability.class)){ return (T)new DAO_ProductAvailability(); } else if(daoClass.equals(DAO_ProductCategory.class)){ return (T)new DAO_ProductCategory(); } else{ throw new DAOInstanceFactoryException("No class for "+daoClass+"]"); } } @Override @SuppressWarnings("unchecked") public <T> T[] getArrayInstance(Class<? extends DAO> daoClass, int n) throws DAOInstanceFactoryException{ if(daoClass.equals(DAO_Category.class)){ return (T[])new DAO_Category[n]; } else if(daoClass.equals(DAO_Product.class)){ return (T[])new DAO_Product[n]; } else if(daoClass.equals(DAO_ProductAvailability.class)){ return (T[])new DAO_ProductAvailability[n]; } else if(daoClass.equals(DAO_ProductCategory.class)){ return (T[])new DAO_ProductCategory[n]; } else{ throw new DAOInstanceFactoryException("No class for "+daoClass+"]"); } } }
onezens/QQTweak
qqtw/qqheaders7.2/QQValidButton.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "UIButton.h" @class UIColor; @interface QQValidButton : UIButton { UIColor *_lineColor; } - (void)dealloc; - (void)drawRect:(struct CGRect)arg1; - (void)setLineColor:(id)arg1; @end
s3a-spatialaudio/VISR
src/python/rbbl/multichannel_convolver_uniform.cpp
<filename>src/python/rbbl/multichannel_convolver_uniform.cpp /* Copyright Institute of Sound and Vibration Research - All rights reserved */ #include <librbbl/multichannel_convolver_uniform.hpp> #include <libefl/basic_matrix.hpp> #include <libpml/filter_routing_parameter.hpp> #include <libpml/matrix_parameter.hpp> #include <libvisr/detail/compose_message_string.hpp> #include <pybind11/pybind11.h> #include <pybind11/numpy.h> namespace visr { namespace rbbl { namespace python { namespace // unnamed { template<typename DataType> pybind11::array_t<DataType> wrapProcess( MultichannelConvolverUniform<DataType> & convolver, pybind11::array const & input ) { if( not input.dtype().is( pybind11::dtype::of<DataType>() ) ) { throw std::invalid_argument( "MultichannelConvolverUniform::process(): The data type input matrix does not match the used sample data type." ); } if( input.ndim() != 2 ) { throw std::invalid_argument( "MultichannelConvolverUniform::process(): The input matrix is not 2D" ); } if( input.shape( 0 ) != static_cast<pybind11::ssize_t>(convolver.numberOfInputs()) ) { throw std::invalid_argument( "MultichannelConvolverUniform::process(): Dimension 1 input of the input matrix does not match the number of capture channels." ); } if( input.shape( 1 ) != static_cast<pybind11::ssize_t>(convolver.blockLength()) ) { throw std::invalid_argument( "MultichannelConvolverUniform::process(): Dimension 0 input of the input matrix does not match the block size of the convolver." ); } if( input.strides(1) != sizeof(DataType) ) { throw std::invalid_argument( "MultichannelConvolverUniform::process(): The channel data must be consecutive." ); } pybind11::array outputSignal( pybind11::dtype::of<DataType>(), { convolver.numberOfOutputs(), convolver.blockLength() }, { sizeof( DataType )*convolver.blockLength(), sizeof( DataType ) } // TODO: Take care of alignment ); std::size_t const outChannelStride = outputSignal.strides( 0 ) / sizeof( DataType ); try { convolver.process( static_cast<DataType const *>(input.data()), input.strides( 0 ) / sizeof( DataType ), static_cast<DataType *>(outputSignal.mutable_data()), outChannelStride ); } catch( std::exception const & ex ) { // For the time being we are using std::invalid_argument because it is recognised by pybind11 and translated to a proper Python exeption // todo: register a more fitting exception, e.g., std::runtime_error throw std::invalid_argument( detail::composeMessageString( "Exception while execution signal flow:", ex.what() ) ); } return outputSignal; } /** * Templated export function for concrete MultichannelConvolverUniform instantiations with different * sample types. */ template<typename ElementType> void exportMultichannelConvolverUniform( pybind11::module & m, char const * name ) { pybind11::class_< MultichannelConvolverUniform<ElementType> >( m, name ) .def( pybind11::init<std::size_t, std::size_t, std::size_t, std::size_t, std::size_t, std::size_t, rbbl::FilterRoutingList const &, efl::BasicMatrix<ElementType> const &, std::size_t, char const *>(), pybind11::arg( "numberOfInputs" ), pybind11::arg( "numberOfOutputs" ), pybind11::arg( "blockLength" ), pybind11::arg( "maxFilterLength" ), pybind11::arg( "maxRoutingPoints" ), pybind11::arg( "maxFilterEntries" ), pybind11::arg( "initialRoutings" ) = rbbl::FilterRoutingList(), pybind11::arg( "initialFilters" ), pybind11::arg( "alignment" ) = 0, pybind11::arg( "fftImplementation" ) = "default" ) .def_property_readonly_static( "numberOfInputs", &MultichannelConvolverUniform<ElementType>::numberOfInputs ) .def_property_readonly_static( "numberOfOutputs", &MultichannelConvolverUniform<ElementType>::numberOfOutputs ) .def_property_readonly_static( "blockLength", &MultichannelConvolverUniform<ElementType>::blockLength ) .def_property_readonly_static( "maxNumberOfRoutingPoints", &MultichannelConvolverUniform<ElementType>::maxNumberOfRoutingPoints ) .def_property_readonly_static( "maxNumberOfFilterEntries", &MultichannelConvolverUniform<ElementType>::maxNumberOfFilterEntries ) .def_property_readonly_static( "maxFilterLength", &MultichannelConvolverUniform<ElementType>::maxFilterLength ) .def_property_readonly_static( "numberOfRoutingPoints", &MultichannelConvolverUniform<ElementType>::numberOfRoutingPoints ) // .def_property_readonly_static( "numberOfRoutings", &MultichannelConvolverUniform<ElementType>::numberOfRoutings ) .def( "process", []( MultichannelConvolverUniform<ElementType> & convolver, pybind11::array const & input ) { return wrapProcess( convolver, input ); }, pybind11::arg("input") ) .def( "clearRoutingTable", &MultichannelConvolverUniform<ElementType>::clearRoutingTable ) .def( "initRoutingTable", &MultichannelConvolverUniform<ElementType>::initRoutingTable, pybind11::arg( "routings" ) ) .def( "setRoutingEntry", static_cast<void(MultichannelConvolverUniform<ElementType>::*)(rbbl::FilterRouting const &)>(&MultichannelConvolverUniform<ElementType>::setRoutingEntry), pybind11::arg("routing") ) .def( "setRoutingEntry", static_cast<void(MultichannelConvolverUniform<ElementType>::*)(std::size_t, std::size_t, std::size_t, ElementType)> (&MultichannelConvolverUniform<ElementType>::setRoutingEntry), pybind11::arg( "inputIndex"), pybind11::arg( "outputIndex"), pybind11::arg( "filterIndex"), pybind11::arg( "gain") = 1.0 ) .def( "removeRoutingEntry", static_cast<bool(MultichannelConvolverUniform<ElementType>::*)(std::size_t, std::size_t)>(&MultichannelConvolverUniform<ElementType>::removeRoutingEntry), pybind11::arg( "inputIndex" ), pybind11::arg( "outputIndex" ) ) .def( "clearFilters", &MultichannelConvolverUniform<ElementType>::clearFilters ) .def( "initFilters", &MultichannelConvolverUniform<ElementType>::initFilters, pybind11::arg( "newFilters" ) ) .def( "setImpulseResponse", &MultichannelConvolverUniform<ElementType>::setImpulseResponse, pybind11::arg("ir"), pybind11::arg( "filterLength"), pybind11::arg( "filterIdx" ), pybind11::arg( "alignment" ) = 0 ) ; } } // unnamed namespace void exportMultichannelConvolversUniform( pybind11::module & m ) { exportMultichannelConvolverUniform<float>( m, "MultichannelConvolverUniformFloat" ); exportMultichannelConvolverUniform<double>( m, "MultichannelConvolverUniformDouble" ); } } // namespace python } // namepace rbbl } // namespace visr
soamsy/leetcode
src/0955_min_deletion_size.py
def minDeletionSize(strs: list[str]) -> int: needToCheck = set(range(len(strs))) count = 0 for col in zip(*strs): pairs = [p for p in zip(col, col[1:])] if all([a <= b for i, (a, b) in enumerate(pairs) if i in needToCheck]): needToCheck -= {i for i, (a, b) in enumerate(pairs) if a < b} if not needToCheck: return count else: count += 1 return count
jhnaldo/jest
data/generated/1098.js
<gh_stars>1-10 var x = Promise . prototype . finally . call ( x => { } , x == x ) ;
olivergeith/android_jcodec
src/org/jcodec/codecs/h264/decode/aso/MBToSliceGroupMap.java
<reponame>olivergeith/android_jcodec package org.jcodec.codecs.h264.decode.aso; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License * * Contains a mapping of macroblocks to slice groups. Groups is an array of * group slice group indices having a dimension picWidthInMbs x picHeightInMbs * * @author The JCodec project * */ public class MBToSliceGroupMap { private int[] groups; private int[] indices; private int[][] inverse; public MBToSliceGroupMap(int[] groups, int[] indices, int[][] inverse) { this.groups = groups; this.indices = indices; this.inverse = inverse; } public int[] getGroups() { return groups; } public int[] getIndices() { return indices; } public int[][] getInverse() { return inverse; } }
honeytavis/cpp
Thinking_in_Cpp/I/C10/reference/ReferenceToPointer.cc
<filename>Thinking_in_Cpp/I/C10/reference/ReferenceToPointer.cc #include <iostream> void increament(int*& i) { ++i; } int main() { //int* i = 0; int* i = NULL; std::cout << "i = " << i << '\n'; increament(i); std::cout << "i = " << i << '\n'; i = NULL; }
nellochen/springboot-start
utils/src/main/java/com/xiaofeng/utils/designpatterns/interpreter/context/Node.java
<filename>utils/src/main/java/com/xiaofeng/utils/designpatterns/interpreter/context/Node.java package com.xiaofeng.utils.designpatterns.interpreter.context; /** * @author <NAME> * @version 1.0.0 * @date 2017/07/28 * @email <EMAIL> */ abstract public class Node { public abstract void interpret(Context text); //声明一个方法用于解释语句 public abstract void execute(); //声明一个方法用于执行标记对应的命令 }
lorenz0890/pytorch-admm-pruning
experiments/baseline.py
<gh_stars>0 from __future__ import print_function import argparse import copy import torch import torch.nn.functional as F from torch.optim import Adam, SGD from torch.optim.lr_scheduler import MultiStepLR from pruning import GradientDiversity, GradientDiversityTopKGradients, RePruningLinearDet from pruning import RePruningConvDet from optimizer import PruneAdam from model import LeNet, AlexNet from performance_model import PerformanceModel from utils import regularized_nll_loss, admm_loss, \ initialize_Z_and_U, update_X, update_Z, update_Z_l1, update_U, \ print_convergence, print_prune, apply_prune, apply_l1_prune from torchvision import datasets, transforms from tqdm import tqdm class Baseline: def __init__(self, model, train_loader, test_loader, config, logger, visualization=None): self.model = model self.train_loader = train_loader self.test_loader = test_loader self.config = config self.use_cuda = not config.get('OTHER', 'no_cuda', bool) and torch.cuda.is_available() self.kwargs = {'num_workers': 1, 'pin_memory': True} if self.use_cuda else {} self.device = torch.device("cuda" if self.use_cuda else "cpu") self.gradient_diversity = GradientDiversityTopKGradients(1, 1) # Only required for gradient normalization self.logger = logger self.visualization = visualization self.optimizer = SGD(self.model.parameters(), lr=self.config.get('SPECIFICATION', 'lr', float), weight_decay=0.0) self.scheduler = MultiStepLR(self.optimizer, milestones=self.config.get('SPECIFICATION', 'steps', lambda a: [int(b) for b in str(a).split(',')]), gamma=config.get('SPECIFICATION', 'gamma', float)) self.performance_model = PerformanceModel(model, train_loader, config, logger=logger) def dispatch(self): self.performance_model.print_cuda_status() torch.manual_seed(self.config.get('OTHER', 'seed', int)) self.__train() self.__test() self.logger.store() if self.config.get('OTHER', 'vis_model', bool): self.visualization.visualize_model(self.model) if self.config.get('OTHER', 'vis_log', bool): self.visualization.visualize_perfstats(self.logger) self.visualization.visualize_key_list(self.logger, ['test_accuracy', 'test_loss', 'train_loss']) if self.config.get('OTHER', 'save_model', bool): torch.save(self.model.state_dict(), self.config.get('OTHER', 'out_path', str)) def __train(self): for epoch in range(self.config.get('SPECIFICATION', 'epochs', int)): print('Epoch: {}'.format(epoch + 1)) self.model.train() for batch_idx, (data, target) in enumerate(tqdm(self.train_loader)): data, target = data.to(self.device), target.to(self.device) self.optimizer.zero_grad() output = self.model(data) loss = F.nll_loss(output, target, reduction='sum') l1 = sum(p.abs().sum() for p in self.model.parameters()) l2 = sum(p.norm() for p in self.model.parameters()) loss += self.config.get('SPECIFICATION', 'l1', float) * l1 +self. config.get('SPECIFICATION', 'l1', float) * l2 loss.backward() self.gradient_diversity.norm_grads(self.model) self.logger.log('train_loss', loss.item()) self.optimizer.step() self.__test() self.scheduler.step() def __test(self): self.model.eval() test_loss = 0 correct = 0 with torch.no_grad(): for data, target in self.test_loader: data, target = data.to(self.device), target.to(self.device) output = self.model(data) test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability correct += pred.eq(target.view_as(pred)).sum().item() test_loss /= len(self.test_loader.dataset) self.logger.log('test_loss', test_loss) self.logger.log('test_accuracy', correct / len(self.test_loader.dataset)) print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format( test_loss, correct, len(self.test_loader.dataset), 100. * correct / len(self.test_loader.dataset)))
Greedylightning/LeetCode_Second
LinkedList/LinkedListCycle.java
<reponame>Greedylightning/LeetCode_Second class LinkedListCycle{ public boolean hasCircle(ListNode head){ if(head == null || head.next == null) return false; Set<ListNode> set = new HashSet<ListNode>(); ListNode current = head; while(current.next != null){ if(set.contains(current)) return true; else{ set.add(current); current = current.next; } } return false; } public boolean hasCircle(ListNode head){ if(head == null || head.next == null) return false; ListNode slow = head; ListNode fast = head; while(fast.next != null && fast.next.next != null){ slow = slow.next; fast = fast.next.next; if(slow == fast) return true; } return false; } }
ored95/data-analysis-course
dawp2020/hy-data-analysis-with-python-2020/part03-e03_most_frequent_first/src/most_frequent_first.py
<gh_stars>0 #!/usr/bin/env python3 import numpy as np def most_frequent_first(a, c): # Get c-th column col = a[:, c] # Get unique values from col and its frequencies values, counts = np.unique(col, return_counts=True) # Sort values by index in descending order idx = np.argsort(-counts) # minus means negative all elements # Return list indexes of array by sorting descending frequency order order = np.concatenate([np.where(col == x)[0] for x in values[idx]]) # Select 2D-array by order return a[order] def main(): a = np.array([ [5, 0, 3, 3, 7, 9, 3, 5, 2, 4], [7, 6, 8, 8, 1, 6, 7, 7, 8, 1], [5, 9, 8, 9, 4, 3, 0, 3, 5, 0], [2, 3, 8, 1, 3, 3, 3, 7, 0, 1], [9, 9, 0, 4, 7, 3, 2, 7, 2, 0], [0, 4, 5, 5, 6, 8, 4, 1, 4, 9], [8, 1, 1, 7, 9, 9, 3, 6, 7, 2], [0, 3, 5, 9, 4, 4, 6, 4, 4, 3], [4, 4, 8, 4, 3, 7, 5, 5, 0, 1], [5, 9, 3, 0, 5, 0, 1, 2, 4, 2] ]) print(most_frequent_first(a, -1)) pass if __name__ == "__main__": main()
krill11/RoboRavens-UltimateGoal
FtcRobotController/src/main/java/Team7159/OpModes/RoverRuckus/Crater.java
//package Team7159.OpModes.RoverRuckus; // //import com.qualcomm.robotcore.eventloop.opmode.Disabled; //import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; //import com.qualcomm.robotcore.eventloop.opmode.Autonomous; // //import org.firstinspires.ftc.robotcore.external.ClassFactory; //import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer; //import org.firstinspires.ftc.robotcore.external.tfod.Recognition; //import org.firstinspires.ftc.robotcore.external.tfod.TFObjectDetector; // //import java.util.List; // //import Team7159.LegacyRobots.VacuumBot; //import Team7159.Enums.Direction; //import Team7159.Enums.Side; // //@Autonomous(name="Crater") //@Disabled //public class Crater extends LinearOpMode{ // // VacuumBot robot = new VacuumBot(); // // private static final String TFOD_MODEL_ASSET = "RoverRuckus.tflite"; // private static final String LABEL_GOLD_MINERAL = "Gold Mineral"; // private static final String LABEL_SILVER_MINERAL = "Silver Mineral"; // // Side side; // // /* // * IMPORTANT: You need to obtain your own license key to use Vuforia. The string below with which // * 'parameters.vuforiaLicenseKey' is initialized is for illustration only, and will not function. // * A Vuforia 'Development' license key, can be obtained free of charge from the Vuforia developer // * web site at https://developer.vuforia.com/license-manager. // * // * Vuforia license keys are always 380 characters long, and look as if they contain mostly // * random data. As an example, here is a example of a fragment of a valid key: // * ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ... // * Once you've obtained a license key, copy the string from the Vuforia web site // * and paste it in to your code on the next line, between the double quotes. // */ // private static final String VUFORIA_KEY = "<KEY>" + // "<KEY>" + // "<KEY>" + // "<KEY>" + // "<KEY>"; // // /** // * {@link #vuforia} is the variable we will use to store our instance of the Vuforia // * localization engine. // */ // private VuforiaLocalizer vuforia; // // /** // * {@link #tfod} is the variable we will use to store our instance of the Tensor Flow Object // * Detection engine. // */ // private TFObjectDetector tfod; // // @Override // public void runOpMode(){ // // The TFObjectDetector uses the camera frames from the VuforiaLocalizer, so we create that // // first. // initVuforia(); // // initTfod(); // /** Wait for the game to begin */ // telemetry.addData(">", "Press Play to start tracking"); // telemetry.update(); // robot.init(hardwareMap); // waitForStart(); // // robot.AMotor.setPower(0.2); // try { // wait(1000); // robot.AMotor.setPower(0); // robot.strafe(Direction.RIGHT,0.4,0.2); // robot.AMotor.setPower(-0.2); // wait(1000); // }catch(Exception e){ // e.printStackTrace(); // } // /** Activate Tensor Flow Object Detection. */ // if (tfod != null) { // tfod.activate(); // } // // while (side != null) { // if (tfod != null) { // // getUpdatedRecognitions() will return null if no new information is available since // // the last time that call was made. // List<Recognition> updatedRecognitions = tfod.getUpdatedRecognitions(); // if (updatedRecognitions != null) { // telemetry.addData("# Object Detected", updatedRecognitions.size()); // if (updatedRecognitions.size() == 3) { // int goldMineralX = -1; // int silverMineral1X = -1; // int silverMineral2X = -1; // for (Recognition recognition : updatedRecognitions) { // if (recognition.getLabel().equals(LABEL_GOLD_MINERAL)) { // goldMineralX = (int) recognition.getLeft(); // } else if (silverMineral1X == -1) { // silverMineral1X = (int) recognition.getLeft(); // } else { // silverMineral2X = (int) recognition.getLeft(); // } // } // if (goldMineralX != -1 && silverMineral1X != -1 && silverMineral2X != -1) { // if (goldMineralX < silverMineral1X && goldMineralX < silverMineral2X) { // telemetry.addData("Gold Mineral Position", "Left"); // side = Side.LEFT; // } else if (goldMineralX > silverMineral1X && goldMineralX > silverMineral2X) { // telemetry.addData("Gold Mineral Position", "Right"); // side = Side.RIGHT; // } else { // telemetry.addData("Gold Mineral Position", "Center"); // side = Side.CENTER; // } // } // } // telemetry.update(); // } // } // } // // try { // if (side == Side.LEFT) { // telemetry.addData("Strafing", "On the Left side"); // robot.strafe(Direction.LEFT, 0.5, 2); // } else if (side == Side.RIGHT) { // telemetry.addData("Strafing", "On the Right side"); // robot.strafe(Direction.RIGHT,0.5, 2); // } else if (side == Side.CENTER) { // telemetry.addData("Center", "No need to strafe"); // } // telemetry.update(); // }catch (Exception e){ // e.printStackTrace(); // } //// robot.driveDir(Direction.FORWARDS,0.5); //// robot.turn(Direction.LEFT,90); //// robot.driveDir(Direction.FORWARDS,1); //// robot.turn(Direction.LEFT,45); //// robot.driveDir(Direction.FORWARDS,2); //// //Write some code to let down the marker //// robot.driveDir(Direction.BACKWARDS,3.5); // // } // // /** // * Initialize the Vuforia localization engine. // */ // private void initVuforia() { // /* // * Configure Vuforia by creating a Parameter object, and passing it to the Vuforia engine. // */ // VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(); // // parameters.vuforiaLicenseKey = VUFORIA_KEY; // parameters.cameraDirection = VuforiaLocalizer.CameraDirection.BACK; // // // Instantiate the Vuforia engine // vuforia = ClassFactory.getInstance().createVuforia(parameters); // // // Loading trackables is not necessary for the Tensor Flow Object Detection engine. // } // // /** // * Initialize the Tensor Flow Object Detection engine. // */ // private void initTfod() { // int tfodMonitorViewId = hardwareMap.appContext.getResources().getIdentifier( // "tfodMonitorViewId", "id", hardwareMap.appContext.getPackageName()); // TFObjectDetector.Parameters tfodParameters = new TFObjectDetector.Parameters(tfodMonitorViewId); // tfod = ClassFactory.getInstance().createTFObjectDetector(tfodParameters, vuforia); // tfod.loadModelFromAsset(TFOD_MODEL_ASSET, LABEL_GOLD_MINERAL, LABEL_SILVER_MINERAL); // } // // public void strafe(Direction direction, double power, double time){ // if(direction == Direction.LEFT){ // robot.LFMotor.set(-power); // robot.RFMotor.set(power); // robot.LBMotor.set(power); // robot.RBMotor.set(-power); // sleep((int)time * 1000); // }else if(direction == Direction.RIGHT){ // robot.LFMotor.set(power); // robot.RFMotor.set(-power); // robot.LBMotor.set(-power); // robot.RBMotor.set(power); // sleep((int)time * 1000); // }else{ // //Throw an exception about the wrong side // } // } // // public void stopMotors(){ // robot.RFMotor.set(0); // robot.RBMotor.set(0); // robot.LFMotor.set(0); // robot.LBMotor.set(0); // } // //}
chuckbot/social-network
frontend/src/router/index.js
import { createRouter, createWebHashHistory } from "vue-router"; const routes = [ { path: "/", name: "app", redirect: "/home", component: () => import("../App.vue"), }, { path: "/home", name: "home", component: () => import("../views/Home.vue"), meta: { requiresAuth: true }, }, { path: "/about", name: "About", // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ "../views/About.vue"), meta: { guest: true }, }, { path: "/my-profile/:userId", name: "my-profile", component: () => import("../views/MyProfile.vue"), meta: { requiresAuth: true }, }, { path: "/profile/:userId", name: "profile", component: () => import("../views/Profile.vue"), meta: { requiresAuth: true }, }, { path: "/profiles", name: "profiles", component: () => import("../views/Profiles.vue"), meta: { requiresAuth: true }, }, { path: "/moderate-profile/:userId", name: "moderate-profile", component: () => import("../views/ModerateProfile.vue"), meta: { requiresAuth: true }, }, { path: "/post/:postId", name: "post", component: () => import("../views/Post.vue"), meta: { requiresAuth: true }, }, { path: "/post", name: "create-post", component: () => import("../views/CreatePost.vue"), meta: { requiresAuth: true }, }, { path: "/post/modify/:postId", name: "modify-post", component: () => import("../views/ModifyPost.vue"), meta: { requiresAuth: true }, }, ]; const router = createRouter({ history: createWebHashHistory(), routes, }); export default router;
LPadial/AcmeDancer
src/main/java/repositories/TutorialRepository.java
package repositories; import java.util.Collection; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import domain.Tutorial; public interface TutorialRepository extends JpaRepository<Tutorial, Integer>{ //Tutoriales de un academia @Query("select a.tutorials from Academy a where a.id=?1") Collection<Tutorial> tutorialsOfAcademy(int academyID); }
dominieq/rule-work
src/main/java/pl/put/poznan/rulestudio/enums/converters/StringToDefaultClassificationResultTypeConverter.java
<gh_stars>1-10 package pl.put.poznan.rulestudio.enums.converters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.convert.converter.Converter; import pl.put.poznan.rulestudio.enums.DefaultClassificationResultType; import pl.put.poznan.rulestudio.exception.WrongParameterException; public class StringToDefaultClassificationResultTypeConverter implements Converter<String, DefaultClassificationResultType> { private static final Logger logger = LoggerFactory.getLogger(StringToDefaultClassificationResultTypeConverter.class); @Override public DefaultClassificationResultType convert(String source) { try { String snake_case = source.replaceAll("([A-Z]+)([A-Z][a-z])", "$1_$2").replaceAll("([a-z])([A-Z])", "$1_$2"); return DefaultClassificationResultType.valueOf(snake_case.toUpperCase()); } catch (IllegalArgumentException e) { WrongParameterException ex = new WrongParameterException(String.format("Given default classification result \"%s\" is unrecognized.", source)); logger.error(ex.getMessage()); throw ex; } } }
HSLdevcom/hsl-map-publisher-ui
cypress/integration/general.spec.js
const uuidv4 = require('uuid/v4'); const API_URL = Cypress.config().apiUrl; const TEST_PREFIX = 'CY-TEST'; describe('General tests', () => { before(() => { cy.hslLogin(); cy.wait(3000); cy.request('GET', `${API_URL}/builds`) .its('body') .then(buildArr => { const testBuilds = buildArr.filter(build => build.title.includes('CY-TEST')); if (testBuilds.length > 0) { console.log('Removing test builds. This indicates that some tests are probably failing.'); } testBuilds.forEach(testBuild => { cy.request('DELETE', `${API_URL}/builds/${testBuild.id}`); console.log(`Deleting ${testBuild.id}.`); }); }); }); beforeEach(() => { cy.visit('/'); cy.hslLogin(); cy.wait(3000); }); it('Tabs change pages', () => { cy.get('[data-cy=template]').click(); cy.get('[data-cy=list]').click(); cy.get('[data-cy=generate]').click(); }); it('Radio buttons change values', () => { cy.get('[data-cy=Aikataulu]') .click() .should('have.value', 'Timetable'); cy.get('[data-cy=Pysäkkijuliste]') .click() .should('have.value', 'StopPoster'); cy.get('[data-cy=Ajolistat]') .click() .should('have.value', 'group'); cy.get('[data-cy=Pysäkit]') .click() .should('have.value', 'stop'); cy.get('[data-cy=Kesä]') .click() .should('have.value', 'true'); cy.get('[data-cy=Talvi]') .click() .should('have.value', 'false'); }); it('Filter filters list and selecting values works', () => { cy.get('[data-cy=filterInput]') .type('1010109,1010128,1020100') .should('have.value', '1010109,1010128,1020100'); cy.get('[data-cy=1010109]').click(); cy.get('[data-cy=1020100]').click(); }); it('Create template and remove it', () => { cy.get('[data-cy=template]').click(); cy.get('[data-cy=new-template]').click(); cy.get('[data-cy=prompt-ok]').should('have.disabled'); const uuid = `${TEST_PREFIX}-${uuidv4()}`; cy.get('[data-cy=prompt-textfield]') .click() .type(uuid); cy.get('[data-cy=prompt-textfield]').should('have.value', uuid); cy.get('[data-cy=prompt-ok]').should('have.enabled'); cy.server(); cy.route('POST', `${API_URL}/templates`).as('postTemplate'); cy.route('DELETE', `${API_URL}/templates`).as('deleteTemplate'); cy.get('[data-cy=prompt-ok]').click(); cy.get('[data-cy=select-template-with-controls]').click(); cy.get(`[data-cy=${uuid}]`).should('exist'); cy.get(`[data-cy=${uuid}]`).click(); cy.get('[data-cy=remove-template]').click(); cy.get('[data-cy=confirm-ok]').click(); // Doesn't work since data-cy is set to template.label and not .id // Using wait(1000) as workaround. // cy.wait('@deleteTemplate'); cy.wait(1000); cy.get('[data-cy=select-template-with-controls]').click(); cy.get(`[data-cy=${uuid}]`).should('not.exist'); }); it('Test name validation for list', () => { cy.get('[data-cy=create-build]').click(); cy.get('[data-cy=prompt-textfield]').type('/'); cy.get('[data-cy=prompt-ok]').should('have.disabled'); }); it('Create and delete build', () => { const uuid = `${TEST_PREFIX}-${uuidv4()}`; cy.server(); cy.route('POST', `${API_URL}/builds`).as('postBuild'); cy.get('[data-cy=create-build]').click(); cy.get('[data-cy=prompt-textfield]').type(uuid); cy.get('[data-cy=prompt-textfield]').should('have.value', uuid); cy.get('[data-cy=prompt-ok]').should('have.enabled'); cy.get('[data-cy=prompt-ok]').click(); cy.wait('@postBuild'); cy.get('[data-cy=list]').click(); cy.get(`[data-cy=${uuid}]`).should('exist'); cy.request('GET', `${API_URL}/builds`) .its('body') .then(buildArr => { const build = buildArr.find(build => build.title === uuid); cy.route('DELETE', `${API_URL}/builds/${build.id}`).as('deleteBuild'); cy.get(`[data-cy=${uuid}-remove]`).click(); cy.get('[data-cy=confirm-ok]').click(); cy.wait('@deleteBuild'); cy.get(`[data-cy=${uuid}]`).should('not.exist'); }); }); it('Create build and start generating poster', () => { const buildTitle = `${TEST_PREFIX}-${uuidv4()}`; const templateId = `${TEST_PREFIX}-${uuidv4()}`; cy.server(); cy.route('POST', `${API_URL}/builds`).as('postBuild'); cy.route('POST', `${API_URL}/templates`).as('postTemplate'); cy.route('POST', `${API_URL}/posters`).as('postPoster'); cy.get('[data-cy=create-build]').click(); cy.get('[data-cy=prompt-textfield]').type(buildTitle); cy.get('[data-cy=prompt-ok]').click(); cy.wait('@postBuild'); cy.get('[data-cy=template]').click(); cy.get('[data-cy=new-template]').click(); cy.get('[data-cy=prompt-textfield]') .click() .type(templateId); cy.get('[data-cy=prompt-ok]').click(); cy.wait('@postTemplate'); cy.get('[data-cy=generate]').click(); cy.get('[data-cy=filterInput]').type('1010128'); cy.get('[data-cy=1010128]').click(); cy.get('[data-cy=select-template]').click(); cy.get(`[data-cy=${templateId}]`).click(); cy.get('[data-cy=build-select]').click(); cy.get(`[data-cy=${buildTitle}-select]`).click(); cy.get('[data-cy=generate-button]').click(); cy.wait('@postPoster'); cy.get('[data-cy=list]').click(); cy.wait(120000); cy.get(`[data-cy=${buildTitle}-show]`).click(); cy.get(`[data-cy=${buildTitle}-buildDetails]`).contains('Rendered successfully'); cy.get(`[data-cy=build-details-close-button]`).click(); cy.get(`[data-cy=${buildTitle}-remove]`).click(); cy.get('[data-cy=confirm-ok]').click(); cy.get('[data-cy=template]').click(); cy.get('[data-cy=remove-template]').click(); cy.get('[data-cy=confirm-ok]').click(); }); });
brianlizhou/GameAuthoringEnvironment
src/main/java/xml/XMLSerializer.java
<reponame>brianlizhou/GameAuthoringEnvironment package xml; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import gameengine.network.ServerMessage; import objects.ClientGame; import objects.Game; /** * This class is to be called when the Game Editor sends all of its information to the Game Engine * as a single Game instance. It is also used for networking purposes to send and receive server messages. * @author <NAME>(ys101), <NAME>(ess42) */ public class XMLSerializer{ private XStream mySerializer = new XStream(new DomDriver()); public String serializeGame(Game game) { return mySerializer.toXML(game); } public Game getGameFromString(String s) { return (Game)mySerializer.fromXML(s); } public String serializeClientGame(ClientGame game) { return mySerializer.toXML(game); } public ClientGame getClientGameFromString(String s) { return (ClientGame)mySerializer.fromXML(s); } public String serializeServerMessage(ServerMessage msg) { return mySerializer.toXML(msg); } public ServerMessage getServerMessageFromString(String s) { return (ServerMessage)mySerializer.fromXML(s); } }
iKevinY/advent
2018/day24.py
import re import copy import fileinput from utils import parse_line, parse_nums class Group: def __init__(self, is_infection, num, _count, hp, weaknesses, immunities, dmg, type, initiative): self.alliance = 'Infection' if is_infection else 'Immune System' self.is_infection = is_infection self.num = num self.count = _count self.hp = hp self.weaknesses = weaknesses self.immunities = immunities self.dmg = dmg + (0 if self.is_infection else BOOST) self.type = type self.initiative = initiative @property def power(self): return self.count * self.dmg def calc_dmg(self, other): if self.type in other.immunities: return 0 elif self.type in other.weaknesses: return 2 * self.power else: return self.power def deal_dmg(self, other): dmg = self.calc_dmg(other) units_lost = min(dmg // other.hp, other.count) other.count -= units_lost return units_lost def setup_simulation(): immune = {} infect = {} groups = [] for i, line in enumerate(IMMUNE): g = Group(False, i, *line) immune[i] = g groups.append(g) for i, line in enumerate(INFECT): g = Group(True, i, *line) infect[i] = g groups.append(g) return immune, infect, groups # Read problem input IMMUNE = [] INFECT = [] BOOST = 0 DEBUG = False on_infection = False for i, line in enumerate(fileinput.input()): line = line.strip() if line == 'Infection:': on_infection = True continue try: _count, hp, dmg, initiative = parse_nums(line, negatives=False) except Exception: continue clauses = next(iter(re.findall(r'(\(.+\))', line)), None) type = re.findall(r'(\S+) damage', line) type = next(iter(type), None) parts = (clauses or '').replace(',', '').replace('(', '').replace(')', '').split(';') weaknesses = [] immunities = [] if parts[0] != '': for part in parts: things = part.split() if things[0] == 'weak': weaknesses = things[2:] else: immunities = things[2:] group = (_count, hp, weaknesses, immunities, dmg, type, initiative) if on_infection: INFECT.append(group) else: IMMUNE.append(group) def simulate(boost=0): global BOOST BOOST = boost immune, infection, groups = setup_simulation() last_infcount = None last_imscount = None while True: # Target selection targets = {} if DEBUG: for alliance, group in [("Immune System", immune), ("Infection", infection)]: print "{}:".format(alliance) for n, g in group.items(): if g.count > 0: print "Group {} contains {} units".format(n, g.count) print for g in sorted(groups, key=lambda g: (g.power, g.initiative), reverse=True): if g.count == 0: continue other = immune if g.is_infection else infection target_num = None for h in (z for z in groups if z.alliance != g.alliance): if h.count == 0: continue leave = False for a, b in targets.items(): if a[0] == g.alliance and h.num == b: leave = True break if leave: continue if DEBUG: print "{} group {} would deal defending group {} {} damage".format(g.alliance, g.num, h.num, g.calc_dmg(h)) if g.calc_dmg(h) > 0: if target_num is None: target_num = h.num else: poss = other[target_num] if g.calc_dmg(h) > g.calc_dmg(poss): target_num = h.num elif g.calc_dmg(h) == g.calc_dmg(poss): if h.power > poss.power: target_num = h.num elif h.power == poss.power: if h.initiative > poss.initiative: target_num = h.num targets[g.alliance, g.num] = target_num if DEBUG: print # Attack for g in sorted(groups, key=lambda g: g.initiative, reverse=True): other = immune if g.is_infection else infection h = other.get(targets.get((g.alliance, g.num), None), None) if h is None: continue killed = g.deal_dmg(h) if DEBUG: print "{} group {} attacks defending group {}, killing {} units".format(g.alliance, g.num, h.num, killed) if DEBUG: print print infcount = 0 imscount = 0 for g in groups: if g.is_infection: infcount += g.count else: imscount += g.count if infcount == 0: return True, imscount elif imscount == 0: return False, infcount elif infcount == last_infcount and imscount == last_imscount: return False, None last_infcount = infcount last_imscount = imscount print "Units in the winning army:", simulate()[1] lo = 0 hi = 1000 while lo < hi: mid = (lo + hi) // 2 res, count = simulate(mid) if not res: lo = mid + 1 else: hi = mid print "Immune system units after smallest boost ({}): {}".format(mid + 1, simulate(mid + 1)[1])
sgrjr/centerpoint
resources/js/src/components/CustomMenuLink.js
<gh_stars>0 import React from 'react'; import MenuItem from '@material-ui/core/MenuItem'; import IconButton from '@material-ui/core/IconButton'; import Badge from '@material-ui/core/Badge'; import PropTypes from 'prop-types'; import IconPicker from './IconPicker' import { Link } from "react-router-dom"; import Divider from '@material-ui/core/Divider'; class CustomMenuLink extends React.Component { render(){ const {link, toggleDrawer, classes, data} = this.props switch(link.icon){ case 'notifications': return (<MenuItem className={classes.menuItem} style={{marginRight: "15px"}}> <Link to={link.url}> <Badge badgeContent={data.processingCount}> <IconPicker name={link.icon}/> </Badge> {link.text} </Link> </MenuItem>) case 'shoppingCart': return (<MenuItem className={classes.menuItem}> <IconButton aria-label="show 17 new notifications" color="inherit" edge="start" className={classes.menuButton} onClick={toggleDrawer} > <Badge badgeContent={data.cartsCount} color="secondary"> <IconPicker name={link.icon}/> </Badge> </IconButton> </MenuItem>) case "HEADING": return (<MenuItem className={classes.menuItem}> <Divider /> <h2>{link.text}</h2> </MenuItem>) default: return (<Link to={link.url}><MenuItem className={classes.menuItem} style={{marginRight: "15px"}}> <IconPicker name={link.icon}/> {link.text} </MenuItem></Link>) } } } CustomMenuLink.propTypes = { handleProfileMenuOpen: PropTypes.func, link: PropTypes.object, classes: PropTypes.object, toggleDrawer: PropTypes.func, data: PropTypes.object }; export default CustomMenuLink
li6722778/mybisheSer
app/actor/model/ScanCounponModel.java
<filename>app/actor/model/ScanCounponModel.java<gh_stars>0 package actor.model; import java.io.Serializable; public class ScanCounponModel implements Serializable{ public final static int TYPE_DEFAULT = 0; public final static int TYPE_SHARE = 1; /** * */ private static final long serialVersionUID = 1L; public String counponcode; public Long userid; //0:默认优惠卷 1:分享送优惠卷 public int type; public int responseResult; }
giantswarm/kvm-operator
service/controller/resource/serviceaccount/desired_test.go
<gh_stars>10-100 package serviceaccount import ( "context" "testing" "github.com/giantswarm/apiextensions/v3/pkg/apis/provider/v1alpha1" "github.com/giantswarm/micrologger/microloggertest" corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes/fake" ) func Test_Resource_ServiceAccount_GetDesiredState(t *testing.T) { testCases := []struct { Obj interface{} ExpectedName string }{ { Obj: &v1alpha1.KVMConfig{ Spec: v1alpha1.KVMConfigSpec{ Cluster: v1alpha1.Cluster{ ID: "al9qy", }, }, }, ExpectedName: "al9qy", }, { Obj: &v1alpha1.KVMConfig{ Spec: v1alpha1.KVMConfigSpec{ Cluster: v1alpha1.Cluster{ ID: "my-cluster", }, }, }, ExpectedName: "my-cluster", }, } var err error var newResource *Resource { resourceConfig := DefaultConfig() resourceConfig.K8sClient = fake.NewSimpleClientset() resourceConfig.Logger = microloggertest.New() newResource, err = New(resourceConfig) if err != nil { t.Fatal("expected", nil, "got", err) } } for i, tc := range testCases { result, err := newResource.GetDesiredState(context.TODO(), tc.Obj) if err != nil { t.Fatal("case", i+1, "expected", nil, "got", err) } name := result.(*corev1.ServiceAccount).Name if tc.ExpectedName != name { t.Fatalf("case %d expected %#v got %#v", i+1, tc.ExpectedName, name) } } }
dxc-automation/TST
src/main/java/com/sap/config/BrowserManager.java
package com.sap.config; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.Dimension; import org.openqa.selenium.Point; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxDriverLogLevel; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.safari.SafariDriver; import org.openqa.selenium.safari.SafariOptions; import org.testng.annotations.Optional; import static com.sap.properties.FilePaths.firefox_driver_file; public class BrowserManager extends GeneralTestConfig { public void browserConfig(@Optional("chrome") String browser) throws Exception { DesiredCapabilities capability = new DesiredCapabilities(); if (browser.equalsIgnoreCase("chrome")) { WebDriverManager.chromedriver().setup(); ChromeOptions options = new ChromeOptions(); options.addArguments("scripts-type"); options.addArguments("start-maximized"); options.addArguments("--disable-search-geolocation-disclosure"); options.addArguments("--disable-popup-blocking"); options.addArguments("--incognito"); driver = new ChromeDriver(options); LOG.info("| Chrome browser launched successfully |"); } else if (browser.equalsIgnoreCase("firefox")) { System.setProperty("webdriver.gecko.driver", firefox_driver_file); FirefoxProfile profile = new FirefoxProfile(); profile.setAcceptUntrustedCertificates(true); profile.setAssumeUntrustedCertificateIssuer(true); FirefoxOptions options = new FirefoxOptions(); options.setLogLevel(FirefoxDriverLogLevel.TRACE); driver = new FirefoxDriver(); LOG.info("| Firefox browser launched successfully |"); } else if (browser.equalsIgnoreCase("safari")) { capability.setCapability("browserstack.safari.driver", "3.141.59"); capability.setCapability("browserstack.safari.enablePopups", false); capability.setCapability("browserstack.debug", true); capability.setCapability("browserstack.console", "debug"); capability.setCapability("browserstack.networkLogs", true); SafariOptions sOptions = new SafariOptions(); SafariOptions.fromCapabilities(capability); capability.setCapability(SafariOptions.CAPABILITY, sOptions); driver = new SafariDriver(); LOG.info("| Safari browser launched successfully |"); } } // Minimize browser window public void minimizeBrowserWindow() { Point p = driver.manage().window().getPosition(); Dimension d = driver.manage().window().getSize(); driver.manage().window().setPosition(new Point((d.getHeight()-p.getX()), (d.getWidth()-p.getY()))); } // Maximize browser window public void maximizeBrowserWindow() { driver.manage().window().maximize(); } public void tearDownDriver() { driver.quit(); } }
rien/nanoc
nanoc-live/spec/nanoc/live/command_runners/live_spec.rb
<reponame>rien/nanoc # frozen_string_literal: true describe Nanoc::Live::CommandRunners::Live, site: true, stdio: true, fork: true do def run_cmd pipe_stdout_read, pipe_stdout_write = IO.pipe pid = fork do trap(:INT) { exit(0) } pipe_stdout_read.close $stdout = pipe_stdout_write Nanoc::CLI.run(['live']) end pipe_stdout_write.close # Wait until ready Timeout.timeout(5) do progress = 0 pipe_stdout_read.each_line do |line| progress += 1 if line.start_with?('Listening for lib/ changes') progress += 1 if line.start_with?('Listening for site changes') progress += 1 if line.start_with?('View the site at') break if progress == 3 end end sleep 0.5 # Still needs time to warm up… begin yield ensure Process.kill('INT', pid) Process.waitpid(pid) end end it 'watches' do run_cmd do File.write('content/lol.html', 'hej') sleep_until { File.file?('output/lol.html') } expect(File.read('output/lol.html')).to eq('hej') sleep 1.0 # HFS+ mtime resolution is 1s File.write('content/lol.html', 'bye') sleep_until { File.read('output/lol.html') == 'bye' } end end it 'listens' do run_cmd do File.write('content/lol.html', 'hej') sleep_until { File.file?('output/lol.html') } expect(File.read('output/lol.html')).to eq('hej') res = Net::HTTP.get_response(URI.parse('http://127.0.0.1:3000/lol.html')) expect(res.code).to eq('200') expect(res.body).to eq('hej') end end it 'listens for websocket connections' do run_cmd do socket = TCPSocket.new('localhost', 35_729) expect(socket).not_to be_closed end end end
Const-me/vis_avs_dx
avs_dx/DxVisuals/Utils/Intrinsics/Extra/sse2-extra.hpp
// This file is generated automatically by a tool. If you want to change it, fork & modify the tool instead: https://github.com/Const-me/IntelIntrinsics #pragma once #include "../sse.hpp" namespace Intrinsics { namespace Sse { using VecFloat64 = __m128d; // movemask_pd will return this value when every lane has the most significant bit set. static constexpr int allValuesMask_pd = 0x3; using VecInteger = __m128i; // movemask_epi8 will return this value when every lane has the most significant bit set. static constexpr int allValuesMask_epi8 = 0xFFFF; // movemask_epi32 will return this value when every lane has the most significant bit set. static constexpr int allValuesMask_epi32 = allValuesMask_ps; // movemask_epi64 will return this value when every lane has the most significant bit set. static constexpr int allValuesMask_epi64 = allValuesMask_pd; // Shuffle double-precision (64-bit) floating-point elements using the control in "imm8", and store the results in "dst". template<uint8_t c1, uint8_t c2> inline __m128d XM_CALLCONV shuffle_pd( __m128d a, __m128d b ) { static_assert( c1 < 2 && c2 < 2, "Shuffle constants out of range" ); constexpr int imm = _MM_SHUFFLE2( (int)c2, (int)c1 ); return shuffle_pd<imm>( a, b ); } // ==== Basic floating-point arithmetic ==== // Return vector with just the sign bits set inline __m128d XM_CALLCONV signBitsMask_pd() { return set1_pd( -0.0 ); } // Produce vector filled with all ones. The value is NaN, you should only use this for bitwise operations. inline __m128d XM_CALLCONV allones_pd() { return cmpeq_pd( setzero_pd(), setzero_pd() ); } // Absolute value inline __m128d XM_CALLCONV abs( __m128d a ) { const __m128d mask = signBitsMask_pd(); return andnot_pd( mask, a ); } // Flip sign bit inline __m128d XM_CALLCONV negate( __m128d a ) { const __m128d mask = signBitsMask_pd(); return xor_pd( mask, a ); } #if INTRINSICS_SUPPORT_OPERATORS inline __m128d XM_CALLCONV operator +( __m128d a, __m128d b ) { return add_pd( a, b ); } inline __m128d XM_CALLCONV operator -( __m128d a, __m128d b ) { return sub_pd( a, b ); } inline __m128d XM_CALLCONV operator *( __m128d a, __m128d b ) { return mul_pd( a, b ); } inline __m128d XM_CALLCONV operator /( __m128d a, __m128d b ) { return div_pd( a, b ); } inline void XM_CALLCONV operator +=( __m128d &a, __m128d b ) { a = a + b; } inline void XM_CALLCONV operator -=( __m128d &a, __m128d b ) { a = a - b; } inline void XM_CALLCONV operator *=( __m128d &a, __m128d b ) { a = a * b; } inline void XM_CALLCONV operator /=( __m128d &a, __m128d b ) { a = a / b; } // Unary '-' inline __m128d XM_CALLCONV operator -( __m128d a ) { return negate( a ); } #endif // INTRINSICS_SUPPORT_OPERATORS // Test for equality, return true if all lanes are equal inline bool XM_CALLCONV equals( __m128d a, __m128d b ) { return allValuesMask_pd == movemask_pd( cmpeq_pd( a, b ) ); } // Test for inequality, return true if at least one lane is not equal inline bool XM_CALLCONV notEquals( __m128d a, __m128d b ) { return allValuesMask_pd != movemask_pd( cmpeq_pd( a, b ) ); } #if INTRINSICS_SUPPORT_OPERATORS // Comparison operators return per-lane result vectors. inline __m128d XM_CALLCONV operator ==( __m128d a, __m128d b ) { return cmpeq_pd( a, b ); } inline __m128d XM_CALLCONV operator !=( __m128d a, __m128d b ) { return cmpneq_pd( a, b ); } inline __m128d XM_CALLCONV operator >( __m128d a, __m128d b ) { return cmpgt_pd( a, b ); } inline __m128d XM_CALLCONV operator <( __m128d a, __m128d b ) { return cmplt_pd( a, b ); } inline __m128d XM_CALLCONV operator >=( __m128d a, __m128d b ) { return cmpge_pd( a, b ); } inline __m128d XM_CALLCONV operator <=( __m128d a, __m128d b ) { return cmple_pd( a, b ); } #endif // INTRINSICS_SUPPORT_OPERATORS // ==== Bitwise operations ==== #if INTRINSICS_SUPPORT_OPERATORS // Bitwise operator processing the complete vectors inline __m128d XM_CALLCONV operator &( __m128d a, __m128d b ) { return and_pd( a, b ); } inline __m128d XM_CALLCONV operator |( __m128d a, __m128d b ) { return or_pd( a, b ); } inline __m128d XM_CALLCONV operator ^( __m128d a, __m128d b ) { return xor_pd( a, b ); } inline void XM_CALLCONV operator &=( __m128d &a, __m128d b ) { a = a & b; } inline void XM_CALLCONV operator |=( __m128d &a, __m128d b ) { a = a | b; } inline void XM_CALLCONV operator ^=( __m128d &a, __m128d b ) { a = a ^ b; } inline __m128d XM_CALLCONV operator~( __m128d a ) { return xor_pd( a, allones_pd() ); } #endif // INTRINSICS_SUPPORT_OPERATORS // Return vector filled with all one-s. inline __m128i XM_CALLCONV allones_all() { return cmpeq_epi8( setzero_all(), setzero_all() ); } // Set each bit of mask "dst" based on the most significant bit of the corresponding packed 32-bit element in "a". inline int movemask_epi32( __m128i a ) { return movemask_ps( castall_ps( a ) ); } // Set each bit of mask "dst" based on the most significant bit of the corresponding packed 64-bit element in "a". inline int movemask_epi64( __m128i a ) { return movemask_pd( castall_pd( a ) ); } // Test for equality, return true if all lanes are equal inline bool XM_CALLCONV equals( __m128i a, __m128i b ) { return allValuesMask_epi8 == movemask_epi8( cmpeq_epi8( a, b ) ); } // Test for inequality, return true if at least one lane is not equal inline bool XM_CALLCONV notEquals( __m128i a, __m128i b ) { return allValuesMask_epi8 != movemask_epi8( cmpeq_epi8( a, b ) ); } // Shuffle 32-bit integers in "a" within 128-bit lanes template<uint8_t c1, uint8_t c2, uint8_t c3, uint8_t c4> inline __m128i XM_CALLCONV shuffle_epi32( __m128i a ) { static_assert( c1 < 4 && c2 < 4 && c3 < 4 && c4 < 4, "Shuffle constants out of range" ); constexpr int imm = _MM_SHUFFLE( (int)c4, (int)c3, (int)c2, (int)c1 ); return shuffle_epi32<imm>( a ); } // ==== Bitwise operations ==== #if INTRINSICS_SUPPORT_OPERATORS // Bitwise operator processing the complete vectors inline __m128i XM_CALLCONV operator &( __m128i a, __m128i b ) { return and_all( a, b ); } inline __m128i XM_CALLCONV operator |( __m128i a, __m128i b ) { return or_all( a, b ); } inline __m128i XM_CALLCONV operator ^( __m128i a, __m128i b ) { return xor_all( a, b ); } inline void XM_CALLCONV operator &=( __m128i &a, __m128i b ) { a = a & b; } inline void XM_CALLCONV operator |=( __m128i &a, __m128i b ) { a = a | b; } inline void XM_CALLCONV operator ^=( __m128i &a, __m128i b ) { a = a ^ b; } inline __m128i XM_CALLCONV operator~( __m128i a ) { return xor_all( a, allones_all() ); } #endif // INTRINSICS_SUPPORT_OPERATORS // ==== Couple missing integer comparison intrinsics ==== // operator >= inline __m128i XM_CALLCONV cmpge_epi8( __m128i a, __m128i b ) { const __m128i lt = cmplt_epi8( a, b ); return xor_all( lt, allones_all() ); } // operator <= inline __m128i XM_CALLCONV cmple_epi8( __m128i a, __m128i b ) { const __m128i gt = cmpgt_epi8( a, b ); return xor_all( gt, allones_all() ); } // operator != inline __m128i XM_CALLCONV cmpneq_epi8( __m128i a, __m128i b ) { const __m128i ee = cmpeq_epi8( a, b ); return xor_all( ee, allones_all() ); } // operator >= inline __m128i XM_CALLCONV cmpge_epi16( __m128i a, __m128i b ) { const __m128i lt = cmplt_epi16( a, b ); return xor_all( lt, allones_all() ); } // operator <= inline __m128i XM_CALLCONV cmple_epi16( __m128i a, __m128i b ) { const __m128i gt = cmpgt_epi16( a, b ); return xor_all( gt, allones_all() ); } // operator != inline __m128i XM_CALLCONV cmpneq_epi16( __m128i a, __m128i b ) { const __m128i ee = cmpeq_epi16( a, b ); return xor_all( ee, allones_all() ); } // operator >= inline __m128i XM_CALLCONV cmpge_epi32( __m128i a, __m128i b ) { const __m128i lt = cmplt_epi32( a, b ); return xor_all( lt, allones_all() ); } // operator <= inline __m128i XM_CALLCONV cmple_epi32( __m128i a, __m128i b ) { const __m128i gt = cmpgt_epi32( a, b ); return xor_all( gt, allones_all() ); } // operator != inline __m128i XM_CALLCONV cmpneq_epi32( __m128i a, __m128i b ) { const __m128i ee = cmpeq_epi32( a, b ); return xor_all( ee, allones_all() ); } #if INTRINSICS_SUPPORT_OPERATORS namespace Int8 { // Basic arithmetic inline __m128i XM_CALLCONV operator +( __m128i a, __m128i b ) { return add_epi8( a, b ); } inline void XM_CALLCONV operator +=( __m128i& a, __m128i b ) { a = add_epi8( a, b ); } inline __m128i XM_CALLCONV operator -( __m128i a ) { return sub_epi8( setzero_all(), a ); } inline __m128i XM_CALLCONV operator -( __m128i a, __m128i b ) { return sub_epi8( a, b ); } inline void XM_CALLCONV operator -=( __m128i& a, __m128i b ) { a = sub_epi8( a, b ); } // Comparison operators return per-lane result vectors. inline __m128i XM_CALLCONV operator ==( __m128i a, __m128i b ) { return cmpeq_epi8( a, b ); } inline __m128i XM_CALLCONV operator !=( __m128i a, __m128i b ) { return cmpneq_epi8( a, b ); } inline __m128i XM_CALLCONV operator >( __m128i a, __m128i b ) { return cmpgt_epi8( a, b ); } inline __m128i XM_CALLCONV operator <( __m128i a, __m128i b ) { return cmplt_epi8( a, b ); } inline __m128i XM_CALLCONV operator >=( __m128i a, __m128i b ) { return cmpge_epi8( a, b ); } inline __m128i XM_CALLCONV operator <=( __m128i a, __m128i b ) { return cmple_epi8( a, b ); } } // namespace Intrinsics::Sse::Int8 namespace Int16 { // Basic arithmetic inline __m128i XM_CALLCONV operator +( __m128i a, __m128i b ) { return add_epi16( a, b ); } inline void XM_CALLCONV operator +=( __m128i& a, __m128i b ) { a = add_epi16( a, b ); } inline __m128i XM_CALLCONV operator -( __m128i a ) { return sub_epi16( setzero_all(), a ); } inline __m128i XM_CALLCONV operator -( __m128i a, __m128i b ) { return sub_epi16( a, b ); } inline void XM_CALLCONV operator -=( __m128i& a, __m128i b ) { a = sub_epi16( a, b ); } // Comparison operators return per-lane result vectors. inline __m128i XM_CALLCONV operator ==( __m128i a, __m128i b ) { return cmpeq_epi16( a, b ); } inline __m128i XM_CALLCONV operator !=( __m128i a, __m128i b ) { return cmpneq_epi16( a, b ); } inline __m128i XM_CALLCONV operator >( __m128i a, __m128i b ) { return cmpgt_epi16( a, b ); } inline __m128i XM_CALLCONV operator <( __m128i a, __m128i b ) { return cmplt_epi16( a, b ); } inline __m128i XM_CALLCONV operator >=( __m128i a, __m128i b ) { return cmpge_epi16( a, b ); } inline __m128i XM_CALLCONV operator <=( __m128i a, __m128i b ) { return cmple_epi16( a, b ); } } // namespace Intrinsics::Sse::Int16 namespace Int32 { // Basic arithmetic inline __m128i XM_CALLCONV operator +( __m128i a, __m128i b ) { return add_epi32( a, b ); } inline void XM_CALLCONV operator +=( __m128i& a, __m128i b ) { a = add_epi32( a, b ); } inline __m128i XM_CALLCONV operator -( __m128i a ) { return sub_epi32( setzero_all(), a ); } inline __m128i XM_CALLCONV operator -( __m128i a, __m128i b ) { return sub_epi32( a, b ); } inline void XM_CALLCONV operator -=( __m128i& a, __m128i b ) { a = sub_epi32( a, b ); } // Comparison operators return per-lane result vectors. inline __m128i XM_CALLCONV operator ==( __m128i a, __m128i b ) { return cmpeq_epi32( a, b ); } inline __m128i XM_CALLCONV operator !=( __m128i a, __m128i b ) { return cmpneq_epi32( a, b ); } inline __m128i XM_CALLCONV operator >( __m128i a, __m128i b ) { return cmpgt_epi32( a, b ); } inline __m128i XM_CALLCONV operator <( __m128i a, __m128i b ) { return cmplt_epi32( a, b ); } inline __m128i XM_CALLCONV operator >=( __m128i a, __m128i b ) { return cmpge_epi32( a, b ); } inline __m128i XM_CALLCONV operator <=( __m128i a, __m128i b ) { return cmple_epi32( a, b ); } } // namespace Intrinsics::Sse::Int32 #endif // INTRINSICS_SUPPORT_OPERATORS } // namespace Intrinsics::Sse } // namespace Intrinsics
denizyuret/fastsubs
sentence.c
#include <stdio.h> #include "foreach.h" #include "sentence.h" #define SOSTAG "<s>" #define EOSTAG "</s>" #define UNKTAG "<unk>" static Token SOS, EOS, UNK; static void init_special_tokens() { SOS = token_from_string(SOSTAG); EOS = token_from_string(EOSTAG); UNK = token_from_string(UNKTAG); } guint32 sentence_from_string(Sentence st, char *str, int nmax, char **w) { if (SOS == 0) init_special_tokens(); guint32 ntok = 0; g_assert(ntok < nmax); st[++ntok] = SOS; if (w != NULL) w[ntok] = SOSTAG; foreach_token(word, str) { Token wtok = token_try_string(word); g_assert(ntok < nmax); st[++ntok] = (wtok == 0 ? UNK : wtok); if (w != NULL) w[ntok] = word; } g_assert(ntok < nmax); st[++ntok] = EOS; if (w != NULL) w[ntok] = EOSTAG; st[0] = ntok; return ntok; } gfloat sentence_logp(Sentence s, int j, LM lm) { g_assert((j >= 1) && (j <= sentence_size(s))); if (j == 1) return (s[j] == SOS ? 0 : SRILM_LOG0); /* s[1] always SOS */ if (s[j] == SOS) return (j == 1 ? 0 : SRILM_LOG0); /* SOS is only in s[1] */ int i = j - lm->order; if (i < 0) i = 0; gfloat ll = 0; while (i < j) { Token si = s[i]; s[i] = (guint32) (j - i); /* ngram order */ gfloat lp = lm_logP(lm, &s[i]); if (lp != SRILM_LOG0) { ll += lp; s[i] = si; break; } else { s[i]--; ll += lm_logB(lm, &s[i]); s[i] = si; } i++; } g_assert(ll < 0); g_assert(ll > SRILM_LOG0); return ll; } void sentence_print(Sentence s) { for (int i = 1; i <= sentence_size(s); i++) { printf("%s ", token_to_string(s[i])); } printf("\n"); }
noear/solon_demo
demo03.solon_mvc/src/main/java/webapp/controller/RenderCustomController.java
<gh_stars>1-10 package webapp.controller; import org.noear.solon.annotation.Controller; import org.noear.solon.annotation.Mapping; import org.noear.solon.core.handle.Context; import org.noear.solon.core.handle.Render; /** * 控制器实现Render,即可获取自定义渲染权限; * * 可以在有需要的控制器上实现;也可以定义一个基类,然后有需要的控制器继承一下 * * @author noear 2020/12/14 created */ @Mapping("/render/custom/") @Controller public class RenderCustomController implements Render { @Override public void render(Object data, Context ctx) throws Throwable { if (data instanceof RenderCustomController) { //你想自己处理的类型,你自己处理; } else { //不想处理的,交给上下文去处理 ctx.render(data); } } @Mapping("demo") public void demo() { } }
raduceaca1234/Requirements-Engineering
src/main/java/com/example/RequirementsProject/domain/Contact.java
<gh_stars>0 package com.example.RequirementsProject.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Embeddable; @Data @NoArgsConstructor @AllArgsConstructor @Embeddable public class Contact { private String phoneNumber; private String workingHours; private String emailAddress; public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getWorkingHours() { return workingHours; } public void setWorkingHours(String workingHours) { this.workingHours = workingHours; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } }
ArcadeFever/vircadia-content
Marketplace/Cardz/Deck_Handler.js
// // Deck_Handler.js // unpublished/marketplace/ // // Created by Je'Don (ROC) Carter on 9/14/2017 // Copyright 2017 High Fidelity, Inc. // // Server script that controls some card visibility behavior by swapping textures and creating cards // // Distributed under the Apache License, Version 7.1. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // (function() { var _this = this; //channels var cardChannel; //holds ID of all cards var cardIDs = []; //holds number of the last card grabbed var lastCard; //holds names of cards for shuffle var cards = []; var deckLocation; var deckRotation; //id for reset button var resetButton; //number of cards in a deck var NUMBER_OF_CARDS = 52; _this.preload = function(entityID) { print("Loading Deck Handler script."); _this.entityID = entityID; //set last card number lastCard = 52; //position of deck handler deckLocation = Entities.getEntityProperties(entityID).position; deckRotation = Entities.getEntityProperties(entityID).rotation; for (i = 1; i <= NUMBER_OF_CARDS; i++) { cards.push(i); } cards = shuffle(cards); //create a single card var cardProperties = { "type": "Model", "lifetime": -1, "dynamic": true, "damping": 0.98, "angularDamping": 0.98, "gravity": { x: 0, y: -4, z: 0 }, "textures": '{ "HiddenCardFile": "https://hifi-content.s3.amazonaws.com/jedon/Game_Creater_Toolkit/Cardz/DeckOfCardsTexture/CARD_' + cards[51] + '.jpg"}', "rotation": Quat.multiply(deckRotation, Quat.angleAxis(90, {x: 0, y: 0, z: 0})), "dimensions": { x: .07, y: .12, z: .006 }, userData: JSON.stringify({ grabbableKey: { grabbable: true, ignoreIK: false }, "held": false, "card": true, "deckHandlerID": entityID }), "position": { x: deckLocation.x, y: deckLocation.y + (.035), z: deckLocation.z }, "collisionless": false, "collidesWith": "static,dynamic", "modelURL": "https://hifi-content.s3.amazonaws.com/jedon/Game_Creater_Toolkit/Cardz/DeckOfCardsAssets/master_card.fbx", name: "CARD_" + cards[51], shapeType: "box", "script": Script.resolvePath("./Card.js") + "?" + Date.now() }; cardIDs.push(Entities.addEntity(cardProperties)); //find right of deck var direction = Quat.getRight(deckRotation); var distance = .7; var resetPosition = Vec3.sum(deckLocation, Vec3.multiply(direction, distance)); //Make reset button var resetButtonProperties = { "type": "Model", "lifetime": -1, "dynamic": false, "dimensions": { x: .07, y: .12, z: .1 }, userData: JSON.stringify({ grabbableKey: { grabbable: false, ignoreIK: false, wantsTrigger: true }, "deckHandlerID": entityID }), "position": resetPosition, "collisionless": false, "collidesWith": "", "modelURL": "https://hifi-content.s3.amazonaws.com/jedon/Assets/Basic_Cube.fbx", name: "CARD_Reset_Button", shapeType: "box", "script": Script.resolvePath("./Reset_Button.js") + "?" + Date.now() }; resetButton = Entities.addEntity(resetButtonProperties); //get all channels cardChannel = "card-channel-".concat(entityID); resetChannel = "reset-channel-".concat(entityID); Messages.subscribe(cardChannel); Messages.subscribe(resetChannel); Messages.messageReceived.connect(_this, _this.onReceivedMessage); }; _this.onReceivedMessage = function(channel, message, senderID) { if (channel == cardChannel) { showOrHideCard(message); } else if (channel == resetChannel) { resetDeck(); } }; function showOrHideCard(message) { var data = JSON.parse(message); if (data[0] == true) { var cardName = Entities.getEntityProperties(data[1]).name; var usability = { textures: '{ "HiddenCardFile": "https://hifi-content.s3.amazonaws.com/jedon/Game_Creater_Toolkit/Cardz/DeckOfCardsTexture/' + cardName + '.jpg"}', }; Entities.editEntity(data[1], usability); } else if (data[0] == false) { var showChannel = "show-channel".concat(data[1]); var dataToPassBack = [data[2], data[3], data[1]]; Messages.sendMessage(showChannel, JSON.stringify(dataToPassBack)); var cardName = Entities.getEntityProperties(data[1]).name; if ((("CARD_" + cards[lastCard - 1]) == cardName) && (lastCard != 1)) { --lastCard; //position of deck handler deckLocation = Entities.getEntityProperties(_this.entityID).position; deckRotation = Entities.getEntityProperties(_this.entityID).rotation; //spawn card but make it inactive, do this because if a player grabs cards from the deck too fast the scripts dont load on time and it causes confusion. var cardProperties = { "type": "Model", "lifetime": -1, "dynamic": true, "damping": 0.98, "angularDamping": 0.98, "visible": false, "gravity": { x: 0, y: -4, z: 0 }, "textures": '{ "HiddenCardFile": "https://hifi-content.s3.amazonaws.com/jedon/Game_Creater_Toolkit/Cardz/DeckOfCardsTexture/CARD_' + cards[lastCard - 1] + '.jpg"}', "rotation": Quat.multiply(deckRotation, Quat.angleAxis(90, { x: 0, y: 0, z: 0 })), "dimensions": { x: .07, y: .12, z: .006 }, userData: JSON.stringify({ grabbableKey: { grabbable: false, ignoreIK: false }, "held": false, "card": true, "deckHandlerID": _this.entityID }), "position": { x: deckLocation.x, y: deckLocation.y + (.035), z: deckLocation.z }, "collisionless": false, "collidesWith": "", "modelURL": "https://hifi-content.s3.amazonaws.com/jedon/Game_Creater_Toolkit/Cardz/DeckOfCardsAssets/master_card.fbx", name: "CARD_" + cards[lastCard - 1], shapeType: "box", "script": Script.resolvePath("./Card.js") + "?" + Date.now() }; var temporaryIDHolder = Entities.addEntity(cardProperties) cardIDs.push(temporaryIDHolder); //activate the card Script.setTimeout(function () { var allowPickup = { userData: JSON.stringify({ grabbableKey: { grabbable: true, ignoreIK: false }, "held": false, "card": true, "deckHandlerID": _this.entityID }), "collidesWith": "static,dynamic", "visible": true }; Entities.editEntity(temporaryIDHolder, allowPickup); }, 1000); } } } function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } function resetDeck() { //position of deck handler deckLocation = Entities.getEntityProperties(_this.entityID).position; deckRotation = Entities.getEntityProperties(_this.entityID).rotation; //shuffle deck cards = shuffle(cards); //delete all cards for (i = 0; i < NUMBER_OF_CARDS; i++) { Entities.deleteEntity(cardIDs[i]); } cardIDs = []; //create a single card var cardProperties = { "type": "Model", "lifetime": -1, "dynamic": true, "damping": 0.98, "angularDamping": 0.98, "gravity": { x: 0, y: -4, z: 0 }, "textures": '{ "HiddenCardFile": "https://hifi-content.s3.amazonaws.com/jedon/Game_Creater_Toolkit/Cardz/DeckOfCardsTexture/CARD_' + cards[51] + '.jpg"}', "rotation": Quat.multiply(deckRotation, Quat.angleAxis(90, {x: 0, y: 0, z: 0})), "dimensions": { x: .07, y: .12, z: .006 }, userData: JSON.stringify({ grabbableKey: { grabbable: true, ignoreIK: false }, "held": false, "card": true, "deckHandlerID": _this.entityID }), "position": { x: deckLocation.x, y: deckLocation.y + (.035), z: deckLocation.z }, "collisionless": false, "collidesWith": "static,dynamic", "modelURL": "https://hifi-content.s3.amazonaws.com/jedon/Game_Creater_Toolkit/Cardz/DeckOfCardsAssets/master_card.fbx", name: "CARD_" + cards[51], shapeType: "box", "script": Script.resolvePath("./Card.js") + "?" + Date.now() }; cardIDs.push(Entities.addEntity(cardProperties)); //change last card lastCard = 52; } _this.unload = function () { //preload will spawn new cards so you need to delete old ones so reset cube works //delete all cards for (i = 0; i < NUMBER_OF_CARDS; i++) { Entities.deleteEntity(cardIDs[i]); } Entities.deleteEntity(resetButton); cardIDs = []; Messages.unsubscribe(cardChannel); Messages.unsubscribe(resetChannel); Messages.messageReceived.disconnect(_this, _this.onReceivedMessage); }; //Added this because sometimes I was seeing two buttons on reload var removeAssets = function () { //preload will spawn new cards so you need to delete old ones so reset cube works //delete all cards for (i = 0; i < NUMBER_OF_CARDS; i++) { Entities.deleteEntity(cardIDs[i]); } Entities.deleteEntity(resetButton); cardIDs = []; Messages.unsubscribe(cardChannel); Messages.unsubscribe(resetChannel); Messages.messageReceived.disconnect(_this, _this.onReceivedMessage); }; Script.scriptEnding.connect(removeAssets); })
comic/comic-django
app/grandchallenge/emails/tasks.py
<filename>app/grandchallenge/emails/tasks.py<gh_stars>1-10 from celery import shared_task from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.sites.models import Site from django.core.exceptions import ObjectDoesNotExist from django.core.mail import EmailMultiAlternatives, get_connection from django.core.paginator import Paginator from django.template.loader import render_to_string from django.utils.html import strip_tags from django.utils.timezone import now from grandchallenge.core.templatetags.bleach import md2html from grandchallenge.emails.models import Email from grandchallenge.emails.utils import SendActionChoices from grandchallenge.subdomains.utils import reverse def get_receivers(action): if action == SendActionChoices.MAILING_LIST: receivers = ( get_user_model() .objects.filter(user_profile__receive_newsletter=True) .order_by("pk") ) elif action == SendActionChoices.STAFF: receivers = ( get_user_model().objects.filter(is_staff=True).order_by("pk") ) elif action == SendActionChoices.CHALLENGE_ADMINS: receivers = ( get_user_model() .objects.filter( groups__admins_of_challenge__isnull=False, user_profile__receive_newsletter=True, ) .distinct() .order_by("pk") ) elif action == SendActionChoices.READER_STUDY_EDITORS: receivers = ( get_user_model() .objects.filter( groups__editors_of_readerstudy__isnull=False, user_profile__receive_newsletter=True, ) .distinct() .order_by("pk") ) elif action == SendActionChoices.ALGORITHM_EDITORS: receivers = ( get_user_model() .objects.filter( groups__editors_of_algorithm__isnull=False, user_profile__receive_newsletter=True, ) .distinct() .order_by("pk") ) return receivers def send_mass_html_email(datatuple): connection = get_connection() messages = [] for subject, message, sender, recipient, html in datatuple: email = EmailMultiAlternatives( subject, message, sender, recipient, connection=connection ) email.attach_alternative(html, "text/html") messages.append(email) return connection.send_messages(messages) @shared_task(**settings.CELERY_TASK_DECORATOR_KWARGS["acks-late-micro-short"]) def send_bulk_email(action, email_pk): try: email = Email.objects.filter(sent=False).get(pk=email_pk) except ObjectDoesNotExist: return subject = email.subject body = email.body html_body = md2html(body) receivers = get_receivers(action=action) paginator = Paginator(receivers, 100) site = Site.objects.get_current() if email.status_report: start_page = email.status_report["last_processed_batch"] else: start_page = 0 for page_nr in paginator.page_range[start_page:]: messages = [] for recipient in paginator.page(page_nr).object_list: user = get_user_model().objects.get(pk=recipient.pk) link = reverse( "profile-update", kwargs={"username": user.username} ) html_content = render_to_string( "vendor/mailgun_transactional_emails/action.html", { "title": subject, "username": user.username, "content": html_body, "link": link, }, ) html_content_without_linebreaks = html_content.replace("\n", "") text_content = strip_tags(html_content_without_linebreaks) messages.append( ( f"[{site.domain.lower()}] {subject}", text_content, settings.DEFAULT_FROM_EMAIL, [user.email], html_content_without_linebreaks, ) ) send_mass_html_email(messages) email.status_report = {"last_processed_batch": page_nr} email.save() email.sent = True email.sent_at = now() email.status_report = None email.save()
rccarper/aws-sdk-java-v2
test/dynamodbdocument-v1/src/test/java/software/amazon/awssdk/services/dynamodb/document/QueryOutcome.java
/* * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.services.dynamodb.document; import java.util.List; import software.amazon.awssdk.services.dynamodb.document.internal.InternalUtils; import software.amazon.awssdk.services.dynamodb.model.QueryResponse; /** * The outcome of query on DynamoDB table. */ public class QueryOutcome { private final QueryResponse result; /** * @param result the low-level result; must not be null */ public QueryOutcome(QueryResponse result) { if (result == null) { throw new IllegalArgumentException(); } this.result = result; } /** * Returns a non-null list of the returned items; can be empty. */ public List<Item> getItems() { return InternalUtils.toItemList(result.items()); } /** * Returns a non-null low-level result returned from the server side. */ public QueryResponse getQueryResponse() { return result; } @Override public String toString() { return String.valueOf(result); } }
fgulan/p-p-j
semantic-analysis/system-test/additional-examples/b98242ec5c36c83eed5eb61280687283/b98242ec5c36c83eed5eb61280687283.c
<gh_stars>1-10 void foo (int x, int c, char h); int f(void) { return 0; } int x = 3; //int deklaracijaBezDefinicije(int x); int main(void) { int a = 5; const char c = 'i'; int niz[3]; void foo (int x, int c, char h); int x = 5; int y = x + 1; a = a+3; if (a > 2) { int a; int b; a = b; x = 4; } return f(); } int fact(int bzvz); void foo (int x, int c, char h) { int i = fact(x); int a = a+1; void foo3 (void); int niz1[5] = { 1, 2, 3 }; //int niz[10] = a; for (i = 0; i < 5; i++) break; while(1) { break; i = i + 2; } // return 5; return; // break; } char proba3(void) { x = 4; if (0) { x = 6; return 'a'; } else { return (char)97; return 97; } } char proba(void) { return (char)97; } int proba2(void) { // i = 5; return 'a'; } int fact(int n) { foo(1,2,'h'); if (n > 0) return n * fact(n-1); else return 1; } void foo3(void) { int i = 8; // main2(); return; } void f2(int x, int a[]){ x = x + 1; // a[0] = a[0] + 1; } /* int f2(int y) { return 5; } */ // char f2; int main2(void) { int x = 2147483647, y; // int a = 2147483648; (int)'a'; (const char)x; (const int)'a'; (char)((const int)300 + (int)'a'); (int)(char)(const int)(const char)(x + y); return 0; }
datoga/go-form3
pkg/generated/models/account_attributes_identification_address.go
// Code generated by go-swagger; DO NOT EDIT. package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "encoding/json" "log" "github.com/form3tech-oss/go-form3/pkg/client" strfmt "github.com/go-openapi/strfmt" "github.com/go-openapi/errors" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // AccountAttributesIdentificationAddress account attributes identification address // swagger:model AccountAttributesIdentificationAddress type AccountAttributesIdentificationAddress struct { // city // Max Length: 35 // Min Length: 1 City string `json:"city,omitempty"` // country // Pattern: ^[A-Z]{2}$ Country string `json:"country,omitempty"` // street number // Max Length: 140 // Min Length: 1 StreetNumber string `json:"street_number,omitempty"` } func AccountAttributesIdentificationAddressWithDefaults(defaults client.Defaults) *AccountAttributesIdentificationAddress { return &AccountAttributesIdentificationAddress{ City: defaults.GetString("AccountAttributesIdentificationAddress", "city"), Country: defaults.GetString("AccountAttributesIdentificationAddress", "country"), StreetNumber: defaults.GetString("AccountAttributesIdentificationAddress", "street_number"), } } func (m *AccountAttributesIdentificationAddress) WithCity(city string) *AccountAttributesIdentificationAddress { m.City = city return m } func (m *AccountAttributesIdentificationAddress) WithCountry(country string) *AccountAttributesIdentificationAddress { m.Country = country return m } func (m *AccountAttributesIdentificationAddress) WithStreetNumber(streetNumber string) *AccountAttributesIdentificationAddress { m.StreetNumber = streetNumber return m } // Validate validates this account attributes identification address func (m *AccountAttributesIdentificationAddress) Validate(formats strfmt.Registry) error { var res []error if err := m.validateCity(formats); err != nil { res = append(res, err) } if err := m.validateCountry(formats); err != nil { res = append(res, err) } if err := m.validateStreetNumber(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *AccountAttributesIdentificationAddress) validateCity(formats strfmt.Registry) error { if swag.IsZero(m.City) { // not required return nil } if err := validate.MinLength("city", "body", string(m.City), 1); err != nil { return err } if err := validate.MaxLength("city", "body", string(m.City), 35); err != nil { return err } return nil } func (m *AccountAttributesIdentificationAddress) validateCountry(formats strfmt.Registry) error { if swag.IsZero(m.Country) { // not required return nil } if err := validate.Pattern("country", "body", string(m.Country), `^[A-Z]{2}$`); err != nil { return err } return nil } func (m *AccountAttributesIdentificationAddress) validateStreetNumber(formats strfmt.Registry) error { if swag.IsZero(m.StreetNumber) { // not required return nil } if err := validate.MinLength("street_number", "body", string(m.StreetNumber), 1); err != nil { return err } if err := validate.MaxLength("street_number", "body", string(m.StreetNumber), 140); err != nil { return err } return nil } // MarshalBinary interface implementation func (m *AccountAttributesIdentificationAddress) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *AccountAttributesIdentificationAddress) UnmarshalBinary(b []byte) error { var res AccountAttributesIdentificationAddress if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil } func (m *AccountAttributesIdentificationAddress) Json() string { json, err := json.MarshalIndent(m, " ", " ") if err != nil { log.Fatal(err) } return string(json) }
cacerrillos/nhaystack
src/nhaystack/driver/point/learn/BNHaystackLearnStructureJob.java
<gh_stars>0 // // Copyright (c) 2012, J2 Innovations // Licensed under the Academic Free License version 3.0 // // History: // 14 Apr 2014 <NAME> Creation package nhaystack.driver.point.learn; import java.util.*; import javax.baja.control.*; import javax.baja.history.*; import javax.baja.job.*; import javax.baja.log.*; import javax.baja.naming.*; import javax.baja.sys.*; import javax.baja.util.*; import org.projecthaystack.*; import org.projecthaystack.client.*; import nhaystack.*; import nhaystack.driver.*; import nhaystack.driver.history.*; import nhaystack.driver.point.*; import nhaystack.res.*; import nhaystack.server.*; import nhaystack.site.*; /** * BNHaystackLearnStructureJob is a Job which 'learns' all the remote * points from a remote haystack server, and puts them into a folder structure. */ public class BNHaystackLearnStructureJob extends BSimpleJob { /*- class BNHaystackLearnStructureJob { properties { } } -*/ /*+ ------------ BEGIN BAJA AUTO GENERATED CODE ------------ +*/ /*@ $nhaystack.driver.point.learn.BNHaystackLearnStructureJob(1124661438)1.0$ @*/ /* Generated Wed Apr 08 12:16:28 EDT 2015 by Slot-o-Matic 2000 (c) Tridium, Inc. 2000 */ //////////////////////////////////////////////////////////////// // Type //////////////////////////////////////////////////////////////// public Type getType() { return TYPE; } public static final Type TYPE = Sys.loadType(BNHaystackLearnStructureJob.class); /*+ ------------ END BAJA AUTO GENERATED CODE -------------- +*/ public BNHaystackLearnStructureJob() {} public BNHaystackLearnStructureJob(BNHaystackServer server) { this.server = server; BStructureSettings settings = server.getStructureSettings(); this.siteFilter = makeFilter(settings.getSiteFilter()); this.equipFilter = makeFilter(settings.getEquipFilter()); this.pointFilter = makeFilter(settings.getPointFilter()); this.groups = settings.getPointGroupings(); this.groupFilters = new HFilter[groups.length]; for (int i = 0; i < groups.length; i++) groupFilters[i] = HFilter.make(groups[i].getFilter()); } private static HFilter makeFilter(String str) { if (str.equals("")) return HFilter.make("id"); else return HFilter.make(str); } public void doCancel(Context ctx) { super.doCancel(ctx); throw new JobCancelException(); } public void run(Context ctx) throws Exception { try { HClient client = server.getHaystackClient(); traverse(client, HUri.make("equip:/"), server.getPoints()); // rebuild cache BNHaystackService service = (BNHaystackService) Sys.getService(BNHaystackService.TYPE); BNHaystackRebuildCacheJob job = new BNHaystackRebuildCacheJob(service); job.run(null); } catch (Exception e) { e.printStackTrace(); throw e; } } private void traverse(HClient client, HUri parentNav, BComponent parent) { if (LOG.isTraceOn()) LOG.trace("learn structure: nav " + parentNav); // use a name generator to create unique names NameGenerator nameGen = new NameGenerator(); // call the nav() op HGrid req = makeNavGrid(parentNav); HGrid res = client.call("nav", req); for (int i = 0; i < res.numRows(); i++) { HDict rec = res.row(i); // skip things which do not pass the settings if (rec.has("site") && !siteFilter.include(rec, PATHER)) continue; if (rec.has("equip") && !equipFilter.include(rec, PATHER)) continue; if (rec.has("point") && !pointFilter.include(rec, PATHER)) continue; // make a name String name = rec.has("dis") ? rec.getStr("dis") : rec.getStr("navName"); name = SlotPath.escape(nameGen.makeUniqueName(name)); if (rec.has("point")) { createPoint(parent, rec, name); } else { // add site if (rec.has("site")) addSite(rec, name); // make folder BNHaystackPointFolder folder = ensureFolder(parent, name); // add implicit equip if (rec.has("equip") && (folder.get("equip") == null)) folder.add("equip", createEquip(rec, name)); // traverse recursively HUri childNav = (HUri) rec.get("navId"); traverse(client, childNav, folder); } } } private void createPoint(BComponent parent, HDict rec, String name) { String groupName = findGroupName(rec); if (groupName != null) parent = ensureFolder(parent, groupName); BControlPoint point = (BControlPoint) parent.get(name); if (point == null) { point = makeControlPoint(rec); // create haystack dict point.add("haystack", BHDict.make(createHaystackDict(rec).toDict())); // create proxy ext BNHaystackProxyExt ext = (BNHaystackProxyExt) point.getProxyExt(); point.setFacets(BNHaystackLearnPointsJob.makePointFacets(rec)); ext.setId(BHRef.make(rec.id())); ext.setImportedTags(BHTags.make(rec)); // add point parent.add(name, point); // create import if (rec.has("his")) { String hisName = SlotPath.escape(rec.dis()); if (server.getHistories().get(hisName) == null) { // site name BHSite site = (BHSite) idComponents.get(rec.getRef("siteRef")); HDict d = site.getHaystack().getDict(); String siteName = d.has("dis") ? d.getStr("dis") : d.getStr("navName"); siteName = SlotPath.escape(siteName); // equip name BHEquip equip = (BHEquip) idComponents.get(rec.getRef("equipRef")); d = equip.getHaystack().getDict(); String equipName = d.has("dis") ? d.getStr("dis") : d.getStr("navName"); equipName = SlotPath.escape(equipName); BNHaystackHistoryImport imp = new BNHaystackHistoryImport(); BHistoryId hisId = BHistoryId.make( siteName, equipName + "_" + name); imp.setId(BHRef.make(rec.id())); imp.setImportedTags(BHTags.make(rec)); imp.setHistoryId(hisId); server.getHistories().add(hisName, imp); } } } } private void addSite(HDict rec, String name) { BComponent root = (BComponent) BOrd.make("station:|slot:/").get(server, null); BHSite site = (BHSite) root.get(name); if (site == null) { site = new BHSite(); site.setHaystack(BHDict.make(createHaystackDict(rec).toDict())); root.add(name, site); } idComponents.put(rec.id(), site); } private BHEquip createEquip(HDict rec, String name) { BHSite site = (BHSite) idComponents.get(rec.getRef("siteRef")); BHEquip equip = new BHEquip(); // create haystack dict, with ref to site HDictBuilder hdb = createHaystackDict(rec); hdb.add("siteRef", TagManager.makeSlotPathRef(site).getHRef()); hdb.add("navNameFormat", "%parent.displayName%"); equip.setHaystack(BHDict.make(hdb.toDict())); idComponents.put(rec.id(), equip); return equip; } private HDictBuilder createHaystackDict(HDict rec) { HDictBuilder hdb = new HDictBuilder(); Iterator itr = rec.iterator(); while (itr.hasNext()) { Map.Entry e = (Map.Entry) itr.next(); String name = (String) e.getKey(); HVal val = (HVal) e.getValue(); if (!((val instanceof HRef) || (val instanceof HBin) || (val instanceof HUri) || (val instanceof HDate) || (val instanceof HTime) || (val instanceof HDateTime))) hdb.add(name, val); } return hdb; } private String findGroupName(HDict rec) { for (int i = 0; i < groupFilters.length; i++) { if (groupFilters[i].include(rec, PATHER)) return groups[i].getGroupName(); } return null; } private static BControlPoint makeControlPoint(HDict rec) { String kind = rec.getStr("kind"); boolean writable = rec.has("writable"); if (kind.equals("Bool")) { return writable ? (BControlPoint) new BNHaystackBoolWritable() : (BControlPoint) new BNHaystackBoolPoint(); } else if (kind.equals("Number")) { return writable ? (BControlPoint) new BNHaystackNumberWritable() : (BControlPoint) new BNHaystackNumberPoint(); } else if (kind.equals("Str")) { return writable ? (BControlPoint) new BNHaystackStrWritable() : (BControlPoint) new BNHaystackStrPoint(); } else throw new IllegalStateException("Cannot create point for " + kind); } private static BNHaystackPointFolder ensureFolder(BComponent parent, String name) { BNHaystackPointFolder folder = (BNHaystackPointFolder) parent.get(name); if (folder == null) parent.add(name, folder = new BNHaystackPointFolder()); return folder; } private static HGrid makeNavGrid(HUri navId) { HDictBuilder hd = new HDictBuilder(); hd.add("navId", navId); return HGridBuilder.dictsToGrid(new HDict[] { hd.toDict() }); } //////////////////////////////////////////////////////////////// // Attributes //////////////////////////////////////////////////////////////// private static final Log LOG = Log.getLog("nhaystack.driver"); private BNHaystackServer server; private HFilter siteFilter; private HFilter equipFilter; private HFilter pointFilter; private BPointGrouping[] groups; private HFilter[] groupFilters; private HFilter.Pather PATHER = new HFilter.Pather() { public HDict find(String ref) { return null; } }; private Map idComponents = new HashMap(); }
vrazdalovschi/kbcli
kbclient/payment/void_payment_responses.go
<gh_stars>10-100 // Code generated by go-swagger; DO NOT EDIT. package payment // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/runtime" "github.com/killbill/kbcli/v2/kbcommon" strfmt "github.com/go-openapi/strfmt" ) // VoidPaymentReader is a Reader for the VoidPayment structure. type VoidPaymentReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *VoidPaymentReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 204: result := NewVoidPaymentNoContent() result.HttpResponse = response if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil default: errorResult := kbcommon.NewKillbillError(response.Code()) if err := consumer.Consume(response.Body(), &errorResult); err != nil && err != io.EOF { return nil, err } return nil, errorResult } } // NewVoidPaymentNoContent creates a VoidPaymentNoContent with default headers values func NewVoidPaymentNoContent() *VoidPaymentNoContent { return &VoidPaymentNoContent{} } /*VoidPaymentNoContent handles this case with default header values. Successful operation */ type VoidPaymentNoContent struct { HttpResponse runtime.ClientResponse } func (o *VoidPaymentNoContent) Error() string { return fmt.Sprintf("[DELETE /1.0/kb/payments/{paymentId}][%d] voidPaymentNoContent ", 204) } func (o *VoidPaymentNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil } // NewVoidPaymentBadRequest creates a VoidPaymentBadRequest with default headers values func NewVoidPaymentBadRequest() *VoidPaymentBadRequest { return &VoidPaymentBadRequest{} } /*VoidPaymentBadRequest handles this case with default header values. Invalid paymentId supplied */ type VoidPaymentBadRequest struct { HttpResponse runtime.ClientResponse } func (o *VoidPaymentBadRequest) Error() string { return fmt.Sprintf("[DELETE /1.0/kb/payments/{paymentId}][%d] voidPaymentBadRequest ", 400) } func (o *VoidPaymentBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil } // NewVoidPaymentPaymentRequired creates a VoidPaymentPaymentRequired with default headers values func NewVoidPaymentPaymentRequired() *VoidPaymentPaymentRequired { return &VoidPaymentPaymentRequired{} } /*VoidPaymentPaymentRequired handles this case with default header values. Transaction declined by gateway */ type VoidPaymentPaymentRequired struct { HttpResponse runtime.ClientResponse } func (o *VoidPaymentPaymentRequired) Error() string { return fmt.Sprintf("[DELETE /1.0/kb/payments/{paymentId}][%d] voidPaymentPaymentRequired ", 402) } func (o *VoidPaymentPaymentRequired) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil } // NewVoidPaymentNotFound creates a VoidPaymentNotFound with default headers values func NewVoidPaymentNotFound() *VoidPaymentNotFound { return &VoidPaymentNotFound{} } /*VoidPaymentNotFound handles this case with default header values. Account or payment not found */ type VoidPaymentNotFound struct { HttpResponse runtime.ClientResponse } func (o *VoidPaymentNotFound) Error() string { return fmt.Sprintf("[DELETE /1.0/kb/payments/{paymentId}][%d] voidPaymentNotFound ", 404) } func (o *VoidPaymentNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil } // NewVoidPaymentUnprocessableEntity creates a VoidPaymentUnprocessableEntity with default headers values func NewVoidPaymentUnprocessableEntity() *VoidPaymentUnprocessableEntity { return &VoidPaymentUnprocessableEntity{} } /*VoidPaymentUnprocessableEntity handles this case with default header values. Payment is aborted by a control plugin */ type VoidPaymentUnprocessableEntity struct { HttpResponse runtime.ClientResponse } func (o *VoidPaymentUnprocessableEntity) Error() string { return fmt.Sprintf("[DELETE /1.0/kb/payments/{paymentId}][%d] voidPaymentUnprocessableEntity ", 422) } func (o *VoidPaymentUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil } // NewVoidPaymentBadGateway creates a VoidPaymentBadGateway with default headers values func NewVoidPaymentBadGateway() *VoidPaymentBadGateway { return &VoidPaymentBadGateway{} } /*VoidPaymentBadGateway handles this case with default header values. Failed to submit payment transaction */ type VoidPaymentBadGateway struct { HttpResponse runtime.ClientResponse } func (o *VoidPaymentBadGateway) Error() string { return fmt.Sprintf("[DELETE /1.0/kb/payments/{paymentId}][%d] voidPaymentBadGateway ", 502) } func (o *VoidPaymentBadGateway) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil } // NewVoidPaymentServiceUnavailable creates a VoidPaymentServiceUnavailable with default headers values func NewVoidPaymentServiceUnavailable() *VoidPaymentServiceUnavailable { return &VoidPaymentServiceUnavailable{} } /*VoidPaymentServiceUnavailable handles this case with default header values. Payment in unknown status, failed to receive gateway response */ type VoidPaymentServiceUnavailable struct { HttpResponse runtime.ClientResponse } func (o *VoidPaymentServiceUnavailable) Error() string { return fmt.Sprintf("[DELETE /1.0/kb/payments/{paymentId}][%d] voidPaymentServiceUnavailable ", 503) } func (o *VoidPaymentServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil } // NewVoidPaymentGatewayTimeout creates a VoidPaymentGatewayTimeout with default headers values func NewVoidPaymentGatewayTimeout() *VoidPaymentGatewayTimeout { return &VoidPaymentGatewayTimeout{} } /*VoidPaymentGatewayTimeout handles this case with default header values. Payment operation timeout */ type VoidPaymentGatewayTimeout struct { HttpResponse runtime.ClientResponse } func (o *VoidPaymentGatewayTimeout) Error() string { return fmt.Sprintf("[DELETE /1.0/kb/payments/{paymentId}][%d] voidPaymentGatewayTimeout ", 504) } func (o *VoidPaymentGatewayTimeout) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil }
z-zxq-123456/myproject
personalRabbitmp/src/main/java/com/example/rabbitmp/consumer/FirstConsumer2.java
package com.example.rabbitmp.consumer; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component @RabbitListener(queues = "FIRST_QUEUE") public class FirstConsumer2 { @RabbitHandler public void receive(String message){ System.out.println("first2 queue receive message + "+message); } }
Didotto/QT-GUI-Miner
apps/QT-GUI-Client/src/main/controller/SaveController.java
package controller; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.SocketException; import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanBinding; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.stage.Stage; import view.AlertDialog; import javafx.scene.control.Alert.AlertType; import model.DataModel; import javafx.scene.input.MouseEvent; import javafx.scene.control.ButtonType; import java.util.Optional; /** * This class manages some events generated by the graphic elements present in the "SaveView" view */ public class SaveController extends Controller{ @FXML private Button saveButton; @FXML private Button resetButton; @FXML private TextField fileName; private ObjectInputStream input; private ObjectOutputStream output; /** * Builds an object instance of SaveController and initialize the attributes * Handles binds of buttons and textfields * @param model the info of the client * @param controlledStage references to the stage of the window */ public void init(DataModel model, Stage controlledStage) { super.init(model, controlledStage); input = model.getInputStream(); output = model.getOutputStream(); //Binding resetButton and saveButton BooleanBinding isfileNameEmpty = Bindings.isEmpty(fileName.textProperty()); resetButton.disableProperty().bind(isfileNameEmpty); saveButton.disableProperty().bind(isfileNameEmpty); } /** * Handler for the event generated by the click of the "Reset" button * @param e the event generated by Reset click */ public void resetClicked (MouseEvent e) { if (!fileName.getText().equals("")) { fileName.clear(); } } /** * Handler for the event generated by the click of the "Save" button (asks the user for the file name, if the server already has a file with this * name it asks whether to overwrite it or not) * @param ev the event generated by Save click */ public void saveClicked (MouseEvent ev) { try { storeClustersInFile(); }catch(SocketException e) { new AlertDialog(AlertType.ERROR, "ERROR", "CONNECTION ERROR", "Try to connect again to the server!" ); }catch(ServerException e) { new AlertDialog(AlertType.ERROR, "ERROR", "SERVER ERROR", e.getMessage() ); }catch (IOException | ClassNotFoundException e) { new AlertDialog(AlertType.ERROR, "ERROR", "COMMUNICATION ERROR", "An error occurred while communicating with the server!" ); } } /** * Send to server the name user specified, if the server already has a file with the name specified then, * it tells the client which will "ask" the user if he wants to overwrite it or not. * The result will be communicated to the server * @throws SocketException Thrown to indicate that there is an error creating or accessing a Socket. * @throws IOException Signals that an I/O exception of some sort has occurred. * @throws ClassNotFoundException Thrown when an application tries to load in a class through its string name * @throws ServerException Thrown if there is something wrong with the communication with server */ private void storeClustersInFile() throws SocketException,ServerException,IOException,ClassNotFoundException{ output.writeObject(2); output.writeObject(fileName.getText()); if(((String)input.readObject()).equals("OK")) { new AlertDialog(AlertType.INFORMATION, "SAVING DIALOG", "ALL RIGHT !", "Saving Successful !", "successful_Icon.png" ); String result = (String)input.readObject(); if(!result.equals("OK")) throw new ServerException(result); }else { AlertDialog a= new AlertDialog(AlertType.CONFIRMATION, "SAVING DIALOG", "WE'RE ALMOST DONE !", "Do you want to overwrite the file ?" ); Optional<ButtonType> result = a.showAndWait(); if (result.get() == ButtonType.OK){ output.writeObject("Y"); new AlertDialog(AlertType.INFORMATION, "SAVING DIALOG", "ALL RIGHT !", "Saving Successful !", "successful_Icon.png" ); String results = (String)input.readObject(); if(!results.equals("OK")) throw new ServerException(results); }else { output.writeObject("N"); } } //CHIUDO LA FINESTRA controlledStage.close(); } }
poliglota-ti/hubspot-api-ruby
spec/features/crm/schemas/core_api_spec.rb
<reponame>poliglota-ti/hubspot-api-ruby<gh_stars>10-100 require 'spec_helper' describe 'Hubspot::Crm::Schemas::CoreApi' do subject(:core_api) { Hubspot::Crm::Schemas::CoreApi.new } it { is_expected.to respond_to(:archive) } it { is_expected.to respond_to(:archive_association) } it { is_expected.to respond_to(:create) } it { is_expected.to respond_to(:create_association) } it { is_expected.to respond_to(:get_all) } it { is_expected.to respond_to(:get_by_id) } it { is_expected.to respond_to(:update) } end
creative-sensor/echo-home
codev/RemoteMP3Player/src/java/db/exfacades/Mp3itemFacadeExt.java
<reponame>creative-sensor/echo-home /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package db.exfacades; import db.facades.AbstractFacade; import entity.Mp3item; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author creativ */ @Stateless public class Mp3itemFacadeExt extends AbstractFacade<Mp3item> implements Mp3itemFacadeLocalExt { @PersistenceContext(unitName = "RemoteMP3PlayerPU") private EntityManager em; String queryStr="SELECT i from Mp3item i where i.name like :keyword or i.artist like :keyword"; @Override protected EntityManager getEntityManager() { return em; } public Mp3itemFacadeExt() { super(Mp3item.class); } @Override public List<Mp3item> search(String keyword) { Query query = em.createQuery(queryStr, Mp3item.class); query.setParameter("keyword", "%" + keyword + "%"); return query.getResultList(); } }
kgudger/ResistorCam
node_modules/cordova/node_modules/npm/test/tap/peer-deps-invalid.js
var fs = require('graceful-fs') var path = require('path') var mkdirp = require('mkdirp') var mr = require('npm-registry-mock') var osenv = require('osenv') var rimraf = require('rimraf') var test = require('tap').test var Tacks = require('tacks') var Dir = Tacks.Dir var File = Tacks.File var npm = require('../../') var common = require('../common-tap') var testdir = path.resolve(__dirname, path.basename(__filename, '.js')) var cachedir = path.resolve(testdir, 'cache') var fixtures = new Tacks(Dir({ cache: Dir({}), 'package.json': File({ author: '<NAME> <<EMAIL>> (http://domenicdenicola.com/)', name: 'peer-deps-invalid', version: '0.0.0', dependencies: { 'npm-test-peer-deps-file': 'file-ok/', 'npm-test-peer-deps-file-invalid': 'file-fail/' } }), 'file-ok': Dir({ 'package.json': File({ name: 'npm-test-peer-deps-file', main: 'index.js', version: '1.2.3', description:'This one should conflict with the other one', peerDependencies: { underscore: '1.3.1' }, dependencies: { mkdirp: '0.3.5' } }), 'index.js': File( "module.exports = 'I\'m just a lonely index, naked as the day I was born.'" ), }), 'file-fail': Dir({ 'package.json': File({ name: 'npm-test-peer-deps-file-invalid', main: 'index.js', version: '1.2.3', description:'This one should conflict with the other one', peerDependencies: { underscore: '1.3.3' } }), 'index.js': File( "module.exports = 'I\'m just a lonely index, naked as the day I was born.'" ), }), })) test('setup', function (t) { cleanup() fixtures.create(testdir) process.chdir(testdir) t.end() }) test('installing dependencies that have conflicting peerDependencies', function (t) { mr({port: common.port}, function (err, s) { // create mock registry. t.ifError(err, 'mock registry started') npm.load({ cache: cachedir, registry: common.registry }, function () { npm.commands.install([], function (err) { if (!err) { t.fail("No error!") } else { t.equal(err.code, "EPEERINVALID") t.equal(err.packageName, "underscore") t.match(err.packageVersion, /^1\.3\.[13]$/) t.match(err.message, /^The package underscore@1\.3\.[13] does not satisfy its siblings' peerDependencies requirements!$/) } s.close() // shutdown mock registry. t.end() }) }) }) }) test('cleanup', function (t) { cleanup() t.end() }) function cleanup () { fixtures.remove(testdir) }
Titzi90/hpx
hpx/parallel/util/scan_partitioner.hpp
// Copyright (c) 2007-2015 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !defined(HPX_PARALLEL_UTIL_SCAN_PARTITIONER_DEC_30_2014_0227PM) #define HPX_PARALLEL_UTIL_SCAN_PARTITIONER_DEC_30_2014_0227PM #include <hpx/hpx_fwd.hpp> #include <hpx/async.hpp> #include <hpx/exception_list.hpp> #include <hpx/lcos/wait_all.hpp> #include <hpx/lcos/local/dataflow.hpp> #include <hpx/util/bind.hpp> #include <hpx/util/decay.hpp> #include <hpx/parallel/execution_policy.hpp> #include <hpx/parallel/util/detail/chunk_size.hpp> #include <hpx/parallel/util/detail/handle_local_exceptions.hpp> #include <hpx/parallel/traits/extract_partitioner.hpp> /////////////////////////////////////////////////////////////////////////////// namespace hpx { namespace parallel { namespace util { /////////////////////////////////////////////////////////////////////////// namespace detail { /////////////////////////////////////////////////////////////////////// // The static partitioner simply spawns one chunk of iterations for // each available core. template <typename ExPolicy, typename R, typename Result = void> struct static_scan_partitioner { template <typename FwdIter, typename T, typename F1, typename F2, typename F3> static R call(ExPolicy const& policy, FwdIter first, std::size_t count_, T && init, F1 && f1, F2 && f2, F3 && f3, std::size_t chunk_size) { std::vector<hpx::shared_future<Result> > workitems; std::vector<std::size_t> chunk_sizes; std::list<boost::exception_ptr> errors; try { // pre-initialize first intermediate result workitems.push_back(make_ready_future(std::forward<T>(init))); // estimate a chunk size based on number of cores used std::size_t count = count_; chunk_size = get_static_chunk_size(policy, workitems, f1, first, count, chunk_size); HPX_ASSERT(workitems.size() == 2); // schedule every chunk on a separate thread workitems.reserve(count_ / chunk_size + 2); chunk_sizes.reserve(workitems.capacity()); chunk_sizes.push_back(count_ - count); // pre-initialize second intermediate result workitems[1] = lcos::local::dataflow(hpx::launch::sync, f2, workitems[0], workitems[1]); // Schedule first step of scan algorithm, step 2 is // performed as soon as the current partition and the // partition to the left is ready. threads::executor exec = policy.get_executor(); while (count != 0) { std::size_t chunk = (std::min)(chunk_size, count); if (exec) { workitems.push_back( lcos::local::dataflow( hpx::launch::sync, f2, workitems.back(), hpx::async(exec, f1, first, chunk) )); } else { workitems.push_back( lcos::local::dataflow( hpx::launch::sync, f2, workitems.back(), hpx::async(hpx::launch::fork, f1, first, chunk) )); } chunk_sizes.push_back(chunk); count -= chunk; std::advance(first, chunk); } } catch (...) { detail::handle_local_exceptions<ExPolicy>::call( boost::current_exception(), errors); } // wait for all tasks to finish hpx::wait_all(workitems); detail::handle_local_exceptions< ExPolicy>::call(workitems, errors); // Execute step 3 of the scan algorithm return f3(std::move(workitems), chunk_sizes); } }; template <typename R, typename Result> struct static_scan_partitioner<parallel_task_execution_policy, R, Result> { template <typename FwdIter, typename T, typename F1, typename F2, typename F3> static hpx::future<R> call( parallel_task_execution_policy const& policy, FwdIter first, std::size_t count_, T && init, F1 && f1, F2 && f2, F3 && f3, std::size_t chunk_size) { std::vector<hpx::shared_future<Result> > workitems; std::vector<std::size_t> chunk_sizes; std::list<boost::exception_ptr> errors; try { // pre-initialize first intermediate result workitems.push_back(make_ready_future(std::forward<T>(init))); // estimate a chunk size based on number of cores used std::size_t count = count_; chunk_size = get_static_chunk_size(policy, workitems, f1, first, count, chunk_size); HPX_ASSERT(workitems.size() == 2); // schedule every chunk on a separate thread workitems.reserve(count_ / chunk_size + 2); chunk_sizes.reserve(workitems.capacity()); chunk_sizes.push_back(count_ - count); // pre-initialize second intermediate result workitems[1] = lcos::local::dataflow(hpx::launch::sync, f2, workitems[0], workitems[1]); // Schedule first step of scan algorithm, step 2 is // performed as soon as the current partition and the // partition to the left is ready. threads::executor exec = policy.get_executor(); while (count != 0) { std::size_t chunk = (std::min)(chunk_size, count); if (exec) { workitems.push_back( lcos::local::dataflow( hpx::launch::sync, f2, workitems.back(), hpx::async(exec, f1, first, chunk) )); } else { workitems.push_back( lcos::local::dataflow( hpx::launch::sync, f2, workitems.back(), hpx::async(hpx::launch::fork, f1, first, chunk) )); } chunk_sizes.push_back(chunk); count -= chunk; std::advance(first, chunk); } } catch (std::bad_alloc const&) { return hpx::make_exceptional_future<R>( boost::current_exception()); } catch (...) { errors.push_back(boost::current_exception()); } typedef typename parallel::detail::algorithm_result< parallel_task_execution_policy, R >::type result_type; // wait for all tasks to finish return lcos::local::dataflow( [=](std::vector<hpx::shared_future<Result> >&& r) mutable -> result_type { detail::handle_local_exceptions< parallel_task_execution_policy >::call(r, errors); // Execute step 3 of the scan algorithm return f3(std::move(r), chunk_sizes); }, std::move(workitems)); } }; /////////////////////////////////////////////////////////////////////// // ExPolicy: execution policy // R: overall result type // Result: intermediate result type of first step // PartTag: select appropriate partitioner template <typename ExPolicy, typename R, typename Result, typename PartTag> struct scan_partitioner; /////////////////////////////////////////////////////////////////////// template <typename ExPolicy, typename R, typename Result> struct scan_partitioner<ExPolicy, R, Result, parallel::traits::static_partitioner_tag> { template <typename FwdIter, typename T, typename F1, typename F2, typename F3> static R call(ExPolicy const& policy, FwdIter first, std::size_t count, T && init, F1 && f1, F2 && f2, F3 && f3, std::size_t chunk_size = 0) { return static_scan_partitioner<ExPolicy, R, Result>::call( policy, first, count, std::forward<T>(init), std::forward<F1>(f1), std::forward<F2>(f2), std::forward<F3>(f3), chunk_size); } }; template <typename R, typename Result> struct scan_partitioner<parallel_task_execution_policy, R, Result, parallel::traits::static_partitioner_tag> { template <typename FwdIter, typename T, typename F1, typename F2, typename F3> static hpx::future<R> call( parallel_task_execution_policy const& policy, FwdIter first, std::size_t count, T && init, F1 && f1, F2 && f2, F3 && f3, std::size_t chunk_size = 0) { return static_scan_partitioner< parallel_task_execution_policy, R, Result >::call(policy, first, count, std::forward<T>(init), std::forward<F1>(f1), std::forward<F2>(f2), std::forward<F3>(f3), chunk_size); } }; /////////////////////////////////////////////////////////////////////// template <typename ExPolicy, typename R, typename Result> struct scan_partitioner<ExPolicy, R, Result, parallel::traits::default_partitioner_tag> : scan_partitioner<ExPolicy, R, Result, parallel::traits::static_partitioner_tag> {}; } /////////////////////////////////////////////////////////////////////////// template <typename ExPolicy, typename R = void, typename Result = R, typename PartTag = typename parallel::traits::extract_partitioner< typename hpx::util::decay<ExPolicy>::type >::type> struct scan_partitioner : detail::scan_partitioner< typename hpx::util::decay<ExPolicy>::type, R, Result, PartTag> {}; }}} #endif
iFun/Project-G
solutions/0637-average-of-levels-in-binary-tree/average-of-levels-in-binary-tree.py
# Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. # # Example 1: # # Input: # 3 # / \ # 9 20 # / \ # 15 7 # Output: [3, 14.5, 11] # Explanation: # The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. # # # # Note: # # The range of node's value is in the range of 32-bit signed integer. # # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: if not root: return [] queue = deque() result = [] queue.append(root) while queue: level = len(queue) total = 0 for _ in range(level): current = queue.popleft() total += current.val if current.left: queue.append(current.left) if current.right: queue.append(current.right) result.append(total/level) return result