code
stringlengths
2
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
2
1.05M
odoo.define('website_slides/static/src/tests/activity_tests.js', function (require) { 'use strict'; const components = { Activity: require('mail/static/src/components/activity/activity.js'), }; const { afterEach, beforeEach, createRootComponent, start, } = require('mail/static/src/utils/test_utils.js'); QUnit.module('website_slides', {}, function () { QUnit.module('components', {}, function () { QUnit.module('activity', {}, function () { QUnit.module('activity_tests.js', { beforeEach() { beforeEach(this); this.createActivityComponent = async activity => { await createRootComponent(this, components.Activity, { props: { activityLocalId: activity.localId }, target: this.widget.el, }); }; this.start = async params => { const { env, widget } = await start(Object.assign({}, params, { data: this.data, })); this.env = env; this.widget = widget; }; }, afterEach() { afterEach(this); }, }); QUnit.test('grant course access', async function (assert) { assert.expect(8); await this.start({ async mockRPC(route, args) { if (args.method === 'action_grant_access') { assert.strictEqual(args.args.length, 1); assert.strictEqual(args.args[0].length, 1); assert.strictEqual(args.args[0][0], 100); assert.strictEqual(args.kwargs.partner_id, 5); assert.step('access_grant'); } return this._super(...arguments); }, }); const activity = this.env.models['mail.activity'].create({ id: 100, canWrite: true, thread: [['insert', { id: 100, model: 'slide.channel', }]], requestingPartner: [['insert', { id: 5, displayName: "Pauvre pomme", }]], type: [['insert', { id: 1, displayName: "Access Request", }]], }); await this.createActivityComponent(activity); assert.containsOnce(document.body, '.o_Activity', "should have activity component"); assert.containsOnce(document.body, '.o_Activity_grantAccessButton', "should have grant access button"); document.querySelector('.o_Activity_grantAccessButton').click(); assert.verifySteps(['access_grant'], "Grant button should trigger the right rpc call"); }); QUnit.test('refuse course access', async function (assert) { assert.expect(8); await this.start({ async mockRPC(route, args) { if (args.method === 'action_refuse_access') { assert.strictEqual(args.args.length, 1); assert.strictEqual(args.args[0].length, 1); assert.strictEqual(args.args[0][0], 100); assert.strictEqual(args.kwargs.partner_id, 5); assert.step('access_refuse'); } return this._super(...arguments); }, }); const activity = this.env.models['mail.activity'].create({ id: 100, canWrite: true, thread: [['insert', { id: 100, model: 'slide.channel', }]], requestingPartner: [['insert', { id: 5, displayName: "Pauvre pomme", }]], type: [['insert', { id: 1, displayName: "Access Request", }]], }); await this.createActivityComponent(activity); assert.containsOnce(document.body, '.o_Activity', "should have activity component"); assert.containsOnce(document.body, '.o_Activity_refuseAccessButton', "should have refuse access button"); document.querySelector('.o_Activity_refuseAccessButton').click(); assert.verifySteps(['access_refuse'], "refuse button should trigger the right rpc call"); }); }); }); }); });
rven/odoo
addons/website_slides/static/src/components/activity/activity_tests.js
JavaScript
agpl-3.0
3,940
/*****************************************/ /* Written by andrew.wilkins@csiro.au */ /* Please contact me if you make changes */ /*****************************************/ #include "RichardsExcavFlow.h" #include "Function.h" #include "Material.h" template<> InputParameters validParams<RichardsExcavFlow>() { InputParameters params = validParams<SideIntegralVariablePostprocessor>(); params.addRequiredParam<FunctionName>("excav_geom_function", "The function describing the excavation geometry (type RichardsExcavGeom)"); params.addRequiredParam<UserObjectName>("richardsVarNames_UO", "The UserObject that holds the list of Richards variable names."); params.addClassDescription("Records total flow INTO an excavation (if quantity is positive then flow has occured from rock into excavation void)"); return params; } RichardsExcavFlow::RichardsExcavFlow(const std::string & name, InputParameters parameters) : SideIntegralVariablePostprocessor(name, parameters), _richards_name_UO(getUserObject<RichardsVarNames>("richardsVarNames_UO")), _pvar(_richards_name_UO.richards_var_num(_var.number())), _flux(getMaterialProperty<std::vector<RealVectorValue> >("flux")), _func(getFunction("excav_geom_function")) {} Real RichardsExcavFlow::computeQpIntegral() { return -_func.value(_t, _q_point[_qp])*_normals[_qp]*_flux[_qp][_pvar]*_dt; }
cpritam/moose
modules/richards/src/postprocessors/RichardsExcavFlow.C
C++
lgpl-2.1
1,375
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.main.contactlist.contactsource; import java.util.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.service.contactsource.*; import net.java.sip.communicator.service.protocol.*; /** * The <tt>StringContactSourceServiceImpl</tt> is an implementation of the * <tt>ContactSourceService</tt> that returns the searched string as a result * contact. * * @author Yana Stamcheva */ public class StringContactSourceServiceImpl implements ContactSourceService { /** * The protocol provider to be used with this string contact source. */ private final ProtocolProviderService protocolProvider; /** * The operation set supported by this string contact source. */ private final Class<? extends OperationSet> opSetClass; /** * Can display disable adding display details for source contacts. */ private boolean disableDisplayDetails = true; /** * Creates an instance of <tt>StringContactSourceServiceImpl</tt>. * * @param protocolProvider the protocol provider to be used with this string * contact source * @param opSet the operation set supported by this string contact source */ public StringContactSourceServiceImpl( ProtocolProviderService protocolProvider, Class<? extends OperationSet> opSet) { this.protocolProvider = protocolProvider; this.opSetClass = opSet; } /** * Returns the type of this contact source. * * @return the type of this contact source */ public int getType() { return SEARCH_TYPE; } /** * Returns a user-friendly string that identifies this contact source. * * @return the display name of this contact source */ public String getDisplayName() { return GuiActivator.getResources().getI18NString( "service.gui.SEARCH_STRING_CONTACT_SOURCE"); } /** * Creates query for the given <tt>queryString</tt>. * * @param queryString the string to search for * @return the created query */ public ContactQuery createContactQuery(String queryString) { return createContactQuery(queryString, -1); } /** * Creates query for the given <tt>queryString</tt>. * * @param queryString the string to search for * @param contactCount the maximum count of result contacts * @return the created query */ public ContactQuery createContactQuery( String queryString, int contactCount) { return new StringQuery(queryString); } /** * Changes whether to add display details for contact sources. * @param disableDisplayDetails */ public void setDisableDisplayDetails(boolean disableDisplayDetails) { this.disableDisplayDetails = disableDisplayDetails; } /** * Returns the source contact corresponding to the query string. * * @return the source contact corresponding to the query string */ public SourceContact createSourceContact(String queryString) { ArrayList<ContactDetail> contactDetails = new ArrayList<ContactDetail>(); ContactDetail contactDetail = new ContactDetail(queryString); // Init supported operation sets. ArrayList<Class<? extends OperationSet>> supportedOpSets = new ArrayList<Class<? extends OperationSet>>(); supportedOpSets.add(opSetClass); contactDetail.setSupportedOpSets(supportedOpSets); // Init preferred protocol providers. Map<Class<? extends OperationSet>,ProtocolProviderService> providers = new HashMap<Class<? extends OperationSet>, ProtocolProviderService>(); providers.put(opSetClass, protocolProvider); contactDetail.setPreferredProviders(providers); contactDetails.add(contactDetail); GenericSourceContact sourceContact = new GenericSourceContact( StringContactSourceServiceImpl.this, queryString, contactDetails); if(disableDisplayDetails) { sourceContact.setDisplayDetails( GuiActivator.getResources().getI18NString( "service.gui.CALL_VIA") + " " + protocolProvider.getAccountID().getDisplayName()); } return sourceContact; } /** * The query implementation. */ private class StringQuery extends AbstractContactQuery<ContactSourceService> { /** * The query string. */ private String queryString; /** * The query result list. */ private final List<SourceContact> results; /** * Creates an instance of this query implementation. * * @param queryString the string to query */ public StringQuery(String queryString) { super(StringContactSourceServiceImpl.this); this.queryString = queryString; this.results = new ArrayList<SourceContact>(); } /** * Returns the query string. * * @return the query string */ public String getQueryString() { return queryString; } /** * Returns the list of query results. * * @return the list of query results */ public List<SourceContact> getQueryResults() { return results; } @Override public void start() { SourceContact contact = createSourceContact(queryString); results.add(contact); fireContactReceived(contact); if (getStatus() != QUERY_CANCELED) setStatus(QUERY_COMPLETED); } } /** * Returns the index of the contact source in the result list. * * @return the index of the contact source in the result list */ public int getIndex() { return 0; } }
marclaporte/jitsi
src/net/java/sip/communicator/impl/gui/main/contactlist/contactsource/StringContactSourceServiceImpl.java
Java
lgpl-2.1
6,347
/** * Created : Mar 26, 2012 * * @author pquiring */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ProgrammerPanel extends javax.swing.JPanel implements Display, ActionListener { /** * Creates new form MainPanel */ public ProgrammerPanel(Backend backend) { initComponents(); divide.setText("\u00f7"); this.backend = backend; Insets zero = new Insets(0, 0, 0, 0); JButton b; for(int a=0;a<getComponentCount();a++) { Component c = getComponent(a); if (c instanceof JButton) { b = (JButton)c; b.addActionListener(this); b.setMargin(zero); } } backend.setRadix(10); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); output = new javax.swing.JTextField(); n7 = new javax.swing.JButton(); n8 = new javax.swing.JButton(); n9 = new javax.swing.JButton(); n4 = new javax.swing.JButton(); n5 = new javax.swing.JButton(); n6 = new javax.swing.JButton(); n1 = new javax.swing.JButton(); n2 = new javax.swing.JButton(); n3 = new javax.swing.JButton(); n0 = new javax.swing.JButton(); divide = new javax.swing.JButton(); multiple = new javax.swing.JButton(); minus = new javax.swing.JButton(); plus = new javax.swing.JButton(); allClear = new javax.swing.JButton(); open = new javax.swing.JButton(); close = new javax.swing.JButton(); eq = new javax.swing.JButton(); open1 = new javax.swing.JButton(); open2 = new javax.swing.JButton(); open3 = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); hex = new javax.swing.JRadioButton(); decimal = new javax.swing.JRadioButton(); oct = new javax.swing.JRadioButton(); bin = new javax.swing.JRadioButton(); n10 = new javax.swing.JButton(); n11 = new javax.swing.JButton(); n12 = new javax.swing.JButton(); n13 = new javax.swing.JButton(); n14 = new javax.swing.JButton(); n15 = new javax.swing.JButton(); open4 = new javax.swing.JButton(); open5 = new javax.swing.JButton(); dec1 = new javax.swing.JButton(); allClear1 = new javax.swing.JButton(); output.setEditable(false); output.setHorizontalAlignment(javax.swing.JTextField.RIGHT); n7.setText("7"); n8.setText("8"); n9.setText("9"); n4.setText("4"); n5.setText("5"); n6.setText("6"); n1.setText("1"); n2.setText("2"); n3.setText("3"); n0.setText("0"); divide.setText("/"); multiple.setText("x"); minus.setText("-"); plus.setText("+"); allClear.setText("AC"); allClear.setToolTipText("All Clear"); open.setText("("); close.setText(")"); eq.setText("="); open1.setText("XOR"); open2.setText("AND"); open3.setText("NOT"); buttonGroup1.add(hex); hex.setText("Hex"); hex.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { hexActionPerformed(evt); } }); buttonGroup1.add(decimal); decimal.setSelected(true); decimal.setText("Dec"); decimal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { decimalActionPerformed(evt); } }); buttonGroup1.add(oct); oct.setText("Oct"); oct.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { octActionPerformed(evt); } }); buttonGroup1.add(bin); bin.setText("Bin"); bin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { binActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(hex) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(decimal) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(oct) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bin) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(hex) .addComponent(decimal) .addComponent(oct) .addComponent(bin)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); n10.setText("A"); n11.setText("B"); n12.setText("C"); n13.setText("D"); n14.setText("E"); n15.setText("F"); open4.setText("MOD"); open5.setText("OR"); dec1.setText("+/-"); allClear1.setText("<"); allClear1.setToolTipText("All Clear"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(output, javax.swing.GroupLayout.DEFAULT_SIZE, 386, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(n10, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(n0, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(n1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(n4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(n7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(n8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(n9, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(divide, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(allClear, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(dec1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(62, 62, 62) .addComponent(plus, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(eq, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(minus, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(56, 56, 56)) .addGroup(layout.createSequentialGroup() .addComponent(n5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(n6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(multiple, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(open, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(allClear1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(open4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(open5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(open1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(open2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(open3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addComponent(n11, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(n12, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(n13, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(n14, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(n15, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(output, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(n7) .addComponent(n8) .addComponent(n9) .addComponent(divide) .addComponent(allClear) .addComponent(open2) .addComponent(allClear1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(n4) .addComponent(n5) .addComponent(n6) .addComponent(multiple) .addComponent(close) .addComponent(open5) .addComponent(open)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(n1) .addComponent(n2) .addComponent(n3) .addComponent(minus) .addComponent(open1) .addComponent(open4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(n0) .addComponent(plus) .addComponent(dec1) .addComponent(open3) .addComponent(eq)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(n10) .addComponent(n11) .addComponent(n12) .addComponent(n13) .addComponent(n14) .addComponent(n15)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void hexActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hexActionPerformed backend.setRadix(16); }//GEN-LAST:event_hexActionPerformed private void decimalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_decimalActionPerformed backend.setRadix(10); }//GEN-LAST:event_decimalActionPerformed private void octActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_octActionPerformed backend.setRadix(8); }//GEN-LAST:event_octActionPerformed private void binActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_binActionPerformed backend.setRadix(2); }//GEN-LAST:event_binActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton allClear; private javax.swing.JButton allClear1; private javax.swing.JRadioButton bin; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton close; private javax.swing.JButton dec1; private javax.swing.JRadioButton decimal; private javax.swing.JButton divide; private javax.swing.JButton eq; private javax.swing.JRadioButton hex; private javax.swing.JPanel jPanel1; private javax.swing.JButton minus; private javax.swing.JButton multiple; private javax.swing.JButton n0; private javax.swing.JButton n1; private javax.swing.JButton n10; private javax.swing.JButton n11; private javax.swing.JButton n12; private javax.swing.JButton n13; private javax.swing.JButton n14; private javax.swing.JButton n15; private javax.swing.JButton n2; private javax.swing.JButton n3; private javax.swing.JButton n4; private javax.swing.JButton n5; private javax.swing.JButton n6; private javax.swing.JButton n7; private javax.swing.JButton n8; private javax.swing.JButton n9; private javax.swing.JRadioButton oct; private javax.swing.JButton open; private javax.swing.JButton open1; private javax.swing.JButton open2; private javax.swing.JButton open3; private javax.swing.JButton open4; private javax.swing.JButton open5; private javax.swing.JTextField output; private javax.swing.JButton plus; // End of variables declaration//GEN-END:variables private Backend backend; public void setDisplay(String str) { int idx = str.indexOf(','); if (idx != -1) { output.setText(str.substring(0,idx)); //remove radix } else { output.setText(str); } } public void actionPerformed(ActionEvent ae) { JButton b = (JButton)ae.getSource(); String txt = b.getText(); if (txt.length() == 1) { char first = txt.charAt(0); if (((first >= '0') && (first <= '9')) || (first == '.') || ((first >= 'A') && (first <= 'F'))) { backend.addDigit(first); return; } } backend.addOperation(txt); } public void cut() { output.cut(); } public void copy() { output.copy(); } public void setRadix(int rx) { switch (rx) { case 16: hex.setSelected(true); break; case 10: decimal.setSelected(true); break; case 8: oct.setSelected(true); break; case 2: bin.setSelected(true); break; } backend.setRadix(rx); } }
ericomattos/javaforce
projects/jfcalc/src/ProgrammerPanel.java
Java
lgpl-3.0
20,790
/* Copyright 2011, AUTHORS.txt (http://ui.operamasks.org/about) Dual licensed under the MIT or LGPL Version 2 licenses. */ /** * @file Spell checker */ // Register a plugin named "wsc". OMEDITOR.plugins.add( 'wsc', { requires : [ 'dialog' ], init : function( editor ) { var commandName = 'checkspell'; var command = editor.addCommand( commandName, new OMEDITOR.dialogCommand( commandName ) ); // SpellChecker doesn't work in Opera and with custom domain command.modes = { wysiwyg : ( !OMEDITOR.env.opera && !OMEDITOR.env.air && document.domain == window.location.hostname ) }; editor.ui.addButton( 'SpellChecker', { label : editor.lang.spellCheck.toolbar, command : commandName }); OMEDITOR.dialog.add( commandName, this.path + 'dialogs/wsc.js' ); } }); OMEDITOR.config.wsc_customerId = OMEDITOR.config.wsc_customerId || '1:ua3xw1-2XyGJ3-GWruD3-6OFNT1-oXcuB1-nR6Bp4-hgQHc-EcYng3-sdRXG3-NOfFk' ; OMEDITOR.config.wsc_customLoaderScript = OMEDITOR.config.wsc_customLoaderScript || null;
yonghuang/fastui
samplecenter/basic/timeTest/operamasks-ui-2.0/development-bundle/ui/editor/_source/plugins/wsc/plugin.js
JavaScript
lgpl-3.0
1,027
/* * Copyright © 2012, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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. */ /** * @file tgSimView.cpp * @brief Contains the definitions of members of class tgSimView * @author Brian Mirletz, Ryan Adams * $Id$ */ // This module #include "tgSimulation.h" // This application #include "tgModelVisitor.h" #include "tgSimView.h" // The C++ Standard Library #include <cassert> #include <iostream> #include <stdexcept> tgSimView::tgSimView(tgWorld& world, double stepSize, double renderRate) : m_world(world), m_pSimulation(NULL), m_pModelVisitor(NULL), m_stepSize(stepSize), m_renderRate(renderRate), m_renderTime(0.0), m_initialized(false) { if (m_stepSize < 0.0) { throw std::invalid_argument("stepSize is not positive"); } else if (renderRate < m_stepSize) { throw std::invalid_argument("renderRate is less than stepSize"); } // Postcondition assert(invariant()); assert(m_pSimulation == NULL); assert(m_pModelVisitor == NULL); assert(m_stepSize == stepSize); assert(m_renderRate == renderRate); assert(m_renderTime == 0.0); assert(!m_initialized); } tgSimView::~tgSimView() { if (m_pSimulation != NULL) { // The tgSimView has been passed to a tgSimulation teardown(); } delete m_pModelVisitor; } void tgSimView::bindToSimulation(tgSimulation& simulation) { if (m_pSimulation != NULL) { throw std::invalid_argument("The view already belongs to a simulation."); } else { m_pSimulation = &simulation; tgWorld& world = simulation.getWorld(); bindToWorld(world); } // Postcondition assert(invariant()); assert(m_pSimulation == &simulation); } void tgSimView::releaseFromSimulation() { // The destructor that calls this must not fail, so don't assert or throw // on a precondition m_pSimulation = NULL; // The destructor that calls this must not fail, so don't assert a // postcondition } void tgSimView::bindToWorld(tgWorld& world) { } void tgSimView::setup() { assert(m_pSimulation != NULL); // Just note that this function was called. // tgSimViewGraphics needs to know for now. m_initialized = true; // Postcondition assert(invariant()); assert(m_initialized); } void tgSimView::teardown() { // Just note that this function was called. // tgSimViewGraphics needs to know for now. m_initialized = false; // Postcondition assert(invariant()); assert(!m_initialized); } void tgSimView::run() { // This would normally run forever, but this is just for testing run(10); } void tgSimView::run(int steps) { if (m_pSimulation != NULL) { // The tgSimView has been passed to a tgSimulation std::cout << "SimView::run("<<steps<<")" << std::endl; // This would normally run forever, but this is just for testing m_renderTime = 0; double totalTime = 0.0; for (int i = 0; i < steps; i++) { m_pSimulation->step(m_stepSize); m_renderTime += m_stepSize; totalTime += m_stepSize; if (m_renderTime >= m_renderRate) { render(); //std::cout << totalTime << std::endl; m_renderTime = 0; } } } } void tgSimView::render() const { if ((m_pSimulation != NULL) && (m_pModelVisitor != NULL)) { // The tgSimView has been passed to a tgSimulation m_pSimulation->onVisit(*m_pModelVisitor); } } void tgSimView::render(const tgModelVisitor& r) const { if (m_pSimulation != NULL) { // The tgSimView has been passed to a tgSimulation m_pSimulation->onVisit(r); } } void tgSimView::reset() { if (m_pSimulation != NULL) { // The tgSimView has been passed to a tgSimulation m_pSimulation->reset(); } } void tgSimView::setRenderRate(double renderRate) { m_renderRate = (renderRate > m_stepSize) ? renderRate : m_stepSize; // Postcondition assert(invariant()); } void tgSimView::setStepSize(double stepSize) { if (stepSize <= 0.0) { throw std::invalid_argument("stepSize is not positive"); } else { m_stepSize = stepSize; // Assure that the render rate is no less than the new step size setRenderRate(m_renderRate); } // Postcondition assert(invariant()); assert((stepSize <= 0.0) || (m_stepSize == stepSize)); } bool tgSimView::invariant() const { return (m_stepSize >= 0.0) && (m_renderRate >= m_stepSize) && (m_renderTime >= 0.0); }
MRNAS/NTRT
src/core/tgSimView.cpp
C++
apache-2.0
5,374
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include <iostream> #include <fstream> #include <sstream> #include <algorithm> #include <cctype> #include "BodyOnlyXmlParser.hh" #include "MdsException.hh" using namespace mdsd::details; void BodyOnlyXmlParser::ParseFile(std::string xmlFilePath) { m_xmlFilePath = std::move(xmlFilePath); std::ifstream infile{m_xmlFilePath}; if (!infile) { std::ostringstream strm; strm << "Failed to open file '" << m_xmlFilePath << "'."; throw MDSEXCEPTION(strm.str()); } std::string line; while(std::getline(infile, line)) { ParseChunk(line); } if (!infile.eof()) { std::ostringstream strm; strm << "Failed to parse file '" << m_xmlFilePath << "': "; if (infile.bad()) { strm << "Corrupted stream."; } else if (infile.fail()) { strm << "IO operation failed."; } else { strm << "std::getline() returned 0 for unknown reason."; } throw MDSEXCEPTION(strm.str()); } } void BodyOnlyXmlParser::OnCharacters(const std::string& chars) { bool isEmptyOrWhiteSpace = std::all_of(chars.cbegin(), chars.cend(), ::isspace); if (!isEmptyOrWhiteSpace) { m_body.append(chars); } }
Azure/azure-linux-extensions
Diagnostic/mdsd/mdscommands/BodyOnlyXmlParser.cc
C++
apache-2.0
1,350
<?php /* Copyright 2016 Rustici Software 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. */ namespace TinCanTest; use TinCan\Document; class StubDocument extends Document {} class DocumentTest extends \PHPUnit_Framework_TestCase { public function testExceptionOnInvalidDateTime() { $this->setExpectedException( "InvalidArgumentException", 'type of arg1 must be string or DateTime' ); $obj = new StubDocument(); $obj->setTimestamp(1); } }
RusticiSoftware/TinCanPHP
tests/DocumentTest.php
PHP
apache-2.0
1,020
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.gradle.swiftpm.internal; import com.google.common.collect.ImmutableSet; import javax.annotation.Nullable; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class DefaultTarget implements Serializable { private final String name; private final File path; private final Collection<File> sourceFiles; private final List<String> requiredTargets = new ArrayList<String>(); private final List<String> requiredProducts = new ArrayList<String>(); private File publicHeaderDir; public DefaultTarget(String name, File path, Iterable<File> sourceFiles) { this.name = name; this.path = path; this.sourceFiles = ImmutableSet.copyOf(sourceFiles); } public String getName() { return name; } public File getPath() { return path; } public Collection<File> getSourceFiles() { return sourceFiles; } @Nullable public File getPublicHeaderDir() { return publicHeaderDir; } public void setPublicHeaderDir(File publicHeaderDir) { this.publicHeaderDir = publicHeaderDir; } public Collection<String> getRequiredTargets() { return requiredTargets; } public Collection<String> getRequiredProducts() { return requiredProducts; } }
gradle/gradle
subprojects/language-native/src/main/java/org/gradle/swiftpm/internal/DefaultTarget.java
Java
apache-2.0
2,004
/* * Copyright 2010 Google Inc. * * 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 symbolicexecutor; import com.google.common.collect.Sets; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.ScriptableObject; import java.io.IOException; import java.util.Set; /** * An object that runs symbolic execution on one program to generate a bunch of * tests and their outputs, runs a second program with these tests, compares * against the first set of outputs, and reports the differences. * * @author elnatan@google.com (Elnatan Reisner) * */ public class CompareFiles { /** The file names of the original and new programs */ private final String originalProgram; private final String newProgram; /** The name of the function at which to start symbolic execution */ private final String entryFunction; /** The arguments to pass to the entry function to start execution */ private final String[] arguments; /** * @param originalProgram file name of the original version of the program * @param newProgram file name of the new version of the program * @param entryFunction the function at which to start symbolic execution * @param arguments the arguments to pass to the entry function */ public CompareFiles(String originalProgram, String newProgram, String entryFunction, String... arguments) { this.originalProgram = originalProgram; this.newProgram = newProgram; this.entryFunction = entryFunction; this.arguments = arguments; } /** * @param maxTests the maximum number of tests to generate * @return the set of differences between the old and new programs, given as * pairs (x, y), where x is the {@link Output} from the original * program and y is the new program's output on {@code x.input} * @throws IOException */ public Set<Pair<Output, Object>> compare(FileLoader loader, int maxTests) throws IOException { Cvc3Context cvc3Context = Cvc3Context.create(arguments.length, loader); NewInputGenerator inputGenerator = new ApiBasedInputGenerator(cvc3Context); SymbolicExecutor executor = SymbolicExecutor.create( originalProgram, loader, inputGenerator, maxTests, entryFunction, arguments); Context rhinoContext = Context.enter(); Set<Pair<Output, Object>> differences = Sets.newHashSet(); // Run symbolic execution, and iterate through all generated inputs for (Output output : executor.run()) { // Run the new program with the old arguments ScriptableObject scope = rhinoContext.initStandardObjects(); rhinoContext.evaluateString(scope, loader.toString(newProgram), "new program", 0, null); Object result = ScriptableObject.callMethod(scope, entryFunction, output.input.toArray(ContextFactory.getGlobal())); // If the results differ, add them to the set of differences if (!output.result.equals(result)) { differences.add(new Pair<Output, Object>(output, result)); } } return differences; } }
ehsan/js-symbolic-executor
js-symbolic-executor/src/symbolicexecutor/CompareFiles.java
Java
apache-2.0
3,614
# # Cookbook Name:: bork # Recipe:: configure # # Copyright 2015, GING, ETSIT, UPM # # 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. # node.set['bork']['version'] = '0.0.1' include_recipe 'bork::configure'
Fiware/ops.Validator
extras/ChefCookBook/bork/recipes/0.0.1_configure.rb
Ruby
apache-2.0
702
// 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. #include <gtest/gtest.h> #include <mesos/mesos.hpp> #include <mesos/resource_provider/resource_provider.hpp> #include <stout/error.hpp> #include <stout/gtest.hpp> #include <stout/option.hpp> #include <stout/uuid.hpp> #include "common/protobuf_utils.hpp" #include "resource_provider/validation.hpp" namespace call = mesos::internal::resource_provider::validation::call; using mesos::resource_provider::Call; namespace mesos { namespace internal { namespace tests { TEST(ResourceProviderCallValidationTest, Subscribe) { Call call; call.set_type(Call::SUBSCRIBE); // Expecting `Call::Subscribe`. Option<Error> error = call::validate(call); EXPECT_SOME(error); Call::Subscribe* subscribe = call.mutable_subscribe(); ResourceProviderInfo* info = subscribe->mutable_resource_provider_info(); info->set_type("org.apache.mesos.rp.test"); info->set_name("test"); error = call::validate(call); EXPECT_NONE(error); } TEST(ResourceProviderCallValidationTest, UpdateOperationStatus) { Call call; call.set_type(Call::UPDATE_OPERATION_STATUS); // Expecting a resource provider ID and `Call::UpdateOperationStatus`. Option<Error> error = call::validate(call); EXPECT_SOME(error); ResourceProviderID* id = call.mutable_resource_provider_id(); id->set_value(id::UUID::random().toString()); // Still expecting `Call::UpdateOperationStatus`. error = call::validate(call); EXPECT_SOME(error); Call::UpdateOperationStatus* update = call.mutable_update_operation_status(); update->mutable_framework_id()->set_value(id::UUID::random().toString()); update->mutable_operation_uuid()->CopyFrom(protobuf::createUUID()); OperationStatus* status = update->mutable_status(); status->mutable_operation_id()->set_value(id::UUID::random().toString()); status->set_state(OPERATION_FINISHED); error = call::validate(call); EXPECT_NONE(error); } TEST(ResourceProviderCallValidationTest, UpdateState) { Call call; call.set_type(Call::UPDATE_STATE); // Expecting a resource provider ID and `Call::UpdateState`. Option<Error> error = call::validate(call); EXPECT_SOME(error); ResourceProviderID* id = call.mutable_resource_provider_id(); id->set_value(id::UUID::random().toString()); // Still expecting `Call::UpdateState`. error = call::validate(call); EXPECT_SOME(error); Call::UpdateState* updateState = call.mutable_update_state(); updateState->mutable_resource_version_uuid()->CopyFrom( protobuf::createUUID()); error = call::validate(call); EXPECT_NONE(error); } } // namespace tests { } // namespace internal { } // namespace mesos {
chhsia0/mesos
src/tests/resource_provider_validation_tests.cpp
C++
apache-2.0
3,426
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * Additional information of DPM Protected item. * */ class DPMProtectedItemExtendedInfo { /** * Create a DPMProtectedItemExtendedInfo. * @member {object} [protectableObjectLoadPath] Attribute to provide * information on various DBs. * @member {boolean} [protectedProperty] To check if backup item is disk * protected. * @member {boolean} [isPresentOnCloud] To check if backup item is cloud * protected. * @member {string} [lastBackupStatus] Last backup status information on * backup item. * @member {date} [lastRefreshedAt] Last refresh time on backup item. * @member {date} [oldestRecoveryPoint] Oldest cloud recovery point time. * @member {number} [recoveryPointCount] cloud recovery point count. * @member {date} [onPremiseOldestRecoveryPoint] Oldest disk recovery point * time. * @member {date} [onPremiseLatestRecoveryPoint] latest disk recovery point * time. * @member {number} [onPremiseRecoveryPointCount] disk recovery point count. * @member {boolean} [isCollocated] To check if backup item is collocated. * @member {string} [protectionGroupName] Protection group name of the backup * item. * @member {string} [diskStorageUsedInBytes] Used Disk storage in bytes. * @member {string} [totalDiskStorageSizeInBytes] total Disk storage in * bytes. */ constructor() { } /** * Defines the metadata of DPMProtectedItemExtendedInfo * * @returns {object} metadata of DPMProtectedItemExtendedInfo * */ mapper() { return { required: false, serializedName: 'DPMProtectedItemExtendedInfo', type: { name: 'Composite', className: 'DPMProtectedItemExtendedInfo', modelProperties: { protectableObjectLoadPath: { required: false, serializedName: 'protectableObjectLoadPath', type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, protectedProperty: { required: false, serializedName: 'protected', type: { name: 'Boolean' } }, isPresentOnCloud: { required: false, serializedName: 'isPresentOnCloud', type: { name: 'Boolean' } }, lastBackupStatus: { required: false, serializedName: 'lastBackupStatus', type: { name: 'String' } }, lastRefreshedAt: { required: false, serializedName: 'lastRefreshedAt', type: { name: 'DateTime' } }, oldestRecoveryPoint: { required: false, serializedName: 'oldestRecoveryPoint', type: { name: 'DateTime' } }, recoveryPointCount: { required: false, serializedName: 'recoveryPointCount', type: { name: 'Number' } }, onPremiseOldestRecoveryPoint: { required: false, serializedName: 'onPremiseOldestRecoveryPoint', type: { name: 'DateTime' } }, onPremiseLatestRecoveryPoint: { required: false, serializedName: 'onPremiseLatestRecoveryPoint', type: { name: 'DateTime' } }, onPremiseRecoveryPointCount: { required: false, serializedName: 'onPremiseRecoveryPointCount', type: { name: 'Number' } }, isCollocated: { required: false, serializedName: 'isCollocated', type: { name: 'Boolean' } }, protectionGroupName: { required: false, serializedName: 'protectionGroupName', type: { name: 'String' } }, diskStorageUsedInBytes: { required: false, serializedName: 'diskStorageUsedInBytes', type: { name: 'String' } }, totalDiskStorageSizeInBytes: { required: false, serializedName: 'totalDiskStorageSizeInBytes', type: { name: 'String' } } } } }; } } module.exports = DPMProtectedItemExtendedInfo;
xingwu1/azure-sdk-for-node
lib/services/recoveryServicesBackupManagement/lib/models/dPMProtectedItemExtendedInfo.js
JavaScript
apache-2.0
5,048
/* jshint globalstrict:false, strict:false, unused : false */ /* global assertEqual */ // ////////////////////////////////////////////////////////////////////////////// // / @brief tests for dump/reload // / // / @file // / // / DISCLAIMER // / // / Copyright 2010-2012 triagens GmbH, Cologne, Germany // / // / 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. // / // / Copyright holder is triAGENS GmbH, Cologne, Germany // / // / @author Jan Steemann // / @author Copyright 2012, triAGENS GmbH, Cologne, Germany // ////////////////////////////////////////////////////////////////////////////// var db = require('@arangodb').db; var internal = require('internal'); var jsunity = require('jsunity'); function runSetup () { 'use strict'; internal.debugClearFailAt(); db._drop('UnitTestsRecovery'); var c = db._create('UnitTestsRecovery'); // try to re-create collection with the same name try { db._create('UnitTestsRecovery'); } catch (err) { } c.save({ _key: 'foo' }, true); internal.debugTerminate('crashing server'); } // ////////////////////////////////////////////////////////////////////////////// // / @brief test suite // ////////////////////////////////////////////////////////////////////////////// function recoverySuite () { 'use strict'; jsunity.jsUnity.attachAssertions(); return { setUp: function () {}, tearDown: function () {}, // ////////////////////////////////////////////////////////////////////////////// // / @brief test whether we can restore the trx data // ////////////////////////////////////////////////////////////////////////////// testCollectionDuplicate: function () { var c = db._collection('UnitTestsRecovery'); assertEqual(1, c.count()); } }; } // ////////////////////////////////////////////////////////////////////////////// // / @brief executes the test suite // ////////////////////////////////////////////////////////////////////////////// function main (argv) { 'use strict'; if (argv[1] === 'setup') { runSetup(); return 0; } else { jsunity.run(recoverySuite); return jsunity.writeDone().status ? 0 : 1; } }
wiltonlazary/arangodb
tests/js/server/recovery/collection-duplicate.js
JavaScript
apache-2.0
2,684
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.oozie.ambari.view.assets; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import org.apache.ambari.view.ViewContext; import org.apache.oozie.ambari.view.*; import org.apache.oozie.ambari.view.assets.model.ActionAsset; import org.apache.oozie.ambari.view.assets.model.ActionAssetDefinition; import org.apache.oozie.ambari.view.assets.model.AssetDefintion; import org.apache.oozie.ambari.view.exception.ErrorCode; import org.apache.oozie.ambari.view.exception.WfmException; import org.apache.oozie.ambari.view.exception.WfmWebException; import org.apache.oozie.ambari.view.model.APIResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.*; import javax.ws.rs.core.*; import java.io.IOException; import java.util.*; import static org.apache.oozie.ambari.view.Constants.*; public class AssetResource { private final static Logger LOGGER = LoggerFactory .getLogger(AssetResource.class); private final AssetService assetService; private final ViewContext viewContext; private final HDFSFileUtils hdfsFileUtils; private final OozieUtils oozieUtils = new OozieUtils(); private final OozieDelegate oozieDelegate; public AssetResource(ViewContext viewContext) { this.viewContext = viewContext; this.assetService = new AssetService(viewContext); hdfsFileUtils = new HDFSFileUtils(viewContext); oozieDelegate = new OozieDelegate(viewContext); } @GET public Response getAssets() { try { Collection<ActionAsset> assets = assetService.getAssets(); APIResult result = new APIResult(); result.setStatus(APIResult.Status.SUCCESS); result.getPaging().setTotal(assets != null ? assets.size() : 0L); result.setData(assets); return Response.ok(result).build(); } catch (Exception ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex); } } @GET @Path("/mine") public Response getMyAssets() { try { Collection<ActionAsset> assets = assetService.getMyAssets(); APIResult result = new APIResult(); result.setStatus(APIResult.Status.SUCCESS); result.getPaging().setTotal(assets != null ? assets.size() : 0L); result.setData(assets); return Response.ok(result).build(); } catch (Exception ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex); } } @POST public Response saveAsset(@Context HttpHeaders headers, @QueryParam("id") String id, @Context UriInfo ui, String body) { try { Gson gson = new Gson(); AssetDefintion assetDefinition = gson.fromJson(body, AssetDefintion.class); Map<String, String> validateAsset = validateAsset(headers, assetDefinition.getDefinition(), ui.getQueryParameters()); if (!STATUS_OK.equals(validateAsset.get(STATUS_KEY))) { throw new WfmWebException(ErrorCode.ASSET_INVALID_FROM_OOZIE); } assetService.saveAsset(id, viewContext.getUsername(), assetDefinition); APIResult result = new APIResult(); result.setStatus(APIResult.Status.SUCCESS); return Response.ok(result).build(); } catch (WfmWebException ex) { LOGGER.error(ex.getMessage(),ex); throw ex; } catch (Exception ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex); } } private List<String> getAsList(String string) { ArrayList<String> li = new ArrayList<>(1); li.add(string); return li; } public Map<String, String> validateAsset(HttpHeaders headers, String postBody, MultivaluedMap<String, String> queryParams) { String workflowXml = oozieUtils.generateWorkflowXml(postBody); Map<String, String> result = new HashMap<>(); String tempWfPath = "/tmp" + "/tmpooziewfs/tempwf_" + Math.round(Math.random() * 100000) + ".xml"; try { hdfsFileUtils.writeToFile(tempWfPath, workflowXml, true); } catch (IOException ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex, ErrorCode.FILE_ACCESS_UNKNOWN_ERROR); } queryParams.put("oozieparam.action", getAsList("dryrun")); queryParams.put("oozieconfig.rerunOnFailure", getAsList("false")); queryParams.put("oozieconfig.useSystemLibPath", getAsList("true")); queryParams.put("resourceManager", getAsList("useDefault")); String dryRunResp = oozieDelegate.submitWorkflowJobToOozie(headers, tempWfPath, queryParams, JobType.WORKFLOW); LOGGER.info(String.format("resp from validating asset=[%s]", dryRunResp)); try { hdfsFileUtils.deleteFile(tempWfPath); } catch (IOException ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex, ErrorCode.FILE_ACCESS_UNKNOWN_ERROR); } if (dryRunResp != null && dryRunResp.trim().startsWith("{")) { JsonElement jsonElement = new JsonParser().parse(dryRunResp); JsonElement idElem = jsonElement.getAsJsonObject().get("id"); if (idElem != null) { result.put(STATUS_KEY, STATUS_OK); } else { result.put(STATUS_KEY, STATUS_FAILED); result.put(MESSAGE_KEY, dryRunResp); } } else { result.put(STATUS_KEY, STATUS_FAILED); result.put(MESSAGE_KEY, dryRunResp); } return result; } @GET @Path("/assetNameAvailable") public Response assetNameAvailable(@QueryParam("name") String name){ try { boolean available = assetService.isAssetNameAvailable(name); return Response.ok(available).build(); }catch (Exception ex){ LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex); } } @GET @Path("/{id}") public Response getAssetDetail(@PathParam("id") String id) { try { AssetDefintion assetDefinition = assetService.getAssetDetail(id); APIResult result = new APIResult(); result.setStatus(APIResult.Status.SUCCESS); result.setData(assetDefinition); return Response.ok(result).build(); } catch (Exception ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex); } } @GET @Path("/definition/id}") public Response getAssetDefinition(@PathParam("defnitionId") String id) { try { ActionAssetDefinition assetDefinition = assetService.getAssetDefinition(id); APIResult result = new APIResult(); result.setStatus(APIResult.Status.SUCCESS); result.setData(assetDefinition); return Response.ok(result).build(); } catch (Exception ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex); } } @DELETE @Path("/{id}") public Response delete(@PathParam("id") String id) { try { ActionAsset asset = assetService.getAsset(id); if (asset == null) { throw new WfmWebException(ErrorCode.ASSET_NOT_EXIST); } if (!viewContext.getUsername().equals(asset.getOwner())){ throw new WfmWebException(ErrorCode.PERMISSION_ERROR); } assetService.deleteAsset(id); APIResult result = new APIResult(); result.setStatus(APIResult.Status.SUCCESS); return Response.ok(result).build(); } catch (WfmWebException ex) { LOGGER.error(ex.getMessage(),ex); throw ex; } catch (Exception ex) { LOGGER.error(ex.getMessage(),ex); throw new WfmWebException(ex); } } }
arenadata/ambari
contrib/views/wfmanager/src/main/java/org/apache/oozie/ambari/view/assets/AssetResource.java
Java
apache-2.0
8,219
/**************************************************************** * 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.james.smtpserver.netty; import org.apache.james.lifecycle.api.LifecycleUtil; import org.apache.james.protocols.api.Encryption; import org.apache.james.protocols.api.Protocol; import org.apache.james.protocols.api.ProtocolSession.State; import org.apache.james.protocols.netty.BasicChannelUpstreamHandler; import org.apache.james.protocols.smtp.SMTPSession; import org.apache.james.smtpserver.SMTPConstants; import org.jboss.netty.channel.ChannelHandler.Sharable; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.slf4j.Logger; /** * {@link ChannelUpstreamHandler} which is used by the SMTPServer */ @Sharable public class SMTPChannelUpstreamHandler extends BasicChannelUpstreamHandler { public SMTPChannelUpstreamHandler(Protocol protocol, Logger logger, Encryption encryption) { super(protocol, encryption); } public SMTPChannelUpstreamHandler(Protocol protocol, Logger logger) { super(protocol); } /** * Cleanup temporary files * * @param ctx */ protected void cleanup(ChannelHandlerContext ctx) { // Make sure we dispose everything on exit on session close SMTPSession smtpSession = (SMTPSession) ctx.getAttachment(); if (smtpSession != null) { LifecycleUtil.dispose(smtpSession.getAttachment(SMTPConstants.MAIL, State.Transaction)); LifecycleUtil.dispose(smtpSession.getAttachment(SMTPConstants.DATA_MIMEMESSAGE_STREAMSOURCE, State.Transaction)); } super.cleanup(ctx); } }
chibenwa/james
protocols/protocols-smtp/src/main/java/org/apache/james/smtpserver/netty/SMTPChannelUpstreamHandler.java
Java
apache-2.0
2,858
<?php /** * The foo test class * * @author mepeisen */ class FooTest extends PHPUnit_Framework_TestCase { /** * tests the bar function */ public function testFoo() { include "folderA/MyClassA.php"; $o = new folderA\MyMavenTestClassA(); $this->assertEquals("foo", $o->getFoo()); include "folderB/MyClassB.php"; $o = new folderB\MyMavenTestClassB(); $this->assertEquals("foo", $o->getFoo()); } }
Vaysman/maven-php-plugin
maven-plugins/it/src/test/resources/org/phpmaven/test/projects/mojos-phar/phar-with-dep1-folders/src/test/php/FooTest.php
PHP
apache-2.0
423
'use strict'; (function (scope) { /** * Shape erased * * @class ShapeErased * @extends ShapeCandidate * @param {Object} [obj] * @constructor */ function ShapeErased(obj) { scope.ShapeCandidate.call(this, obj); } /** * Inheritance property */ ShapeErased.prototype = new scope.ShapeCandidate(); /** * Constructor property */ ShapeErased.prototype.constructor = ShapeErased; // Export scope.ShapeErased = ShapeErased; })(MyScript);
countshadow/MyScriptJS
src/output/shape/shapeErased.js
JavaScript
apache-2.0
532
// ------------------------------------------------------------------------- // @FileName : NFCGameServerScriptModule.cpp // @Author : LvSheng.Huang // @Date : 2013-01-02 // @Module : NFCGameServerScriptModule // @Desc : // ------------------------------------------------------------------------- //#include "stdafx.h" #include "NFCGameServerScriptModule.h" #include "NFGameServerScriptPlugin.h" bool NFCGameServerScriptModule::Init() { m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule("NFCEventProcessModule")); m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule")); m_pLogicClassModule = dynamic_cast<NFILogicClassModule*>(pPluginManager->FindModule("NFCLogicClassModule")); assert(NULL != m_pEventProcessModule); assert(NULL != m_pKernelModule); assert(NULL != m_pLogicClassModule); return true; } bool NFCGameServerScriptModule::AfterInit() { return true; } bool NFCGameServerScriptModule::Shut() { return true; } bool NFCGameServerScriptModule::Execute(const float fLasFrametime, const float fStartedTime) { return true; }
MRunFoss/NoahGameFrame
NFServer/NFGameServerScriptPlugin/NFCGameServerScriptModule.cpp
C++
apache-2.0
1,286
/** * Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved. * * 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.kaazing.gateway.transport.wsr; import static java.util.Collections.singleton; import java.util.Collection; import org.kaazing.gateway.transport.dispatch.ProtocolDispatcher; class RtmpProtocolDispatcher implements ProtocolDispatcher { private static final String RTMP_PROTOCOL = "rtmp/1.0"; private static final Collection<byte[]> RTMP_DISCRIMINATORS = singleton(new byte[] { 0x03 }); @Override public int compareTo(ProtocolDispatcher pd) { return protocolDispatchComparator.compare(this, pd); } @Override public String getProtocolName() { return RTMP_PROTOCOL; } @Override public Collection<byte[]> getDiscriminators() { return RTMP_DISCRIMINATORS; } }
EArdeleanu/gateway
transport/wsr/src/main/java/org/kaazing/gateway/transport/wsr/RtmpProtocolDispatcher.java
Java
apache-2.0
1,627
""" GeoJSON example using addItem Python 2/3 ArcREST version 3.5.0 """ from __future__ import print_function import arcrest if __name__ == "__main__": username = "" password = "" geojsonFile = r"" sh = arcrest.AGOLTokenSecurityHandler(username, password) admin = arcrest.manageorg.Administration(securityHandler=sh) user = admin.content.users.user() ip = arcrest.manageorg.ItemParameter() ip.title = "MyGeoJSONTestFile" ip.type = "GeoJson" ip.tags = "Geo1,Geo2" ip.description = "Publishing a geojson file" addedItem = user.addItem(itemParameters=ip, filePath=geojsonFile) itemId = addedItem.id pp = arcrest.manageorg.PublishGeoJSONParameter() pp.name = "Geojsonrocks" pp.hasStaticData = True print( user.publishItem(fileType="geojson", publishParameters=pp, itemId=itemId, wait=True))
Esri/ArcREST
samples/publishingGeoJSON.py
Python
apache-2.0
864
/* * Copyright 2017 Amadeus s.a.s. * 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. */ Aria.classDefinition({ $classpath : "test.aria.widgets.container.tab.focusTab.FocusTabTestCase", $extends : "aria.jsunit.TemplateTestCase", $prototype : { runTemplateTest : function () { this.templateCtxt._tpl.$focus("summaryTab"); var domElt = this.getElementById("summaryTab"); var anchor = domElt.getElementsByTagName("a")[0]; this.waitForDomEltFocus(anchor, function () { this.templateCtxt._tpl.$focus("mapTab"); var span = this.getElementById("mapTab"); this.waitForDomEltFocus(span, this.end()); }); } } });
fbasso/ariatemplates
test/aria/widgets/container/tab/focusTab/FocusTabTestCase.js
JavaScript
apache-2.0
1,249
// // immer: immutable data structures for C++ // Copyright (C) 2016, 2017, 2018 Juan Pedro Bolivar Puente // // This software is distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt // #include <immer/set.hpp> template <typename T, typename Hash = std::hash<T>, typename Eq = std::equal_to<T>> using test_set_t = immer::set<T, Hash, Eq, immer::default_memory_policy, 3u>; #define SET_T test_set_t #include "generic.ipp"
wiltonlazary/arangodb
3rdParty/immer/v0.7.0/test/set/B3.cpp
C++
apache-2.0
529
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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.facebook.buck.cxx; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.rules.BuildRule; import com.facebook.buck.core.rules.BuildRuleResolver; import com.facebook.buck.core.rules.common.BuildableSupport; import com.facebook.buck.core.util.immutables.BuckStyleValueWithBuilder; import com.facebook.buck.rules.args.Arg; import com.facebook.buck.rules.coercer.FrameworkPath; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import java.util.Optional; /** The components that get contributed to a top-level run of the C++ preprocessor. */ @BuckStyleValueWithBuilder public abstract class CxxPreprocessorInput { private static final CxxPreprocessorInput INSTANCE = ImmutableCxxPreprocessorInput.builder().build(); public abstract Multimap<CxxSource.Type, Arg> getPreprocessorFlags(); public abstract ImmutableList<CxxHeaders> getIncludes(); // Framework paths. public abstract ImmutableSet<FrameworkPath> getFrameworks(); // The build rules which produce headers found in the includes below. protected abstract ImmutableSet<BuildTarget> getRules(); public Iterable<BuildRule> getDeps(BuildRuleResolver ruleResolver) { ImmutableList.Builder<BuildRule> builder = ImmutableList.builder(); for (CxxHeaders cxxHeaders : getIncludes()) { cxxHeaders.getDeps(ruleResolver).forEachOrdered(builder::add); } builder.addAll(ruleResolver.getAllRules(getRules())); for (FrameworkPath frameworkPath : getFrameworks()) { if (frameworkPath.getSourcePath().isPresent()) { Optional<BuildRule> frameworkRule = ruleResolver.getRule(frameworkPath.getSourcePath().get()); if (frameworkRule.isPresent()) { builder.add(frameworkRule.get()); } } } for (Arg arg : getPreprocessorFlags().values()) { builder.addAll(BuildableSupport.getDepsCollection(arg, ruleResolver)); } return builder.build(); } public static CxxPreprocessorInput concat(Iterable<CxxPreprocessorInput> inputs) { CxxPreprocessorInput.Builder builder = CxxPreprocessorInput.builder(); for (CxxPreprocessorInput input : inputs) { builder.putAllPreprocessorFlags(input.getPreprocessorFlags()); builder.addAllIncludes(input.getIncludes()); builder.addAllFrameworks(input.getFrameworks()); builder.addAllRules(input.getRules()); } return builder.build(); } public static CxxPreprocessorInput of() { return INSTANCE; } public static Builder builder() { return new Builder(); } public static class Builder extends ImmutableCxxPreprocessorInput.Builder { @Override public CxxPreprocessorInput build() { CxxPreprocessorInput cxxPreprocessorInput = super.build(); if (cxxPreprocessorInput.equals(INSTANCE)) { return INSTANCE; } return cxxPreprocessorInput; } } }
facebook/buck
src/com/facebook/buck/cxx/CxxPreprocessorInput.java
Java
apache-2.0
3,593
package storage import ( "fmt" ) // ErrOldVersion is returned when a newer version of TUF metadata is already available type ErrOldVersion struct{} // ErrOldVersion is returned when a newer version of TUF metadata is already available func (err ErrOldVersion) Error() string { return fmt.Sprintf("Error updating metadata. A newer version is already available") } // ErrNotFound is returned when TUF metadata isn't found for a specific record type ErrNotFound struct{} // Error implements error func (err ErrNotFound) Error() string { return fmt.Sprintf("No record found") } // ErrKeyExists is returned when a key already exists type ErrKeyExists struct { gun string role string } // ErrKeyExists is returned when a key already exists func (err ErrKeyExists) Error() string { return fmt.Sprintf("Error, timestamp key already exists for %s:%s", err.gun, err.role) } // ErrNoKey is returned when no timestamp key is found type ErrNoKey struct { gun string } // ErrNoKey is returned when no timestamp key is found func (err ErrNoKey) Error() string { return fmt.Sprintf("Error, no timestamp key found for %s", err.gun) } // ErrBadQuery is used when the parameters provided cannot be appropriately // coerced. type ErrBadQuery struct { msg string } func (err ErrBadQuery) Error() string { return fmt.Sprintf("did not recognize parameters: %s", err.msg) }
jfrazelle/notary
server/storage/errors.go
GO
apache-2.0
1,372
/** * View attribute injection library for Android which generates the obtainStyledAttributes() and * TypedArray boilerplate code for you at compile time. * <p> * No more handing to deal with context.obtainStyledAttributes(...) or manually retrieving values * from the resulting {@link android.content.res.TypedArray TypedArray} instance. Just annotate your * field or method with {@link io.sweers.barber.StyledAttr @StyledAttr}. */ package io.sweers.barber;
lord19871207/barber
api/src/main/java/io/sweers/barber/package-info.java
Java
apache-2.0
465
// legal JS, if nonsensical, which also triggers the issue const { date, } = (inspectedElement: any) => 0; date.toISOString(); // Working flow code const { date2, } = (inspectedElement: any).props; date2.toISOString(); // It could also be an async function const { constructor } = async () => {};
Microsoft/TypeScript
tests/cases/compiler/destructuringControlFlowNoCrash.ts
TypeScript
apache-2.0
323
module Clever module APIOperations # Represents a list of results for a paged request. class ResultsList include Enumerable # Create a results list from a PageList # @api private # @return [ResultsList] def initialize(pagelist) @pages = pagelist end # Iterate over results list # @api public # @return [nil] # @example # results = Clever::District.find # returns a ResultsList # results.each do |district| # puts district.name # end def each @pages.each do |page| page.each do |elem| yield elem end end end end end end
mchavarriagam/clever-ruby
lib/clever-ruby/api_operations/results_list.rb
Ruby
apache-2.0
699
({ L_MENU_GRID: "Valikkoruudukko", L_MENU_ITEM_DISABLED: "%1 ei ole k\u00e4ytett\u00e4viss\u00e4", L_MENU_ITEM_SUBMENU: "%1 (alivalikko)", L_MENU_SUBMENU: "alivalikko", L_MENU_CHECK: "valinta" })
iharkhukhrakou/XPagesExtensionLibrary
extlib/lwp/product/runtime/eclipse/plugins/com.ibm.xsp.extlib.domino/resources/web/dwa/common/nls/fi/menu.js
JavaScript
apache-2.0
196
module td.output { /** * List of states the parser of [[PrettyPrintPlugin]] can be in. */ enum PrettyPrintState { /** * Default state of the parser. Empty lines will be removed and indention will be adjusted. */ Default, /** * Comment state, the parser waits for a comment closing tag. */ Comment, /** * Pre state, the parser waits for the closing tag of the current pre block. */ Pre } /** * A plugin that pretty prints the generated html. * * This not only aids in making the generated html source code more readable, by removing * blank lines and unnecessary whitespaces the size of the documentation is reduced without * visual impact. * * At the point writing this the docs of TypeDoc took 97.8 MB without and 66.4 MB with this * plugin enabled, so it reduced the size to 68% of the original output. */ export class PrettyPrintPlugin extends RendererPlugin { /** * Map of all tags that will be ignored. */ static IGNORED_TAGS:any = { area: true, base: true, br: true, wbr: true, col: true, command: true, embed: true, hr: true, img: true, input: true, link: true, meta: true, param: true, source: true }; /** * Map of all tags that prevent this plugin form modifying the following code. */ static PRE_TAGS:any = { pre: true, code: true, textarea: true, script: true, style: true }; /** * Create a new PrettyPrintPlugin instance. * * @param renderer The renderer this plugin should be attached to. */ constructor(renderer:Renderer) { super(renderer); renderer.on(Renderer.EVENT_END_PAGE, this.onRendererEndPage, this, -1024); } /** * Triggered after a document has been rendered, just before it is written to disc. * * @param event */ onRendererEndPage(event:OutputPageEvent) { var match, line, lineState, lineDepth, tagName, preName; var tagExp = /<\s*(\w+)[^>]*>|<\/\s*(\w+)[^>]*>|<!--|-->/g; var emptyLineExp = /^[\s]*$/; var minLineDepth = 1; var state = PrettyPrintState.Default; var stack = []; var lines = event.contents.split(/\r\n?|\n/); var index = 0; var count = lines.length; while (index < count) { line = lines[index]; if (emptyLineExp.test(line)) { if (state == PrettyPrintState.Default) { lines.splice(index, 1); count -= 1; continue; } } else { lineState = state; lineDepth = stack.length; while (match = tagExp.exec(line)) { if (state == PrettyPrintState.Comment) { if (match[0] == '-->') { state = PrettyPrintState.Default; } } else if (state == PrettyPrintState.Pre) { if (match[2] && match[2].toLowerCase() == preName) { state = PrettyPrintState.Default; } } else { if (match[0] == '<!--') { state = PrettyPrintState.Comment; } else if (match[1]) { tagName = match[1].toLowerCase(); if (tagName in PrettyPrintPlugin.IGNORED_TAGS) continue; if (tagName in PrettyPrintPlugin.PRE_TAGS) { state = PrettyPrintState.Pre; preName = tagName; } else { if (tagName == 'body') minLineDepth = 2; stack.push(tagName); } } else if (match[2]) { tagName = match[2].toLowerCase(); if (tagName in PrettyPrintPlugin.IGNORED_TAGS) continue; var n = stack.lastIndexOf(tagName); if (n != -1) { stack.length = n; } } } } if (lineState == PrettyPrintState.Default) { lineDepth = Math.min(lineDepth, stack.length); line = line.replace(/^\s+/, '').replace(/\s+$/, ''); if (lineDepth > minLineDepth) { line = Array(lineDepth - minLineDepth + 1).join('\t') + line; } lines[index] = line; } } index++; } event.contents = lines.join('\n'); } } /** * Register this plugin. */ Renderer.registerPlugin('prettyPrint', PrettyPrintPlugin); }
innerverse/typedoc
src/td/output/plugins/PrettyPrintPlugin.ts
TypeScript
apache-2.0
5,741
/** * @@@ START COPYRIGHT @@@ 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. * @@@ END COPYRIGHT @@@ */ package org.trafodion.dcs.master.listener; import java.sql.SQLException; import java.io.*; import java.nio.*; import java.nio.channels.*; import java.nio.channels.spi.*; import java.net.*; import java.util.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; class ConnectionContext { private static final Log LOG = LogFactory.getLog(ConnectionContext.class); String datasource = ""; String catalog = ""; String schema = ""; String location = ""; String userRole = ""; String connectOptions = ""; short accessMode; short autoCommit; int queryTimeoutSec; int idleTimeoutSec; int loginTimeoutSec; short txnIsolationLevel; short rowSetSize; int diagnosticFlag; int processId; String computerName = ""; String windowText = ""; VersionList clientVersionList = null; UserDesc user = null; int ctxACP; int ctxDataLang; int ctxErrorLang; short ctxCtrlInferNXHAR; short cpuToUse; short cpuToUseEnd; int srvrType; short retryCount; int optionFlags1; int optionFlags2; String vproc; String client; ConnectionContext(){ clientVersionList = new VersionList(); user = new UserDesc(); } void extractFromByteBuffer(ByteBuffer buf) throws java.io.UnsupportedEncodingException { datasource = Util.extractString(buf); catalog= Util.extractString(buf); schema= Util.extractString(buf); location= Util.extractString(buf); userRole= Util.extractString(buf); accessMode=buf.getShort(); autoCommit=buf.getShort(); queryTimeoutSec=buf.getInt(); idleTimeoutSec=buf.getInt(); loginTimeoutSec=buf.getInt(); txnIsolationLevel=buf.getShort(); rowSetSize=buf.getShort(); diagnosticFlag=buf.getInt(); processId=buf.getInt(); computerName=Util.extractString(buf); windowText=Util.extractString(buf); ctxACP=buf.getInt(); ctxDataLang=buf.getInt(); ctxErrorLang=buf.getInt(); ctxCtrlInferNXHAR=buf.getShort(); cpuToUse=buf.getShort(); cpuToUseEnd=buf.getShort(); connectOptions=Util.extractString(buf); clientVersionList.extractFromByteBuffer(buf); user.extractFromByteBuffer(buf); srvrType = buf.getInt(); retryCount = buf.getShort(); optionFlags1 = buf.getInt(); optionFlags2 = buf.getInt(); vproc= Util.extractString(buf); client= Util.extractString(buf); } }
apache/incubator-trafodion
dcs/src/main/java/org/trafodion/dcs/master/listener/ConnectionContext.java
Java
apache-2.0
3,102
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('event_mapper', '0005_user_is_confirmed'), ] operations = [ migrations.AlterField( model_name='event', name='date_time', field=models.DateTimeField(help_text=b'Date and time when the event happened.', verbose_name=b'Date and Time'), preserve_default=True, ), migrations.AlterField( model_name='event', name='victim', field=models.ForeignKey(default=0, verbose_name=b'Victim', to='event_mapper.Victim', help_text=b'The victim of the event.'), preserve_default=True, ), ]
MariaSolovyeva/watchkeeper
django_project/event_mapper/migrations/0006_auto_20150505_0922.py
Python
bsd-2-clause
789
cask 'picka' do version '1.0.0' sha256 '981209f1bd432d99ce082429cbb182b17194063b6b0eb8ae9fa22a0dbe37bca8' url 'https://getpicka.com/downloads/Picka.zip' appcast 'https://getpicka.com/appcast-trial.xml' name 'Picka' homepage 'https://getpicka.com/' app 'Picka.app' end
jawshooah/homebrew-cask
Casks/picka.rb
Ruby
bsd-2-clause
284
// Copyright 2010, Shuo Chen. All rights reserved. // http://code.google.com/p/evproto/ // // Use of this source code is governed by a BSD-style license // that can be found in the License file. // Author: Shuo Chen (chenshuo at chenshuo dot com) // #include "evproto/evproto.h" #include <gflags/gflags.h> #include <glog/logging.h> #include <google/protobuf/message.h> #include <event2/event.h> #include <event2/thread.h> #if !defined(LIBEVENT_VERSION_NUMBER) || LIBEVENT_VERSION_NUMBER < 0x02000400 #error "This version of Libevent is not supported; Get 2.0.4-alpha or later." #endif namespace evproto { namespace internal { void eventLogToGlog(int severity, const char *msg) { switch (severity) { case _EVENT_LOG_DEBUG: VLOG(1) << msg; break; case _EVENT_LOG_MSG: LOG(INFO) << msg; break; case _EVENT_LOG_WARN: LOG(WARNING) << msg; break; case _EVENT_LOG_ERR: LOG(ERROR) << msg; break; default: LOG(ERROR) << msg; break; } } void protobufLogHandler(google::protobuf::LogLevel level, const char* filename, int line, const std::string& message) { google::LogMessage(filename, line, level).stream() << message; } void eventFatal(int err) { LOG(FATAL) << "libevent2 fatal " << err; } } // namespace internal // TODO: pass back modified argc and argv. void initialize(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]); ::event_set_log_callback(internal::eventLogToGlog); google::protobuf::SetLogHandler(internal::protobufLogHandler); #if EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED CHECK_EQ(::evthread_use_windows_threads(), 0); #elif EVTHREAD_USE_PTHREADS_IMPLEMENTED CHECK_EQ(::evthread_use_pthreads(), 0); #endif #ifndef NDEBUG // ::evthread_enable_lock_debuging(); // ::event_enable_debug_mode(); #endif CHECK_EQ(LIBEVENT_VERSION_NUMBER, ::event_get_version_number()) << "libevent2 version number mismatch"; google::ParseCommandLineFlags(&argc, &argv, true); LOG(INFO) << argv[0] << " initialized"; } }
cetium/evproto
evproto/evproto.cc
C++
bsd-3-clause
2,066
--TEST-- Protocol Buffers setting integer value --SKIPIF-- <?php require 'skipif.inc' ?> --FILE-- <?php require 'test.inc'; $foo = new Foo(); /* from int type */ $foo->setInt32Field(2); var_dump($foo->getInt32Field()); /* from float type */ $foo->setInt32Field(3.0); var_dump($foo->getInt32Field()); /* from string type */ $foo->setInt32Field('4'); var_dump($foo->getInt32Field()); ?> --EXPECT-- int(2) int(3) int(4)
nosun/php-protobuf
tests/set_int_field.phpt
PHP
bsd-3-clause
421
// (C) Copyright Joel de Guzman 2003. // 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) // Modified by Troy D. Straszheim and Jakob van Santen, 2009-03-26 // Pulled in to ecto in 2010-11 by Troy D. Straszheim // Willow Garage BSD License not applicable #ifndef ICETRAY_PYTHON_STD_MAP_INDEXING_SUITE_HPP_INCLUDED # define ICETRAY_PYTHON_STD_MAP_INDEXING_SUITE_HPP_INCLUDED # include <ecto/python.hpp> # include <boost/python/suite/indexing/indexing_suite.hpp> # include <boost/python/iterator.hpp> # include <boost/python/call_method.hpp> # include <boost/python/tuple.hpp> # include <boost/iterator/transform_iterator.hpp> namespace bp = boost::python; namespace boost { namespace python { // Forward declaration template <class Container, bool NoProxy, class DerivedPolicies> class std_map_indexing_suite; namespace detail { template <class Container, bool NoProxy> class final_std_map_derived_policies : public std_map_indexing_suite<Container, NoProxy, final_std_map_derived_policies<Container, NoProxy> > {}; } // The map_indexing_suite class is a predefined indexing_suite derived // class for wrapping std::vector (and std::vector like) classes. It provides // all the policies required by the indexing_suite (see indexing_suite). // Example usage: // // class X {...}; // // ... // // class_<std::map<std::string, X> >("XMap") // .def(map_indexing_suite<std::map<std::string, X> >()) // ; // // By default indexed elements are returned by proxy. This can be // disabled by supplying *true* in the NoProxy template parameter. // template < class Container, bool NoProxy = false, class DerivedPolicies = detail::final_std_map_derived_policies<Container, NoProxy> > class std_map_indexing_suite : public indexing_suite< Container , DerivedPolicies , NoProxy , true , typename Container::value_type::second_type , typename Container::key_type , typename Container::key_type > { public: typedef typename Container::value_type value_type; typedef typename Container::value_type::second_type data_type; typedef typename Container::key_type key_type; typedef typename Container::key_type index_type; typedef typename Container::size_type size_type; typedef typename Container::difference_type difference_type; typedef typename Container::const_iterator const_iterator; // __getitem__ for std::pair // FIXME: horrible (20x) performance regression vs. (pair.key(),pair.data()) static object pair_getitem(value_type const& x, int i) { if (i==0 || i==-2) return object(x.first); else if (i==1 || i==-1) return object(x.second); else { PyErr_SetString(PyExc_IndexError,"Index out of range."); throw_error_already_set(); return object(); // None } } // __iter__ for std::pair // here we cheat by making a tuple and returning its iterator // FIXME: replace this with a pure C++ iterator // how to handle the different return types of first and second? static PyObject* pair_iter(value_type const& x) { object tuple = bp::make_tuple(x.first,x.second); return incref(tuple.attr("__iter__")().ptr()); } // __len__ std::pair = 2 static int pair_len(value_type const& x) { return 2; } // return a list of keys static bp::list keys(Container const& x) { bp::list t; for(typename Container::const_iterator it = x.begin(); it != x.end(); it++) t.append(it->first); return t; } // return a list of values static bp::list values(Container const& x) { bp::list t; for(typename Container::const_iterator it = x.begin(); it != x.end(); it++) t.append(it->second); return t; } // return a list of (key,value) tuples static bp::list items(Container const& x) { bp::list t; for(typename Container::const_iterator it = x.begin(); it != x.end(); it++) t.append(bp::make_tuple(it->first, it->second)); return t; } #if 0 // return a shallow copy of the map // FIXME: is this actually a shallow copy, or did i duplicate the pairs? static Container copy(Container const& x) { Container newmap; for(const_iterator it = x.begin();it != x.end();it++) newmap.insert(*it); return newmap; } #endif // get with default value static object dict_get(Container const& x, index_type const& k, object const& default_val = object()) { const_iterator it = x.find(k); if (it != x.end()) return object(it->second); else return default_val; } // preserve default value info BOOST_PYTHON_FUNCTION_OVERLOADS(dict_get_overloads, dict_get, 2, 3); // pop map[key], or throw an error if it doesn't exist static object dict_pop(Container & x, index_type const& k) { const_iterator it = x.find(k); object result; if (it != x.end()) { result = object(it->second); x.erase(it->first); return result; } else { PyErr_SetString(PyExc_KeyError,"Key not found."); throw_error_already_set(); return object(); // None }; } // pop map[key], or return default_val if it doesn't exist static object dict_pop_default(Container & x, index_type const& k, object const& default_val) { const_iterator it = x.find(k); object result; if (it != x.end()) { result = object(it->second); x.erase(it->first); return result; } else return default_val; } // pop a tuple, or throw an error if empty static object dict_pop_item(Container & x) { const_iterator it = x.begin(); object result; if (it != x.end()) { result = boost::python::make_tuple(it->first,it->second); x.erase(it->first); return result; } else { PyErr_SetString(PyExc_KeyError,"No more items to pop"); throw_error_already_set(); return object(); // None }; } // create a new map with given keys, initialialized to value static object dict_fromkeys(object const& keys, object const& value) { object newmap = object(typename Container::storage_type()); int numkeys = extract<int>(keys.attr("__len__")()); for(int i=0;i<numkeys;i++) { // 'cuz python is more fun in C++... newmap.attr("__setitem__") (keys.attr("__getitem__")(i),value); } return newmap; } // spice up the constructors a bit template <typename PyClassT> struct init_factory { typedef typename PyClassT::metadata::holder Holder; typedef bp::objects::instance<Holder> instance_t; // connect the PyObject to a wrapped C++ instance // borrowed from boost/python/object/make_holder.hpp static void make_holder(PyObject *p) { void* memory = Holder::allocate(p, offsetof(instance_t, storage), sizeof(Holder)); try { // this only works for blank () constructors (new (memory) Holder(p))->install(p); } catch(...) { Holder::deallocate(p, memory); throw; } } static void from_dict(PyObject *p, bp::dict const& dict) { make_holder(p); object newmap = object(bp::handle<>(borrowed(p))); newmap.attr("update")(dict); } static void from_list(PyObject *p, bp::list const& list) { make_holder(p); object newmap = object(bp::handle<>(borrowed(p))); newmap.attr("update")(bp::dict(list)); } }; // copy keys and values from dictlike object (anything with keys()) static void dict_update(object & x, object const& dictlike) { object key; object keys = dictlike.attr("keys")(); int numkeys = extract<int>(keys.attr("__len__")()); for(int i=0;i<numkeys;i++) { key = keys.attr("__getitem__")(i); x.attr("__setitem__")(key,dictlike.attr("__getitem__")(key)); } } // set up operators to sample the key, value, or a tuple from a std::pair struct iterkeys { typedef key_type result_type; result_type operator()(value_type const& x) const { return x.first; } }; struct itervalues { typedef data_type result_type; result_type operator()(value_type const& x) const { return x.second; } }; struct iteritems { typedef tuple result_type; result_type operator()(value_type const& x) const { return boost::python::make_tuple(x.first,x.second); } }; template <typename Transform> struct make_transform_impl { typedef boost::transform_iterator<Transform, const_iterator> iterator; static iterator begin(const Container& m) { return boost::make_transform_iterator(m.begin(), Transform()); } static iterator end(const Container& m) { return boost::make_transform_iterator(m.end(), Transform()); } static bp::object range() { return bp::range(&begin, &end); } }; template <typename Transform> static bp::object make_transform() { return make_transform_impl<Transform>::range(); } static object print_elem(typename Container::value_type const& e) { return "(%s, %s)" % python::make_tuple(e.first, e.second); } static typename mpl::if_< is_class<data_type> , data_type& , data_type >::type get_data(typename Container::value_type& e) { return e.second; } static typename Container::key_type get_key(typename Container::value_type& e) { return e.first; } static data_type& get_item(Container& container, index_type i_) { typename Container::iterator i = container.find(i_); if (i == container.end()) { PyErr_SetString(PyExc_KeyError, "Invalid key"); throw_error_already_set(); } return i->second; } static void set_item(Container& container, index_type i, data_type const& v) { container[i] = v; } static void delete_item(Container& container, index_type i) { container.erase(i); } static size_t size(Container& container) { return container.size(); } static bool contains(Container& container, key_type const& key) { return container.find(key) != container.end(); } static bool compare_index(Container& container, index_type a, index_type b) { return container.key_comp()(a, b); } static index_type convert_index(Container& container, PyObject* i_) { extract<key_type const&> i(i_); if (i.check()) { return i(); } else { extract<key_type> i(i_); if (i.check()) return i(); } PyErr_SetString(PyExc_TypeError, "Invalid index type"); throw_error_already_set(); return index_type(); } template <class Class> static void extension_def(Class& cl) { // Wrap the map's element (value_type) std::string elem_name = "std_map_indexing_suite_"; std::string cl_name; object class_name(cl.attr("__name__")); extract<std::string> class_name_extractor(class_name); cl_name = class_name_extractor(); elem_name += cl_name; elem_name += "_entry"; typedef typename mpl::if_< is_class<data_type> , return_internal_reference<> , default_call_policies >::type get_data_return_policy; class_<value_type>(elem_name.c_str()) .def("__repr__", &DerivedPolicies::print_elem) .def("data", &DerivedPolicies::get_data, get_data_return_policy(), "K.data() -> the value associated with this pair.\n") .def("key", &DerivedPolicies::get_key, "K.key() -> the key associated with this pair.\n") .def("__getitem__",&pair_getitem) .def("__iter__",&pair_iter) .def("__len__",&pair_len) .def("first",&DerivedPolicies::get_key, "K.first() -> the first item in this pair.\n") .def("second",&DerivedPolicies::get_data, get_data_return_policy(), "K.second() -> the second item in this pair.\n") ; // add convenience methods to the map cl // declare constructors in descending order of arity .def("__init__", init_factory<Class>::from_list, "Initialize with keys and values from a Python dictionary: {'key':'value'}\n") .def("__init__", init_factory<Class>::from_dict, "Initialize with keys and values as tuples in a Python list: [('key','value')]\n") .def(init<>()) // restore default constructor .def("keys", &keys, "D.keys() -> list of D's keys\n") .def("has_key", &contains, "D.has_key(k) -> True if D has a key k, else False\n") // don't re-invent the wheel .def("values", &values, "D.values() -> list of D's values\n") .def("items", &items, "D.items() -> list of D's (key, value) pairs, as 2-tuples\n") .def("clear", &Container::clear, "D.clear() -> None. Remove all items from D.\n") //.def("copy", &copy, "D.copy() -> a shallow copy of D\n") .def("get", dict_get, dict_get_overloads(args("default_val"), "D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.\n")) .def("pop", &dict_pop ) .def("pop", &dict_pop_default, "D.pop(k[,d]) -> v, remove specified key and return the corresponding value\nIf key is not found, d is returned if given, otherwise KeyError is raised\n") .def("popitem", &dict_pop_item, "D.popitem() -> (k, v), remove and return some (key, value) pair as a\n2-tuple; but raise KeyError if D is empty\n") .def("fromkeys", &dict_fromkeys, (cl_name+".fromkeys(S,v) -> New "+cl_name+" with keys from S and values equal to v.\n").c_str()) .staticmethod("fromkeys") .def("update", &dict_update, "D.update(E) -> None. Update D from E: for k in E: D[k] = E[k]\n") .def("iteritems", make_transform<iteritems>(), "D.iteritems() -> an iterator over the (key, value) items of D\n") .def("iterkeys", make_transform<iterkeys>(), "D.iterkeys() -> an iterator over the keys of D\n") .def("itervalues", make_transform<itervalues>(), "D.itervalues() -> an iterator over the values of D\n") ; } }; }} // namespace boost::python #endif // ICETRAY_PYTHON_STD_MAP_INDEXING_SUITE_HPP_INCLUDED
stonier/ecto
include/ecto/python/std_map_indexing_suite.hpp
C++
bsd-3-clause
17,030
require('should'); var option = require('..').sdk.option; describe('option', function() { it('can get default values', function() { option.get('encoding').should.equal('utf8'); }); it('can set values', function() { option.set('encoding', 'unicode'); option.get('encoding').should.equal('unicode'); option.clean(); option.get('encoding').should.equal('utf8'); option.option('encoding').should.equal('utf8'); option.option('encoding', 'unicode'); option.get('encoding').should.equal('unicode'); option.clean(); }); it('will init with some values', function() { var o = new option.Option({foo: 'bar'}); o.get('foo').should.equal('bar'); }); it('can clean a key', function() { var o = new option.Option({foo: 'bar'}); o.clean('foo'); o._cache.should.eql({}); }); it('can set defaults', function() { option.defaults({ foo: { foo: 'bar' } }); option.set('foo', {bar: 'foo'}); option.get('foo').should.have.ownProperty('foo'); option.get('foo').should.have.ownProperty('bar'); }); });
thcode/nico
tests/sdk.option.test.js
JavaScript
bsd-3-clause
1,096
using Shouldly.Tests.TestHelpers; namespace Shouldly.Tests.Strings.DetailedDifference.CaseInsensitive.LongStrings.MultipleDiffs { // Just before the edge case for consolidation. 2 differences are exactly the required length apart to be consolidated into one diff public class DiffsCloseToEachOtherAreConsolidatedBorderConditionOne: ShouldlyShouldTestScenario { protected override void ShouldPass() { "1A,1b,1c,1d,1e,1f,1g,1h,1i,1j,1k,1l,1m,1n,1o,1p,1q,1r,1s,1t,1u,1v" .ShouldBe( "1a,1b,1c,1d,1e,1f,1g,1h,1i,1j,1k,1l,1m,1n,1o,1p,1q,1r,1s,1t,1u,1v", Case.Insensitive); } protected override void ShouldThrowAWobbly() { "1a,1b,1c,1d,1e,1f,1g,1h,1i,1j,1k,1l,1m,1n,1o,1p,1q,1r,1s,1t,1u,1v" .ShouldBe( "1a,1b.1c,1d,1e,1f,1g,1h,1j,1j,1k,1l,1m,1n,1o.1p,1q,1r,1s,1t,1u,1w", Case.Insensitive); } protected override string ChuckedAWobblyErrorMessage { get { return @"""1a,1b,1c,1d,1e,1f,1g,1h,1i,1j,1k,1l,1m,1n,1o,1p,1q,1r,1s,1t,1u,1v"" should be ""1a,1b.1c,1d,1e,1f,1g,1h,1j,1j,1k,1l,1m,1n,1o.1p,1q,1r,1s,1t,1u,1w"" but was ""1a,1b,1c,1d,1e,1f,1g,1h,1i,1j,1k,1l,1m,1n,1o,1p,1q,1r,1s,1t,1u,1v"" difference Case Insensitive Comparison Difference | | | | \|/ \|/ Index | ... 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 ... Expected Value | ... . 1 c , 1 d , 1 e , 1 f , 1 g , 1 h , 1 j ... Actual Value | ... , 1 c , 1 d , 1 e , 1 f , 1 g , 1 h , 1 i ... Expected Code | ... 46 49 99 44 49 100 44 49 101 44 49 102 44 49 103 44 49 104 44 49 106 ... Actual Code | ... 44 49 99 44 49 100 44 49 101 44 49 102 44 49 103 44 49 104 44 49 105 ... Difference | | | | \|/ \|/ Index | ... 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 Expected Value | ... . 1 p , 1 q , 1 r , 1 s , 1 t , 1 u , 1 w Actual Value | ... , 1 p , 1 q , 1 r , 1 s , 1 t , 1 u , 1 v Expected Code | ... 46 49 112 44 49 113 44 49 114 44 49 115 44 49 116 44 49 117 44 49 119 Actual Code | ... 44 49 112 44 49 113 44 49 114 44 49 115 44 49 116 44 49 117 44 49 118 " ; } } } }
yannisgu/shouldly
src/Shouldly.Tests/Strings/DetailedDifference/CaseInsensitive/LongStrings/MultipleDiffs/DiffsCloseToEachOtherAreConsolidatedBorderConditionOne.cs
C#
bsd-3-clause
3,647
function setSearchTextField(paramname, field) { var passed = location.search.substring(1); var query = getParm(passed,paramname); var query = getParm(passed,paramname); query = query.replace(/\+/g," "); var loc = document.location; if(/.*search.html/.test(loc)) { document.title = decodeURIComponent(query) + ' - Wolfram Search'; } field.value = decodeURIComponent(query); } function getParm(string,parm) { // returns value of parm from string var startPos = string.indexOf(parm + "="); if (startPos > -1) { startPos = startPos + parm.length + 1; var endPos = string.indexOf("&",startPos); if (endPos == -1) endPos = string.length; return string.substring(startPos,endPos); } return ''; }
mfroeling/DTITools
docs/htmldoc/standard/javascript/search.js
JavaScript
bsd-3-clause
723
#include "consoletools.h" #include "log/logger.h" #include <QTextStream> #include <Windows.h> LOGGER(ConsoleTools); class ConsoleTools::Private { public: Private() { hConsole = ::GetStdHandle(STD_INPUT_HANDLE); if (hConsole == INVALID_HANDLE_VALUE) { LOG_ERROR("Unable to get console handle"); } } HANDLE hConsole; }; ConsoleTools::ConsoleTools() : d(new Private) { } ConsoleTools::~ConsoleTools() { enableEcho(); delete d; } bool ConsoleTools::enableEcho() { DWORD value; ::GetConsoleMode(d->hConsole, &value); value |= ENABLE_ECHO_INPUT; ::SetConsoleMode(d->hConsole, value); return true; } bool ConsoleTools::disableEcho() { DWORD value; ::GetConsoleMode(d->hConsole, &value); value &= ~ENABLE_ECHO_INPUT; ::SetConsoleMode(d->hConsole, value); return true; } QString ConsoleTools::readLine() { QTextStream stream(stdin); return stream.readLine(); } QString ConsoleTools::readPassword() { disableEcho(); QTextStream stream(stdin); QString pw = stream.readLine(); enableEcho(); return pw; }
MKV21/glimpse_client
src/console/consoletools_win.cpp
C++
bsd-3-clause
1,142
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/autofill/core/browser/payments/test_authentication_requester.h" #include <string> #include "build/build_config.h" #include "components/autofill/core/browser/data_model/credit_card.h" namespace autofill { TestAuthenticationRequester::TestAuthenticationRequester() {} TestAuthenticationRequester::~TestAuthenticationRequester() {} base::WeakPtr<TestAuthenticationRequester> TestAuthenticationRequester::GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } void TestAuthenticationRequester::OnCVCAuthenticationComplete( const CreditCardCVCAuthenticator::CVCAuthenticationResponse& response) { did_succeed_ = response.did_succeed; if (*did_succeed_) { DCHECK(response.card); number_ = response.card->number(); } } #if BUILDFLAG(IS_ANDROID) bool TestAuthenticationRequester::ShouldOfferFidoAuth() const { return false; } bool TestAuthenticationRequester::UserOptedInToFidoFromSettingsPageOnMobile() const { return false; } #endif #if !BUILDFLAG(IS_IOS) void TestAuthenticationRequester::OnFIDOAuthenticationComplete( const CreditCardFIDOAuthenticator::FidoAuthenticationResponse& response) { did_succeed_ = response.did_succeed; if (*did_succeed_) { DCHECK(response.card); number_ = response.card->number(); } failure_type_ = response.failure_type; } void TestAuthenticationRequester::OnFidoAuthorizationComplete( bool did_succeed) { did_succeed_ = did_succeed; } void TestAuthenticationRequester::IsUserVerifiableCallback( bool is_user_verifiable) { is_user_verifiable_ = is_user_verifiable; } #endif void TestAuthenticationRequester::OnOtpAuthenticationComplete( const CreditCardOtpAuthenticator::OtpAuthenticationResponse& response) { did_succeed_ = response.result == CreditCardOtpAuthenticator::OtpAuthenticationResponse::Result::kSuccess; if (*did_succeed_) { DCHECK(response.card); number_ = response.card->number(); } } } // namespace autofill
chromium/chromium
components/autofill/core/browser/payments/test_authentication_requester.cc
C++
bsd-3-clause
2,142
'use strict'; const hljs = require('highlight.js'); const languages = hljs.listLanguages(); const fs = require('fs'); const result = { languages: languages, aliases: {} }; languages.forEach(lang => { result.aliases[lang] = lang; const def = require('highlight.js/lib/languages/' + lang)(hljs); const aliases = def.aliases; if (aliases) { aliases.forEach(alias => { result.aliases[alias] = lang; }); } }); const stream = fs.createWriteStream('highlight_alias.json'); stream.write(JSON.stringify(result)); stream.on('end', () => { stream.end(); });
hexojs/hexo-util
scripts/build_highlight_alias.js
JavaScript
mit
583
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace ScintillaNET { /// <summary> /// Provides data for the <see cref="Scintilla.DoubleClick" /> event. /// </summary> public class DoubleClickEventArgs : EventArgs { private readonly Scintilla scintilla; private readonly int bytePosition; private int? position; /// <summary> /// Gets the line double clicked. /// </summary> /// <returns>The zero-based index of the double clicked line.</returns> public int Line { get; private set; } /// <summary> /// Gets the modifier keys (SHIFT, CTRL, ALT) held down when double clicked. /// </summary> /// <returns>A bitwise combination of the Keys enumeration indicating the modifier keys.</returns> public Keys Modifiers { get; private set; } /// <summary> /// Gets the zero-based document position of the text double clicked. /// </summary> /// <returns> /// The zero-based character position within the document of the double clicked text; /// otherwise, -1 if not a document position. /// </returns> public int Position { get { if (position == null) position = scintilla.Lines.ByteToCharPosition(bytePosition); return (int)position; } } /// <summary> /// Initializes a new instance of the <see cref="DoubleClickEventArgs" /> class. /// </summary> /// <param name="scintilla">The <see cref="Scintilla" /> control that generated this event.</param> /// <param name="modifiers">The modifier keys that where held down at the time of the double click.</param> /// <param name="bytePosition">The zero-based byte position of the double clicked text.</param> /// <param name="line">The zero-based line index of the double clicked text.</param> public DoubleClickEventArgs(Scintilla scintilla, Keys modifiers, int bytePosition, int line) { this.scintilla = scintilla; this.bytePosition = bytePosition; Modifiers = modifiers; Line = line; if (bytePosition == -1) position = -1; } } }
suvjunmd/ScintillaNET
src/ScintillaNET/DoubleClickEventArgs.cs
C#
mit
2,400
using System; using ProvisioningLibrary; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; namespace ProvisioningLibrary { public class GroupBudgetState : TableEntity { private string _ResourceId = string.Empty; public GroupBudgetState() { } public GroupBudgetState(string groupId) : this() { this.RowKey = groupId; this.PartitionKey = groupId; } public string GroupId { get { return this.PartitionKey; } } public long UnitsBudgetted { get; set; } public long UnitsAllocated { get; set; } public long UnitsUsed { get; set; } } }
GabrieleCastellani/SCAMP
ProvisioningLibrary/VolatileStorage/GroupBudgetState.cs
C#
mit
755
// // ConvertLambdaBodyExpressionToStatementAction.cs // // Author: // Mansheng Yang <lightyang0@gmail.com> // // Copyright (c) 2012 Mansheng Yang <lightyang0@gmail.com> // // 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. namespace ICSharpCode.NRefactory.CSharp.Refactoring { [ContextAction ("Converts expression of lambda body to statement", Description = "Converts expression of lambda body to statement")] public class ConvertLambdaBodyExpressionToStatementAction : SpecializedCodeAction<LambdaExpression> { protected override CodeAction GetAction (RefactoringContext context, LambdaExpression node) { if (!node.ArrowToken.Contains (context.Location)) return null; var bodyExpr = node.Body as Expression; if (bodyExpr == null) return null; return new CodeAction (context.TranslateString ("Convert to lambda statement"), script => { var body = new BlockStatement (); if (RequireReturnStatement (context, node)) { body.Add (new ReturnStatement (bodyExpr.Clone ())); } else { body.Add (new ExpressionStatement (bodyExpr.Clone ())); } script.Replace (bodyExpr, body); }); } static bool RequireReturnStatement (RefactoringContext context, LambdaExpression lambda) { var type = LambdaHelper.GetLambdaReturnType (context, lambda); return type != null && type.ReflectionName != "System.Void"; } } }
praeclarum/Netjs
Netjs/Dependencies/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertLambdaBodyExpressionToStatementAction.cs
C#
mit
2,431
export { default, DimmerProps } from './Dimmer';
aabustamante/Semantic-UI-React
src/modules/Dimmer/index.d.ts
TypeScript
mit
49
package keyseq type TernaryTrie struct { root TernaryNode } func NewTernaryTrie() *TernaryTrie { return &TernaryTrie{} } func (t *TernaryTrie) Root() Node { return &t.root } func (t *TernaryTrie) GetList(k KeyList) Node { return Get(t, k) } func (t *TernaryTrie) Get(k Key) Node { return Get(t, KeyList{k}) } func (t *TernaryTrie) Put(k KeyList, v interface{}) Node { return Put(t, k, v) } func (t *TernaryTrie) Size() int { count := 0 EachDepth(t, func(Node) bool { count++ return true }) return count } func (t *TernaryTrie) Balance() { EachDepth(t, func(n Node) bool { n.(*TernaryNode).Balance() return true }) t.root.Balance() } type TernaryNode struct { label Key firstChild *TernaryNode low, high *TernaryNode value interface{} } func NewTernaryNode(l Key) *TernaryNode { return &TernaryNode{label: l} } func (n *TernaryNode) GetList(k KeyList) Node { return n.Get(k[0]) } func (n *TernaryNode) Get(k Key) Node { curr := n.firstChild for curr != nil { switch k.Compare(curr.label) { case 0: // equal return curr case -1: // less curr = curr.low default: //more curr = curr.high } } return nil } func (n *TernaryNode) Dig(k Key) (node Node, isnew bool) { curr := n.firstChild if curr == nil { n.firstChild = NewTernaryNode(k) return n.firstChild, true } for { switch k.Compare(curr.label) { case 0: return curr, false case -1: if curr.low == nil { curr.low = NewTernaryNode(k) return curr.low, true } curr = curr.low default: if curr.high == nil { curr.high = NewTernaryNode(k) return curr.high, true } curr = curr.high } } } func (n *TernaryNode) FirstChild() *TernaryNode { return n.firstChild } func (n *TernaryNode) HasChildren() bool { return n.firstChild != nil } func (n *TernaryNode) Size() int { if n.firstChild == nil { return 0 } count := 0 n.Each(func(Node) bool { count++ return true }) return count } func (n *TernaryNode) Each(proc func(Node) bool) { var f func(*TernaryNode) bool f = func(n *TernaryNode) bool { if n != nil { if !f(n.low) || !proc(n) || !f(n.high) { return false } } return true } f(n.firstChild) } func (n *TernaryNode) RemoveAll() { n.firstChild = nil } func (n *TernaryNode) Label() Key { return n.label } func (n *TernaryNode) Value() interface{} { return n.value } func (n *TernaryNode) SetValue(v interface{}) { n.value = v } func (n *TernaryNode) children() []*TernaryNode { children := make([]*TernaryNode, n.Size()) if n.firstChild == nil { return children } idx := 0 n.Each(func(child Node) bool { children[idx] = child.(*TernaryNode) idx++ return true }) return children } func (n *TernaryNode) Balance() { if n.firstChild == nil { return } children := n.children() for _, child := range children { child.low = nil child.high = nil } n.firstChild = balance(children, 0, len(children)) } func balance(nodes []*TernaryNode, s, e int) *TernaryNode { count := e - s if count <= 0 { return nil } else if count == 1 { return nodes[s] } else if count == 2 { nodes[s].high = nodes[s+1] return nodes[s] } else { mid := (s + e) / 2 n := nodes[mid] n.low = balance(nodes, s, mid) n.high = balance(nodes, mid+1, e) return n } }
dav009/peco
keyseq/ternary.go
GO
mit
3,295
using System; using System.IO; using Foundation; using UIKit; using CoreGraphics; using Dropbox.CoreApi.iOS; namespace DropboxCoreApiSample { public partial class TextViewController : UIViewController { // A TextField with Placeholder CustomUITextView textView; RestClient restClient; string filename; public TextViewController () { View.BackgroundColor = UIColor.White; // Will handle the save to Dropbox process var btnSave = new UIBarButtonItem ("Save", UIBarButtonItemStyle.Plain, WriteFile); btnSave.Enabled = false; // Create the TextField with a Placeholder textView = new CustomUITextView (CGRect.Empty, "Type something nice!"); textView.TranslatesAutoresizingMaskIntoConstraints = false; // If the user has written something, you can save the file textView.Changed += (sender, e) => btnSave.Enabled = textView.Text.Length != 0; // Rest client that will handle the file upload restClient = new RestClient (Session.SharedSession); // Once the file is on Dropbox, notify the user restClient.FileUploaded += (sender, e) => { new UIAlertView ("Saved on Dropbox", "The file was uploaded to Dropbox correctly", null, "OK", null).Show (); #if __UNIFIED__ NavigationController.PopViewController (true); #else NavigationController.PopViewControllerAnimated (true); #endif }; // Handle if something went wrong with the upload of the file restClient.LoadFileFailed += (sender, e) => { // Try to upload the file again var alertView = new UIAlertView ("Hmm...", "Something went wrong when trying to save the file on Dropbox...", null, "Not now", new [] { "Try Again" }); alertView.Clicked += (avSender, avE) => { if (avE.ButtonIndex == 1) restClient.UploadFile (filename, DropboxCredentials.FolderPath, null, Path.GetTempPath () + filename); }; alertView.Show (); }; // Add the view with its constraints View.Add (textView); NavigationItem.RightBarButtonItem = btnSave; AddConstraints (); } void AddConstraints () { var views = new NSDictionary ("textView", textView); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|-0-[textView]-0-|", 0, null, views)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|-0-[textView]-0-|", 0, null, views)); } // Process to save the file on Dropbox void WriteFile (object sender, EventArgs e) { // Notify that the user has ended typing textView.EndEditing (true); // Ask for a name to the file var alertView = new UIAlertView ("Save to Dropbox", "Enter a name for the file", null, "Cancel", new [] { "Save" }); alertView.AlertViewStyle = UIAlertViewStyle.PlainTextInput; alertView.Clicked += (avSender, avE) => { // Once we have the name, we need to save the file locally first and then upload it to Dropbox if (avE.ButtonIndex == 1) { filename = alertView.GetTextField (0).Text + ".txt"; var fullPath = Path.GetTempPath () + filename; // Write the file locally File.WriteAllText (fullPath, textView.Text); // Now upload it to Dropbox restClient.UploadFile (filename, DropboxCredentials.FolderPath, null, fullPath); } }; alertView.Show (); } } }
JonDouglas/XamarinComponents
XPlat/DropboxCoreApi/iOS/samples/DropboxCoreApiSample/DropboxCoreApiSample/TextViewController.cs
C#
mit
3,244
<?php namespace Herrera\Cli\Tests\Provider; use Herrera\Cli\Provider\ErrorHandlingServiceProvider; use Herrera\PHPUnit\TestCase; use Herrera\Service\Container; class ErrorHandlingServiceProviderTest extends TestCase { public function testRegister() { $container = new Container(); $container->register(new ErrorHandlingServiceProvider()); $this->setExpectedException( 'ErrorException', 'Test error.' ); trigger_error('Test error.', E_USER_ERROR); } public function testRegisterIgnored() { $container = new Container(); $container->register(new ErrorHandlingServiceProvider()); error_reporting(E_ALL ^ E_USER_NOTICE); trigger_error('Test error.', E_USER_NOTICE); $this->assertTrue(true); } }
spi-ke/Socialman
src/vendors/herrera-io/cli-app/src/tests/Herrera/Cli/Tests/Provider/ErrorHandlingServiceProviderTest.php
PHP
mit
828
<?php /** * PHPExcel * * Copyright (c) 2006 - 2007 PHPExcel, Maarten Balliauw * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. * * @copyright Copyright (c) 2006 - 2007 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/gpl.txt GPL */ /** * This file creates a build of PHPExcel */ // Starting build echo date('H:i:s') . " Starting build...\n"; // Specify paths and files to include $aFilesToInclude = array('../changelog.txt', '../install.txt', '../license.txt'); $aPathsToInclude = array('../Classes', '../Tests', '../Documentation'); // Resulting file $strResultingFile = 'LatestBuild.zip'; // Create new ZIP file and open it for writing echo date('H:i:s') . " Creating ZIP archive...\n"; $objZip = new ZipArchive(); // Try opening the ZIP file if ($objZip->open($strResultingFile, ZIPARCHIVE::OVERWRITE) !== true) { throw new Exeption("Could not open " . $strResultingFile . " for writing!"); } // Add files to include foreach ($aFilesToInclude as $strFile) { echo date('H:i:s') . " Adding file $strFile\n"; $objZip->addFile($strFile, cleanFileName($strFile)); } // Add paths to include foreach ($aPathsToInclude as $strPath) { addPathToZIP($strPath, $objZip); } // Set archive comment... echo date('H:i:s') . " Set archive comment...\n"; $objZip->setArchiveComment('PHPExcel - http://www.codeplex.com/PHPExcel'); // Close file echo date('H:i:s') . " Saving ZIP archive...\n"; $objZip->close(); // Finished build echo date('H:i:s') . " Finished build!\n"; /** * Add a specific path's files and folders to a ZIP object * * @param string $strPath Path to add * @param ZipArchive $objZip ZipArchive object */ function addPathToZIP($strPath, $objZip) { echo date('H:i:s') . " Adding path $strPath...\n"; $currentDir = opendir($strPath); while ($strFile = readdir($currentDir)) { if ($strFile != '.' && $strFile != '..') { if (is_file($strPath . '/' . $strFile)) { $objZip->addFile($strPath . '/' . $strFile, cleanFileName($strPath . '/' . $strFile)); } else if (is_dir($strPath . '/' . $strFile)) { if (!eregi('.svn', $strFile)) { addPathToZIP( ($strPath . '/' . $strFile), $objZip ); } } } } } /** * Cleanup a filename * * @param string $strFile Filename * @return string Filename */ function cleanFileName($strFile) { $strFile = str_replace('../', '', $strFile); $strFile = str_replace('WINDOWS', '', $strFile); while (eregi('//', $strFile)) { $strFile = str_replace('//', '/', $strFile); } return $strFile; }
ALTELMA/OfficeEquipmentManager
application/libraries/PHPExcel/branches/v1.1.1/Build/build.php
PHP
mit
3,220
//= require locastyle/templates/_popover.jst.eco //= require locastyle/templates/_dropdown.jst.eco
diegoeis/locawebstyle
source/assets/javascripts/templates.js
JavaScript
mit
99
// Copyright 2015-2018 Hans Dembinski // // 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) //[ guide_histogram_serialization #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/histogram.hpp> #include <boost/histogram/serialization.hpp> // includes serialization code #include <cassert> #include <sstream> int main() { using namespace boost::histogram; auto a = make_histogram(axis::regular<>(3, -1.0, 1.0, "axis 0"), axis::integer<>(0, 2, "axis 1")); a(0.5, 1); std::string buf; // to hold persistent representation // store histogram { std::ostringstream os; boost::archive::text_oarchive oa(os); oa << a; buf = os.str(); } auto b = decltype(a)(); // create a default-constructed second histogram assert(b != a); // b is empty, a is not // load histogram { std::istringstream is(buf); boost::archive::text_iarchive ia(is); ia >> b; } assert(b == a); // now b is equal to a } //]
davehorton/drachtio-server
deps/boost_1_77_0/libs/histogram/examples/guide_histogram_serialization.cpp
C++
mit
1,128
window.Reactable = require('../build/reactable.common');
wemcdonald/reactable
src/reactable.global.js
JavaScript
mit
57
package com.prolificinteractive.materialcalendarview; import android.animation.Animator; import android.content.res.Resources; import android.text.TextUtils; import android.util.TypedValue; import android.view.ViewPropertyAnimator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.TextView; import com.prolificinteractive.materialcalendarview.format.TitleFormatter; class TitleChanger { public static final int DEFAULT_ANIMATION_DELAY = 400; public static final int DEFAULT_Y_TRANSLATION_DP = 20; private final TextView title; private TitleFormatter titleFormatter; private final int animDelay; private final int animDuration; private final int translate; private final Interpolator interpolator = new DecelerateInterpolator(2f); private int orientation = MaterialCalendarView.VERTICAL; private long lastAnimTime = 0; private CalendarDay previousMonth = null; public TitleChanger(TextView title) { this.title = title; Resources res = title.getResources(); animDelay = DEFAULT_ANIMATION_DELAY; animDuration = res.getInteger(android.R.integer.config_shortAnimTime) / 2; translate = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, DEFAULT_Y_TRANSLATION_DP, res.getDisplayMetrics() ); } public void change(final CalendarDay currentMonth) { long currentTime = System.currentTimeMillis(); if (currentMonth == null) { return; } if (TextUtils.isEmpty(title.getText()) || (currentTime - lastAnimTime) < animDelay) { doChange(currentTime, currentMonth, false); } if (currentMonth.equals(previousMonth) || (currentMonth.getMonth() == previousMonth.getMonth() && currentMonth.getYear() == previousMonth.getYear())) { return; } doChange(currentTime, currentMonth, true); } private void doChange(final long now, final CalendarDay currentMonth, boolean animate) { title.animate().cancel(); doTranslation(title, 0); title.setAlpha(1); lastAnimTime = now; final CharSequence newTitle = titleFormatter.format(currentMonth); if (!animate) { title.setText(newTitle); } else { final int translation = translate * (previousMonth.isBefore(currentMonth) ? 1 : -1); final ViewPropertyAnimator viewPropertyAnimator = title.animate(); if (orientation == MaterialCalendarView.HORIZONTAL) { viewPropertyAnimator.translationX(translation * -1); } else { viewPropertyAnimator.translationY(translation * -1); } viewPropertyAnimator .alpha(0) .setDuration(animDuration) .setInterpolator(interpolator) .setListener(new AnimatorListener() { @Override public void onAnimationCancel(Animator animator) { doTranslation(title, 0); title.setAlpha(1); } @Override public void onAnimationEnd(Animator animator) { title.setText(newTitle); doTranslation(title, translation); final ViewPropertyAnimator viewPropertyAnimator = title.animate(); if (orientation == MaterialCalendarView.HORIZONTAL) { viewPropertyAnimator.translationX(0); } else { viewPropertyAnimator.translationY(0); } viewPropertyAnimator .alpha(1) .setDuration(animDuration) .setInterpolator(interpolator) .setListener(new AnimatorListener()) .start(); } }).start(); } previousMonth = currentMonth; } private void doTranslation(final TextView title, final int translate) { if (orientation == MaterialCalendarView.HORIZONTAL) { title.setTranslationX(translate); } else { title.setTranslationY(translate); } } public TitleFormatter getTitleFormatter() { return titleFormatter; } public void setTitleFormatter(TitleFormatter titleFormatter) { this.titleFormatter = titleFormatter; } public void setOrientation(int orientation) { this.orientation = orientation; } public int getOrientation() { return orientation; } public void setPreviousMonth(CalendarDay previousMonth) { this.previousMonth = previousMonth; } }
netcosports/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/TitleChanger.java
Java
mit
5,089
<?php namespace Kunstmaan\AdminBundle\Helper\Menu; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; /** * SettingsMenuAdaptor to add the Settings MenuItem to the top menu and build the Settings tree */ class SettingsMenuAdaptor implements MenuAdaptorInterface { /** @var AuthorizationCheckerInterface */ private $authorizationChecker; /** @var bool */ private $isEnabledVersionChecker; /** @var bool */ private $exceptionLoggingEnabled; /** * @param bool $isEnabledVersionChecker */ public function __construct(AuthorizationCheckerInterface $authorizationChecker, $isEnabledVersionChecker, bool $exceptionLoggingEnabled = true) { $this->authorizationChecker = $authorizationChecker; $this->isEnabledVersionChecker = (bool) $isEnabledVersionChecker; $this->exceptionLoggingEnabled = $exceptionLoggingEnabled; } public function adaptChildren(MenuBuilder $menu, array &$children, MenuItem $parent = null, Request $request = null) { if (\is_null($parent)) { $menuItem = new TopMenuItem($menu); $menuItem ->setRoute('KunstmaanAdminBundle_settings') ->setLabel('settings.title') ->setUniqueId('settings') ->setParent($parent) ->setRole('settings'); if (stripos($request->attributes->get('_route'), $menuItem->getRoute()) === 0) { $menuItem->setActive(true); } $children[] = $menuItem; } if (!\is_null($parent) && 'KunstmaanAdminBundle_settings' == $parent->getRoute()) { if ($this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN') && $this->isEnabledVersionChecker) { $menuItem = new MenuItem($menu); $menuItem ->setRoute('KunstmaanAdminBundle_settings_bundle_version') ->setLabel('settings.version.bundle') ->setUniqueId('bundle_versions') ->setParent($parent); if (stripos($request->attributes->get('_route'), $menuItem->getRoute()) === 0) { $menuItem->setActive(true); } $children[] = $menuItem; } if ($this->exceptionLoggingEnabled) { $menuItem = new MenuItem($menu); $menuItem ->setRoute('kunstmaanadminbundle_admin_exception') ->setLabel('settings.exceptions.title') ->setUniqueId('exceptions') ->setParent($parent); if (stripos($request->attributes->get('_route'), $menuItem->getRoute()) === 0) { $menuItem->setActive(true); $parent->setActive(true); } $children[] = $menuItem; } } } }
Kunstmaan/KunstmaanBundlesCMS
src/Kunstmaan/AdminBundle/Helper/Menu/SettingsMenuAdaptor.php
PHP
mit
2,981
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * dmccann - August 6/2009 - 2.0 - Initial implementation ******************************************************************************/ package org.eclipse.persistence.oxm.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; import org.eclipse.persistence.config.DescriptorCustomizer; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * The XmlCustomizer annotation is used to specify a class that implements the * org.eclipse.persistence.config.DescriptorCustomizer * interface and is to run against a class descriptor after all metadata * processing has been completed. */ @Target({TYPE}) @Retention(RUNTIME) public @interface XmlCustomizer { /** * (Required) Defines the name of the descriptor customizer that should be * applied to this classes descriptor. */ Class<? extends DescriptorCustomizer> value(); }
gameduell/eclipselink.runtime
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/oxm/annotations/XmlCustomizer.java
Java
epl-1.0
1,534
#include "gtest/gtest.h" #include "llt_mockcpp.h" #include <stdio.h> #include <stdlib.h> //½¨ÒéÕâÑùÒýÓ㬱ÜÃâÏÂÃæÓùؼü×ÖʱÐèÒª¼Óǰ׺ testing:: using namespace testing; #ifdef __cplusplus extern "C" { #endif extern unsigned int uttest_OM_AcpuCallBackMsgProc_case1(void); extern unsigned int uttest_OM_AcpuCallBackMsgProc_case2(void); extern unsigned int uttest_OM_AcpuCallBackMsgProc_case3(void); extern unsigned int uttest_OM_AcpuCallBackMsgProc_case4(void); extern unsigned int uttest_OM_AcpuCallBackFidInit_case1(void); extern unsigned int uttest_OM_AcpuCallBackFidInit_case2(void); extern unsigned int uttest_OM_AcpuCallBackFidInit_case3(void); extern void OM_Log1(char *cFileName, unsigned int ulLineNum, unsigned int enModuleId, unsigned int enSubModId, unsigned int enLevel, char *pcString, int lPara1); extern unsigned int VOS_RegisterPIDInfo(unsigned int ulPID, void* pfnInitFun, void* pfnMsgFun); extern unsigned int VOS_RegisterMsgTaskPrio(unsigned int ulFID, unsigned int TaskPrio); #ifdef __cplusplus } #endif #ifndef VOS_OK #define VOS_OK 0 #endif #ifndef VOS_ERR #define VOS_ERR 1 #endif TEST(OM_AcpuCallBackMsgProc1, UT) { MOCKER(OM_Log1) .expects(once()); uttest_OM_AcpuCallBackMsgProc_case1(); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackMsgProc2, UT) { MOCKER(OM_Log1) .expects(once()); uttest_OM_AcpuCallBackMsgProc_case2(); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackMsgProc3, UT) { MOCKER(OM_Log1) .expects(once()); uttest_OM_AcpuCallBackMsgProc_case3(); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackMsgProc4, UT) { uttest_OM_AcpuCallBackMsgProc_case4(); } TEST(OM_AcpuCallBackFidInit1, UT) { MOCKER(VOS_RegisterPIDInfo) .stubs() .will(returnValue(VOS_ERR)); EXPECT_EQ(VOS_OK, uttest_OM_AcpuCallBackFidInit_case1()); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackFidInit2, UT) { MOCKER(VOS_RegisterPIDInfo) .stubs() .will(returnValue((unsigned int)VOS_OK)); MOCKER(VOS_RegisterMsgTaskPrio) .stubs() .will(returnValue((unsigned int)VOS_ERR)); EXPECT_EQ(VOS_OK, uttest_OM_AcpuCallBackFidInit_case2()); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackFidInit3, UT) { MOCKER(VOS_RegisterPIDInfo) .stubs() .will(returnValue((unsigned int)VOS_OK)); MOCKER(VOS_RegisterMsgTaskPrio) .stubs() .will(returnValue((unsigned int)VOS_OK)); EXPECT_EQ(VOS_OK, uttest_OM_AcpuCallBackFidInit_case3()); GlobalMockObject::reset(); }
slade87/ALE21-Kernel
drivers/hisi/modem_hi6xxx/oam/comm/acore/om/uttest_omappoutside.cpp
C++
gpl-2.0
2,725
/* SESC: Super ESCalar simulator Copyright (C) 2005 University of California, Santa Cruz Contributed by Jose Renau This file is part of SESC. SESC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. SESC 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 SESC; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdio.h> #include <ctype.h> #include <math.h> //#include "nanassert.h" //#include "Snippets.h" //#include "SescConf.h" #include "nanassert.h" #include "SescConf.h" #include "Snippets.h" extern "C" { #include "cacti42_areadef.h" #include "cacti_interface.h" #include "cacti42_def.h" #include "cacti42_io.h" } #ifdef SESC_SESCTHERM #include "ThermTrace.h" ThermTrace *sescTherm=0; #endif /*------------------------------------------------------------------------------*/ #include <vector> static double tech; static int res_memport; static double wattch2cactiFactor = 1; double getEnergy(int size ,int bsize ,int assoc ,int rdPorts ,int wrPorts ,int subBanks ,int useTag ,int bits ,xcacti_flp *xflp ); double getEnergy(const char *,xcacti_flp *); //extern "C" void output_data(result_type *result, arearesult_type *arearesult, // area_type *arearesult_subbanked, // parameter_type *parameters, double *NSubbanks); /* extern "C" void output_data(result_type *result, arearesult_type *arearesult, parameter_type *parameters); extern "C" total_result_type cacti_interface( int cache_size, int line_size, int associativity, int rw_ports, int excl_read_ports, int excl_write_ports, int single_ended_read_ports, int banks, double tech_node, int output_width, int specific_tag, int tag_width, int access_mode, int pure_sram); extern "C" void xcacti_power_flp(const result_type *result, const arearesult_type *arearesult, const area_type *arearesult_subbanked, const parameter_type *parameters, xcacti_flp *xflp); */ void iterate(); int getInstQueueSize(const char* proc) { // get the clusters int min = SescConf->getRecordMin(proc,"cluster") ; int max = SescConf->getRecordMax(proc,"cluster") ; int total = 0; int num = 0; for(int i = min ; i <= max ; i++){ const char* cc = SescConf->getCharPtr(proc,"cluster",i) ; if(SescConf->checkInt(cc,"winSize")){ int sz = SescConf->getInt(cc,"winSize") ; total += sz; num++; } } // check if(!num){ fprintf(stderr,"no clusters\n"); exit(-1); } return total/num; } #ifdef SESC_SESCTHERM static void update_layout_bank(const char *blockName, xcacti_flp *xflp, const ThermTrace::FLPUnit *flp) { double dx; double dy; double a; // +------------------------------+ // | bank ctrl | // +------------------------------+ // | tag | de | data | // | array | co | array | // | | de | | // +------------------------------+ // | tag_ctrl | data_ctrl | // +------------------------------+ const char *flpSec = SescConf->getCharPtr("","floorplan"); size_t max = SescConf->getRecordMax(flpSec,"blockDescr"); max++; char cadena[1024]; //-------------------------------- // Find top block bank_ctrl dy = flp->delta_y*(xflp->bank_ctrl_a/xflp->total_a); if (xflp->bank_ctrl_e) { // Only if bankCtrl consumes energy sprintf(cadena, "%sBankCtrl %g %g %g %g", blockName, flp->delta_x, dy, flp->x, flp->y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sBankCtrlEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; } double tag_start_y = dy + flp->y; //-------------------------------- // Find lower blocks tag_ctrl and data_ctrl dy = flp->delta_y*((3*xflp->tag_ctrl_a+3*xflp->data_ctrl_a)/xflp->total_a); a = xflp->tag_ctrl_a+xflp->data_ctrl_a; dx = flp->delta_x*(xflp->tag_ctrl_a/a); double tag_end_y = flp->y+flp->delta_y-dy; if (xflp->tag_array_e) { // Only if tag consumes energy sprintf(cadena,"%sTagCtrl %g %g %g %g", blockName, dx/3, dy, flp->x+dx/3, tag_end_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sTagCtrlEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; } sprintf(cadena,"%sDataCtrl %g %g %g %g", blockName, (flp->delta_x-dx)/3, dy, flp->x+dx+(flp->delta_x-dx)/3, tag_end_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sDataCtrlEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; //-------------------------------- // Find middle blocks tag array, decode, and data array a = xflp->tag_array_a+xflp->data_array_a+xflp->decode_a; dy = tag_end_y - tag_start_y; if (xflp->tag_array_e) { dx = flp->delta_x*(xflp->tag_array_a/a); sprintf(cadena, "%sTagArray %g %g %g %g", blockName, dx, dy, flp->x, tag_start_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sTagArrayEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; } double x = flp->x + dx; dx = flp->delta_x*((xflp->decode_a)/a); sprintf(cadena, "%sDecode %g %g %g %g", blockName, dx, dy, x, tag_start_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sDecodeEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; dx = flp->delta_x*((xflp->data_array_a)/a); sprintf(cadena, "%sDataArray %g %g %g %g", blockName, dx, dy, flp->x+flp->delta_x-dx, tag_start_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sDataArrayEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; } static void update_sublayout(const char *blockName, xcacti_flp *xflp, const ThermTrace::FLPUnit *flp, int id) { if(id==1) { update_layout_bank(blockName,xflp,flp); }else if ((id % 2) == 0) { // even number ThermTrace::FLPUnit flp1 = *flp; ThermTrace::FLPUnit flp2 = *flp; if (flp->delta_x > flp->delta_y) { // x-axe is bigger flp1.delta_x = flp->delta_x/2; flp2.delta_x = flp->delta_x/2; flp2.x = flp->x+flp->delta_x/2; }else{ // y-axe is bigger flp1.delta_y = flp->delta_x/2; flp2.delta_y = flp->delta_y/2; flp2.y = flp->y + flp->delta_y/2; } update_sublayout(blockName, xflp, &flp1, id/2); update_sublayout(blockName, xflp, &flp2, id/2); }else{ MSG("Invalid number of banks to partition. Please use power of two"); exit(-1); I(0); // In } } void update_layout(const char *blockName, xcacti_flp *xflp) { const ThermTrace::FLPUnit *flp = sescTherm->findBlock(blockName); I(flp); if (flp == 0) { MSG("Error: blockName[%s] not found in blockDescr",blockName); exit(-1); return; // no match found } update_sublayout(blockName, xflp, flp, xflp->NSubbanks*xflp->assoc); } #endif void iterate() { std::vector<char *> sections; std::vector<char *>::iterator it; SescConf->getAllSections(sections) ; char line[100] ; for(it = sections.begin();it != sections.end(); it++) { const char *block = *it; if (!SescConf->checkCharPtr(block,"deviceType")) continue; const char *name = SescConf->getCharPtr(block,"deviceType") ; if(strcasecmp(name,"vbus")==0){ SescConf->updateRecord(block,"busEnergy",0.0) ; // FIXME: compute BUS energy }else if (strcasecmp(name,"niceCache") == 0) { // No energy for ideal caches (DRAM bank) SescConf->updateRecord(block, "RdHitEnergy" ,0.0); SescConf->updateRecord(block, "RdMissEnergy" ,0.0); SescConf->updateRecord(block, "WrHitEnergy" ,0.0); SescConf->updateRecord(block, "WrMissEnergy" ,0.0); }else if(strstr(name,"cache") || strstr(name,"tlb") || strstr(name,"mem") || strstr(name,"dir") || !strcmp(name,"revLVIDTable") ) { xcacti_flp xflp; double eng = getEnergy(block, &xflp); #ifdef SESC_SESCTHERM2 if (SescConf->checkCharPtr(block,"blockName")) { const char *blockName = SescConf->getCharPtr(block,"blockName"); MSG("%s (block=%s) has blockName %s",name, block, blockName); update_layout(blockName, &xflp); } #else // write it SescConf->updateRecord(block, "RdHitEnergy" ,eng); SescConf->updateRecord(block, "RdMissEnergy" ,eng * 2); // Rd miss + lineFill SescConf->updateRecord(block, "WrHitEnergy" ,eng); SescConf->updateRecord(block, "WrMissEnergy" ,eng * 2); // Wr miss + lineFill #endif } } } char * strfy(int v){ char *t = new char[10] ; sprintf(t,"%d",v); return t ; } char *strfy(double v){ char *t = new char[10] ; sprintf(t,"%lf",v); return t ; } double getEnergy(int size ,int bsize ,int assoc ,int rdPorts ,int wrPorts ,int subBanks ,int useTag ,int bits ,xcacti_flp *xflp ) { int nsets = size/(bsize*assoc); int fully_assoc, associativity; int rwPorts = 0; double ret; if (nsets == 0) { printf("Invalid cache parameters size[%d], bsize[%d], assoc[%d]\n", size, bsize, assoc); exit(0); } if (subBanks == 0) { printf("Invalid cache subbanks parameters\n"); exit(0); } if ((size/subBanks)<64) { printf("size %d: subBanks %d: assoc %d : nset %d\n",size,subBanks,assoc,nsets); size =64*subBanks; } if (rdPorts>1) { wrPorts = rdPorts-2; rdPorts = 2; } if ((rdPorts+wrPorts+rwPorts) < 1) { rdPorts = 0; wrPorts = 0; rwPorts = 1; } if (bsize*8 < bits) bsize = bits/8; BITOUT = bits; if (size == bsize * assoc) { fully_assoc = 1; }else{ fully_assoc = 0; } size = roundUpPower2(size); if (fully_assoc) { associativity = size/bsize; }else{ associativity = assoc; } if (associativity >= 32) associativity = size/bsize; nsets = size/(bsize*associativity); total_result_type result2; printf("\n\n\n########################################################"); printf("\nInput to Cacti_Interface..."); printf("\n size = %d, bsize = %d, assoc = %d, rports = %d, wports = %d", size, bsize, associativity, rdPorts, wrPorts); printf("\n subBanks = %d, tech = %f, bits = %d", subBanks, tech, bits); result2 = cacti_interface(size, bsize, associativity, rwPorts, rdPorts, wrPorts, 0, subBanks, tech, bits, 0, 0, // custom tag 0, useTag); #ifdef DEBUG //output_data(&result,&arearesult,&arearesult_subbanked,&parameters); output_data(&result2.result,&result2.area,&result2.params); #endif //xcacti_power_flp(&result,&arearesult,&arearesult_subbanked,&parameters, xflp); xcacti_power_flp(&result2.result, &result2.area, &result2.arearesult_subbanked, &result2.params, xflp); //return wattch2cactiFactor * 1e9*(result.total_power_without_routing/subBanks + result.total_routing_power); return wattch2cactiFactor * 1e9*(result2.result.total_power_without_routing.readOp.dynamic / subBanks + result2.result.total_routing_power.readOp.dynamic); } double getEnergy(const char *section, xcacti_flp *xflp) { // set the input int cache_size = SescConf->getInt(section,"size") ; int block_size = SescConf->getInt(section,"bsize") ; int assoc = SescConf->getInt(section,"assoc") ; int write_ports = 0 ; int read_ports = SescConf->getInt(section,"numPorts"); int readwrite_ports = 1; int subbanks = 1; int bits = 32; if(SescConf->checkInt(section,"subBanks")) subbanks = SescConf->getInt(section,"subBanks"); if(SescConf->checkInt(section,"bits")) bits = SescConf->getInt(section,"bits"); printf("Module [%s]...\n", section); return getEnergy(cache_size ,block_size ,assoc ,read_ports ,readwrite_ports ,subbanks ,1 ,bits ,xflp); } void processBranch(const char *proc) { // FIXME: add thermal block to branch predictor // get the branch const char* bpred = SescConf->getCharPtr(proc,"bpred") ; // get the type const char* type = SescConf->getCharPtr(bpred,"type") ; xcacti_flp xflp; double bpred_power=0; // switch based on the type if(!strcmp(type,"Taken") || !strcmp(type,"Oracle") || !strcmp(type,"NotTaken") || !strcmp(type,"Static")) { // No tables bpred_power= 0; }else if(!strcmp(type,"2bit")) { int size = SescConf->getInt(bpred,"size") ; // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power = getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp); bpred_power= 0; }else if(!strcmp(type,"2level")) { int size = SescConf->getInt(bpred,"l2size") ; // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power = getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp); }else if(!strcmp(type,"ogehl")) { int mTables = SescConf->getInt(bpred,"mtables") ; int size = SescConf->getInt(bpred,"tsize") ; I(0); // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power = getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp) * mTables; }else if(!strcmp(type,"hybrid")) { int size = SescConf->getInt(bpred,"localSize") ; // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power = getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: update layout #endif size = SescConf->getInt(bpred,"metaSize"); // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power += getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp); }else{ MSG("Unknown energy for branch predictor type [%s]", type); exit(-1); } #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure const char *bpredBlockName = SescConf->getCharPtr(bpred, "blockName"); update_layout(bpredBlockName, &xflp); #else SescConf->updateRecord(proc,"bpredEnergy",bpred_power) ; #endif int btbSize = SescConf->getInt(bpred,"btbSize"); int btbAssoc = SescConf->getInt(bpred,"btbAssoc"); double btb_power = 0; if (btbSize) { btb_power = getEnergy(btbSize*8, 8, btbAssoc, 1, 0, 1, 1, 64, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure update_layout(bpredBlockName, &xflp); #else SescConf->updateRecord(proc,"btbEnergy",btb_power) ; #endif }else{ SescConf->updateRecord(proc,"btbEnergy",0.0) ; } double ras_power =0; int ras_size = SescConf->getInt(bpred,"rasSize"); if (ras_size) { ras_power = getEnergy(ras_size*8, 8, 1, 1, 0, 1, 0, 64, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure (all bpred may share a block) update_layout(bpredBlockName, &xflp); #else SescConf->updateRecord(proc,"rasEnergy",ras_power) ; #endif }else{ SescConf->updateRecord(proc,"rasEnergy",0.0) ; } } void processorCore() { const char *proc = SescConf->getCharPtr("","cpucore",0) ; fprintf(stderr,"proc = [%s]\n",proc); xcacti_flp xflp; //---------------------------------------------- // Branch Predictor processBranch(proc); //---------------------------------------------- // Register File int issueWidth= SescConf->getInt(proc,"issueWidth"); int size = SescConf->getInt(proc,"intRegs"); int banks = 1; int rdPorts = 2*issueWidth; int wrPorts = issueWidth; int bits = 32; int bytes = 8; if(SescConf->checkInt(proc,"bits")) { bits = SescConf->getInt(proc,"bits"); bytes = bits/8; if (bits*8 != bytes) { fprintf(stderr,"Not valid number of bits for the processor core [%d]\n",bits); exit(-2); } } if(SescConf->checkInt(proc,"intRegBanks")) banks = SescConf->getInt(proc,"intRegBanks"); if(SescConf->checkInt(proc,"intRegRdPorts")) rdPorts = SescConf->getInt(proc,"intRegRdPorts"); if(SescConf->checkInt(proc,"intRegWrPorts")) wrPorts = SescConf->getInt(proc,"intRegWrPorts"); double regEnergy = getEnergy(size*bytes, bytes, 1, rdPorts, wrPorts, banks, 0, bits, &xflp); printf("\nRegister [%d bytes] banks[%d] ports[%d] Energy[%g]\n" ,size*bytes, banks, rdPorts+wrPorts, regEnergy); #ifdef SESC_SESCTHERM2 const char *blockName = SescConf->getCharPtr(proc,"IntRegBlockName"); I(blockName); update_layout(blockName, &xflp); blockName = SescConf->getCharPtr(proc,"fpRegBlockName"); I(blockName); update_layout(blockName , &xflp); // FIXME: different energy for FP register #else SescConf->updateRecord(proc,"wrRegEnergy",regEnergy); SescConf->updateRecord(proc,"rdRegEnergy",regEnergy); #endif //---------------------------------------------- // Load/Store Queue size = SescConf->getInt(proc,"maxLoads"); banks = 1; rdPorts = res_memport; wrPorts = res_memport; if(SescConf->checkInt(proc,"lsqBanks")) banks = SescConf->getInt(proc,"lsqBanks"); regEnergy = getEnergy(size*2*bytes,2*bytes,size,rdPorts,wrPorts,banks,1, 2*bits, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure blockName = SescConf->getCharPtr(proc,"LSQBlockName"); I(blockName); update_layout(lsqBlockName, &xflp); #else SescConf->updateRecord(proc,"ldqRdWrEnergy",regEnergy); #endif printf("\nLoad Queue [%d bytes] banks[%d] ports[%d] Energy[%g]\n" ,size*2*bytes, banks, 2*res_memport, regEnergy); size = SescConf->getInt(proc,"maxStores"); regEnergy = getEnergy(size*4*bytes,4*bytes,size,rdPorts,wrPorts,banks,1, 2*bits, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure blockName = SescConf->getCharPtr(proc,"LSQBlockName"); I(blockName); update_layout(lsqBlockName, &xflp); #else SescConf->updateRecord(proc,"stqRdWrEnergy",regEnergy); #endif printf("\nStore Queue [%d bytes] banks[%d] ports[%d] Energy[%g]\n" ,size*4*bytes, banks, 2*res_memport, regEnergy); #ifdef SESC_INORDER size = size/4; regEnergy = getEnergy(size*4*bytes,4*bytes,size,rdPorts,wrPorts,banks,1, 2*bits, &xflp); printf("\nStore Inorder Queue [%d bytes] banks[%d] ports[%d] Energy[%g]\n" ,size*4*bytes, banks, 2*res_memport, regEnergy); SescConf->updateRecord(proc,"stqRdWrEnergyInOrder",regEnergy); #ifdef SESC_SESCTHERM I(0); exit(-1); // Not supported #endif #endif //---------------------------------------------- // Reorder Buffer size = SescConf->getInt(proc,"robSize"); banks = size/64; if (banks == 0) { banks = 1; }else{ banks = roundUpPower2(banks); } // Retirement should hit another bank rdPorts = 1; // continuous possitions wrPorts = 1; regEnergy = getEnergy(size*2,2*issueWidth,1,rdPorts,wrPorts,banks,0,16*issueWidth, &xflp); #ifdef SESC_SESCTHERM2 const char *blockName = SescConf->getCharPtr(proc,"robBlockName"); I(blockName); update_layout(blockName, &xflp); // FIXME: partition energies per structure #else SescConf->updateRecord(proc,"robEnergy",regEnergy); #endif printf("\nROB [%d bytes] banks[%d] ports[%d] Energy[%g]\n",size*2, banks, 2*rdPorts, regEnergy); //---------------------------------------------- // Rename Table { double bitsPerEntry = log(SescConf->getInt(proc,"intRegs"))/log(2); size = roundUpPower2(static_cast<unsigned int>(32*bitsPerEntry/8)); banks = 1; rdPorts = 2*issueWidth; wrPorts = issueWidth; regEnergy = getEnergy(size,1,1,rdPorts,wrPorts,banks,0,1, &xflp); #ifdef SESC_SESCTHERM2 update_layout("IntRAT", &xflp); //FIXME: create a IntRATblockName // FIXME: partition energies per structure #endif printf("\nrename [%d bytes] banks[%d] Energy[%g]\n",size, banks, regEnergy); regEnergy += getEnergy(size,1,1,rdPorts/2+1,wrPorts/2+1,banks,0,1, &xflp); #ifdef SESC_SESCTHERM2 update_layout("IntRAT", &xflp); // FIXME: partition energies per structure #else // unified FP+Int RAT energy counter SescConf->updateRecord(proc,"renameEnergy",regEnergy); #endif } //---------------------------------------------- // Window Energy & Window + DDIS { int min = SescConf->getRecordMin(proc,"cluster") ; int max = SescConf->getRecordMax(proc,"cluster") ; I(min==0); for(int i = min ; i <= max ; i++) { const char *cluster = SescConf->getCharPtr(proc,"cluster",i) ; // TRADITIONAL COLLAPSING ISSUE LOGIC // Recalculate windowRdWrEnergy using CACTI (keep select and wake) size = SescConf->getInt(cluster,"winSize"); banks = 1; rdPorts = SescConf->getInt(cluster,"wakeUpNumPorts"); wrPorts = issueWidth; int robSize = SescConf->getInt(proc,"robSize"); float entryBits = 4*(log(robSize)/log(2)); // src1, src2, dest, instID entryBits += 7; // opcode entryBits += 1; // ready bit int tableBits = static_cast<int>(entryBits * size); int tableBytes; if (tableBits < 8) { tableBits = 8; tableBytes = 1; }else{ tableBytes = tableBits/8; } int assoc= roundUpPower2(static_cast<unsigned int>(entryBits/8)); tableBytes = roundUpPower2(tableBytes); regEnergy = getEnergy(tableBytes,tableBytes/assoc,assoc,rdPorts,wrPorts,banks,1,static_cast<int>(entryBits), &xflp); printf("\nWindow [%d bytes] assoc[%d] banks[%d] ports[%d] Energy[%g]\n" ,tableBytes, assoc, banks, rdPorts+wrPorts, regEnergy); #ifdef SESC_SESCTHERM2 const char *blockName = SescConf->getCharPtr(cluster,"blockName"); I(blockName); update_layout(blockName, &xflp); #else // unified FP+Int RAT energy counter SescConf->updateRecord(cluster,"windowRdWrEnergy" ,regEnergy,0); #endif } } } void cacti_setup() { const char *technology = SescConf->getCharPtr("","technology"); fprintf(stderr,"technology = [%s]\n",technology); tech = SescConf->getInt(technology,"tech"); fprintf(stderr, "tech : %9.0fnm\n" , tech); tech /= 1000; #ifdef SESC_SESCTHERM sescTherm = new ThermTrace(0); // No input trace, just read conf #endif const char *proc = SescConf->getCharPtr("","cpucore",0); const char *l1Cache = SescConf->getCharPtr(proc,"dataSource"); const char *l1CacheSpace = strstr(l1Cache," "); char *l1Section = strdup(l1Cache); if (l1CacheSpace) l1Section[l1CacheSpace - l1Cache] = 0; res_memport = SescConf->getInt(l1Section,"numPorts"); xcacti_flp xflp; double l1Energy = getEnergy(l1Section, &xflp); double WattchL1Energy = SescConf->getDouble("","wattchDataCacheEnergy"); if (WattchL1Energy) { wattch2cactiFactor = WattchL1Energy/l1Energy; fprintf(stderr,"wattch2cacti Factor %g\n", wattch2cactiFactor); }else{ fprintf(stderr,"-----WARNING: No wattch correction factor\n"); } processorCore(); iterate(); }
dilawar/sesc
src_without_LF/libpower/cacti/cacti_setup.cpp
C++
gpl-2.0
23,999
/* * Copyright (c) 2018, 2019, 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 java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /* * @test * @summary It tests (almost) all keytool behaviors with NSS. * @library /test/lib /test/jdk/sun/security/pkcs11 * @modules java.base/sun.security.tools.keytool * java.base/sun.security.util * java.base/sun.security.x509 * @run main/othervm/timeout=600 NssTest */ public class NssTest { public static void main(String[] args) throws Exception { Path libPath = PKCS11Test.getNSSLibPath("softokn3"); if (libPath == null) { return; } System.out.println("Using NSS lib at " + libPath); copyFiles(); System.setProperty("nss", ""); System.setProperty("nss.lib", String.valueOf(libPath)); PKCS11Test.loadNSPR(libPath.getParent().toString()); KeyToolTest.main(args); } private static void copyFiles() throws IOException { Path srcPath = Paths.get(System.getProperty("test.src")); Files.copy(srcPath.resolve("p11-nss.txt"), Paths.get("p11-nss.txt")); Path dbPath = srcPath.getParent().getParent() .resolve("pkcs11").resolve("nss").resolve("db"); Files.copy(dbPath.resolve("cert8.db"), Paths.get("cert8.db")); Files.copy(dbPath.resolve("key3.db"), Paths.get("key3.db")); Files.copy(dbPath.resolve("secmod.db"), Paths.get("secmod.db")); } }
md-5/jdk10
test/jdk/sun/security/tools/keytool/NssTest.java
Java
gpl-2.0
2,505
/* * Copyright (c) 2019, 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. */ /* * @test * @bug 8231598 * @requires os.family == "windows" * @library /test/lib * @summary keytool does not export sun.security.mscapi */ import jdk.test.lib.SecurityTools; public class ProviderClassOption { public static void main(String[] args) throws Throwable { SecurityTools.keytool("-v -storetype Windows-ROOT -list" + " -providerClass sun.security.mscapi.SunMSCAPI") .shouldHaveExitValue(0); } }
md-5/jdk10
test/jdk/sun/security/mscapi/ProviderClassOption.java
Java
gpl-2.0
1,509
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2011-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.web.alarm.filter; import org.opennms.web.filter.NoSubstringFilter; public class NegativeEventParmLikeFilter extends NoSubstringFilter { public static final String TYPE = "noparmmatchany"; public NegativeEventParmLikeFilter(String value) { super(TYPE, "eventParms", "eventParms", value + "(string,text)"); } @Override public String getTextDescription() { String strippedType = getValue().replace("(string,text)", ""); String[] parms = strippedType.split("="); StringBuffer buffer = new StringBuffer(parms[0] + " is not \""); buffer.append(parms[parms.length - 1]); buffer.append("\""); return buffer.toString(); } @Override public String getDescription() { return TYPE + "=" + getValueString().replace("(string,text)", ""); } }
vishwaAbhinav/OpenNMS
opennms-webapp/src/main/java/org/opennms/web/alarm/filter/NegativeEventParmLikeFilter.java
Java
gpl-2.0
2,058
#ifndef NETWORK_RULES_HPP #define NETWORK_RULES_HPP #include <map> #include "ReactionRule.hpp" #include "generator.hpp" class NetworkRules { public: typedef ReactionRule reaction_rule_type; typedef SpeciesTypeID species_id_type; typedef abstract_limited_generator<reaction_rule_type> reaction_rule_generator; typedef reaction_rule_type::identifier_type identifier_type; public: virtual identifier_type add_reaction_rule(ReactionRule const&) = 0; virtual void remove_reaction_rule(ReactionRule const&) = 0; virtual reaction_rule_generator* query_reaction_rule(species_id_type const& r1) const = 0; virtual reaction_rule_generator* query_reaction_rule(species_id_type const& r1, species_id_type const& r2) const = 0; virtual ~NetworkRules() = 0; }; #endif /* NETWORK_RULES_HPP */
navoj/ecell4
ecell4/egfrd/legacy/NetworkRules.hpp
C++
gpl-2.0
821
""" color scheme source data """ schemes = {'classic': [(255, 237, 237), (255, 224, 224), (255, 209, 209), (255, 193, 193), (255, 176, 176), (255, 159, 159), (255, 142, 142), (255, 126, 126), (255, 110, 110), (255, 94, 94), (255, 81, 81), (255, 67, 67), (255, 56, 56), (255, 46, 46), (255, 37, 37), (255, 29, 29), (255, 23, 23), (255, 18, 18), (255, 14, 14), (255, 11, 11), (255, 8, 8), (255, 6, 6), (255, 5, 5), (255, 3, 3), (255, 2, 2), (255, 2, 2), (255, 1, 1), (255, 1, 1), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 1, 0), (255, 4, 0), (255, 6, 0), (255, 10, 0), (255, 14, 0), (255, 18, 0), (255, 22, 0), (255, 26, 0), (255, 31, 0), (255, 36, 0), (255, 41, 0), (255, 45, 0), (255, 51, 0), (255, 57, 0), (255, 62, 0), (255, 68, 0), (255, 74, 0), (255, 81, 0), (255, 86, 0), (255, 93, 0), (255, 99, 0), (255, 105, 0), (255, 111, 0), (255, 118, 0), (255, 124, 0), (255, 131, 0), (255, 137, 0), (255, 144, 0), (255, 150, 0), (255, 156, 0), (255, 163, 0), (255, 169, 0), (255, 175, 0), (255, 181, 0), (255, 187, 0), (255, 192, 0), (255, 198, 0), (255, 203, 0), (255, 208, 0), (255, 213, 0), (255, 218, 0), (255, 222, 0), (255, 227, 0), (255, 232, 0), (255, 235, 0), (255, 238, 0), (255, 242, 0), (255, 245, 0), (255, 247, 0), (255, 250, 0), (255, 251, 0), (253, 252, 0), (250, 252, 1), (248, 252, 2), (244, 252, 2), (241, 252, 3), (237, 252, 3), (233, 252, 3), (229, 252, 4), (225, 252, 4), (220, 252, 5), (216, 252, 5), (211, 252, 6), (206, 252, 7), (201, 252, 7), (197, 252, 8), (191, 251, 8), (185, 249, 9), (180, 247, 9), (174, 246, 10), (169, 244, 11), (164, 242, 11), (158, 240, 12), (151, 238, 13), (146, 236, 14), (140, 233, 14), (134, 231, 15), (128, 228, 16), (122, 226, 17), (116, 223, 18), (110, 221, 19), (105, 218, 20), (99, 216, 21), (93, 214, 22), (88, 211, 23), (82, 209, 24), (76, 207, 25), (71, 204, 26), (66, 202, 28), (60, 200, 30), (55, 198, 31), (50, 196, 33), (45, 194, 34), (40, 191, 35), (36, 190, 37), (31, 188, 39), (27, 187, 40), (23, 185, 43), (19, 184, 44), (15, 183, 46), (12, 182, 48), (9, 181, 51), (6, 181, 53), (3, 180, 55), (1, 180, 57), (0, 180, 60), (0, 180, 62), (0, 180, 65), (0, 181, 68), (0, 182, 70), (0, 182, 74), (0, 183, 77), (0, 184, 80), (0, 184, 84), (0, 186, 88), (0, 187, 92), (0, 188, 95), (0, 190, 99), (0, 191, 104), (0, 193, 108), (0, 194, 112), (0, 196, 116), (0, 198, 120), (0, 200, 125), (0, 201, 129), (0, 203, 134), (0, 205, 138), (0, 207, 143), (0, 209, 147), (0, 211, 151), (0, 213, 156), (0, 215, 160), (0, 216, 165), (0, 219, 171), (0, 222, 178), (0, 224, 184), (0, 227, 190), (0, 229, 197), (0, 231, 203), (0, 233, 209), (0, 234, 214), (0, 234, 220), (0, 234, 225), (0, 234, 230), (0, 234, 234), (0, 234, 238), (0, 234, 242), (0, 234, 246), (0, 234, 248), (0, 234, 251), (0, 234, 254), (0, 234, 255), (0, 232, 255), (0, 228, 255), (0, 224, 255), (0, 219, 255), (0, 214, 254), (0, 208, 252), (0, 202, 250), (0, 195, 247), (0, 188, 244), (0, 180, 240), (0, 173, 236), (0, 164, 232), (0, 156, 228), (0, 147, 222), (0, 139, 218), (0, 130, 213), (0, 122, 208), (0, 117, 205), (0, 112, 203), (0, 107, 199), (0, 99, 196), (0, 93, 193), (0, 86, 189), (0, 78, 184), (0, 71, 180), (0, 65, 175), (0, 58, 171), (0, 52, 167), (0, 46, 162), (0, 40, 157), (0, 35, 152), (0, 30, 147), (0, 26, 142), (0, 22, 136), (0, 18, 131), (0, 15, 126), (0, 12, 120), (0, 9, 115), (1, 8, 110), (1, 6, 106), (1, 5, 101), (2, 4, 97), (3, 4, 92), (4, 5, 89), (5, 5, 85), (6, 6, 82), (7, 7, 79), (8, 8, 77), (10, 10, 77), (12, 12, 77), (14, 14, 76), (16, 16, 74), (19, 19, 73), (21, 21, 72), (24, 24, 71), (26, 26, 69), (29, 29, 70), (32, 32, 69), (35, 35, 68), (37, 37, 67), (40, 40, 67), (42, 42, 65), (44, 44, 65), (46, 46, 64), (48, 48, 63), (49, 50, 62), (51, 51, 61), (53, 52, 61)], 'fire': [(255, 255, 255), (255, 255, 253), (255, 255, 250), (255, 255, 247), (255, 255, 244), (255, 255, 241), (255, 255, 238), (255, 255, 234), (255, 255, 231), (255, 255, 227), (255, 255, 223), (255, 255, 219), (255, 255, 214), (255, 255, 211), (255, 255, 206), (255, 255, 202), (255, 255, 197), (255, 255, 192), (255, 255, 187), (255, 255, 183), (255, 255, 178), (255, 255, 172), (255, 255, 167), (255, 255, 163), (255, 255, 157), (255, 255, 152), (255, 255, 147), (255, 255, 142), (255, 255, 136), (255, 255, 132), (255, 255, 126), (255, 255, 121), (255, 255, 116), (255, 255, 111), (255, 255, 106), (255, 255, 102), (255, 255, 97), (255, 255, 91), (255, 255, 87), (255, 255, 82), (255, 255, 78), (255, 255, 74), (255, 255, 70), (255, 255, 65), (255, 255, 61), (255, 255, 57), (255, 255, 53), (255, 255, 50), (255, 255, 46), (255, 255, 43), (255, 255, 39), (255, 255, 38), (255, 255, 34), (255, 255, 31), (255, 255, 29), (255, 255, 26), (255, 255, 25), (255, 254, 23), (255, 251, 22), (255, 250, 22), (255, 247, 23), (255, 245, 23), (255, 242, 24), (255, 239, 24), (255, 236, 25), (255, 232, 25), (255, 229, 26), (255, 226, 26), (255, 222, 27), (255, 218, 27), (255, 215, 28), (255, 210, 28), (255, 207, 29), (255, 203, 29), (255, 199, 30), (255, 194, 30), (255, 190, 31), (255, 186, 31), (255, 182, 32), (255, 176, 32), (255, 172, 33), (255, 168, 34), (255, 163, 34), (255, 159, 35), (255, 154, 35), (255, 150, 36), (255, 145, 36), (255, 141, 37), (255, 136, 37), (255, 132, 38), (255, 128, 39), (255, 124, 39), (255, 119, 40), (255, 115, 40), (255, 111, 41), (255, 107, 41), (255, 103, 42), (255, 99, 42), (255, 95, 43), (255, 92, 44), (255, 89, 44), (255, 85, 45), (255, 81, 45), (255, 79, 46), (255, 76, 47), (255, 72, 47), (255, 70, 48), (255, 67, 48), (255, 65, 49), (255, 63, 50), (255, 60, 50), (255, 59, 51), (255, 57, 51), (255, 55, 52), (255, 55, 53), (255, 53, 53), (253, 54, 54), (253, 54, 54), (251, 55, 55), (250, 56, 56), (248, 56, 56), (247, 57, 57), (246, 57, 57), (244, 58, 58), (242, 59, 59), (240, 59, 59), (239, 60, 60), (238, 61, 61), (235, 61, 61), (234, 62, 62), (232, 62, 62), (229, 63, 63), (228, 64, 64), (226, 64, 64), (224, 65, 65), (222, 66, 66), (219, 66, 66), (218, 67, 67), (216, 67, 67), (213, 68, 68), (211, 69, 69), (209, 69, 69), (207, 70, 70), (205, 71, 71), (203, 71, 71), (200, 72, 72), (199, 73, 73), (196, 73, 73), (194, 74, 74), (192, 74, 74), (190, 75, 75), (188, 76, 76), (186, 76, 76), (183, 77, 77), (181, 78, 78), (179, 78, 78), (177, 79, 79), (175, 80, 80), (173, 80, 80), (170, 81, 81), (169, 82, 82), (166, 82, 82), (165, 83, 83), (162, 83, 83), (160, 84, 84), (158, 85, 85), (156, 85, 85), (154, 86, 86), (153, 87, 87), (150, 87, 87), (149, 88, 88), (147, 89, 89), (146, 90, 90), (144, 91, 91), (142, 92, 92), (142, 94, 94), (141, 95, 95), (140, 96, 96), (139, 98, 98), (138, 99, 99), (136, 100, 100), (135, 101, 101), (135, 103, 103), (134, 104, 104), (133, 105, 105), (133, 107, 107), (132, 108, 108), (131, 109, 109), (132, 111, 111), (131, 112, 112), (130, 113, 113), (130, 114, 114), (130, 116, 116), (130, 117, 117), (130, 118, 118), (129, 119, 119), (130, 121, 121), (130, 122, 122), (130, 123, 123), (130, 124, 124), (131, 126, 126), (131, 127, 127), (130, 128, 128), (131, 129, 129), (132, 131, 131), (132, 132, 132), (133, 133, 133), (134, 134, 134), (135, 135, 135), (136, 136, 136), (138, 138, 138), (139, 139, 139), (140, 140, 140), (141, 141, 141), (142, 142, 142), (143, 143, 143), (144, 144, 144), (145, 145, 145), (147, 147, 147), (148, 148, 148), (149, 149, 149), (150, 150, 150), (151, 151, 151), (152, 152, 152), (153, 153, 153), (154, 154, 154), (155, 155, 155), (156, 156, 156), (157, 157, 157), (158, 158, 158), (159, 159, 159), (160, 160, 160), (160, 160, 160), (161, 161, 161), (162, 162, 162), (163, 163, 163), (164, 164, 164), (165, 165, 165), (166, 166, 166), (167, 167, 167), (167, 167, 167), (168, 168, 168), (169, 169, 169), (170, 170, 170), (170, 170, 170), (171, 171, 171), (172, 172, 172), (173, 173, 173), (173, 173, 173), (174, 174, 174), (175, 175, 175), (175, 175, 175), (176, 176, 176), (176, 176, 176), (177, 177, 177), (177, 177, 177)], 'omg': [(255, 255, 255), (255, 254, 254), (255, 253, 253), (255, 251, 251), (255, 250, 250), (255, 249, 249), (255, 247, 247), (255, 246, 246), (255, 244, 244), (255, 242, 242), (255, 241, 241), (255, 239, 239), (255, 237, 237), (255, 235, 235), (255, 233, 233), (255, 231, 231), (255, 229, 229), (255, 227, 227), (255, 226, 226), (255, 224, 224), (255, 222, 222), (255, 220, 220), (255, 217, 217), (255, 215, 215), (255, 213, 213), (255, 210, 210), (255, 208, 208), (255, 206, 206), (255, 204, 204), (255, 202, 202), (255, 199, 199), (255, 197, 197), (255, 194, 194), (255, 192, 192), (255, 189, 189), (255, 188, 188), (255, 185, 185), (255, 183, 183), (255, 180, 180), (255, 178, 178), (255, 176, 176), (255, 173, 173), (255, 171, 171), (255, 169, 169), (255, 167, 167), (255, 164, 164), (255, 162, 162), (255, 160, 160), (255, 158, 158), (255, 155, 155), (255, 153, 153), (255, 151, 151), (255, 149, 149), (255, 147, 147), (255, 145, 145), (255, 143, 143), (255, 141, 141), (255, 139, 139), (255, 137, 137), (255, 136, 136), (255, 134, 134), (255, 132, 132), (255, 131, 131), (255, 129, 129), (255, 128, 128), (255, 127, 127), (255, 127, 127), (255, 126, 126), (255, 125, 125), (255, 125, 125), (255, 124, 124), (255, 123, 122), (255, 123, 122), (255, 122, 121), (255, 122, 121), (255, 121, 120), (255, 120, 119), (255, 119, 118), (255, 119, 118), (255, 118, 116), (255, 117, 116), (255, 117, 115), (255, 115, 114), (255, 115, 114), (255, 114, 113), (255, 114, 112), (255, 113, 111), (255, 113, 111), (255, 112, 110), (255, 111, 108), (255, 111, 108), (255, 110, 107), (255, 110, 107), (255, 109, 105), (255, 109, 105), (255, 108, 104), (255, 107, 104), (255, 107, 102), (255, 106, 102), (255, 106, 101), (255, 105, 101), (255, 104, 99), (255, 104, 99), (255, 103, 98), (255, 103, 98), (255, 102, 97), (255, 102, 96), (255, 101, 96), (255, 101, 96), (255, 100, 94), (255, 100, 94), (255, 99, 93), (255, 99, 92), (255, 98, 91), (255, 98, 91), (255, 97, 90), (255, 97, 89), (255, 96, 89), (255, 96, 89), (255, 95, 88), (255, 95, 88), (255, 94, 86), (255, 93, 86), (255, 93, 85), (255, 93, 85), (255, 92, 85), (255, 92, 84), (255, 91, 83), (255, 91, 83), (255, 90, 82), (255, 90, 82), (255, 89, 81), (255, 89, 82), (255, 89, 80), (255, 89, 80), (255, 89, 79), (255, 89, 79), (255, 88, 79), (255, 88, 79), (255, 87, 78), (255, 87, 78), (255, 87, 78), (255, 87, 77), (255, 87, 77), (255, 86, 77), (255, 86, 77), (255, 85, 76), (255, 85, 76), (255, 85, 75), (255, 85, 76), (255, 85, 75), (255, 85, 76), (255, 84, 75), (255, 84, 75), (255, 84, 75), (255, 84, 75), (255, 85, 75), (255, 84, 75), (255, 84, 75), (255, 83, 74), (255, 83, 75), (255, 83, 75), (255, 84, 75), (255, 83, 75), (255, 83, 75), (255, 83, 75), (255, 83, 75), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 77), (255, 84, 78), (255, 83, 78), (255, 84, 79), (255, 84, 78), (255, 84, 79), (255, 83, 79), (255, 84, 80), (255, 83, 80), (255, 84, 81), (255, 85, 82), (255, 85, 82), (255, 85, 83), (255, 85, 83), (255, 85, 84), (255, 85, 84), (255, 86, 85), (255, 86, 85), (255, 87, 87), (254, 89, 89), (254, 91, 92), (253, 92, 93), (252, 94, 96), (251, 96, 98), (251, 97, 100), (249, 99, 103), (249, 100, 105), (248, 102, 108), (247, 104, 111), (246, 105, 113), (245, 107, 116), (244, 109, 119), (243, 110, 122), (242, 112, 125), (241, 113, 127), (240, 115, 130), (239, 117, 134), (238, 118, 136), (237, 120, 140), (236, 121, 142), (235, 123, 145), (234, 124, 148), (233, 126, 151), (232, 127, 154), (232, 129, 157), (230, 130, 159), (230, 132, 162), (229, 133, 165), (228, 135, 168), (227, 136, 170), (227, 138, 173), (226, 139, 176), (225, 140, 178), (224, 142, 181), (223, 143, 183), (223, 144, 185), (223, 146, 188), (222, 147, 190), (221, 148, 192), (221, 150, 195), (220, 151, 197), (219, 152, 199), (219, 153, 201), (219, 154, 202), (219, 156, 205), (218, 157, 207), (217, 158, 208), (217, 159, 210), (217, 160, 211), (217, 161, 213), (216, 162, 214), (216, 163, 216), (216, 164, 217), (215, 165, 218), (216, 166, 219), (215, 166, 220), (215, 167, 222), (215, 168, 223), (215, 169, 223), (215, 170, 224), (215, 170, 225)], 'pbj': [(41, 10, 89), (41, 10, 89), (42, 10, 89), (42, 10, 89), (42, 10, 88), (43, 10, 88), (43, 9, 88), (43, 9, 88), (44, 9, 88), (44, 9, 88), (45, 10, 89), (46, 10, 88), (46, 9, 88), (47, 9, 88), (47, 9, 88), (47, 9, 88), (48, 8, 88), (48, 8, 87), (49, 8, 87), (49, 8, 87), (49, 7, 87), (50, 7, 87), (50, 7, 87), (51, 7, 86), (51, 6, 86), (53, 7, 86), (53, 7, 86), (54, 7, 86), (54, 6, 85), (55, 6, 85), (55, 6, 85), (56, 5, 85), (56, 5, 85), (57, 5, 84), (57, 5, 84), (58, 4, 84), (59, 4, 84), (59, 5, 84), (60, 4, 84), (60, 4, 84), (61, 4, 84), (61, 4, 83), (62, 3, 83), (63, 3, 83), (63, 3, 83), (64, 3, 82), (64, 3, 82), (65, 3, 82), (66, 3, 82), (67, 4, 82), (68, 4, 82), (69, 4, 82), (69, 4, 81), (70, 4, 81), (71, 4, 81), (71, 4, 80), (72, 4, 80), (73, 4, 80), (73, 4, 79), (75, 5, 80), (76, 5, 80), (77, 5, 79), (77, 5, 79), (78, 5, 79), (79, 5, 78), (80, 5, 78), (80, 5, 78), (80, 5, 77), (81, 5, 77), (83, 6, 76), (83, 6, 76), (84, 6, 76), (85, 6, 75), (86, 6, 75), (87, 6, 74), (88, 6, 74), (88, 6, 73), (89, 6, 73), (91, 7, 73), (92, 7, 73), (93, 7, 72), (94, 7, 72), (94, 7, 71), (95, 7, 71), (96, 7, 70), (96, 7, 70), (97, 7, 69), (99, 9, 70), (100, 9, 69), (101, 10, 69), (102, 10, 68), (103, 11, 67), (104, 11, 67), (105, 12, 66), (106, 13, 66), (107, 14, 66), (108, 15, 65), (109, 16, 64), (110, 16, 64), (111, 17, 63), (112, 18, 62), (113, 18, 61), (114, 19, 61), (115, 20, 60), (118, 22, 60), (119, 22, 59), (120, 22, 58), (120, 23, 58), (121, 24, 57), (122, 25, 56), (124, 26, 55), (125, 27, 54), (127, 29, 54), (128, 30, 54), (130, 31, 53), (131, 32, 52), (132, 33, 51), (133, 34, 50), (134, 35, 49), (135, 36, 48), (137, 38, 48), (138, 39, 47), (140, 40, 46), (141, 41, 46), (142, 42, 45), (143, 42, 44), (144, 43, 43), (145, 44, 42), (146, 45, 42), (149, 47, 41), (150, 48, 41), (151, 49, 40), (152, 50, 39), (153, 51, 38), (154, 52, 38), (155, 53, 37), (157, 55, 36), (159, 57, 36), (160, 57, 35), (160, 58, 34), (162, 59, 33), (163, 60, 33), (164, 61, 32), (165, 62, 31), (167, 63, 30), (168, 65, 30), (169, 66, 29), (170, 67, 29), (172, 68, 28), (173, 69, 27), (174, 70, 26), (175, 71, 26), (176, 71, 25), (178, 73, 25), (179, 74, 24), (180, 75, 24), (181, 76, 23), (182, 77, 23), (183, 78, 23), (184, 79, 22), (186, 80, 22), (187, 81, 21), (188, 82, 21), (189, 83, 21), (190, 83, 20), (191, 84, 20), (192, 85, 19), (192, 86, 19), (193, 87, 18), (194, 87, 18), (196, 89, 18), (196, 90, 18), (197, 90, 18), (198, 90, 18), (199, 91, 18), (200, 92, 18), (201, 93, 18), (202, 93, 18), (203, 94, 18), (204, 96, 19), (204, 96, 19), (205, 97, 19), (206, 98, 19), (207, 99, 19), (208, 99, 19), (209, 100, 19), (210, 100, 19), (211, 100, 19), (212, 102, 20), (213, 103, 20), (214, 103, 20), (214, 104, 20), (215, 105, 20), (215, 105, 20), (216, 106, 20), (217, 107, 20), (218, 107, 20), (219, 108, 20), (220, 109, 21), (221, 109, 21), (222, 110, 21), (222, 111, 21), (223, 111, 21), (224, 112, 21), (225, 113, 21), (226, 113, 21), (227, 114, 21), (227, 114, 21), (228, 115, 22), (229, 116, 22), (229, 116, 22), (230, 117, 22), (231, 117, 22), (231, 118, 22), (232, 119, 22), (233, 119, 22), (234, 120, 22), (234, 120, 22), (235, 121, 22), (236, 121, 22), (237, 122, 23), (237, 122, 23), (238, 123, 23), (239, 124, 23), (239, 124, 23), (240, 125, 23), (240, 125, 23), (241, 126, 23), (241, 126, 23), (242, 127, 23), (243, 127, 23), (243, 128, 23), (244, 128, 24), (244, 128, 24), (245, 129, 24), (246, 129, 24), (246, 130, 24), (247, 130, 24), (247, 131, 24), (248, 131, 24), (249, 131, 24), (249, 132, 24), (250, 132, 24), (250, 133, 24), (250, 133, 24), (250, 133, 24), (251, 134, 24), (251, 134, 25), (252, 135, 25), (252, 135, 25), (253, 135, 25), (253, 136, 25), (253, 136, 25), (254, 136, 25), (254, 136, 25), (255, 137, 25)], 'pgaitch': [(255, 254, 165), (255, 254, 164), (255, 253, 163), (255, 253, 162), (255, 253, 161), (255, 252, 160), (255, 252, 159), (255, 252, 157), (255, 251, 156), (255, 251, 155), (255, 251, 153), (255, 250, 152), (255, 250, 150), (255, 250, 149), (255, 249, 148), (255, 249, 146), (255, 249, 145), (255, 248, 143), (255, 248, 141), (255, 248, 139), (255, 247, 138), (255, 247, 136), (255, 246, 134), (255, 246, 132), (255, 246, 130), (255, 245, 129), (255, 245, 127), (255, 245, 125), (255, 244, 123), (255, 244, 121), (255, 243, 119), (255, 243, 117), (255, 242, 114), (255, 242, 112), (255, 241, 111), (255, 241, 109), (255, 240, 107), (255, 240, 105), (255, 239, 102), (255, 239, 100), (255, 238, 99), (255, 238, 97), (255, 237, 95), (255, 237, 92), (255, 236, 90), (255, 237, 89), (255, 236, 87), (255, 235, 84), (255, 235, 82), (255, 234, 80), (255, 233, 79), (255, 233, 77), (255, 232, 74), (255, 231, 72), (255, 230, 70), (255, 230, 69), (255, 229, 67), (255, 228, 65), (255, 227, 63), (255, 226, 61), (255, 225, 60), (255, 225, 58), (255, 224, 56), (255, 223, 54), (255, 222, 52), (255, 222, 51), (255, 221, 49), (255, 220, 47), (255, 219, 46), (255, 218, 44), (255, 216, 43), (255, 215, 42), (255, 214, 41), (255, 213, 39), (255, 212, 39), (255, 211, 37), (255, 209, 36), (255, 208, 34), (255, 208, 33), (255, 206, 33), (255, 205, 32), (255, 204, 30), (255, 202, 29), (255, 201, 29), (255, 199, 28), (254, 199, 28), (254, 199, 27), (253, 198, 27), (252, 197, 27), (251, 196, 27), (250, 195, 26), (249, 195, 26), (248, 194, 26), (248, 193, 26), (247, 192, 26), (246, 192, 25), (245, 191, 26), (244, 190, 26), (243, 189, 25), (241, 188, 25), (240, 187, 25), (239, 187, 25), (238, 186, 25), (236, 185, 25), (236, 184, 26), (235, 183, 26), (233, 182, 25), (232, 181, 25), (230, 181, 26), (229, 180, 26), (228, 179, 25), (227, 178, 25), (226, 177, 26), (224, 176, 26), (222, 176, 25), (221, 175, 25), (220, 173, 26), (219, 172, 26), (217, 171, 25), (215, 170, 25), (214, 170, 26), (212, 169, 26), (211, 167, 25), (209, 166, 25), (208, 166, 26), (206, 165, 26), (204, 163, 26), (203, 162, 26), (202, 161, 25), (200, 161, 26), (198, 159, 26), (197, 158, 26), (195, 157, 26), (193, 157, 27), (192, 155, 27), (190, 154, 27), (189, 153, 27), (187, 152, 28), (186, 151, 28), (184, 150, 28), (182, 149, 28), (181, 148, 29), (179, 147, 29), (177, 146, 29), (175, 144, 29), (174, 144, 30), (172, 142, 30), (170, 141, 30), (169, 140, 30), (167, 139, 31), (165, 138, 31), (164, 137, 31), (162, 136, 31), (161, 135, 32), (159, 134, 32), (157, 133, 32), (154, 132, 32), (153, 131, 33), (151, 130, 33), (150, 129, 33), (148, 127, 33), (147, 127, 34), (145, 126, 34), (143, 124, 34), (141, 123, 34), (140, 122, 35), (139, 121, 35), (137, 120, 35), (135, 119, 35), (134, 118, 36), (132, 117, 36), (130, 116, 36), (129, 115, 36), (127, 113, 36), (126, 113, 37), (124, 112, 37), (122, 111, 37), (121, 110, 37), (120, 109, 38), (118, 108, 38), (116, 107, 38), (115, 105, 38), (113, 104, 38), (112, 104, 39), (110, 103, 39), (108, 102, 39), (107, 101, 39), (106, 100, 40), (104, 99, 40), (102, 98, 40), (101, 96, 40), (99, 96, 40), (99, 96, 41), (97, 94, 41), (96, 93, 41), (94, 92, 41), (92, 91, 41), (92, 90, 42), (90, 90, 42), (89, 89, 42), (87, 87, 42), (86, 86, 42), (85, 86, 43), (84, 85, 43), (83, 84, 43), (81, 83, 43), (80, 82, 43), (80, 82, 44), (78, 80, 44), (77, 80, 44), (75, 79, 44), (75, 78, 44), (74, 78, 45), (73, 76, 45), (71, 75, 45), (71, 75, 45), (70, 74, 45), (69, 74, 46), (68, 73, 46), (67, 72, 46), (66, 71, 46), (65, 71, 46), (64, 69, 46), (64, 69, 47), (63, 68, 47), (62, 67, 47), (61, 67, 47), (60, 66, 47), (59, 65, 47), (59, 65, 48), (59, 64, 48), (58, 63, 48), (57, 63, 48), (56, 62, 48), (56, 62, 48), (55, 61, 48), (55, 61, 49), (55, 60, 49), (55, 60, 49), (54, 59, 49), (53, 58, 49), (53, 57, 49), (52, 57, 49), (52, 57, 50), (52, 56, 50), (52, 56, 50), (52, 56, 50), (52, 55, 50), (51, 54, 50), (51, 53, 50), (51, 53, 50), (51, 52, 50), (51, 53, 51), (51, 53, 51), (51, 52, 51), (51, 52, 51)]} def valid_schemes(): return schemes.keys()
ashmastaflash/IDCOAS
integration/heatmaps/heatmap/colorschemes.py
Python
gpl-2.0
33,688
<?php /** * File containing the ezpOauthBadRequestException class. * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version 2014.11.1 * @package kernel */ /** * This is the base exception for triggering BAD REQUEST response. * * @package oauth */ abstract class ezpOauthBadRequestException extends ezpOauthException { public function __construct( $message ) { parent::__construct( $message ); } } ?>
CG77/ezpublish-legacy
kernel/private/rest/classes/exceptions/bad_request.php
PHP
gpl-2.0
558
package fr.xephi.authme.data.limbo.persistence; import org.junit.Test; import java.util.HashSet; import java.util.Set; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.EIGHT; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.FOUR; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.ONE; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.SIXTEEN; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.SIXTY_FOUR; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.THIRTY_TWO; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.TWO_FIFTY; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; /** * Test for {@link SegmentNameBuilder}. */ public class SegmentNameBuilderTest { /** * Checks that using a given segment size really produces as many segments as defined. * E.g. if we partition with {@link SegmentSize#EIGHT} we expect eight different buckets. */ @Test public void shouldCreatePromisedSizeOfSegments() { for (SegmentSize part : SegmentSize.values()) { // Perform this check only for `length` <= 5 because the test creates all hex numbers with `length` digits. if (part.getLength() <= 5) { checkTotalSegmentsProduced(part); } } } private void checkTotalSegmentsProduced(SegmentSize part) { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(part); Set<String> encounteredSegments = new HashSet<>(); int shift = part.getLength() * 4; // e.g. (1 << 16) - 1 = 0xFFFF. (Number of digits = shift/4, since 16 = 2^4) int max = (1 << shift) - 1; // when for (int i = 0; i <= max; ++i) { String uuid = toPaddedHex(i, part.getLength()); encounteredSegments.add(nameBuilder.createSegmentName(uuid)); } // then assertThat(encounteredSegments, hasSize(part.getTotalSegments())); } private static String toPaddedHex(int dec, int padLength) { String hexResult = Integer.toString(dec, 16); while (hexResult.length() < padLength) { hexResult = "0" + hexResult; } return hexResult; } @Test public void shouldCreateOneSegment() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(ONE); // when / then assertThat(nameBuilder.createSegmentName("abc"), equalTo("seg1-0")); assertThat(nameBuilder.createSegmentName("f0e"), equalTo("seg1-0")); assertThat(nameBuilder.createSegmentName("329"), equalTo("seg1-0")); } @Test public void shouldCreateFourSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(FOUR); // when / then assertThat(nameBuilder.createSegmentName("f9cc"), equalTo("seg4-3")); assertThat(nameBuilder.createSegmentName("84c9"), equalTo("seg4-2")); assertThat(nameBuilder.createSegmentName("3799"), equalTo("seg4-0")); } @Test public void shouldCreateEightSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(EIGHT); // when / then assertThat(nameBuilder.createSegmentName("fc9c"), equalTo("seg8-7")); assertThat(nameBuilder.createSegmentName("90ad"), equalTo("seg8-4")); assertThat(nameBuilder.createSegmentName("35e4"), equalTo("seg8-1")); assertThat(nameBuilder.createSegmentName("a39f"), equalTo("seg8-5")); } @Test public void shouldCreateSixteenSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(SIXTEEN); // when / then assertThat(nameBuilder.createSegmentName("fc9a054"), equalTo("seg16-f")); assertThat(nameBuilder.createSegmentName("b0a945e"), equalTo("seg16-b")); assertThat(nameBuilder.createSegmentName("7afebab"), equalTo("seg16-7")); } @Test public void shouldCreateThirtyTwoSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(THIRTY_TWO); // when / then assertThat(nameBuilder.createSegmentName("f890c9"), equalTo("seg32-11101")); assertThat(nameBuilder.createSegmentName("49c39a"), equalTo("seg32-01101")); assertThat(nameBuilder.createSegmentName("b75d09"), equalTo("seg32-10010")); } @Test public void shouldCreateSixtyFourSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(SIXTY_FOUR); // when / then assertThat(nameBuilder.createSegmentName("82f"), equalTo("seg64-203")); assertThat(nameBuilder.createSegmentName("9b4"), equalTo("seg64-221")); assertThat(nameBuilder.createSegmentName("068"), equalTo("seg64-012")); } @Test public void shouldCreate256Segments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(TWO_FIFTY); // when / then assertThat(nameBuilder.createSegmentName("a813c"), equalTo("seg256-a8")); assertThat(nameBuilder.createSegmentName("b4d01"), equalTo("seg256-b4")); assertThat(nameBuilder.createSegmentName("7122f"), equalTo("seg256-71")); } }
Xephi/AuthMeReloaded
src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentNameBuilderTest.java
Java
gpl-3.0
5,364
/* * Copyright (C) 2015 The Android Open Source Project * * 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 android.os.storage; import android.os.Parcel; import android.os.Parcelable; import android.util.DebugUtils; import android.util.TimeUtils; import com.android.internal.util.IndentingPrintWriter; import com.android.internal.util.Preconditions; import java.util.Objects; /** * Metadata for a storage volume which may not be currently present. * * @hide */ public class VolumeRecord implements Parcelable { public static final String EXTRA_FS_UUID = "android.os.storage.extra.FS_UUID"; public static final int USER_FLAG_INITED = 1 << 0; public static final int USER_FLAG_SNOOZED = 1 << 1; public final int type; public final String fsUuid; public String partGuid; public String nickname; public int userFlags; public long createdMillis; public long lastTrimMillis; public long lastBenchMillis; public VolumeRecord(int type, String fsUuid) { this.type = type; this.fsUuid = Preconditions.checkNotNull(fsUuid); } public VolumeRecord(Parcel parcel) { type = parcel.readInt(); fsUuid = parcel.readString(); partGuid = parcel.readString(); nickname = parcel.readString(); userFlags = parcel.readInt(); createdMillis = parcel.readLong(); lastTrimMillis = parcel.readLong(); lastBenchMillis = parcel.readLong(); } public int getType() { return type; } public String getFsUuid() { return fsUuid; } public String getNickname() { return nickname; } public boolean isInited() { return (userFlags & USER_FLAG_INITED) != 0; } public boolean isSnoozed() { return (userFlags & USER_FLAG_SNOOZED) != 0; } public void dump(IndentingPrintWriter pw) { pw.println("VolumeRecord:"); pw.increaseIndent(); pw.printPair("type", DebugUtils.valueToString(VolumeInfo.class, "TYPE_", type)); pw.printPair("fsUuid", fsUuid); pw.printPair("partGuid", partGuid); pw.println(); pw.printPair("nickname", nickname); pw.printPair("userFlags", DebugUtils.flagsToString(VolumeRecord.class, "USER_FLAG_", userFlags)); pw.println(); pw.printPair("createdMillis", TimeUtils.formatForLogging(createdMillis)); pw.printPair("lastTrimMillis", TimeUtils.formatForLogging(lastTrimMillis)); pw.printPair("lastBenchMillis", TimeUtils.formatForLogging(lastBenchMillis)); pw.decreaseIndent(); pw.println(); } @Override public VolumeRecord clone() { final Parcel temp = Parcel.obtain(); try { writeToParcel(temp, 0); temp.setDataPosition(0); return CREATOR.createFromParcel(temp); } finally { temp.recycle(); } } @Override public boolean equals(Object o) { if (o instanceof VolumeRecord) { return Objects.equals(fsUuid, ((VolumeRecord) o).fsUuid); } else { return false; } } @Override public int hashCode() { return fsUuid.hashCode(); } public static final Creator<VolumeRecord> CREATOR = new Creator<VolumeRecord>() { @Override public VolumeRecord createFromParcel(Parcel in) { return new VolumeRecord(in); } @Override public VolumeRecord[] newArray(int size) { return new VolumeRecord[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int flags) { parcel.writeInt(type); parcel.writeString(fsUuid); parcel.writeString(partGuid); parcel.writeString(nickname); parcel.writeInt(userFlags); parcel.writeLong(createdMillis); parcel.writeLong(lastTrimMillis); parcel.writeLong(lastBenchMillis); } }
syslover33/ctank
java/android-sdk-linux_r24.4.1_src/sources/android-23/android/os/storage/VolumeRecord.java
Java
gpl-3.0
4,577
#include "AtomicMaker.h" #include <string> void AtomicMaker::readParam(std::istream& in) { read<Boundary>(in, "boundary", boundary_); readParamComposite(in, random_); read<int>(in, "nMolecule", nMolecule_); } void AtomicMaker::writeConfig(std::ostream& out) { Vector r; Vector v; int iMol; out << "BOUNDARY" << std::endl; out << std::endl; out << boundary_ << std::endl; out << std::endl; out << "MOLECULES" << std::endl; out << std::endl; out << "species " << 0 << std::endl; out << "nMolecule " << nMolecule_ << std::endl; out << std::endl; for (iMol = 0; iMol < nMolecule_; ++iMol) { out << "molecule " << iMol << std::endl; boundary_.randomPosition(random_, r); out << r << std::endl; out << std::endl; } } int main() { AtomicMaker obj; obj.readParam(std::cin); obj.writeConfig(std::cout); }
jmysona/testing2
src/draft/tools/atomicMaker/AtomicMaker.cpp
C++
gpl-3.0
898
#Copyright (C) 2014 Marc Herndon # #This program is free software; you can redistribute it and/or #modify it under the terms of the GNU General Public License, #version 2, as published by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. """ This module contains the definition of the `Attribute` class, used to represent individual SMART attributes associated with a `Device`. """ class Attribute(object): """ Contains all of the information associated with a single SMART attribute in a `Device`'s SMART table. This data is intended to exactly mirror that obtained through smartctl. """ def __init__(self, num, name, flags, value, worst, thresh, attr_type, updated, when_failed, raw): self.num = num """**(str):** Attribute's ID as a decimal value (1-255).""" self.name = name """ **(str):** Attribute's name, as reported by smartmontools' drive.db. """ self.flags = flags """**(str):** Attribute flags as a hexadecimal value (ie: 0x0032).""" self.value = value """**(str):** Attribute's current normalized value.""" self.worst = worst """**(str):** Worst recorded normalized value for this attribute.""" self.thresh = thresh """**(str):** Attribute's failure threshold.""" self.type = attr_type """**(str):** Attribute's type, generally 'pre-fail' or 'old-age'.""" self.updated = updated """ **(str):** When is this attribute updated? Generally 'Always' or 'Offline' """ self.when_failed = when_failed """ **(str):** When did this attribute cross below `pySMART.attribute.Attribute.thresh`? Reads '-' when not failed. Generally either 'FAILING_NOW' or 'In_the_Past' otherwise. """ self.raw = raw """**(str):** Attribute's current raw (non-normalized) value.""" def __repr__(self): """Define a basic representation of the class object.""" return "<SMART Attribute %r %s/%s raw:%s>" % ( self.name, self.value, self.thresh, self.raw) def __str__(self): """ Define a formatted string representation of the object's content. In the interest of not overflowing 80-character lines this does not print the value of `pySMART.attribute.Attribute.flags_hex`. """ return "{0:>3} {1:24}{2:4}{3:4}{4:4}{5:9}{6:8}{7:12}{8}".format( self.num, self.name, self.value, self.worst, self.thresh, self.type, self.updated, self.when_failed, self.raw) __all__ = ['Attribute']
scith/htpc-manager_ynh
sources/libs/pySMART/attribute.py
Python
gpl-3.0
3,070
define([ 'angular' , './view-rubberband-controller' , './view-rubberband-directive' ], function( angular , Controller , directive ) { "use strict"; return angular.module('mtk.viewRubberband', []) .controller('ViewRubberbandController', Controller) .directive('mtkViewRubberband', directive) ; });
jeroenbreen/metapolator
app/lib/ui/metapolator/view-rubberband/view-rubberband.js
JavaScript
gpl-3.0
354
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera 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. *****************************************************************************/ // sync_reset.cpp -- test for // // Original Author: John Aynsley, Doulos, Inc. // // MODIFICATION LOG - modifiers, enter your name, affiliation, date and // // $Log: sync_reset.cpp,v $ // Revision 1.2 2011/05/08 19:18:46 acg // Andy Goodrich: remove extraneous + prefixes from git diff. // // sync_reset_on/off #define SC_INCLUDE_DYNAMIC_PROCESSES #include <systemc> using namespace sc_core; using std::cout; using std::endl; struct M2: sc_module { M2(sc_module_name _name) { SC_THREAD(ticker); SC_THREAD(calling); SC_THREAD(target1); t1 = sc_get_current_process_handle(); sc_spawn_options opt; opt.spawn_method(); opt.dont_initialize(); opt.set_sensitivity( &t1.reset_event() ); sc_spawn(sc_bind( &M2::reset_handler, this ), "reset_handler", &opt); SC_THREAD(target2); t2 = sc_get_current_process_handle(); SC_METHOD(target3); sensitive << ev; t3 = sc_get_current_process_handle(); count = 1; f0 = f1 = f2 = f3 = f4 = f5 = f6 = f7 = f8 = f9 = 0; f10 = f11 = f12 = f13 = f14 = f15 = f16 = f17 = f18 = f19 = 0; f20 = f21 = f22 = f23 = f24 = f25 = f26 = f27 = f28 = f29 = 0; f30 = f31 = f32 = f33 = f34 = f35 = f36 = f37 = f38 = f39 = 0; f40 = f41 = f42 = f43 = f44 = f45 = f46 = f47 = f48 = f49 = 0; } sc_process_handle t1, t2, t3; sc_event ev; int count; int f0, f1, f2, f3, f4, f5, f6, f7, f8, f9; int f10, f11, f12, f13, f14, f15, f16, f17, f18, f19; int f20, f21, f22, f23, f24, f25, f26, f27, f28, f29; int f30, f31, f32, f33, f34, f35, f36, f37, f38, f39; int f40, f41, f42, f43, f44, f45, f46, f47, f48, f49; void ticker() { for (;;) { wait(10, SC_NS); sc_assert( !sc_is_unwinding() ); ev.notify(); } } void calling() { count = 1; wait(15, SC_NS); // Target runs at 10 NS count = 2; t1.sync_reset_on(); // Target does not run at 15 NS wait(10, SC_NS); // Target is reset at 20 NS count = 3; wait(10, SC_NS); // Target is reset again at 30 NS count = 4; t1.sync_reset_off(); // Target does not run at 35 NS wait(10, SC_NS); // Target runs at 40 NS count = 5; t1.sync_reset_off(); // Double sync_reset_off wait(10, SC_NS); // Target runs at 50 NS count = 6; t1.sync_reset_on(); t1.disable(); wait(10, SC_NS); // Target does not run at 60 NS count = 7; t1.enable(); // Target does not run at 65 NS wait(10, SC_NS); // Target reset at 70 NS count = 8; t1.disable(); wait(10, SC_NS); // Target does not run at 80 NS count = 9; t1.sync_reset_off(); wait(10, SC_NS); // Target still disabled at 90 NS count = 10; t1.enable(); wait(10, SC_NS); // Target runs at 100 NS count = 11; t1.suspend(); wait(10, SC_NS); // Target does not run at 110 NS count = 12; wait(10, SC_NS); // Target still suspended at 120 NS count = 13; t1.resume(); // Target runs at 125 NS wait(1, SC_NS); count = 14; wait(9, SC_NS); // Target runs again at 130 NS count = 15; t1.sync_reset_on(); // Double sync_reset_on wait(10, SC_NS); // Target reset at 140 NS count = 16; t1.sync_reset_off(); wait(10, SC_NS); // Target runs at 150 NS count = 17; t1.sync_reset_off(); wait(10, SC_NS); // Target runs at 160 NS count = 18; t1.sync_reset_on(); wait(10, SC_NS); // Target reset at 170 NS count = 19; t1.reset(); // Target reset at 175 NS wait(SC_ZERO_TIME); count = 20; wait(1, SC_NS); t1.reset(); // Target reset at 176 NS count = 21; t1.reset(); // Target reset at 176 NS wait(1, SC_NS); count = 22; wait(8, SC_NS); // Target reset at 180 NS count = 23; wait(10, SC_NS); // Target reset at 190 NS count = 24; t1.sync_reset_off(); wait(10, SC_NS); // Target runs at 200 NS count = 25; wait(10, SC_NS); // Target runs at 210 NS count = 26; t1.reset(); wait(SC_ZERO_TIME); // Target reset at 215 t1.disable(); // Close it down wait(sc_time(300, SC_NS) - sc_time_stamp()); count = 27; t2.resume(); wait(SC_ZERO_TIME); count = 28; wait(15, SC_NS); count = 29; t2.sync_reset_on(); wait(10, SC_NS); t2.sync_reset_off(); t2.suspend(); wait(sc_time(405, SC_NS) - sc_time_stamp()); count = 30; t3.resume(); wait(SC_ZERO_TIME); count = 31; wait(10, SC_NS); count = 32; t3.sync_reset_on(); wait(10, SC_NS); sc_stop(); } void target1() { //cout << "Target1 called/reset at " << sc_time_stamp() << " count = " << count << endl; switch (count) { case 1: sc_assert( sc_time_stamp() == sc_time(0, SC_NS) ); f0=1; break; case 2: sc_assert( sc_time_stamp() == sc_time(20, SC_NS) ); f1=1; break; case 3: sc_assert( sc_time_stamp() == sc_time(30, SC_NS) ); f2=1; break; case 7: sc_assert( sc_time_stamp() == sc_time(70, SC_NS) ); f3=1; break; case 15: sc_assert( sc_time_stamp() == sc_time(140, SC_NS) ); f4=1; break; case 18: sc_assert( sc_time_stamp() == sc_time(170, SC_NS) ); f5=1; break; case 19: sc_assert( sc_time_stamp() == sc_time(175, SC_NS) ); f6=1; break; case 20: sc_assert( sc_time_stamp() == sc_time(176, SC_NS) ); f7=1; break; case 21: sc_assert( sc_time_stamp() == sc_time(176, SC_NS) ); f8=1; break; case 22: sc_assert( sc_time_stamp() == sc_time(180, SC_NS) ); f9=1; break; case 23: sc_assert( sc_time_stamp() == sc_time(190, SC_NS) ); f10=1; break; case 26: sc_assert( sc_time_stamp() == sc_time(215, SC_NS) ); f11=1; break; default: sc_assert( false ); break; } for (;;) { try { wait(ev); //cout << "Target1 awoke at " << sc_time_stamp() << " count = " << count << endl; sc_assert( !sc_is_unwinding() ); switch (count) { case 1: sc_assert( sc_time_stamp() == sc_time(10, SC_NS) ); f12=1; break; case 4: sc_assert( sc_time_stamp() == sc_time(40, SC_NS) ); f13=1; break; case 5: sc_assert( sc_time_stamp() == sc_time(50, SC_NS) ); f14=1; break; case 10: sc_assert( sc_time_stamp() == sc_time(100, SC_NS) ); f15=1; break; case 13: sc_assert( sc_time_stamp() == sc_time(125, SC_NS) ); f16=1; break; case 14: sc_assert( sc_time_stamp() == sc_time(130, SC_NS) ); f17=1; break; case 16: sc_assert( sc_time_stamp() == sc_time(150, SC_NS) ); f18=1; break; case 17: sc_assert( sc_time_stamp() == sc_time(160, SC_NS) ); f19=1; break; case 24: sc_assert( sc_time_stamp() == sc_time(200, SC_NS) ); f20=1; break; case 25: sc_assert( sc_time_stamp() == sc_time(210, SC_NS) ); f21=1; break; default: sc_assert( false ); break; } } catch (const sc_unwind_exception& ex) { sc_assert( sc_is_unwinding() ); sc_assert( ex.is_reset() ); throw ex; } } } void reset_handler() { //cout << "reset_handler awoke at " << sc_time_stamp() << " count = " << count << endl; sc_assert( !sc_is_unwinding() ); switch (count) { case 2: sc_assert( sc_time_stamp() == sc_time(20, SC_NS) ); f22=1; break; case 3: sc_assert( sc_time_stamp() == sc_time(30, SC_NS) ); f23=1; break; case 7: sc_assert( sc_time_stamp() == sc_time(70, SC_NS) ); f24=1; break; case 15: sc_assert( sc_time_stamp() == sc_time(140, SC_NS) ); f27=1; break;; case 18: sc_assert( sc_time_stamp() == sc_time(170, SC_NS) ); f28=1; break; case 19: sc_assert( sc_time_stamp() == sc_time(175, SC_NS) ); f29=1; break; case 21: sc_assert( sc_time_stamp() == sc_time(176, SC_NS) ); f31=1; break; case 22: sc_assert( sc_time_stamp() == sc_time(180, SC_NS) ); f32=1; break; case 23: sc_assert( sc_time_stamp() == sc_time(190, SC_NS) ); f33=1; break; case 26: sc_assert( sc_time_stamp() == sc_time(215, SC_NS) ); f34=1; break; default: sc_assert( false ); break; } } void target2() { if (sc_delta_count() == 0) t2.suspend(); // Hack to work around not being able to call suspend during elab switch (count) { case 27: sc_assert( sc_time_stamp() == sc_time(300, SC_NS) ); f35=1; break; case 29: sc_assert( sc_time_stamp() == sc_time(320, SC_NS) ); f37=1; break; default: sc_assert( false ); break; } while(1) { try { wait(10, SC_NS); } catch (const sc_unwind_exception& e) { switch (count) { case 29: sc_assert( sc_time_stamp() == sc_time(320, SC_NS) ); f38=1; break; default: sc_assert( false ); break; } throw e; } switch (count) { case 28: sc_assert( sc_time_stamp() == sc_time(310, SC_NS) ); f36=1; break; default: sc_assert( false ); break; } } } void target3() { if (sc_delta_count() == 0) t3.suspend(); // Hack to work around not being able to call suspend during elab switch (count) { case 1: sc_assert( sc_time_stamp() == sc_time(0, SC_NS) ); break; case 30: sc_assert( sc_time_stamp() == sc_time(405, SC_NS) ); f39=1; break; case 31: sc_assert( sc_time_stamp() == sc_time(410, SC_NS) ); f40=1; break; case 32: sc_assert( sc_time_stamp() == sc_time(420, SC_NS) ); f41=1; break; default: sc_assert( false ); break; } } SC_HAS_PROCESS(M2); }; int sc_main(int argc, char* argv[]) { M2 m("m"); sc_start(); sc_assert(m.f0); sc_assert(m.f1); sc_assert(m.f2); sc_assert(m.f3); sc_assert(m.f4); sc_assert(m.f5); sc_assert(m.f6); sc_assert(m.f7); sc_assert(m.f8); sc_assert(m.f9); sc_assert(m.f10); sc_assert(m.f11); sc_assert(m.f12); sc_assert(m.f13); sc_assert(m.f14); sc_assert(m.f15); sc_assert(m.f16); sc_assert(m.f17); sc_assert(m.f18); sc_assert(m.f19); sc_assert(m.f20); sc_assert(m.f21); sc_assert(m.f22); sc_assert(m.f23); sc_assert(m.f24); sc_assert(m.f27); sc_assert(m.f28); sc_assert(m.f29); sc_assert(m.f31); sc_assert(m.f32); sc_assert(m.f33); sc_assert(m.f34); sc_assert(m.f35); sc_assert(m.f36); sc_assert(m.f37); sc_assert(m.f38); sc_assert(m.f39); sc_assert(m.f40); sc_assert(m.f41); cout << endl << "Success" << endl; return 0; }
vineodd/PIMSim
GEM5Simulation/gem5/src/systemc/tests/systemc/1666-2011-compliance/sync_reset/sync_reset.cpp
C++
gpl-3.0
11,660
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "blimp/common/compositor/reference_tracker.h" #include <stdint.h> #include <algorithm> #include <unordered_set> #include <vector> #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace blimp { namespace { class ReferenceTrackerTest : public testing::Test { public: ReferenceTrackerTest() = default; ~ReferenceTrackerTest() override = default; protected: ReferenceTracker tracker_; std::vector<uint32_t> added_; std::vector<uint32_t> removed_; private: DISALLOW_COPY_AND_ASSIGN(ReferenceTrackerTest); }; TEST_F(ReferenceTrackerTest, SingleItemCommitFlow) { tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_TRUE(removed_.empty()); uint32_t item = 1; tracker_.IncrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item)); EXPECT_TRUE(removed_.empty()); added_.clear(); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_TRUE(removed_.empty()); tracker_.DecrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item)); } TEST_F(ReferenceTrackerTest, SingleItemMultipleTimesInSingleCommit) { uint32_t item = 1; tracker_.IncrementRefCount(item); tracker_.IncrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item)); EXPECT_TRUE(removed_.empty()); added_.clear(); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_TRUE(removed_.empty()); tracker_.DecrementRefCount(item); tracker_.DecrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item)); } TEST_F(ReferenceTrackerTest, SingleItemMultipleTimesAcrossCommits) { uint32_t item = 1; tracker_.IncrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item)); EXPECT_TRUE(removed_.empty()); added_.clear(); tracker_.IncrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_TRUE(removed_.empty()); tracker_.DecrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_TRUE(removed_.empty()); tracker_.DecrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item)); } TEST_F(ReferenceTrackerTest, SingleItemComplexInteractions) { uint32_t item = 1; tracker_.IncrementRefCount(item); tracker_.DecrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_TRUE(removed_.empty()); tracker_.IncrementRefCount(item); tracker_.DecrementRefCount(item); tracker_.IncrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item)); EXPECT_TRUE(removed_.empty()); added_.clear(); tracker_.DecrementRefCount(item); tracker_.IncrementRefCount(item); tracker_.DecrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item)); } TEST_F(ReferenceTrackerTest, MultipleItems) { uint32_t item1 = 1; uint32_t item2 = 2; uint32_t item3 = 3; tracker_.IncrementRefCount(item1); tracker_.IncrementRefCount(item2); tracker_.IncrementRefCount(item3); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item1, item2, item3)); EXPECT_TRUE(removed_.empty()); added_.clear(); tracker_.DecrementRefCount(item3); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item3)); removed_.clear(); tracker_.DecrementRefCount(item2); tracker_.IncrementRefCount(item3); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item3)); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item2)); added_.clear(); removed_.clear(); tracker_.IncrementRefCount(item2); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item2)); EXPECT_TRUE(removed_.empty()); added_.clear(); tracker_.DecrementRefCount(item1); tracker_.DecrementRefCount(item2); tracker_.DecrementRefCount(item3); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item1, item2, item3)); } TEST_F(ReferenceTrackerTest, MultipleItemsWithClear) { uint32_t item1 = 1; uint32_t item2 = 2; tracker_.IncrementRefCount(item1); tracker_.IncrementRefCount(item2); tracker_.ClearRefCounts(); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_TRUE(removed_.empty()); tracker_.IncrementRefCount(item1); tracker_.IncrementRefCount(item2); tracker_.ClearRefCounts(); tracker_.IncrementRefCount(item1); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item1)); EXPECT_TRUE(removed_.empty()); added_.clear(); tracker_.ClearRefCounts(); tracker_.IncrementRefCount(item2); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item2)); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item1)); added_.clear(); removed_.clear(); tracker_.ClearRefCounts(); tracker_.IncrementRefCount(item1); tracker_.IncrementRefCount(item2); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item1)); EXPECT_TRUE(removed_.empty()); added_.clear(); } } // namespace } // namespace blimp
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/blimp/common/compositor/reference_tracker_unittest.cc
C++
gpl-3.0
6,177
/************************************************************************* * Copyright 2009-2014 Eucalyptus Systems, Inc. * * 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 3 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, see http://www.gnu.org/licenses/. * * Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta * CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need * additional information or have any questions. * * This file may incorporate work covered under the following copyright * and permission notice: * * Software License Agreement (BSD License) * * Copyright (c) 2008, Regents of the University of California * All rights reserved. * * Redistribution and use of this software in source and binary forms, * with or without modification, are permitted provided that the * following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. USERS OF THIS SOFTWARE ACKNOWLEDGE * THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE LICENSED MATERIAL, * COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS SOFTWARE, * AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING * IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, * SANTA BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, * WHICH IN THE REGENTS' DISCRETION MAY INCLUDE, WITHOUT LIMITATION, * REPLACEMENT OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO * IDENTIFIED, OR WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT * NEEDED TO COMPLY WITH ANY SUCH LICENSES OR RIGHTS. ************************************************************************/ package com.eucalyptus.ws; import javax.annotation.Nullable; import org.jboss.netty.handler.codec.http.HttpResponseStatus; public class EucalyptusRemoteFault extends Exception { String relatesTo; String action; String faultDetail; String faultCode; String faultString; HttpResponseStatus status; public EucalyptusRemoteFault( final String action, final String relatesTo, final String faultCode, final String faultString ) { super( String.format( "Action:%s Code:%s Id:%s Error: %s", action, faultCode, relatesTo, faultString ) ); this.relatesTo = relatesTo; this.action = action; this.faultCode = faultCode; this.faultString = faultString; } public EucalyptusRemoteFault( final String action, final String relatesTo, final String faultCode, final String faultString, final String faultDetail, final HttpResponseStatus status ) { this( action, relatesTo, faultCode, faultString ); this.faultDetail = faultDetail; this.status = status; } public String getRelatesTo( ) { return this.relatesTo; } public String getAction( ) { return this.action; } public String getFaultDetail( ) { return this.faultDetail; } public String getFaultCode( ) { return this.faultCode; } public String getFaultString( ) { return this.faultString; } @Nullable public HttpResponseStatus getStatus( ) { return status; } }
eethomas/eucalyptus
clc/modules/msgs/src/main/java/com/eucalyptus/ws/EucalyptusRemoteFault.java
Java
gpl-3.0
4,910
<?php /* * This file is part of Phraseanet * * (c) 2005-2016 Alchemy * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Guzzle\Http\Url; class media_adapter extends media_abstract { /** * Constructor * * Enforces Url to de defined * * @param int $width * @param int $height * @param Url $url */ public function __construct($width, $height, Url $url) { parent::__construct($width, $height, $url); } }
nmaillat/Phraseanet
lib/classes/media/adapter.php
PHP
gpl-3.0
556
/* * eXist Open Source Native XML Database * Copyright (C) 2010 The eXist Project * http://exist-db.org * * This program 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 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * $Id$ */ package org.exist.versioning.svn.xquery; import org.exist.dom.QName; import org.exist.util.io.Resource; import org.exist.versioning.svn.internal.wc.DefaultSVNOptions; import org.exist.versioning.svn.wc.SVNClientManager; import org.exist.versioning.svn.wc.SVNWCUtil; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.FunctionReturnSequenceType; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.Type; import org.tmatesoft.svn.core.SVNException; /** * Recursively cleans up the working copy, removing locks and resuming unfinished operations. * * @author <a href="mailto:amir.akhmedov@gmail.com">Amir Akhmedov</a> * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> */ public class SVNCleanup extends AbstractSVNFunction { public final static FunctionSignature signature = new FunctionSignature( new QName("clean-up", SVNModule.NAMESPACE_URI, SVNModule.PREFIX), "Recursively cleans up the working copy, removing locks and resuming unfinished operations.", new SequenceType[] { DB_PATH }, new FunctionReturnSequenceType(Type.EMPTY, Cardinality.ZERO, "")); /** * * @param context */ public SVNCleanup(XQueryContext context) { super(context, signature); } /** * Process the function. All arguments are passed in the array args. The number of * arguments, their type and cardinality have already been checked to match * the function signature. * * @param args * @param contextSequence */ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { String uri = args[0].getStringValue(); DefaultSVNOptions options = SVNWCUtil.createDefaultOptions(true); SVNClientManager manager = SVNClientManager.newInstance(options, "", ""); try { manager.getWCClient().doCleanup(new Resource(uri)); } catch (SVNException e) { throw new XPathException(this, e.getMessage(), e); } return Sequence.EMPTY_SEQUENCE; } }
shabanovd/exist
extensions/svn/src/org/exist/versioning/svn/xquery/SVNCleanup.java
Java
lgpl-2.1
3,112
package org.jaudiotagger.issues; import org.jaudiotagger.AbstractTestCase; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.tag.FieldKey; import java.io.File; /** * Test deletions of ID3v1 tag */ public class Issue383Test extends AbstractTestCase { /** * This song is incorrectly shown as 6:08 when should be 3:34 but all apps (Media Monkey, iTunes) * also report incorrect length, however think problem is audio does continue until 6:08 but is just quiet sound * * @throws Exception */ public void testIssueIncorrectTrackLength() throws Exception { Exception caught = null; try { File orig = new File("testdata", "test106.mp3"); if (!orig.isFile()) { System.err.println("Unable to test file - not available"); return; } File testFile = AbstractTestCase.copyAudioToTmp("test106.mp3"); AudioFile af = AudioFileIO.read(testFile); assertEquals(af.getAudioHeader().getTrackLength(),368); } catch(Exception e) { caught=e; } assertNull(caught); } /** * This song is incorrectly shown as 01:12:52, but correct length was 2:24. Other applications * such as Media Monkey show correct value. * * @throws Exception */ public void testIssue() throws Exception { Exception caught = null; try { File orig = new File("testdata", "test107.mp3"); if (!orig.isFile()) { System.err.println("Unable to test file - not available"); return; } File testFile = AbstractTestCase.copyAudioToTmp("test107.mp3"); AudioFile af = AudioFileIO.read(testFile); assertEquals(af.getTag().getFirst(FieldKey.TRACK),"01"); assertEquals(af.getAudioHeader().getTrackLength(),4372); } catch(Exception e) { caught=e; } assertNull(caught); } }
nhminus/jaudiotagger-androidpatch
srctest/org/jaudiotagger/issues/Issue383Test.java
Java
lgpl-2.1
2,217
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "currentprojectfind.h" #include "projectexplorer.h" #include "project.h" #include "session.h" #include <coreplugin/idocument.h> #include <utils/qtcassert.h> #include <QDebug> #include <QSettings> #include <QLabel> #include <QHBoxLayout> using namespace Find; using namespace ProjectExplorer; using namespace ProjectExplorer::Internal; using namespace TextEditor; CurrentProjectFind::CurrentProjectFind(ProjectExplorerPlugin *plugin) : AllProjectsFind(plugin), m_plugin(plugin) { connect(m_plugin, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)), this, SLOT(handleProjectChanged())); } QString CurrentProjectFind::id() const { return QLatin1String("Current Project"); } QString CurrentProjectFind::displayName() const { return tr("Current Project"); } bool CurrentProjectFind::isEnabled() const { return ProjectExplorerPlugin::currentProject() != 0 && BaseFileFind::isEnabled(); } QVariant CurrentProjectFind::additionalParameters() const { Project *project = ProjectExplorerPlugin::currentProject(); if (project && project->document()) return qVariantFromValue(project->document()->fileName()); return QVariant(); } Utils::FileIterator *CurrentProjectFind::files(const QStringList &nameFilters, const QVariant &additionalParameters) const { QTC_ASSERT(additionalParameters.isValid(), return new Utils::FileIterator()); QList<Project *> allProjects = m_plugin->session()->projects(); QString projectFile = additionalParameters.toString(); foreach (Project *project, allProjects) { if (project->document() && projectFile == project->document()->fileName()) return filesForProjects(nameFilters, QList<Project *>() << project); } return new Utils::FileIterator(); } QString CurrentProjectFind::label() const { QTC_ASSERT(ProjectExplorerPlugin::currentProject(), return QString()); return tr("Project '%1':").arg(ProjectExplorerPlugin::currentProject()->displayName()); } void CurrentProjectFind::handleProjectChanged() { emit enabledChanged(isEnabled()); } void CurrentProjectFind::writeSettings(QSettings *settings) { settings->beginGroup(QLatin1String("CurrentProjectFind")); writeCommonSettings(settings); settings->endGroup(); } void CurrentProjectFind::readSettings(QSettings *settings) { settings->beginGroup(QLatin1String("CurrentProjectFind")); readCommonSettings(settings, QString(QLatin1Char('*'))); settings->endGroup(); }
ostash/qt-creator-i18n-uk
src/plugins/projectexplorer/currentprojectfind.cpp
C++
lgpl-2.1
3,806
/* The contents of this file are subject to the license and copyright terms * detailed in the license directory at the root of the source tree (also * available online at http://fedora-commons.org/license/). */ package org.fcrepo.server.utilities.status; public class ServerState { public static final ServerState NEW_SERVER = new ServerState("New Server"); public static final ServerState NOT_STARTING = new ServerState("Not Starting"); public static final ServerState STARTING = new ServerState("Starting"); public static final ServerState STARTED = new ServerState("Started"); public static final ServerState STARTUP_FAILED = new ServerState("Startup Failed"); public static final ServerState STOPPING = new ServerState("Stopping"); public static final ServerState STOPPED = new ServerState("Stopped"); public static final ServerState STOPPED_WITH_ERR = new ServerState("Stopped with error"); public static final ServerState[] STATES = new ServerState[] {NEW_SERVER, NOT_STARTING, STARTING, STARTED, STARTUP_FAILED, STOPPING, STOPPED, STOPPED_WITH_ERR}; private final String _name; private ServerState(String name) { _name = name; } public String getName() { return _name; } @Override public String toString() { return _name; } public static ServerState fromString(String name) throws Exception { for (ServerState element : STATES) { if (element.getName().equals(name)) { return element; } } throw new Exception("Unrecognized Server State: " + name); } }
andreasnef/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/utilities/status/ServerState.java
Java
apache-2.0
1,711
/* * 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.mnemonic.service.memory.internal; import java.nio.ByteBuffer; import java.util.BitSet; import java.util.HashMap; import java.util.Map; public class BufferBlockInfo { long bufferBlockBaseAddress = 0L; int bufferBlockSize; ByteBuffer bufferBlock = null; BitSet bufferBlockChunksMap = null; Map<Long, Integer> chunkSizeMap = new HashMap<>(); public ByteBuffer getBufferBlock() { return bufferBlock; } public void setBufferBlock(ByteBuffer byteBufferBlock) { this.bufferBlock = byteBufferBlock; } public BitSet getBufferBlockChunksMap() { return bufferBlockChunksMap; } public void setBufferBlockChunksMap(BitSet chunksMap) { this.bufferBlockChunksMap = chunksMap; } public long getBufferBlockBaseAddress() { return bufferBlockBaseAddress; } public void setBufferBlockBaseAddress(long bufferBlockBaseAddress) { this.bufferBlockBaseAddress = bufferBlockBaseAddress; } public int getBufferBlockSize() { return bufferBlockSize; } public void setBufferBlockSize(int blockSize) { this.bufferBlockSize = blockSize; } public Map<Long, Integer> getChunkSizeMap() { return chunkSizeMap; } public void setChunkSizeMap(long chunkHandler, int chunkSize) { chunkSizeMap.put(chunkHandler, chunkSize); } }
lql5083psu/incubator-mnemonic
mnemonic-memory-services/mnemonic-java-vmem-service/src/main/java/org/apache/mnemonic/service/memory/internal/BufferBlockInfo.java
Java
apache-2.0
2,204
// Code generated by counterfeiter. DO NOT EDIT. package mock import ( "sync" ) type Writer struct { WriteFileStub func(string, string, []byte) error writeFileMutex sync.RWMutex writeFileArgsForCall []struct { arg1 string arg2 string arg3 []byte } writeFileReturns struct { result1 error } writeFileReturnsOnCall map[int]struct { result1 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *Writer) WriteFile(arg1 string, arg2 string, arg3 []byte) error { var arg3Copy []byte if arg3 != nil { arg3Copy = make([]byte, len(arg3)) copy(arg3Copy, arg3) } fake.writeFileMutex.Lock() ret, specificReturn := fake.writeFileReturnsOnCall[len(fake.writeFileArgsForCall)] fake.writeFileArgsForCall = append(fake.writeFileArgsForCall, struct { arg1 string arg2 string arg3 []byte }{arg1, arg2, arg3Copy}) fake.recordInvocation("WriteFile", []interface{}{arg1, arg2, arg3Copy}) fake.writeFileMutex.Unlock() if fake.WriteFileStub != nil { return fake.WriteFileStub(arg1, arg2, arg3) } if specificReturn { return ret.result1 } fakeReturns := fake.writeFileReturns return fakeReturns.result1 } func (fake *Writer) WriteFileCallCount() int { fake.writeFileMutex.RLock() defer fake.writeFileMutex.RUnlock() return len(fake.writeFileArgsForCall) } func (fake *Writer) WriteFileCalls(stub func(string, string, []byte) error) { fake.writeFileMutex.Lock() defer fake.writeFileMutex.Unlock() fake.WriteFileStub = stub } func (fake *Writer) WriteFileArgsForCall(i int) (string, string, []byte) { fake.writeFileMutex.RLock() defer fake.writeFileMutex.RUnlock() argsForCall := fake.writeFileArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } func (fake *Writer) WriteFileReturns(result1 error) { fake.writeFileMutex.Lock() defer fake.writeFileMutex.Unlock() fake.WriteFileStub = nil fake.writeFileReturns = struct { result1 error }{result1} } func (fake *Writer) WriteFileReturnsOnCall(i int, result1 error) { fake.writeFileMutex.Lock() defer fake.writeFileMutex.Unlock() fake.WriteFileStub = nil if fake.writeFileReturnsOnCall == nil { fake.writeFileReturnsOnCall = make(map[int]struct { result1 error }) } fake.writeFileReturnsOnCall[i] = struct { result1 error }{result1} } func (fake *Writer) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.writeFileMutex.RLock() defer fake.writeFileMutex.RUnlock() copiedInvocations := map[string][][]interface{}{} for key, value := range fake.invocations { copiedInvocations[key] = value } return copiedInvocations } func (fake *Writer) 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) }
stemlending/fabric
internal/peer/lifecycle/chaincode/mock/writer.go
GO
apache-2.0
3,051
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.operator; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.trino.connector.CatalogName; import static java.util.Objects.requireNonNull; public class SplitOperatorInfo implements OperatorInfo { private final CatalogName catalogName; // NOTE: this deserializes to a map instead of the expected type private final Object splitInfo; @JsonCreator public SplitOperatorInfo( @JsonProperty("catalogName") CatalogName catalogName, @JsonProperty("splitInfo") Object splitInfo) { this.catalogName = requireNonNull(catalogName, "catalogName is null"); this.splitInfo = splitInfo; } @Override public boolean isFinal() { return true; } @JsonProperty public Object getSplitInfo() { return splitInfo; } @JsonProperty public CatalogName getCatalogName() { return catalogName; } }
electrum/presto
core/trino-main/src/main/java/io/trino/operator/SplitOperatorInfo.java
Java
apache-2.0
1,565
/** * Copyright (C) 2011-2020 Red Hat, Inc. (https://github.com/Commonjava/indy) * * 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.commonjava.indy.core.inject; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.commonjava.indy.conf.DefaultIndyConfiguration; import org.commonjava.maven.galley.model.ConcreteResource; import org.commonjava.maven.galley.model.Location; import org.commonjava.maven.galley.model.SimpleLocation; import org.junit.Test; public class ExpiringMemoryNotFoundCacheTest { @Test public void expireUsingConfiguredValue() throws Exception { final DefaultIndyConfiguration config = new DefaultIndyConfiguration(); config.setNotFoundCacheTimeoutSeconds( 1 ); final ExpiringMemoryNotFoundCache nfc = new ExpiringMemoryNotFoundCache( config ); final ConcreteResource res = new ConcreteResource( new SimpleLocation( "test:uri" ), "/path/to/expired/object" ); nfc.addMissing( res ); assertThat( nfc.isMissing( res ), equalTo( true ) ); Thread.sleep( TimeUnit.SECONDS.toMillis( 2 ) ); assertThat( nfc.isMissing( res ), equalTo( false ) ); final Set<String> locMissing = nfc.getMissing( res.getLocation() ); assertThat( locMissing == null || locMissing.isEmpty(), equalTo( true ) ); final Map<Location, Set<String>> allMissing = nfc.getAllMissing(); assertThat( allMissing == null || allMissing.isEmpty(), equalTo( true ) ); } @Test public void expireUsingConfiguredValue_DirectCheckDoesntAffectAggregateChecks() throws Exception { final DefaultIndyConfiguration config = new DefaultIndyConfiguration(); config.setNotFoundCacheTimeoutSeconds( 1 ); final ExpiringMemoryNotFoundCache nfc = new ExpiringMemoryNotFoundCache( config ); final ConcreteResource res = new ConcreteResource( new SimpleLocation( "test:uri" ), "/path/to/expired/object" ); nfc.addMissing( res ); assertThat( nfc.isMissing( res ), equalTo( true ) ); Thread.sleep( TimeUnit.SECONDS.toMillis( 2 ) ); Set<String> locMissing = nfc.getMissing( res.getLocation() ); System.out.println( locMissing ); assertThat( locMissing == null || locMissing.isEmpty(), equalTo( true ) ); Map<Location, Set<String>> allMissing = nfc.getAllMissing(); assertThat( allMissing == null || allMissing.isEmpty(), equalTo( true ) ); assertThat( nfc.isMissing( res ), equalTo( false ) ); locMissing = nfc.getMissing( res.getLocation() ); assertThat( locMissing == null || locMissing.isEmpty(), equalTo( true ) ); allMissing = nfc.getAllMissing(); assertThat( allMissing == null || allMissing.isEmpty(), equalTo( true ) ); } }
pkocandr/indy
core/src/test/java/org/commonjava/indy/core/inject/ExpiringMemoryNotFoundCacheTest.java
Java
apache-2.0
3,446
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("OSharp.Autofac")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("柳柳软件")] [assembly: AssemblyProduct("OSharp.Autofac")] [assembly: AssemblyCopyright("Copyright © 柳柳软件 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("50a2b6a0-8e08-4554-9595-6801f627e16b")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.3.0")] [assembly: AssemblyInformationalVersion("3.0.3")]
BiaoLiu/osharp-2015.8.28
src/OSharp.Autofac/Properties/AssemblyInfo.cs
C#
apache-2.0
1,374
/** * Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.sesame.graph; /** * Provides IDs for function instances. * <p> * If two functions are logically equal they will be assigned the same ID. This is used by the caching mechanism * to allow safe sharing of values calculated by different functions. * <p> * Two function instances are considered to be logically equal if their {@link FunctionModelNode} instances are * equal. */ public interface FunctionIdProvider { /** * Returns the ID of a function instance. * * @param fn a function * @return the function's ID * @throws IllegalArgumentException if the function has no known ID */ FunctionId getFunctionId(Object fn); }
jeorme/OG-Platform
sesame/sesame-engine/src/main/java/com/opengamma/sesame/graph/FunctionIdProvider.java
Java
apache-2.0
810
/* * Copyright 2021 Red Hat, Inc. and/or its affiliates. * * 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.kie.workbench.common.stunner.bpmn.project.backend.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Supplier; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.jboss.errai.bus.server.annotations.Service; import org.kie.soup.commons.util.Sets; import org.kie.workbench.common.services.refactoring.model.index.terms.valueterms.ValueIndexTerm; import org.kie.workbench.common.services.refactoring.model.index.terms.valueterms.ValueResourceIndexTerm; import org.kie.workbench.common.services.refactoring.service.RefactoringQueryService; import org.kie.workbench.common.services.refactoring.service.ResourceType; import org.kie.workbench.common.stunner.bpmn.project.backend.query.FindBpmnProcessIdsQuery; import org.kie.workbench.common.stunner.bpmn.project.service.ProjectOpenReusableSubprocessService; import org.uberfire.backend.vfs.Path; @ApplicationScoped @Service public class ProjectOpenReusableSubprocessServiceImpl implements ProjectOpenReusableSubprocessService { private final RefactoringQueryService queryService; private final Supplier<ResourceType> resourceType; private final Supplier<String> queryName; private final Set<ValueIndexTerm> queryTerms; // CDI proxy. protected ProjectOpenReusableSubprocessServiceImpl() { this(null); } @Inject public ProjectOpenReusableSubprocessServiceImpl(final RefactoringQueryService queryService) { this.queryService = queryService; this.resourceType = () -> ResourceType.BPMN2; this.queryName = () -> FindBpmnProcessIdsQuery.NAME; this.queryTerms = new Sets.Builder<ValueIndexTerm>() .add(new ValueResourceIndexTerm("*", resourceType.get(), ValueIndexTerm.TermSearchType.WILDCARD)) .build(); } String getQueryName() { return queryName.get(); } Set<ValueIndexTerm> createQueryTerms() { return queryTerms; } @Override @SuppressWarnings("unchecked") public List<String> openReusableSubprocess(String processId) { List<String> answer = new ArrayList<>(); Map<String, Path> subprocesses = queryService .query(getQueryName(), createQueryTerms()) .stream() .map(row -> (Map<String, Path>) row.getValue()) .filter(row -> row.get(processId) != null) .findFirst() .orElse(null); if (subprocesses == null) { return answer; } answer.add(subprocesses.get(processId).getFileName()); answer.add(subprocesses.get(processId).toURI()); return answer; } }
romartin/kie-wb-common
kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-project-backend/src/main/java/org/kie/workbench/common/stunner/bpmn/project/backend/service/ProjectOpenReusableSubprocessServiceImpl.java
Java
apache-2.0
3,469
class SearchController < ApplicationController using ArrayItemWrapper def index q, limit, type = search_params.values_at(:q, :limit, :type) respond_with perform_search(q, limit, type).merge(q: q) end private def perform_search(q, limit, *types) types = %w(template local_image remote_image) if types.compact.empty? {}.tap do |results| results[:templates] = wrapped_templates(q, limit) if types.include? 'template' results[:local_images] = wrapped_local_images(q, limit) if types.include? 'local_image' if types.include? 'remote_image' results[:remote_images], results[:errors] = wrapped_remote_images(q, limit) end end end def search_params # Coerce limit to an integer params[:limit] = params[:limit].to_i if params[:limit].present? params.permit(:q, :type, :limit) end def wrapped_templates(q, limit) Template.search(q, limit).wrap(TemplateSerializer) end def wrapped_local_images(q, limit) LocalImage.search(q, limit).wrap(LocalImageSearchResultSerializer) end def wrapped_remote_images(q, limit) images, errors = Registry.search(q, limit) return images.wrap(RemoteImageSearchResultSerializer), errors end end
rheinwein/panamax-api
app/controllers/search_controller.rb
Ruby
apache-2.0
1,231
/* * Copyright 2010 Utkin Dmitry * * 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. */ /* * This file is part of the WSF Staff project. * Please, visit http://code.google.com/p/staff for more information. */ #include <staff/utils/Log.h> #include <staff/utils/SharedPtr.h> #include <staff/utils/File.h> #include <staff/utils/DynamicLibrary.h> #include <staff/utils/PluginManager.h> #include <staff/common/Runtime.h> #include "ProviderFactory.h" namespace staff { namespace das { class ProviderFactory::ProviderFactoryImpl { public: typedef std::map<std::string, IProviderAllocator*> ProviderAllocatorMap; public: void Init() { const std::string sProvidersDir = Runtime::Inst().GetComponentHome("staff.das") + STAFF_PATH_SEPARATOR "providers"; StringList lsProviderDirs; // find directories with providers File(sProvidersDir).List(lsProviderDirs, "*", File::AttributeDirectory); if (lsProviderDirs.size() == 0) { LogDebug() << "providers is not found"; } for (StringList::const_iterator itDir = lsProviderDirs.begin(); itDir != lsProviderDirs.end(); ++itDir) { // finding libraries with providers StringList lsProvidersLibs; StringList lsProvidersNames; const std::string& sProviderDir = sProvidersDir + STAFF_PATH_SEPARATOR + *itDir + STAFF_PATH_SEPARATOR; File(sProviderDir).List(lsProvidersLibs, "*" STAFF_LIBRARY_VEREXT, File::AttributeRegularFile); for (StringList::const_iterator itProvider = lsProvidersLibs.begin(); itProvider != lsProvidersLibs.end(); ++itProvider) { const std::string& sProviderPluginPath = sProviderDir + *itProvider; try { // loading provider LogDebug() << "Loading DAS provider: " << sProviderPluginPath; IProviderAllocator* pAllocator = m_tPluginManager.Load(sProviderPluginPath, true); STAFF_ASSERT(pAllocator, "Can't get allocator for provider: " + *itProvider); pAllocator->GetProvidersList(lsProvidersNames); for (StringList::const_iterator itProviderName = lsProvidersNames.begin(); itProviderName != lsProvidersNames.end(); ++itProviderName) { LogDebug1() << "Setting DAS provider: " << *itProviderName; m_mAllocators[*itProviderName] = pAllocator; } } catch (const Exception& rEx) { LogWarning() << "Can't load provider: " << sProviderPluginPath << ": " << rEx.what(); continue; } } } } public: ProviderAllocatorMap m_mAllocators; PluginManager<IProviderAllocator> m_tPluginManager; }; ProviderFactory::ProviderFactory() { m_pImpl = new ProviderFactoryImpl; try { m_pImpl->Init(); } STAFF_CATCH_ALL } ProviderFactory::~ProviderFactory() { delete m_pImpl; } ProviderFactory& ProviderFactory::Inst() { static ProviderFactory tInst; return tInst; } void ProviderFactory::GetProviders(StringList& rlsProviders) { rlsProviders.clear(); for (ProviderFactoryImpl::ProviderAllocatorMap::const_iterator itProvider = m_pImpl->m_mAllocators.begin(); itProvider != m_pImpl->m_mAllocators.end(); ++itProvider) { rlsProviders.push_back(itProvider->first); } } PProvider ProviderFactory::Allocate(const std::string& sProvider) { ProviderFactoryImpl::ProviderAllocatorMap::iterator itProvider = m_pImpl->m_mAllocators.find(sProvider); STAFF_ASSERT(itProvider != m_pImpl->m_mAllocators.end(), "Can't get allocator for " + sProvider); return itProvider->second->Allocate(sProvider); } } }
gale320/staff
das/common/src/ProviderFactory.cpp
C++
apache-2.0
4,315
/* * Copyright 2018, OpenCensus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.opencensus.contrib.appengine.standard.util; import static com.google.common.base.Preconditions.checkNotNull; import com.google.apphosting.api.CloudTraceContext; import com.google.common.annotations.VisibleForTesting; import io.opencensus.trace.SpanContext; import io.opencensus.trace.SpanId; import io.opencensus.trace.TraceId; import io.opencensus.trace.TraceOptions; import io.opencensus.trace.Tracestate; import java.nio.ByteBuffer; /** * Utility class to convert between {@link io.opencensus.trace.SpanContext} and {@link * CloudTraceContext}. * * @since 0.14 */ public final class AppEngineCloudTraceContextUtils { private static final byte[] INVALID_TRACE_ID = TraceIdProto.newBuilder().setHi(0).setLo(0).build().toByteArray(); private static final long INVALID_SPAN_ID = 0L; private static final long INVALID_TRACE_MASK = 0L; private static final Tracestate TRACESTATE_DEFAULT = Tracestate.builder().build(); @VisibleForTesting static final CloudTraceContext INVALID_CLOUD_TRACE_CONTEXT = new CloudTraceContext(INVALID_TRACE_ID, INVALID_SPAN_ID, INVALID_TRACE_MASK); /** * Converts AppEngine {@code CloudTraceContext} to {@code SpanContext}. * * @param cloudTraceContext the AppEngine {@code CloudTraceContext}. * @return the converted {@code SpanContext}. * @since 0.14 */ public static SpanContext fromCloudTraceContext(CloudTraceContext cloudTraceContext) { checkNotNull(cloudTraceContext, "cloudTraceContext"); try { // Extract the trace ID from the binary protobuf CloudTraceContext#traceId. TraceIdProto traceIdProto = TraceIdProto.parseFrom(cloudTraceContext.getTraceId()); ByteBuffer traceIdBuf = ByteBuffer.allocate(TraceId.SIZE); traceIdBuf.putLong(traceIdProto.getHi()); traceIdBuf.putLong(traceIdProto.getLo()); ByteBuffer spanIdBuf = ByteBuffer.allocate(SpanId.SIZE); spanIdBuf.putLong(cloudTraceContext.getSpanId()); return SpanContext.create( TraceId.fromBytes(traceIdBuf.array()), SpanId.fromBytes(spanIdBuf.array()), TraceOptions.builder().setIsSampled(cloudTraceContext.isTraceEnabled()).build(), TRACESTATE_DEFAULT); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw new RuntimeException(e); } } /** * Converts {@code SpanContext} to AppEngine {@code CloudTraceContext}. * * @param spanContext the {@code SpanContext}. * @return the converted AppEngine {@code CloudTraceContext}. * @since 0.14 */ public static CloudTraceContext toCloudTraceContext(SpanContext spanContext) { checkNotNull(spanContext, "spanContext"); ByteBuffer traceIdBuf = ByteBuffer.wrap(spanContext.getTraceId().getBytes()); TraceIdProto traceIdProto = TraceIdProto.newBuilder().setHi(traceIdBuf.getLong()).setLo(traceIdBuf.getLong()).build(); ByteBuffer spanIdBuf = ByteBuffer.wrap(spanContext.getSpanId().getBytes()); return new CloudTraceContext( traceIdProto.toByteArray(), spanIdBuf.getLong(), spanContext.getTraceOptions().isSampled() ? 1L : 0L); } private AppEngineCloudTraceContextUtils() {} }
bogdandrutu/opencensus-java
contrib/appengine_standard_util/src/main/java/io/opencensus/contrib/appengine/standard/util/AppEngineCloudTraceContextUtils.java
Java
apache-2.0
3,787
/* * 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.druid.query.aggregation.post; import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import org.apache.druid.java.util.common.guava.Comparators; import org.apache.druid.math.expr.Expr; import org.apache.druid.math.expr.ExprMacroTable; import org.apache.druid.math.expr.Parser; import org.apache.druid.query.aggregation.AggregatorFactory; import org.apache.druid.query.aggregation.PostAggregator; import org.apache.druid.query.cache.CacheKeyBuilder; import org.apache.druid.utils.CollectionUtils; import javax.annotation.Nullable; import java.util.Comparator; import java.util.Map; import java.util.Objects; import java.util.Set; public class ExpressionPostAggregator implements PostAggregator { private static final Comparator<Comparable> DEFAULT_COMPARATOR = Comparator.nullsFirst( (Comparable o1, Comparable o2) -> { if (o1 instanceof Long && o2 instanceof Long) { return Long.compare((long) o1, (long) o2); } else if (o1 instanceof Number && o2 instanceof Number) { return Double.compare(((Number) o1).doubleValue(), ((Number) o2).doubleValue()); } else { return o1.compareTo(o2); } } ); private final String name; private final String expression; private final Comparator<Comparable> comparator; private final String ordering; private final ExprMacroTable macroTable; private final Map<String, Function<Object, Object>> finalizers; private final Supplier<Expr> parsed; private final Supplier<Set<String>> dependentFields; /** * Constructor for serialization. */ @JsonCreator public ExpressionPostAggregator( @JsonProperty("name") String name, @JsonProperty("expression") String expression, @JsonProperty("ordering") @Nullable String ordering, @JacksonInject ExprMacroTable macroTable ) { this(name, expression, ordering, macroTable, ImmutableMap.of()); } /** * Constructor for {@link #decorate(Map)}. */ private ExpressionPostAggregator( final String name, final String expression, @Nullable final String ordering, final ExprMacroTable macroTable, final Map<String, Function<Object, Object>> finalizers ) { this( name, expression, ordering, macroTable, finalizers, Suppliers.memoize(() -> Parser.parse(expression, macroTable)) ); } private ExpressionPostAggregator( final String name, final String expression, @Nullable final String ordering, final ExprMacroTable macroTable, final Map<String, Function<Object, Object>> finalizers, final Supplier<Expr> parsed ) { this( name, expression, ordering, macroTable, finalizers, parsed, Suppliers.memoize(() -> parsed.get().analyzeInputs().getRequiredBindings())); } private ExpressionPostAggregator( final String name, final String expression, @Nullable final String ordering, final ExprMacroTable macroTable, final Map<String, Function<Object, Object>> finalizers, final Supplier<Expr> parsed, final Supplier<Set<String>> dependentFields ) { Preconditions.checkArgument(expression != null, "expression cannot be null"); this.name = name; this.expression = expression; this.ordering = ordering; this.comparator = ordering == null ? DEFAULT_COMPARATOR : Ordering.valueOf(ordering); this.macroTable = macroTable; this.finalizers = finalizers; this.parsed = parsed; this.dependentFields = dependentFields; } @Override public Set<String> getDependentFields() { return dependentFields.get(); } @Override public Comparator getComparator() { return comparator; } @Override public Object compute(Map<String, Object> values) { // Maps.transformEntries is lazy, will only finalize values we actually read. final Map<String, Object> finalizedValues = Maps.transformEntries( values, (String k, Object v) -> { final Function<Object, Object> finalizer = finalizers.get(k); return finalizer != null ? finalizer.apply(v) : v; } ); return parsed.get().eval(Parser.withMap(finalizedValues)).value(); } @Override @JsonProperty public String getName() { return name; } @Override public ExpressionPostAggregator decorate(final Map<String, AggregatorFactory> aggregators) { return new ExpressionPostAggregator( name, expression, ordering, macroTable, CollectionUtils.mapValues(aggregators, aggregatorFactory -> obj -> aggregatorFactory.finalizeComputation(obj)), parsed, dependentFields ); } @JsonProperty("expression") public String getExpression() { return expression; } @JsonProperty("ordering") public String getOrdering() { return ordering; } @Override public String toString() { return "ExpressionPostAggregator{" + "name='" + name + '\'' + ", expression='" + expression + '\'' + ", ordering=" + ordering + '}'; } @Override public byte[] getCacheKey() { return new CacheKeyBuilder(PostAggregatorIds.EXPRESSION) .appendString(expression) .appendString(ordering) .build(); } public enum Ordering implements Comparator<Comparable> { /** * Ensures the following order: numeric > NaN > Infinite. * * The name may be referenced via Ordering.valueOf(String) in the constructor {@link * ExpressionPostAggregator#ExpressionPostAggregator(String, String, String, ExprMacroTable, Map)}. */ @SuppressWarnings("unused") numericFirst { @Override public int compare(Comparable lhs, Comparable rhs) { if (lhs instanceof Long && rhs instanceof Long) { return Long.compare(((Number) lhs).longValue(), ((Number) rhs).longValue()); } else if (lhs instanceof Number && rhs instanceof Number) { double d1 = ((Number) lhs).doubleValue(); double d2 = ((Number) rhs).doubleValue(); if (Double.isFinite(d1) && !Double.isFinite(d2)) { return 1; } if (!Double.isFinite(d1) && Double.isFinite(d2)) { return -1; } return Double.compare(d1, d2); } else { return Comparators.<Comparable>naturalNullsFirst().compare(lhs, rhs); } } } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ExpressionPostAggregator that = (ExpressionPostAggregator) o; if (!comparator.equals(that.comparator)) { return false; } if (!Objects.equals(name, that.name)) { return false; } if (!Objects.equals(expression, that.expression)) { return false; } if (!Objects.equals(ordering, that.ordering)) { return false; } return true; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + expression.hashCode(); result = 31 * result + comparator.hashCode(); result = 31 * result + (ordering != null ? ordering.hashCode() : 0); return result; } }
deltaprojects/druid
processing/src/main/java/org/apache/druid/query/aggregation/post/ExpressionPostAggregator.java
Java
apache-2.0
8,546
/****************************************************************************** * Copyright (c) 2006, 2010 VMware Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0 * is available at http://www.opensource.org/licenses/apache2.0.php. * You may elect to redistribute this code under either of these licenses. * * Contributors: * VMware Inc. *****************************************************************************/ package org.eclipse.gemini.blueprint.service.importer.support.internal.aop; import org.eclipse.gemini.blueprint.service.importer.ServiceReferenceProxy; import org.eclipse.gemini.blueprint.service.importer.support.internal.util.ServiceComparatorUtil; import org.osgi.framework.Bundle; import org.osgi.framework.ServiceReference; import org.springframework.util.Assert; /** * Simple {@link ServiceReference} proxy which simply does delegation, without any extra features. It's main purpose is * to allow the consistent behaviour between dynamic and static proxies. * * @author Costin Leau * */ public class StaticServiceReferenceProxy implements ServiceReferenceProxy { private static final int HASH_CODE = StaticServiceReferenceProxy.class.hashCode() * 13; private final ServiceReference target; /** * Constructs a new <code>StaticServiceReferenceProxy</code> instance. * * @param target service reference */ public StaticServiceReferenceProxy(ServiceReference target) { Assert.notNull(target); this.target = target; } public Bundle getBundle() { return target.getBundle(); } public Object getProperty(String key) { return target.getProperty(key); } public String[] getPropertyKeys() { return target.getPropertyKeys(); } public Bundle[] getUsingBundles() { return target.getUsingBundles(); } public boolean isAssignableTo(Bundle bundle, String className) { return target.isAssignableTo(bundle, className); } public ServiceReference getTargetServiceReference() { return target; } public boolean equals(Object obj) { if (obj instanceof StaticServiceReferenceProxy) { StaticServiceReferenceProxy other = (StaticServiceReferenceProxy) obj; return (target.equals(other.target)); } return false; } public int hashCode() { return HASH_CODE + target.hashCode(); } public int compareTo(Object other) { return ServiceComparatorUtil.compare(target, other); } }
eclipse/gemini.blueprint
core/src/main/java/org/eclipse/gemini/blueprint/service/importer/support/internal/aop/StaticServiceReferenceProxy.java
Java
apache-2.0
2,728
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Common.Authentication.Abstractions; using Microsoft.Azure.Commands.Sql.AdvancedThreatProtection.Model; using Microsoft.Azure.Commands.Sql.Common; using Microsoft.Azure.Commands.Sql.ThreatDetection.Model; using Microsoft.Azure.Commands.Sql.ThreatDetection.Services; using Microsoft.Azure.Management.Sql.LegacySdk.Models; using Microsoft.Azure.Management.Sql.Models; using System.Linq; namespace Microsoft.Azure.Commands.Sql.AdvancedThreatProtection.Services { /// <summary> /// The SqlAdvancedThreatProtectionAdapter class is responsible for transforming the data that was received form the endpoints to the cmdlets model of AdvancedThreatProtection policy and vice versa /// </summary> public class SqlAdvancedThreatProtectionAdapter { /// <summary> /// Gets or sets the Azure subscription /// </summary> private IAzureSubscription Subscription { get; set; } /// <summary> /// The Threat Detection endpoints communicator used by this adapter /// </summary> private SqlThreatDetectionAdapter SqlThreatDetectionAdapter { get; set; } /// <summary> /// The Azure endpoints communicator used by this adapter /// </summary> private AzureEndpointsCommunicator AzureCommunicator { get; set; } /// <summary> /// Gets or sets the Azure profile /// </summary> public IAzureContext Context { get; set; } public SqlAdvancedThreatProtectionAdapter(IAzureContext context) { Context = context; Subscription = context.Subscription; SqlThreatDetectionAdapter = new SqlThreatDetectionAdapter(Context); } /// <summary> /// Provides a server Advanced Threat Protection policy model for the given database /// </summary> public ServerAdvancedThreatProtectionPolicyModel GetServerAdvancedThreatProtectionPolicy(string resourceGroup, string serverName) { // Currently Advanced Threat Protection policy is a TD policy until the backend will support Advanced Threat Protection APIs var threatDetectionPolicy = SqlThreatDetectionAdapter.GetServerThreatDetectionPolicy(resourceGroup, serverName); var serverAdvancedThreatProtectionPolicyModel = new ServerAdvancedThreatProtectionPolicyModel() { ResourceGroupName = resourceGroup, ServerName = serverName, IsEnabled = (threatDetectionPolicy.ThreatDetectionState == ThreatDetectionStateType.Enabled) }; return serverAdvancedThreatProtectionPolicyModel; } /// <summary> /// Sets a server Advanced Threat Protection policy model for the given database /// </summary> public ServerAdvancedThreatProtectionPolicyModel SetServerAdvancedThreatProtection(ServerAdvancedThreatProtectionPolicyModel model) { // Currently Advanced Threat Protection policy is a TD policy until the backend will support Advanced Threat Protection APIs var threatDetectionPolicy = SqlThreatDetectionAdapter.GetServerThreatDetectionPolicy(model.ResourceGroupName, model.ServerName); threatDetectionPolicy.ThreatDetectionState = model.IsEnabled ? ThreatDetectionStateType.Enabled : ThreatDetectionStateType.Disabled; SqlThreatDetectionAdapter.SetServerThreatDetectionPolicy(threatDetectionPolicy, AzureEnvironment.Endpoint.StorageEndpointSuffix); return model; } } }
AzureAutomationTeam/azure-powershell
src/ResourceManager/Sql/Commands.Sql/AdvancedThreatProtection/Services/SqlAdvancedThreatProtectionAdapter.cs
C#
apache-2.0
4,342
/** * 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.hadoop.hdfs.server.datanode; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.SocketException; import java.nio.channels.FileChannel; import java.util.Arrays; import org.apache.hadoop.fs.ChecksumException; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.protocol.DataTransferProtocol; import org.apache.hadoop.hdfs.protocol.FSConstants; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.net.SocketOutputStream; import org.apache.hadoop.util.ChecksumUtil; import org.apache.hadoop.util.CrcConcat; import org.apache.hadoop.util.DataChecksum; import org.apache.hadoop.util.StringUtils; /** * Read from blocks with separate checksum files. * Block file name: * blk_(blockId) * * Checksum file name: * blk_(blockId)_(generation_stamp).meta * * The on disk file format is: * Data file keeps just data in the block: * * +---------------+ * | | * | Data | * | . | * | . | * | . | * | . | * | . | * | . | * | | * +---------------+ * * Checksum file: * +----------------------+ * | Checksum Header | * +----------------------+ * | Checksum for Chunk 1 | * +----------------------+ * | Checksum for Chunk 2 | * +----------------------+ * | . | * | . | * | . | * +----------------------+ * | Checksum for last | * | Chunk (Partial) | * +----------------------+ * */ public class BlockWithChecksumFileReader extends DatanodeBlockReader { private InputStreamWithChecksumFactory streamFactory; private DataInputStream checksumIn; // checksum datastream private BlockDataFile.Reader blockDataFileReader; boolean useTransferTo = false; MemoizedBlock memoizedBlock; BlockWithChecksumFileReader(int namespaceId, Block block, boolean isFinalized, boolean ignoreChecksum, boolean verifyChecksum, boolean corruptChecksumOk, InputStreamWithChecksumFactory streamFactory) throws IOException { super(namespaceId, block, isFinalized, ignoreChecksum, verifyChecksum, corruptChecksumOk); this.streamFactory = streamFactory; this.checksumIn = streamFactory.getChecksumStream(); this.block = block; } @Override public void fadviseStream(int advise, long offset, long len) throws IOException { blockDataFileReader.posixFadviseIfPossible(offset, len, advise); } private void initializeNullChecksum() { checksumIn = null; // This only decides the buffer size. Use BUFFER_SIZE? checksum = DataChecksum.newDataChecksum(DataChecksum.CHECKSUM_NULL, 16 * 1024); } public DataChecksum getChecksumToSend(long blockLength) throws IOException { if (!corruptChecksumOk || checksumIn != null) { // read and handle the common header here. For now just a version try { BlockMetadataHeader header = BlockMetadataHeader.readHeader(checksumIn); short version = header.getVersion(); if (version != FSDataset.FORMAT_VERSION_NON_INLINECHECKSUM) { LOG.warn("Wrong version (" + version + ") for metadata file for " + block + " ignoring ..."); } checksum = header.getChecksum(); } catch (IOException ioe) { if (blockLength == 0) { initializeNullChecksum(); } else { throw ioe; } } } else { LOG.warn("Could not find metadata file for " + block); initializeNullChecksum(); } super.getChecksumInfo(blockLength); return checksum; } public void initialize(long offset, long blockLength) throws IOException { // seek to the right offsets if (offset > 0) { long checksumSkip = (offset / bytesPerChecksum) * checksumSize; // note blockInStream is seeked when created below if (checksumSkip > 0) { // Should we use seek() for checksum file as well? IOUtils.skipFully(checksumIn, checksumSkip); } } blockDataFileReader = streamFactory.getBlockDataFileReader(); memoizedBlock = new MemoizedBlock(blockLength, streamFactory, block); } public boolean prepareTransferTo() throws IOException { useTransferTo = true; return useTransferTo; } @Override public void sendChunks(OutputStream out, byte[] buf, long offset, int checksumOff, int numChunks, int len, BlockCrcUpdater crcUpdater, int packetVersion) throws IOException { if (packetVersion != DataTransferProtocol.PACKET_VERSION_CHECKSUM_FIRST) { throw new IOException("packet version " + packetVersion + " is not supported by non-inline checksum blocks."); } int checksumLen = numChunks * checksumSize; if (checksumSize > 0 && checksumIn != null) { try { checksumIn.readFully(buf, checksumOff, checksumLen); if (dnData != null) { dnData.recordReadChunkCheckSumTime(); } if (crcUpdater != null) { long tempOffset = offset; long remain = len; for (int i = 0; i < checksumLen; i += checksumSize) { long chunkSize = (remain > bytesPerChecksum) ? bytesPerChecksum : remain; crcUpdater.updateBlockCrc(tempOffset, (int) chunkSize, DataChecksum.getIntFromBytes(buf, checksumOff + i)); remain -= chunkSize; } } } catch (IOException e) { LOG.warn(" Could not read or failed to veirfy checksum for data" + " at offset " + offset + " for block " + block + " got : " + StringUtils.stringifyException(e)); IOUtils.closeStream(checksumIn); checksumIn = null; if (corruptChecksumOk) { if (checksumOff < checksumLen) { // Just fill the array with zeros. Arrays.fill(buf, checksumOff, checksumLen, (byte) 0); if (dnData != null) { dnData.recordReadChunkCheckSumTime(); } } } else { throw e; } } } int dataOff = checksumOff + checksumLen; if (!useTransferTo) { // normal transfer blockDataFileReader.readFully(buf, dataOff, len, offset, true); if (dnData != null) { dnData.recordReadChunkDataTime(); } if (verifyChecksum) { int dOff = dataOff; int cOff = checksumOff; int dLeft = len; for (int i = 0; i < numChunks; i++) { checksum.reset(); int dLen = Math.min(dLeft, bytesPerChecksum); checksum.update(buf, dOff, dLen); if (!checksum.compare(buf, cOff)) { throw new ChecksumException("Checksum failed at " + (offset + len - dLeft), len); } dLeft -= dLen; dOff += dLen; cOff += checksumSize; } if (dnData != null) { dnData.recordVerifyCheckSumTime(); } } // only recompute checksum if we can't trust the meta data due to // concurrent writes if (memoizedBlock.hasBlockChanged(len, offset)) { ChecksumUtil.updateChunkChecksum(buf, checksumOff, dataOff, len, checksum); if (dnData != null) { dnData.recordUpdateChunkCheckSumTime(); } } try { out.write(buf, 0, dataOff + len); if (dnData != null) { dnData.recordSendChunkToClientTime(); } } catch (IOException e) { if (LOG.isDebugEnabled()) { LOG.debug("IOException when reading block " + block + " offset " + offset, e); } throw BlockSender.ioeToSocketException(e); } } else { try { // use transferTo(). Checks on out and blockIn are already done. SocketOutputStream sockOut = (SocketOutputStream) out; if (memoizedBlock.hasBlockChanged(len, offset)) { blockDataFileReader.readFully(buf, dataOff, len, offset, true); if (dnData != null) { dnData.recordReadChunkDataTime(); } ChecksumUtil.updateChunkChecksum(buf, checksumOff, dataOff, len, checksum); if (dnData != null) { dnData.recordUpdateChunkCheckSumTime(); } sockOut.write(buf, 0, dataOff + len); if (dnData != null) { dnData.recordSendChunkToClientTime(); } } else { // first write the packet sockOut.write(buf, 0, dataOff); // no need to flush. since we know out is not a buffered stream. blockDataFileReader.transferToSocketFully(sockOut,offset, len); if (dnData != null) { dnData.recordTransferChunkToClientTime(); } } } catch (IOException e) { if (LOG.isDebugEnabled()) { LOG.debug("IOException when reading block " + block + " offset " + offset, e); } /* * exception while writing to the client (well, with transferTo(), it * could also be while reading from the local file). */ throw BlockSender.ioeToSocketException(e); } } } @Override public int getPreferredPacketVersion() { return DataTransferProtocol.PACKET_VERSION_CHECKSUM_FIRST; } public void close() throws IOException { IOException ioe = null; // close checksum file if (checksumIn != null) { try { checksumIn.close(); } catch (IOException e) { ioe = e; } checksumIn = null; } // throw IOException if there is any if (ioe != null) { throw ioe; } } /** * helper class used to track if a block's meta data is verifiable or not */ class MemoizedBlock { // visible block length private long blockLength; private final Block block; private final InputStreamWithChecksumFactory isf; private MemoizedBlock(long blockLength, InputStreamWithChecksumFactory isf, Block block) { this.blockLength = blockLength; this.isf = isf; this.block = block; } // logic: if we are starting or ending on a partial chunk and the block // has more data than we were told at construction, the block has 'changed' // in a way that we care about (ie, we can't trust crc data) boolean hasBlockChanged(long dataLen, long offset) throws IOException { if (isFinalized) { // We would treat it an error case for a finalized block at open time // has an unmatched size when closing. There might be false positive // for append() case. We made the trade-off to avoid false negative. // always return true so it data integrity is guaranteed by checksum // checking. return false; } // check if we are using transferTo since we tell if the file has changed // (blockInPosition >= 0 => we are using transferTo and File Channels if (useTransferTo) { long currentLength = blockDataFileReader.size(); return (offset % bytesPerChecksum != 0 || dataLen % bytesPerChecksum != 0) && currentLength > blockLength; } else { FSDatasetInterface ds = null; if (isf instanceof DatanodeBlockReader.BlockInputStreamFactory) { ds = ((DatanodeBlockReader.BlockInputStreamFactory) isf).getDataset(); } // offset is the offset into the block return (offset % bytesPerChecksum != 0 || dataLen % bytesPerChecksum != 0) && ds != null && ds.getOnDiskLength(namespaceId, block) > blockLength; } } } public static interface InputStreamWithChecksumFactory extends BlockSender.InputStreamFactory { public InputStream createStream(long offset) throws IOException; public DataInputStream getChecksumStream() throws IOException; } /** Find the metadata file for the specified block file. * Return the generation stamp from the name of the metafile. */ static long getGenerationStampFromSeperateChecksumFile(String[] listdir, String blockName) { for (int j = 0; j < listdir.length; j++) { String path = listdir[j]; if (!path.startsWith(blockName)) { continue; } String[] vals = StringUtils.split(path, '_'); if (vals.length != 3) { // blk, blkid, genstamp.meta continue; } String[] str = StringUtils.split(vals[2], '.'); if (str.length != 2) { continue; } return Long.parseLong(str[0]); } DataNode.LOG.warn("Block " + blockName + " does not have a metafile!"); return Block.GRANDFATHER_GENERATION_STAMP; } /** * Find generation stamp from block file and meta file. * @param blockFile * @param metaFile * @return * @throws IOException */ static long parseGenerationStampInMetaFile(File blockFile, File metaFile ) throws IOException { String metaname = metaFile.getName(); String gs = metaname.substring(blockFile.getName().length() + 1, metaname.length() - FSDataset.METADATA_EXTENSION.length()); try { return Long.parseLong(gs); } catch(NumberFormatException nfe) { throw (IOException)new IOException("blockFile=" + blockFile + ", metaFile=" + metaFile).initCause(nfe); } } /** * This class provides the input stream and length of the metadata * of a block * */ static class MetaDataInputStream extends FilterInputStream { MetaDataInputStream(InputStream stream, long len) { super(stream); length = len; } private long length; public long getLength() { return length; } } static protected File getMetaFile(FSDatasetInterface dataset, int namespaceId, Block b) throws IOException { return BlockWithChecksumFileWriter.getMetaFile(dataset.getBlockFile(namespaceId, b), b); } /** * Does the meta file exist for this block? * @param namespaceId - parent namespace id * @param b - the block * @return true of the metafile for specified block exits * @throws IOException */ static public boolean metaFileExists(FSDatasetInterface dataset, int namespaceId, Block b) throws IOException { return getMetaFile(dataset, namespaceId, b).exists(); } /** * Returns metaData of block b as an input stream (and its length) * @param namespaceId - parent namespace id * @param b - the block * @return the metadata input stream; * @throws IOException */ static public MetaDataInputStream getMetaDataInputStream( FSDatasetInterface dataset, int namespace, Block b) throws IOException { File checksumFile = getMetaFile(dataset, namespace, b); return new MetaDataInputStream(new FileInputStream(checksumFile), checksumFile.length()); } static byte[] getMetaData(FSDatasetInterface dataset, int namespaceId, Block block) throws IOException { MetaDataInputStream checksumIn = null; try { checksumIn = getMetaDataInputStream(dataset, namespaceId, block); long fileSize = checksumIn.getLength(); if (fileSize >= 1L << 31 || fileSize <= 0) { throw new IOException("Unexpected size for checksumFile of block" + block); } byte[] buf = new byte[(int) fileSize]; IOUtils.readFully(checksumIn, buf, 0, buf.length); return buf; } finally { IOUtils.closeStream(checksumIn); } } /** * Calculate CRC Checksum of the whole block. Implemented by concatenating * checksums of all the chunks. * * @param datanode * @param ri * @param namespaceId * @param block * @return * @throws IOException */ static public int getBlockCrc(DataNode datanode, ReplicaToRead ri, int namespaceId, Block block) throws IOException { InputStream rawStreamIn = null; DataInputStream streamIn = null; try { int bytesPerCRC; int checksumSize; long crcPerBlock; rawStreamIn = BlockWithChecksumFileReader.getMetaDataInputStream( datanode.data, namespaceId, block); streamIn = new DataInputStream(new BufferedInputStream(rawStreamIn, FSConstants.BUFFER_SIZE)); final BlockMetadataHeader header = BlockMetadataHeader .readHeader(streamIn); final DataChecksum checksum = header.getChecksum(); if (checksum.getChecksumType() != DataChecksum.CHECKSUM_CRC32) { throw new IOException("File Checksum now is only supported for CRC32"); } bytesPerCRC = checksum.getBytesPerChecksum(); checksumSize = checksum.getChecksumSize(); crcPerBlock = (((BlockWithChecksumFileReader.MetaDataInputStream) rawStreamIn) .getLength() - BlockMetadataHeader.getHeaderSize()) / checksumSize; int blockCrc = 0; byte[] buffer = new byte[checksumSize]; for (int i = 0; i < crcPerBlock; i++) { IOUtils.readFully(streamIn, buffer, 0, buffer.length); int intChecksum = ((buffer[0] & 0xff) << 24) | ((buffer[1] & 0xff) << 16) | ((buffer[2] & 0xff) << 8) | ((buffer[3] & 0xff)); if (i == 0) { blockCrc = intChecksum; } else { int chunkLength; if (i != crcPerBlock - 1 || ri.getBytesVisible() % bytesPerCRC == 0) { chunkLength = bytesPerCRC; } else { chunkLength = (int) ri.getBytesVisible() % bytesPerCRC; } blockCrc = CrcConcat.concatCrc(blockCrc, intChecksum, chunkLength); } } return blockCrc; } finally { if (streamIn != null) { IOUtils.closeStream(streamIn); } if (rawStreamIn != null) { IOUtils.closeStream(rawStreamIn); } } } static long readBlockAccelerator(Socket s, File dataFile, Block block, long startOffset, long length, DataNode datanode) throws IOException { File checksumFile = BlockWithChecksumFileWriter.getMetaFile(dataFile, block); FileInputStream datain = new FileInputStream(dataFile); FileInputStream metain = new FileInputStream(checksumFile); FileChannel dch = datain.getChannel(); FileChannel mch = metain.getChannel(); // read in type of crc and bytes-per-checksum from metadata file int versionSize = 2; // the first two bytes in meta file is the version byte[] cksumHeader = new byte[versionSize + DataChecksum.HEADER_LEN]; int numread = metain.read(cksumHeader); if (numread != versionSize + DataChecksum.HEADER_LEN) { String msg = "readBlockAccelerator: metafile header should be atleast " + (versionSize + DataChecksum.HEADER_LEN) + " bytes " + " but could read only " + numread + " bytes."; LOG.warn(msg); throw new IOException(msg); } DataChecksum ckHdr = DataChecksum.newDataChecksum(cksumHeader, versionSize); int type = ckHdr.getChecksumType(); int bytesPerChecksum = ckHdr.getBytesPerChecksum(); long cheaderSize = DataChecksum.getChecksumHeaderSize(); // align the startOffset with the previous bytesPerChecksum boundary. long delta = startOffset % bytesPerChecksum; startOffset -= delta; length += delta; // align the length to encompass the entire last checksum chunk delta = length % bytesPerChecksum; if (delta != 0) { delta = bytesPerChecksum - delta; length += delta; } // find the offset in the metafile long startChunkNumber = startOffset / bytesPerChecksum; long numChunks = length / bytesPerChecksum; long checksumSize = ckHdr.getChecksumSize(); long startMetaOffset = versionSize + cheaderSize + startChunkNumber * checksumSize; long metaLength = numChunks * checksumSize; // get a connection back to the client SocketOutputStream out = new SocketOutputStream(s, datanode.socketWriteTimeout); try { // write out the checksum type and bytesperchecksum to client // skip the first two bytes that describe the version long val = mch.transferTo(versionSize, cheaderSize, out); if (val != cheaderSize) { String msg = "readBlockAccelerator for block " + block + " at offset " + 0 + " but could not transfer checksum header."; LOG.warn(msg); throw new IOException(msg); } if (LOG.isDebugEnabled()) { LOG.debug("readBlockAccelerator metaOffset " + startMetaOffset + " mlength " + metaLength); } // write out the checksums back to the client val = mch.transferTo(startMetaOffset, metaLength, out); if (val != metaLength) { String msg = "readBlockAccelerator for block " + block + " at offset " + startMetaOffset + " but could not transfer checksums of size " + metaLength + ". Transferred only " + val; LOG.warn(msg); throw new IOException(msg); } if (LOG.isDebugEnabled()) { LOG.debug("readBlockAccelerator dataOffset " + startOffset + " length " + length); } // send data block back to client long read = dch.transferTo(startOffset, length, out); if (read != length) { String msg = "readBlockAccelerator for block " + block + " at offset " + startOffset + " but block size is only " + length + " and could transfer only " + read; LOG.warn(msg); throw new IOException(msg); } return read; } catch ( SocketException ignored ) { // Its ok for remote side to close the connection anytime. datanode.myMetrics.blocksRead.inc(); return -1; } catch ( IOException ioe ) { /* What exactly should we do here? * Earlier version shutdown() datanode if there is disk error. */ LOG.warn(datanode.getDatanodeInfo() + ":readBlockAccelerator:Got exception while serving " + block + " to " + s.getInetAddress() + ":\n" + StringUtils.stringifyException(ioe) ); throw ioe; } finally { IOUtils.closeStream(out); IOUtils.closeStream(datain); IOUtils.closeStream(metain); } } public static boolean isMetaFilename(String name) { return name.startsWith(Block.BLOCK_FILE_PREFIX) && name.endsWith(Block.METADATA_EXTENSION); } /** * Returns array of two longs: the first one is the block id, and the second * one is genStamp. The method workds under assumption that metafile name has * the following format: "blk_<blkid>_<gensmp>.meta" */ public static long[] parseMetafileName(String path) { String[] groundSeparated = StringUtils.split(path, '_'); if (groundSeparated.length != 3) { // blk, blkid, genstamp.meta throw new IllegalArgumentException("Not a valid meta file name"); } String[] dotSeparated = StringUtils.split(groundSeparated[2], '.'); if (dotSeparated.length != 2) { throw new IllegalArgumentException("Not a valid meta file name"); } return new long[] { Long.parseLong(groundSeparated[1]), Long.parseLong(dotSeparated[0]) }; } }
shakamunyi/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/datanode/BlockWithChecksumFileReader.java
Java
apache-2.0
24,443
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.forex.forward; import java.util.Collections; import java.util.Set; import com.google.common.collect.Iterables; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.analytics.financial.forex.derivative.Forex; import com.opengamma.analytics.financial.forex.method.ForexForwardPointsMethod; import com.opengamma.analytics.financial.interestrate.YieldCurveBundle; import com.opengamma.analytics.math.curve.DoublesCurve; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValueProperties.Builder; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.analytics.fxforwardcurve.FXForwardCurveDefinition; import com.opengamma.financial.analytics.model.CalculationPropertyNamesAndValues; import com.opengamma.financial.analytics.model.forex.ForexVisitors; import com.opengamma.financial.analytics.model.fx.FXForwardPointsPVFunction; import com.opengamma.financial.security.FinancialSecurity; import com.opengamma.util.money.CurrencyAmount; import com.opengamma.util.money.MultipleCurrencyAmount; /** * Calculates the present value of an FX forward using the FX forward rates directly. * @deprecated Use {@link FXForwardPointsPVFunction} */ @Deprecated public class FXForwardPointsMethodPresentValueFunction extends FXForwardPointsMethodFunction { private static final ForexForwardPointsMethod CALCULATOR = ForexForwardPointsMethod.getInstance(); public FXForwardPointsMethodPresentValueFunction() { super(ValueRequirementNames.PRESENT_VALUE); } @Override protected Set<ComputedValue> getResult(final Forex fxForward, final YieldCurveBundle data, final DoublesCurve forwardPoints, final ComputationTarget target, final Set<ValueRequirement> desiredValues, final FunctionInputs inputs, final FunctionExecutionContext executionContext, final FXForwardCurveDefinition fxForwardCurveDefinition) { final MultipleCurrencyAmount mca = CALCULATOR.presentValue(fxForward, data, forwardPoints); if (mca.size() != 1) { throw new OpenGammaRuntimeException("Expecting a single value for present value"); } final CurrencyAmount ca = mca.getCurrencyAmounts()[0]; final String currency = ((FinancialSecurity) target.getSecurity()).accept(ForexVisitors.getReceiveCurrencyVisitor()).getCode(); if (!ca.getCurrency().getCode().equals(currency)) { throw new OpenGammaRuntimeException("Property currency did not match result currency"); } final ValueProperties properties = getResultProperties(Iterables.getOnlyElement(desiredValues), currency).get(); final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.PRESENT_VALUE, target.toSpecification(), properties); return Collections.singleton(new ComputedValue(spec, ca.getAmount())); } @Override protected ValueProperties.Builder getResultProperties(final ComputationTarget target) { return createValueProperties() .with(ValuePropertyNames.CALCULATION_METHOD, CalculationPropertyNamesAndValues.FORWARD_POINTS) .withAny(ValuePropertyNames.PAY_CURVE) .withAny(ValuePropertyNames.RECEIVE_CURVE) .withAny(ValuePropertyNames.PAY_CURVE_CALCULATION_CONFIG) .withAny(ValuePropertyNames.RECEIVE_CURVE_CALCULATION_CONFIG) .withAny(ValuePropertyNames.FORWARD_CURVE_NAME) .withAny(ValuePropertyNames.CURRENCY); } @Override protected ValueProperties.Builder getResultProperties(final ComputationTarget target, final String payCurveName, final String receiveCurveName, final String payCurveCalculationConfig, final String receiveCurveCalculationConfig, final String forwardCurveName) { return createValueProperties() .with(ValuePropertyNames.CALCULATION_METHOD, CalculationPropertyNamesAndValues.FORWARD_POINTS) .with(ValuePropertyNames.PAY_CURVE, payCurveName) .with(ValuePropertyNames.RECEIVE_CURVE, receiveCurveName) .with(ValuePropertyNames.PAY_CURVE_CALCULATION_CONFIG, payCurveCalculationConfig) .with(ValuePropertyNames.RECEIVE_CURVE_CALCULATION_CONFIG, receiveCurveCalculationConfig) .with(ValuePropertyNames.FORWARD_CURVE_NAME, forwardCurveName) .with(ValuePropertyNames.CURRENCY, ((FinancialSecurity) target.getSecurity()).accept(ForexVisitors.getReceiveCurrencyVisitor()).getCode()); } protected ValueProperties.Builder getResultProperties(final ValueRequirement desiredValue, final String currency) { final String payCurveName = desiredValue.getConstraint(ValuePropertyNames.PAY_CURVE); final String receiveCurveName = desiredValue.getConstraint(ValuePropertyNames.RECEIVE_CURVE); final String payCurveCalculationConfig = desiredValue.getConstraint(ValuePropertyNames.PAY_CURVE_CALCULATION_CONFIG); final String receiveCurveCalculationConfig = desiredValue.getConstraint(ValuePropertyNames.RECEIVE_CURVE_CALCULATION_CONFIG); final String forwardCurveName = desiredValue.getConstraint(ValuePropertyNames.FORWARD_CURVE_NAME); return createValueProperties() .with(ValuePropertyNames.CALCULATION_METHOD, CalculationPropertyNamesAndValues.FORWARD_POINTS) .with(ValuePropertyNames.PAY_CURVE, payCurveName) .with(ValuePropertyNames.RECEIVE_CURVE, receiveCurveName) .with(ValuePropertyNames.PAY_CURVE_CALCULATION_CONFIG, payCurveCalculationConfig) .with(ValuePropertyNames.RECEIVE_CURVE_CALCULATION_CONFIG, receiveCurveCalculationConfig) .with(ValuePropertyNames.FORWARD_CURVE_NAME, forwardCurveName) .with(ValuePropertyNames.CURRENCY, currency); } @Override protected Builder getResultProperties(final ValueRequirement desiredValue, final ComputationTarget target) { throw new UnsupportedOperationException(); } }
jeorme/OG-Platform
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/forex/forward/FXForwardPointsMethodPresentValueFunction.java
Java
apache-2.0
6,310
/** * Derby - Class org.apache.derbyTesting.functionTests.tests.lang.PrecedenceTest * * 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.derbyTesting.functionTests.tests.lang; import java.sql.SQLException; import java.sql.Statement; import junit.framework.Test; import org.apache.derbyTesting.junit.BaseJDBCTestCase; import org.apache.derbyTesting.junit.JDBC; import org.apache.derbyTesting.junit.TestConfiguration; /** * Test case for precedence.sql.It tests precedence of operators other than and, * or, and not that return boolean. */ public class PrecedenceTest extends BaseJDBCTestCase { public PrecedenceTest(String name) { super(name); } public static Test suite(){ return TestConfiguration.defaultSuite(PrecedenceTest.class); } public void testPrecedence() throws SQLException{ String sql = "create table t1(c11 int)"; Statement st = createStatement(); st.executeUpdate(sql); sql = "insert into t1 values(1)"; assertEquals(1, st.executeUpdate(sql)); sql = "select c11 from t1 where 1 in (1,2,3) = (1=1)"; JDBC.assertSingleValueResultSet(st.executeQuery(sql), "1"); sql = "select c11 from t1 where 'acme widgets' " + "like 'acme%' in ('1=1')"; JDBC.assertSingleValueResultSet(st.executeQuery(sql), "1"); sql = "select c11 from t1 where 1 between -100 " + "and 100 is not null"; JDBC.assertSingleValueResultSet(st.executeQuery(sql), "1"); sql = "select c11 from t1 where exists(select *" + " from (values 1) as t) not in ('1=2')"; JDBC.assertEmpty(st.executeQuery(sql)); st.close(); } }
scnakandala/derby
java/testing/org/apache/derbyTesting/functionTests/tests/lang/PrecedenceTest.java
Java
apache-2.0
2,454
/** * 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.hadoop.fs.s3native; import static org.apache.hadoop.fs.s3native.NativeS3FileSystem.PATH_DELIMITER; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.s3.S3Credentials; import org.apache.hadoop.fs.s3.S3Exception; import org.jets3t.service.S3Service; import org.jets3t.service.S3ServiceException; import org.jets3t.service.ServiceException; import org.jets3t.service.StorageObjectsChunk; import org.jets3t.service.impl.rest.httpclient.RestS3Service; import org.jets3t.service.model.MultipartPart; import org.jets3t.service.model.MultipartUpload; import org.jets3t.service.model.S3Bucket; import org.jets3t.service.model.S3Object; import org.jets3t.service.model.StorageObject; import org.jets3t.service.security.AWSCredentials; import org.jets3t.service.utils.MultipartUtils; @InterfaceAudience.Private @InterfaceStability.Unstable class Jets3tNativeFileSystemStore implements NativeFileSystemStore { private S3Service s3Service; private S3Bucket bucket; private long multipartBlockSize; private boolean multipartEnabled; private long multipartCopyBlockSize; static final long MAX_PART_SIZE = (long)5 * 1024 * 1024 * 1024; public static final Log LOG = LogFactory.getLog(Jets3tNativeFileSystemStore.class); @Override public void initialize(URI uri, Configuration conf) throws IOException { S3Credentials s3Credentials = new S3Credentials(); s3Credentials.initialize(uri, conf); try { AWSCredentials awsCredentials = new AWSCredentials(s3Credentials.getAccessKey(), s3Credentials.getSecretAccessKey()); this.s3Service = new RestS3Service(awsCredentials); } catch (S3ServiceException e) { handleS3ServiceException(e); } multipartEnabled = conf.getBoolean("fs.s3n.multipart.uploads.enabled", false); multipartBlockSize = Math.min( conf.getLong("fs.s3n.multipart.uploads.block.size", 64 * 1024 * 1024), MAX_PART_SIZE); multipartCopyBlockSize = Math.min( conf.getLong("fs.s3n.multipart.copy.block.size", MAX_PART_SIZE), MAX_PART_SIZE); bucket = new S3Bucket(uri.getHost()); } @Override public void storeFile(String key, File file, byte[] md5Hash) throws IOException { if (multipartEnabled && file.length() >= multipartBlockSize) { storeLargeFile(key, file, md5Hash); return; } BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); S3Object object = new S3Object(key); object.setDataInputStream(in); object.setContentType("binary/octet-stream"); object.setContentLength(file.length()); if (md5Hash != null) { object.setMd5Hash(md5Hash); } s3Service.putObject(bucket, object); } catch (S3ServiceException e) { handleS3ServiceException(e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } } } public void storeLargeFile(String key, File file, byte[] md5Hash) throws IOException { S3Object object = new S3Object(key); object.setDataInputFile(file); object.setContentType("binary/octet-stream"); object.setContentLength(file.length()); if (md5Hash != null) { object.setMd5Hash(md5Hash); } List<StorageObject> objectsToUploadAsMultipart = new ArrayList<StorageObject>(); objectsToUploadAsMultipart.add(object); MultipartUtils mpUtils = new MultipartUtils(multipartBlockSize); try { mpUtils.uploadObjects(bucket.getName(), s3Service, objectsToUploadAsMultipart, null); } catch (ServiceException e) { handleServiceException(e); } catch (Exception e) { throw new S3Exception(e); } } @Override public void storeEmptyFile(String key) throws IOException { try { S3Object object = new S3Object(key); object.setDataInputStream(new ByteArrayInputStream(new byte[0])); object.setContentType("binary/octet-stream"); object.setContentLength(0); s3Service.putObject(bucket, object); } catch (S3ServiceException e) { handleS3ServiceException(e); } } @Override public FileMetadata retrieveMetadata(String key) throws IOException { StorageObject object = null; try { if(LOG.isDebugEnabled()) { LOG.debug("Getting metadata for key: " + key + " from bucket:" + bucket.getName()); } object = s3Service.getObjectDetails(bucket.getName(), key); return new FileMetadata(key, object.getContentLength(), object.getLastModifiedDate().getTime()); } catch (ServiceException e) { // Following is brittle. Is there a better way? if ("NoSuchKey".equals(e.getErrorCode())) { return null; //return null if key not found } handleServiceException(e); return null; //never returned - keep compiler happy } finally { if (object != null) { object.closeDataInputStream(); } } } /** * @param key * The key is the object name that is being retrieved from the S3 bucket * @return * This method returns null if the key is not found * @throws IOException */ @Override public InputStream retrieve(String key) throws IOException { try { if(LOG.isDebugEnabled()) { LOG.debug("Getting key: " + key + " from bucket:" + bucket.getName()); } S3Object object = s3Service.getObject(bucket.getName(), key); return object.getDataInputStream(); } catch (ServiceException e) { handleServiceException(key, e); return null; //return null if key not found } } /** * * @param key * The key is the object name that is being retrieved from the S3 bucket * @return * This method returns null if the key is not found * @throws IOException */ @Override public InputStream retrieve(String key, long byteRangeStart) throws IOException { try { if(LOG.isDebugEnabled()) { LOG.debug("Getting key: " + key + " from bucket:" + bucket.getName() + " with byteRangeStart: " + byteRangeStart); } S3Object object = s3Service.getObject(bucket, key, null, null, null, null, byteRangeStart, null); return object.getDataInputStream(); } catch (ServiceException e) { handleServiceException(key, e); return null; //return null if key not found } } @Override public PartialListing list(String prefix, int maxListingLength) throws IOException { return list(prefix, maxListingLength, null, false); } @Override public PartialListing list(String prefix, int maxListingLength, String priorLastKey, boolean recurse) throws IOException { return list(prefix, recurse ? null : PATH_DELIMITER, maxListingLength, priorLastKey); } /** * * @return * This method returns null if the list could not be populated * due to S3 giving ServiceException * @throws IOException */ private PartialListing list(String prefix, String delimiter, int maxListingLength, String priorLastKey) throws IOException { try { if (prefix.length() > 0 && !prefix.endsWith(PATH_DELIMITER)) { prefix += PATH_DELIMITER; } StorageObjectsChunk chunk = s3Service.listObjectsChunked(bucket.getName(), prefix, delimiter, maxListingLength, priorLastKey); FileMetadata[] fileMetadata = new FileMetadata[chunk.getObjects().length]; for (int i = 0; i < fileMetadata.length; i++) { StorageObject object = chunk.getObjects()[i]; fileMetadata[i] = new FileMetadata(object.getKey(), object.getContentLength(), object.getLastModifiedDate().getTime()); } return new PartialListing(chunk.getPriorLastKey(), fileMetadata, chunk.getCommonPrefixes()); } catch (S3ServiceException e) { handleS3ServiceException(e); return null; //never returned - keep compiler happy } catch (ServiceException e) { handleServiceException(e); return null; //return null if list could not be populated } } @Override public void delete(String key) throws IOException { try { if(LOG.isDebugEnabled()) { LOG.debug("Deleting key:" + key + "from bucket" + bucket.getName()); } s3Service.deleteObject(bucket, key); } catch (ServiceException e) { handleServiceException(key, e); } } public void rename(String srcKey, String dstKey) throws IOException { try { s3Service.renameObject(bucket.getName(), srcKey, new S3Object(dstKey)); } catch (ServiceException e) { handleServiceException(e); } } @Override public void copy(String srcKey, String dstKey) throws IOException { try { if(LOG.isDebugEnabled()) { LOG.debug("Copying srcKey: " + srcKey + "to dstKey: " + dstKey + "in bucket: " + bucket.getName()); } if (multipartEnabled) { S3Object object = s3Service.getObjectDetails(bucket, srcKey, null, null, null, null); if (multipartCopyBlockSize > 0 && object.getContentLength() > multipartCopyBlockSize) { copyLargeFile(object, dstKey); return; } } s3Service.copyObject(bucket.getName(), srcKey, bucket.getName(), new S3Object(dstKey), false); } catch (ServiceException e) { handleServiceException(srcKey, e); } } public void copyLargeFile(S3Object srcObject, String dstKey) throws IOException { try { long partCount = srcObject.getContentLength() / multipartCopyBlockSize + (srcObject.getContentLength() % multipartCopyBlockSize > 0 ? 1 : 0); MultipartUpload multipartUpload = s3Service.multipartStartUpload (bucket.getName(), dstKey, srcObject.getMetadataMap()); List<MultipartPart> listedParts = new ArrayList<MultipartPart>(); for (int i = 0; i < partCount; i++) { long byteRangeStart = i * multipartCopyBlockSize; long byteLength; if (i < partCount - 1) { byteLength = multipartCopyBlockSize; } else { byteLength = srcObject.getContentLength() % multipartCopyBlockSize; if (byteLength == 0) { byteLength = multipartCopyBlockSize; } } MultipartPart copiedPart = s3Service.multipartUploadPartCopy (multipartUpload, i + 1, bucket.getName(), srcObject.getKey(), null, null, null, null, byteRangeStart, byteRangeStart + byteLength - 1, null); listedParts.add(copiedPart); } Collections.reverse(listedParts); s3Service.multipartCompleteUpload(multipartUpload, listedParts); } catch (ServiceException e) { handleServiceException(e); } } @Override public void purge(String prefix) throws IOException { try { S3Object[] objects = s3Service.listObjects(bucket.getName(), prefix, null); for (S3Object object : objects) { s3Service.deleteObject(bucket, object.getKey()); } } catch (S3ServiceException e) { handleS3ServiceException(e); } } @Override public void dump() throws IOException { StringBuilder sb = new StringBuilder("S3 Native Filesystem, "); sb.append(bucket.getName()).append("\n"); try { S3Object[] objects = s3Service.listObjects(bucket.getName()); for (S3Object object : objects) { sb.append(object.getKey()).append("\n"); } } catch (S3ServiceException e) { handleS3ServiceException(e); } System.out.println(sb); } private void handleServiceException(String key, ServiceException e) throws IOException { if ("NoSuchKey".equals(e.getErrorCode())) { throw new FileNotFoundException("Key '" + key + "' does not exist in S3"); } else { handleServiceException(e); } } private void handleS3ServiceException(S3ServiceException e) throws IOException { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } else { if(LOG.isDebugEnabled()) { LOG.debug("S3 Error code: " + e.getS3ErrorCode() + "; S3 Error message: " + e.getS3ErrorMessage()); } throw new S3Exception(e); } } private void handleServiceException(ServiceException e) throws IOException { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } else { if(LOG.isDebugEnabled()) { LOG.debug("Got ServiceException with Error code: " + e.getErrorCode() + ";and Error message: " + e.getErrorMessage()); } } } }
songweijia/fffs
sources/hadoop-2.4.1-src/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/s3native/Jets3tNativeFileSystemStore.java
Java
apache-2.0
14,116
# Copyright 2014-2015 Canonical Limited. # # 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. # Bootstrap charm-helpers, installing its dependencies if necessary using # only standard libraries. import subprocess import sys try: import six # flake8: noqa except ImportError: if sys.version_info.major == 2: subprocess.check_call(['apt-get', 'install', '-y', 'python-six']) else: subprocess.check_call(['apt-get', 'install', '-y', 'python3-six']) import six # flake8: noqa try: import yaml # flake8: noqa except ImportError: if sys.version_info.major == 2: subprocess.check_call(['apt-get', 'install', '-y', 'python-yaml']) else: subprocess.check_call(['apt-get', 'install', '-y', 'python3-yaml']) import yaml # flake8: noqa
CanonicalBootStack/charm-hacluster
tests/charmhelpers/__init__.py
Python
apache-2.0
1,285
/* * 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.cassandra.auth; import java.util.Map; import java.util.Set; import com.google.common.collect.Iterables; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.schema.KeyspaceParams; import org.apache.cassandra.schema.SchemaConstants; import org.apache.cassandra.schema.TableMetadata; import org.apache.cassandra.service.StorageService; import static org.apache.cassandra.auth.AuthTestUtils.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class CassandraRoleManagerTest { @BeforeClass public static void setupClass() { SchemaLoader.prepareServer(); // create the system_auth keyspace so the IRoleManager can function as normal SchemaLoader.createKeyspace(SchemaConstants.AUTH_KEYSPACE_NAME, KeyspaceParams.simple(1), Iterables.toArray(AuthKeyspace.metadata().tables, TableMetadata.class)); // We start StorageService because confirmFastRoleSetup confirms that CassandraRoleManager will // take a faster path once the cluster is already setup, which includes checking MessagingService // and issuing queries with QueryProcessor.process, which uses TokenMetadata DatabaseDescriptor.daemonInitialization(); StorageService.instance.initServer(0); AuthCacheService.initializeAndRegisterCaches(); } @Before public void setup() throws Exception { ColumnFamilyStore.getIfExists(SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES).truncateBlocking(); ColumnFamilyStore.getIfExists(SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLE_MEMBERS).truncateBlocking(); } @Test public void getGrantedRolesImplMinimizesReads() { // IRoleManager::getRoleDetails was not in the initial API, so a default impl // was added which uses the existing methods on IRoleManager as primitive to // construct the Role objects. While this will work for any IRoleManager impl // it is inefficient, so CassandraRoleManager has its own implementation which // collects all of the necessary info with a single query for each granted role. // This just tests that that is the case, i.e. we perform 1 read per role in the // transitive set of granted roles IRoleManager roleManager = new AuthTestUtils.LocalCassandraRoleManager(); roleManager.setup(); for (RoleResource r : ALL_ROLES) roleManager.createRole(AuthenticatedUser.ANONYMOUS_USER, r, new RoleOptions()); // simple role with no grants fetchRolesAndCheckReadCount(roleManager, ROLE_A); // single level of grants grantRolesTo(roleManager, ROLE_A, ROLE_B, ROLE_C); fetchRolesAndCheckReadCount(roleManager, ROLE_A); // multi level role hierarchy grantRolesTo(roleManager, ROLE_B, ROLE_B_1, ROLE_B_2, ROLE_B_3); grantRolesTo(roleManager, ROLE_C, ROLE_C_1, ROLE_C_2, ROLE_C_3); fetchRolesAndCheckReadCount(roleManager, ROLE_A); // Check that when granted roles appear multiple times in parallel levels of the hierarchy, we don't // do redundant reads. E.g. here role_b_1, role_b_2 and role_b3 are granted to both role_b and role_c // but we only want to actually read them once grantRolesTo(roleManager, ROLE_C, ROLE_B_1, ROLE_B_2, ROLE_B_3); fetchRolesAndCheckReadCount(roleManager, ROLE_A); } private void fetchRolesAndCheckReadCount(IRoleManager roleManager, RoleResource primaryRole) { long before = getRolesReadCount(); Set<Role> granted = roleManager.getRoleDetails(primaryRole); long after = getRolesReadCount(); assertEquals(granted.size(), after - before); } @Test public void confirmFastRoleSetup() { IRoleManager roleManager = new AuthTestUtils.LocalCassandraRoleManager(); roleManager.setup(); for (RoleResource r : ALL_ROLES) roleManager.createRole(AuthenticatedUser.ANONYMOUS_USER, r, new RoleOptions()); CassandraRoleManager crm = new CassandraRoleManager(); assertTrue("Expected the role manager to have existing roles before CassandraRoleManager setup", CassandraRoleManager.hasExistingRoles()); } @Test public void warmCacheLoadsAllEntries() { IRoleManager roleManager = new AuthTestUtils.LocalCassandraRoleManager(); roleManager.setup(); for (RoleResource r : ALL_ROLES) roleManager.createRole(AuthenticatedUser.ANONYMOUS_USER, r, new RoleOptions()); // Multi level role hierarchy grantRolesTo(roleManager, ROLE_B, ROLE_B_1, ROLE_B_2, ROLE_B_3); grantRolesTo(roleManager, ROLE_C, ROLE_C_1, ROLE_C_2, ROLE_C_3); // Use CassandraRoleManager to get entries for pre-warming a cache, then verify those entries CassandraRoleManager crm = new CassandraRoleManager(); crm.setup(); Map<RoleResource, Set<Role>> cacheEntries = crm.bulkLoader().get(); Set<Role> roleBRoles = cacheEntries.get(ROLE_B); assertRoleSet(roleBRoles, ROLE_B, ROLE_B_1, ROLE_B_2, ROLE_B_3); Set<Role> roleCRoles = cacheEntries.get(ROLE_C); assertRoleSet(roleCRoles, ROLE_C, ROLE_C_1, ROLE_C_2, ROLE_C_3); for (RoleResource r : ALL_ROLES) { // We already verified ROLE_B and ROLE_C if (r.equals(ROLE_B) || r.equals(ROLE_C)) continue; // Check the cache entries for the roles without any further grants assertRoleSet(cacheEntries.get(r), r); } } @Test public void warmCacheWithEmptyTable() { CassandraRoleManager crm = new CassandraRoleManager(); crm.setup(); Map<RoleResource, Set<Role>> cacheEntries = crm.bulkLoader().get(); assertTrue(cacheEntries.isEmpty()); } private void assertRoleSet(Set<Role> actual, RoleResource...expected) { assertEquals(expected.length, actual.size()); for (RoleResource expectedRole : expected) assertTrue(actual.stream().anyMatch(role -> role.resource.equals(expectedRole))); } }
belliottsmith/cassandra
test/unit/org/apache/cassandra/auth/CassandraRoleManagerTest.java
Java
apache-2.0
7,254
<?php /* * Copyright 2014 Google Inc. * * 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. */ class Google_Service_CloudKMS_KeyOperationAttestation extends Google_Model { protected $certChainsType = 'Google_Service_CloudKMS_CertificateChains'; protected $certChainsDataType = ''; public $content; public $format; /** * @param Google_Service_CloudKMS_CertificateChains */ public function setCertChains(Google_Service_CloudKMS_CertificateChains $certChains) { $this->certChains = $certChains; } /** * @return Google_Service_CloudKMS_CertificateChains */ public function getCertChains() { return $this->certChains; } public function setContent($content) { $this->content = $content; } public function getContent() { return $this->content; } public function setFormat($format) { $this->format = $format; } public function getFormat() { return $this->format; } }
tsugiproject/tsugi
vendor/google/apiclient-services/src/Google/Service/CloudKMS/KeyOperationAttestation.php
PHP
apache-2.0
1,447
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- using System.Management.Automation; using Microsoft.Azure.Commands.TrafficManager.Models; using Microsoft.Azure.Commands.TrafficManager.Utilities; using ProjectResources = Microsoft.Azure.Commands.TrafficManager.Properties.Resources; namespace Microsoft.Azure.Commands.TrafficManager { [Cmdlet(VerbsCommon.Remove, "AzureRmTrafficManagerEndpointConfig"), OutputType(typeof(TrafficManagerProfile))] public class RemoveAzureTrafficManagerEndpointConfig : TrafficManagerBaseCmdlet { [Parameter(Mandatory = true, HelpMessage = "The name of the endpoint.")] [ValidateNotNullOrEmpty] public string EndpointName { get; set; } [Parameter(Mandatory = true, ValueFromPipeline = true, HelpMessage = "The profile.")] [ValidateNotNullOrEmpty] public TrafficManagerProfile TrafficManagerProfile { get; set; } public override void ExecuteCmdlet() { if (this.TrafficManagerProfile.Endpoints == null) { throw new PSArgumentException(string.Format(ProjectResources.Error_EndpointNotFound, this.EndpointName)); } int endpointsRemoved = this.TrafficManagerProfile.Endpoints.RemoveAll(endpoint => string.Equals(this.EndpointName, endpoint.Name)); if (endpointsRemoved == 0) { throw new PSArgumentException(string.Format(ProjectResources.Error_EndpointNotFound, this.EndpointName)); } this.WriteVerbose(ProjectResources.Success); this.WriteObject(this.TrafficManagerProfile); } } }
dulems/azure-powershell
src/ResourceManager/TrafficManager/Commands.TrafficManager2/Endpoint/RemoveAzureTrafficManagerEndpointConfig.cs
C#
apache-2.0
2,353
cask 'hunt-x' do version :latest sha256 :no_check url 'http://huntx.mobilefirst.in/Apps/Hunt%20X.zip' name 'Hunt X' homepage 'http://huntx.mobilefirst.in/' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder app 'Hunt X.app' end
jppelteret/homebrew-cask
Casks/hunt-x.rb
Ruby
bsd-2-clause
307
class Libwebsockets < Formula desc "C websockets server library" homepage "https://libwebsockets.org" url "https://github.com/warmcat/libwebsockets/archive/v3.1.0.tar.gz" sha256 "db948be74c78fc13f1f1a55e76707d7baae3a1c8f62b625f639e8f2736298324" head "https://github.com/warmcat/libwebsockets.git" bottle do sha256 "c3dee13c27c98c87853ec9d1cbd3db27473c3fee1b0870260dc6c47294dd95e4" => :mojave sha256 "fce83552c866222ad1386145cdd9745b82efc0c0a97b89b9069b98928241e893" => :high_sierra sha256 "a57218f16bde1f484648fd7893d99d3dafc5c0ade4902c7ce442019b9782dc66" => :sierra end depends_on "cmake" => :build depends_on "libevent" depends_on "libuv" depends_on "openssl" def install system "cmake", ".", *std_cmake_args, "-DLWS_IPV6=ON", "-DLWS_WITH_HTTP2=ON", "-DLWS_WITH_LIBEVENT=ON", "-DLWS_WITH_LIBUV=ON", "-DLWS_WITH_PLUGINS=ON", "-DLWS_WITHOUT_TESTAPPS=ON", "-DLWS_UNIX_SOCK=ON" system "make" system "make", "install" end test do (testpath/"test.c").write <<~EOS #include <openssl/ssl.h> #include <libwebsockets.h> int main() { struct lws_context_creation_info info; memset(&info, 0, sizeof(info)); struct lws_context *context; context = lws_create_context(&info); lws_context_destroy(context); return 0; } EOS system ENV.cc, "test.c", "-I#{Formula["openssl"].opt_prefix}/include", "-L#{lib}", "-lwebsockets", "-o", "test" system "./test" end end
adamliter/homebrew-core
Formula/libwebsockets.rb
Ruby
bsd-2-clause
1,637