repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
imgstack/stackpath-cdn-go
client/cdn/disconnect_scope_from_origin_responses.go
// Code generated by go-swagger; DO NOT EDIT. package cdn // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/runtime" "github.com/go-openapi/strfmt" "github.com/renderinc/stackpath-cdn-go/models" ) // DisconnectScopeFromOriginReader is a Reader for the DisconnectScopeFromOrigin structure. type DisconnectScopeFromOriginReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *DisconnectScopeFromOriginReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 204: result := NewDisconnectScopeFromOriginNoContent() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 401: result := NewDisconnectScopeFromOriginUnauthorized() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 500: result := NewDisconnectScopeFromOriginInternalServerError() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: result := NewDisconnectScopeFromOriginDefault(response.Code()) if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } if response.Code()/100 == 2 { return result, nil } return nil, result } } // NewDisconnectScopeFromOriginNoContent creates a DisconnectScopeFromOriginNoContent with default headers values func NewDisconnectScopeFromOriginNoContent() *DisconnectScopeFromOriginNoContent { return &DisconnectScopeFromOriginNoContent{} } /* DisconnectScopeFromOriginNoContent describes a response with status code 204, with default header values. No content */ type DisconnectScopeFromOriginNoContent struct { } func (o *DisconnectScopeFromOriginNoContent) Error() string { return fmt.Sprintf("[DELETE /cdn/v1/stacks/{stack_id}/sites/{site_id}/scopes/{scope_id}/origins/{origin_id}][%d] disconnectScopeFromOriginNoContent ", 204) } func (o *DisconnectScopeFromOriginNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil } // NewDisconnectScopeFromOriginUnauthorized creates a DisconnectScopeFromOriginUnauthorized with default headers values func NewDisconnectScopeFromOriginUnauthorized() *DisconnectScopeFromOriginUnauthorized { return &DisconnectScopeFromOriginUnauthorized{} } /* DisconnectScopeFromOriginUnauthorized describes a response with status code 401, with default header values. Returned when an unauthorized request is attempted. */ type DisconnectScopeFromOriginUnauthorized struct { Payload *models.APIStatus } func (o *DisconnectScopeFromOriginUnauthorized) Error() string { return fmt.Sprintf("[DELETE /cdn/v1/stacks/{stack_id}/sites/{site_id}/scopes/{scope_id}/origins/{origin_id}][%d] disconnectScopeFromOriginUnauthorized %+v", 401, o.Payload) } func (o *DisconnectScopeFromOriginUnauthorized) GetPayload() *models.APIStatus { return o.Payload } func (o *DisconnectScopeFromOriginUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIStatus) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewDisconnectScopeFromOriginInternalServerError creates a DisconnectScopeFromOriginInternalServerError with default headers values func NewDisconnectScopeFromOriginInternalServerError() *DisconnectScopeFromOriginInternalServerError { return &DisconnectScopeFromOriginInternalServerError{} } /* DisconnectScopeFromOriginInternalServerError describes a response with status code 500, with default header values. Internal server error. */ type DisconnectScopeFromOriginInternalServerError struct { Payload *models.APIStatus } func (o *DisconnectScopeFromOriginInternalServerError) Error() string { return fmt.Sprintf("[DELETE /cdn/v1/stacks/{stack_id}/sites/{site_id}/scopes/{scope_id}/origins/{origin_id}][%d] disconnectScopeFromOriginInternalServerError %+v", 500, o.Payload) } func (o *DisconnectScopeFromOriginInternalServerError) GetPayload() *models.APIStatus { return o.Payload } func (o *DisconnectScopeFromOriginInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIStatus) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewDisconnectScopeFromOriginDefault creates a DisconnectScopeFromOriginDefault with default headers values func NewDisconnectScopeFromOriginDefault(code int) *DisconnectScopeFromOriginDefault { return &DisconnectScopeFromOriginDefault{ _statusCode: code, } } /* DisconnectScopeFromOriginDefault describes a response with status code -1, with default header values. Default error structure. */ type DisconnectScopeFromOriginDefault struct { _statusCode int Payload *models.APIStatus } // Code gets the status code for the disconnect scope from origin default response func (o *DisconnectScopeFromOriginDefault) Code() int { return o._statusCode } func (o *DisconnectScopeFromOriginDefault) Error() string { return fmt.Sprintf("[DELETE /cdn/v1/stacks/{stack_id}/sites/{site_id}/scopes/{scope_id}/origins/{origin_id}][%d] DisconnectScopeFromOrigin default %+v", o._statusCode, o.Payload) } func (o *DisconnectScopeFromOriginDefault) GetPayload() *models.APIStatus { return o.Payload } func (o *DisconnectScopeFromOriginDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIStatus) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil }
npocmaka/Windows-Server-2003
windows/appcompat/appverifier/dbsupport.h
<filename>windows/appcompat/appverifier/dbsupport.h #ifndef __APPVERIFIER_DBSUPPORT_H_ #define __APPVERIFIER_DBSUPPORT_H_ typedef enum { TEST_SHIM, TEST_KERNEL } TestType; class CIncludeInfo { public: wstring strModule; BOOL bInclude; CIncludeInfo(void) : bInclude(TRUE) {} }; typedef vector<CIncludeInfo> CIncludeArray; typedef vector<wstring> CWStringArray; class CTestInfo { public: // // valid for all tests // TestType eTestType; wstring strTestName; wstring strTestDescription; wstring strTestFriendlyName; BOOL bDefault; // is this test turned on by default? BOOL bWin2KCompatible; // can this test be run on Win2K? BOOL bRunAlone; // should this test be run alone? BOOL bSetupOK; // can this test be run on a setup app? BOOL bNonSetupOK; // can this test be run on a non-setup app? BOOL bPseudoShim; // this test is not a shim, and shouldn't be applied to apps BOOL bNonTest; // this is not a test at all, and is only in the list to provide an options page BOOL bInternal; // this test is appropriate for internal MS NTDEV use BOOL bExternal; // this test is appropriate for external (non MS or non NTDEV) use // // if type is TEST_SHIM, the following are valid // wstring strDllName; CIncludeArray aIncludes; WORD wVersionHigh; WORD wVersionLow; PROPSHEETPAGE PropSheetPage; // // if type is TEST_KERNEL, the following are valid // DWORD dwKernelFlag; CTestInfo(void) : eTestType(TEST_SHIM), dwKernelFlag(0), bDefault(TRUE), wVersionHigh(0), wVersionLow(0), bWin2KCompatible(TRUE), bRunAlone(FALSE), bSetupOK(TRUE), bNonSetupOK(TRUE), bPseudoShim(FALSE), bNonTest(FALSE), bInternal(TRUE), bExternal(TRUE) { ZeroMemory(&PropSheetPage, sizeof(PROPSHEETPAGE)); PropSheetPage.dwSize = sizeof(PROPSHEETPAGE); } }; typedef vector<CTestInfo> CTestInfoArray; class CAVAppInfo { public: wstring wstrExeName; wstring wstrExePath; // optional DWORD dwRegFlags; CWStringArray awstrShims; //BOOL bClearSessionLogBeforeRun; BOOL bBreakOnLog; BOOL bFullPageHeap; BOOL bUseAVDebugger; BOOL bPropagateTests; wstring wstrDebugger; CAVAppInfo() : dwRegFlags(0), bBreakOnLog(FALSE), bFullPageHeap(FALSE), bUseAVDebugger(FALSE), bPropagateTests(FALSE) {} void AddTest(CTestInfo &Test) { if (Test.eTestType == TEST_KERNEL) { dwRegFlags |= Test.dwKernelFlag; } else { for (wstring *pStr = awstrShims.begin(); pStr != awstrShims.end(); ++pStr) { if (*pStr == Test.strTestName) { return; } } // not found, so add awstrShims.push_back(Test.strTestName); } } void RemoveTest(CTestInfo &Test) { if (Test.eTestType == TEST_KERNEL) { dwRegFlags &= ~(Test.dwKernelFlag); } else { for (wstring *pStr = awstrShims.begin(); pStr != awstrShims.end(); ++pStr) { if (*pStr == Test.strTestName) { awstrShims.erase(pStr); return; } } } } BOOL IsTestActive(CTestInfo &Test) { if (Test.eTestType == TEST_KERNEL) { return (dwRegFlags & Test.dwKernelFlag) == Test.dwKernelFlag; } else { for (wstring *pStr = awstrShims.begin(); pStr != awstrShims.end(); ++pStr) { if (*pStr == Test.strTestName) { return TRUE; } } return FALSE; } } }; typedef vector<CAVAppInfo> CAVAppInfoArray; typedef struct _KERNEL_TEST_INFO { ULONG m_uFriendlyNameStringId; ULONG m_uDescriptionStringId; DWORD m_dwBit; BOOL m_bDefault; LPWSTR m_szCommandLine; BOOL m_bWin2KCompatible; } KERNEL_TEST_INFO, *PKERNEL_TEST_INFO; extern CAVAppInfoArray g_aAppInfo; extern CTestInfoArray g_aTestInfo; void ResetVerifierLog(void); BOOL InitTestInfo(void); void GetCurrentAppSettings(void); void SetCurrentAppSettings(void); BOOL AppCompatWriteShimSettings( CAVAppInfoArray& arrAppInfo, BOOL b32bitOnly ); BOOL AppCompatDeleteSettings( void ); #endif // __APPVERIFIER_DBSUPPORT_H_
JungleComputing/mpj
benchmarks/src/montecarlo/AppDemo.java
<reponame>JungleComputing/mpj /* $Id$ */ /************************************************************************** * * * Java Grande Forum Benchmark Suite - MPJ Version 1.0 * * * * produced by * * * * Java Grande Benchmarking Project * * * * at * * * * Edinburgh Parallel Computing Centre * * * * email: <EMAIL> * * * * Original version of this code by <NAME> (<EMAIL>) * * * * This version copyright (c) The University of Edinburgh, 2001. * * All rights reserved. * * * **************************************************************************/ /************************************************************************** * Ported to MPJ: * * <NAME> * * Vrije Universiteit Amsterdam Department of Computer Science * * 19/06/2005 * **************************************************************************/ package montecarlo; import ibis.mpj.MPJ; import ibis.mpj.MPJException; import java.util.Vector; /** * Code, a test-harness for invoking and driving the Applications Demonstrator * classes. * * <p> * To do: * <ol> * <li>Very long delay prior to connecting to the server.</li> * <li>Some text output seem to struggle to get out, without the user tapping * ENTER on the keyboard!</li> * </ol> * * @author <NAME> * @version $Revision$ $Date: 2008-05-30 15:35:35 +0200 (Fri, 30 May * 2008) $ */ public class AppDemo extends Universal { // ------------------------------------------------------------------------ // Class variables. // ------------------------------------------------------------------------ public static double JGFavgExpectedReturnRateMC = 0.0; /** * A class variable. */ public static boolean DEBUG = true; /** * The prompt to write before any debug messages. */ protected static String prompt = "AppDemo> "; public static final int Serial = 1; // ------------------------------------------------------------------------ // Instance variables. // ------------------------------------------------------------------------ /** * Directory in which to find the historical rates. */ private String dataDirname; /** * Name of the historical rate to model. */ private String dataFilename; /** * The number of time-steps which the Monte Carlo simulation should run for. */ private int nTimeStepsMC = 0; /** * The number of Monte Carlo simulations to run. */ private int nRunsMC = 0; /** * The max no of Monte Carlo simulations per process */ private int p_nRunsMC = 0; /** * The default duration between time-steps, in units of a year. */ private double dTime = 1.0 / 365.0; private Vector<Object> tasks; private Vector<ToResult> results; /** * temporary vector for MPJ */ @SuppressWarnings("unchecked") private Vector[] p_results = new Vector[1]; public AppDemo(String dataDirname, String dataFilename, int nTimeStepsMC, int nRunsMC) { this.dataDirname = dataDirname; this.dataFilename = dataFilename; this.nTimeStepsMC = nTimeStepsMC; this.nRunsMC = nRunsMC; set_prompt(prompt); set_DEBUG(DEBUG); } /** * Single point of contact for running this increasingly bloated class. * Other run modes can later be defined for whether a new rate should be * loaded in, etc. Note that if the <code>hostname</code> is set to the * string "none", then the demonstrator runs in purely serial mode. */ /** * Initialisation and Run methods. */ PriceStock psMC; double pathStartValue = 100.0; double avgExpectedReturnRateMC = 0.0; double avgVolatilityMC = 0.0; ToInitAllTasks initAllTasks = null; public void initSerial() { try { // // Measure the requested path rate. RatePath rateP = new RatePath(dataDirname, dataFilename); rateP.dbgDumpFields(); ReturnPath returnP = rateP.getReturnCompounded(); returnP.estimatePath(); returnP.dbgDumpFields(); double expectedReturnRate = returnP.get_expectedReturnRate(); double volatility = returnP.get_volatility(); // // Now prepare for MC runs. initAllTasks = new ToInitAllTasks(returnP, nTimeStepsMC, pathStartValue); String slaveClassName = "MonteCarlo.PriceStock"; // // Now create the tasks. initTasks(nRunsMC); // } catch (DemoException demoEx) { dbgPrintln(demoEx.toString()); System.exit(-1); } } @SuppressWarnings("unchecked") public void runSerial() throws MPJException { int ilow, ihigh; if (JGFMonteCarloBench.rank == 0) { results = new Vector<ToResult>(nRunsMC); } p_nRunsMC = (nRunsMC + JGFMonteCarloBench.nprocess - 1) / JGFMonteCarloBench.nprocess; p_results[0] = new Vector(p_nRunsMC); ilow = JGFMonteCarloBench.rank * p_nRunsMC; ihigh = (JGFMonteCarloBench.rank + 1) * p_nRunsMC; if (JGFMonteCarloBench.rank == JGFMonteCarloBench.nprocess - 1) ihigh = nRunsMC; // Now do the computation. PriceStock ps; for (int iRun = ilow; iRun < ihigh; iRun++) { ps = new PriceStock(); ps.setInitAllTasks(initAllTasks); ps.setTask(tasks.elementAt(iRun)); ps.run(); p_results[0].addElement(ps.getResult()); } if (JGFMonteCarloBench.rank == 0) { for (int i = 0; i < p_results[0].size(); i++) { results.addElement((ToResult) p_results[0].elementAt(i)); } for (int j = 1; j < JGFMonteCarloBench.nprocess; j++) { p_results[0].removeAllElements(); MPJ.COMM_WORLD.recv(p_results, 0, 1, MPJ.OBJECT, j, j); for (int i = 0; i < p_results[0].size(); i++) { results.addElement((ToResult) p_results[0].elementAt(i)); } } } else { MPJ.COMM_WORLD.send(p_results, 0, 1, MPJ.OBJECT, 0, JGFMonteCarloBench.rank); } } public void processSerial() { // // Process the results. try { processResults(); } catch (DemoException demoEx) { dbgPrintln(demoEx.toString()); System.exit(-1); } } // ------------------------------------------------------------------------ /** * Generates the parameters for the given Monte Carlo simulation. * * @param nRunsMC * the number of tasks, and hence Monte Carlo paths to produce. */ private void initTasks(int nRunsMC) { tasks = new Vector<Object>(nRunsMC); for (int i = 0; i < nRunsMC; i++) { String header = "MC run " + String.valueOf(i); ToTask task = new ToTask(header, (long) i * 11); tasks.addElement((Object) task); } } /** * Method for doing something with the Monte Carlo simulations. It's * probably not mathematically correct, but shall take an average over all * the simulated rate paths. * * @exception DemoException * thrown if there is a problem with reading in any values. */ private void processResults() throws DemoException { double avgExpectedReturnRateMC = 0.0; double avgVolatilityMC = 0.0; double runAvgExpectedReturnRateMC = 0.0; double runAvgVolatilityMC = 0.0; ToResult returnMC; if (nRunsMC != results.size()) { errPrintln("Fatal: TaskRunner managed to finish with no all the results gathered in!"); System.exit(-1); } // // Create an instance of a RatePath, for accumulating the results of the // Monte Carlo simulations. RatePath avgMCrate = new RatePath(nTimeStepsMC, "MC", 19990109, 19991231, dTime); for (int i = 0; i < nRunsMC; i++) { // First, create an instance which is supposed to generate a // particularly simple MC path. returnMC = results.elementAt(i); avgMCrate.inc_pathValue(returnMC.get_pathValue()); avgExpectedReturnRateMC += returnMC.get_expectedReturnRate(); avgVolatilityMC += returnMC.get_volatility(); runAvgExpectedReturnRateMC = avgExpectedReturnRateMC / ((double) (i + 1)); runAvgVolatilityMC = avgVolatilityMC / ((double) (i + 1)); } // for i; avgMCrate.inc_pathValue((double) 1.0 / ((double) nRunsMC)); avgExpectedReturnRateMC /= nRunsMC; avgVolatilityMC /= nRunsMC; /* * try{ Thread.sleep(200); } catch( InterruptedException intEx) { * errPrintln(intEx.toString()); } * */ JGFavgExpectedReturnRateMC = avgExpectedReturnRateMC; // dbgPrintln("Average over "+nRunsMC+": expectedReturnRate="+ // avgExpectedReturnRateMC+" volatility="+avgVolatilityMC + // JGFavgExpectedReturnRateMC); } // // ------------------------------------------------------------------------ // Accessor methods for class AppDemo. // Generated by 'makeJavaAccessor.pl' script. HWY. 20th January 1999. // ------------------------------------------------------------------------ /** * Accessor method for private instance variable <code>dataDirname</code>. * * @return Value of instance variable <code>dataDirname</code>. */ public String get_dataDirname() { return (this.dataDirname); } /** * Set method for private instance variable <code>dataDirname</code>. * * @param dataDirname * the value to set for the instance variable * <code>dataDirname</code>. */ public void set_dataDirname(String dataDirname) { this.dataDirname = dataDirname; } /** * Accessor method for private instance variable <code>dataFilename</code>. * * @return Value of instance variable <code>dataFilename</code>. */ public String get_dataFilename() { return (this.dataFilename); } /** * Set method for private instance variable <code>dataFilename</code>. * * @param dataFilename * the value to set for the instance variable * <code>dataFilename</code>. */ public void set_dataFilename(String dataFilename) { this.dataFilename = dataFilename; } /** * Accessor method for private instance variable <code>nTimeStepsMC</code>. * * @return Value of instance variable <code>nTimeStepsMC</code>. */ public int get_nTimeStepsMC() { return (this.nTimeStepsMC); } /** * Set method for private instance variable <code>nTimeStepsMC</code>. * * @param nTimeStepsMC * the value to set for the instance variable * <code>nTimeStepsMC</code>. */ public void set_nTimeStepsMC(int nTimeStepsMC) { this.nTimeStepsMC = nTimeStepsMC; } /** * Accessor method for private instance variable <code>nRunsMC</code>. * * @return Value of instance variable <code>nRunsMC</code>. */ public int get_nRunsMC() { return (this.nRunsMC); } /** * Set method for private instance variable <code>nRunsMC</code>. * * @param nRunsMC * the value to set for the instance variable * <code>nRunsMC</code>. */ public void set_nRunsMC(int nRunsMC) { this.nRunsMC = nRunsMC; } /** * Accessor method for private instance variable <code>tasks</code>. * * @return Value of instance variable <code>tasks</code>. */ public Vector<Object> get_tasks() { return (this.tasks); } /** * Set method for private instance variable <code>tasks</code>. * * @param tasks * the value to set for the instance variable <code>tasks</code>. */ public void set_tasks(Vector<Object> tasks) { this.tasks = tasks; } /** * Accessor method for private instance variable <code>results</code>. * * @return Value of instance variable <code>results</code>. */ public Vector<ToResult> get_results() { return (this.results); } /** * Set method for private instance variable <code>results</code>. * * @param results * the value to set for the instance variable * <code>results</code>. */ public void set_results(Vector<ToResult> results) { this.results = results; } // ------------------------------------------------------------------------ }
kseckinc/manager
packages/manager/modules/advices/src/advices/component.js
<reponame>kseckinc/manager import controller from './controller'; import template from './template.html'; /** * Makes 2api call to /advices to get advices for a given service type and name. * It uses (serviceType, serviceName) or (url, urlParams) and queryParams to construct the URL. * * Advices returned by the 2api has to be in below format * { * adviceGroups: [ * { * localizedDescription: '', * advices: [ * { * localizedName: string, // this is shown on UI * href: string, // optional, url to a page that need to be opened on clicking a advice * impression: object, // optional, ng-internet impression tracking object, * // if provided impression and impression click will be tracked * external: boolean, // optional, if true, external icon will be shown * } * ] * } * ] * } * * either href or onAdviceClick must be included in each advices * * Example: * <ovh-advices * url="/cloud/:serviceName/instance/:instanceId" * url-params="{ * serviceName: $ctrl.projectId, * instanceId: $ctrl.instance.id, * }" * > * </ovh-advices> * <ovh-advices * service-type="dedicated-server" * advice-name="{{ ::$ctrl.serviceName }}" * on-advice-click="$ctrl.onAdviceClick(advice)"> * </ovh-advices> */ export default { bindings: { /** * Type of the service like instance, dedicated-server, domain-web etc. * Use url and urlParams option for nested serviceType * @type {string} */ serviceType: '@', /** * name of the service * @type {string} */ serviceName: '@', /** * map of query params * @type {object} */ queryParams: '<?', /** * event handler to notify click on a advice. * @type {Function} */ onAdviceClick: '&?', /** * url to use to fetch advices ex: /cloud/:serviceName/instance/:instanceId * This option should not be used along with serviceType and serviceName. * Either serviceType and serviceName or url and urlParams must be used. * @type {String} */ url: '@', /** * Used along with url option. Params to replace in url ex: * { * serviceName: $ctrl.projectId, * instanceId: $ctrl.instance.id, * } * @type {Object} */ urlParams: '<', /** * Type of advice. Available values are 'retention' and 'upsell-cross-sell' * Default value is 'upsell-cross-sell' */ adviceType: '@', /** * callback handler called on load of advices * @type {Function} */ onLoad: '&?', }, controller, template, };
SoftmedTanzania/UNFPA_UzaziSalama_CHW
softmed-uzazi-salama/src/main/java/com/softmed/uzazi_salama/QuickstartPreferences.java
<reponame>SoftmedTanzania/UNFPA_UzaziSalama_CHW package com.softmed.uzazi_salama; /** * Created by kency on 12/11/17. */ public class QuickstartPreferences { public static final String SENT_TOKEN_TO_SERVER = "sentTokenToServer"; public static final String REGISTRATION_COMPLETE = "registrationComplete"; }
monsanto/6to5
src/babel/generation/generators/expressions.js
<filename>src/babel/generation/generators/expressions.js<gh_stars>0 import isInteger from "is-integer"; import isNumber from "lodash/lang/isNumber"; import * as t from "../../types"; export function UnaryExpression(node, print) { var hasSpace = /[a-z]$/.test(node.operator); var arg = node.argument; if (t.isUpdateExpression(arg) || t.isUnaryExpression(arg)) { hasSpace = true; } if (t.isUnaryExpression(arg) && arg.operator === "!") { hasSpace = false; } this.push(node.operator); if (hasSpace) this.push(" "); print(node.argument); } export function DoExpression(node, print) { this.push("do"); this.space(); print(node.body); } export function UpdateExpression(node, print) { if (node.prefix) { this.push(node.operator); print(node.argument); } else { print(node.argument); this.push(node.operator); } } export function ConditionalExpression(node, print) { print(node.test); this.space(); this.push("?"); this.space(); print(node.consequent); this.space(); this.push(":"); this.space(); print(node.alternate); } export function NewExpression(node, print) { this.push("new "); print(node.callee); this.push("("); print.list(node.arguments); this.push(")"); } export function SequenceExpression(node, print) { print.list(node.expressions); } export function ThisExpression() { this.push("this"); } export function Super() { this.push("super"); } export function Decorator(node, print) { this.push("@"); print(node.expression); } export function CallExpression(node, print) { print(node.callee); this.push("("); var separator = ","; if (node._prettyCall) { separator += "\n"; this.newline(); this.indent(); } else { separator += " "; } print.list(node.arguments, { separator: separator }); if (node._prettyCall) { this.newline(); this.dedent(); } this.push(")"); } var buildYieldAwait = function (keyword) { return function (node, print) { this.push(keyword); if (node.delegate || node.all) { this.push("*"); } if (node.argument) { this.space(); print(node.argument); } }; }; export var YieldExpression = buildYieldAwait("yield"); export var AwaitExpression = buildYieldAwait("await"); export function EmptyStatement() { this.semicolon(); } export function ExpressionStatement(node, print) { print(node.expression); this.semicolon(); } export function AssignmentExpression(node, print) { // todo: add cases where the spaces can be dropped when in compact mode print(node.left); this.push(" "); this.push(node.operator); this.push(" "); print(node.right); } export { AssignmentExpression as BinaryExpression, AssignmentExpression as LogicalExpression, AssignmentExpression as AssignmentPattern }; var SCIENTIFIC_NOTATION = /e/i; export function MemberExpression(node, print) { var obj = node.object; print(obj); if (!node.computed && t.isMemberExpression(node.property)) { throw new TypeError("Got a MemberExpression for MemberExpression property"); } var computed = node.computed; if (t.isLiteral(node.property) && isNumber(node.property.value)) { computed = true; } if (computed) { this.push("["); print(node.property); this.push("]"); } else { // 5..toFixed(2); if (t.isLiteral(obj) && isInteger(obj.value) && !SCIENTIFIC_NOTATION.test(obj.value.toString())) { this.push("."); } this.push("."); print(node.property); } } export { MemberExpression as MetaProperty };
Da3dalu2/SmartExperiment
src/main/java/controller/MsgParserLoop.java
<filename>src/main/java/controller/MsgParserLoop.java package controller; public interface MsgParserLoop { /** * Starts the parsing loop. */ void startLoop(); /** * Temporarily stops the loop until resume() is called. */ void pauseLoop(); /** * Makes the loop restart if it was previously paused. */ void resumeLoop(); }
njligames/Engine
src/njli/AbstractState.h
// // AbstractState.h // JLIGameEngineTest // // Created by <NAME> on 11/10/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #ifndef JLIGameEngineTest_AbstractState_h #define JLIGameEngineTest_AbstractState_h //#include "btAlignedAllocator.h" #include "AbstractBuilder.h" #include "Util.h" #include "btScalar.h" #include <stdlib.h> #ifndef NULL #define NULL ((void*)0) #endif namespace njli { class Telegram; /// <#Description#> template <class OBJECT_TYPE> class AbstractState : public AbstractFactoryObject { public: using AbstractDecorator::setName; using AbstractDecorator::getName; using AbstractFactoryObject::create; // using AbstractFactoryObject::clone; using AbstractFactoryObject::getPointer; using AbstractFactoryObject::getPointerValue; using AbstractFactoryObject::serializeObject; /** * <#Description#> */ AbstractState(); /** * <#Description#> */ AbstractState(const AbstractBuilder& builder); /** * <#Description#> */ AbstractState(const AbstractState& copy); /** * <#Description#> * * @return <#return value description#> */ virtual ~AbstractState() = 0; /** * <#Description#> * * @param AbstractState& <#AbstractState& description#> * * @return <#return value description#> */ AbstractState& operator=(const AbstractState&); public: /** * <#Description#> * * @return <#return value description#> */ virtual bool isFinished() const; /** * <#Description#> * * @param bool <#bool description#> */ virtual void enableFinished(const bool = true); /** * <#Description#> * * @param OBJECT_TYPE <#OBJECT_TYPE description#> */ virtual void enter(OBJECT_TYPE*) = 0; /** * <#Description#> * * @param OBJECT_TYPE <#OBJECT_TYPE description#> * @param f32 <#f32 description#> */ virtual void update(OBJECT_TYPE*, f32) = 0; /** * <#Description#> * * @param OBJECT_TYPE <#OBJECT_TYPE description#> */ virtual void exit(OBJECT_TYPE*) = 0; /** * <#Description#> * * @param OBJECT_TYPE <#OBJECT_TYPE description#> * @param Telegram& <#Telegram& description#> * * @return <#return value description#> */ virtual bool onMessage(OBJECT_TYPE*, const Telegram&) const = 0; virtual void enableCanDelete(const bool enable = true); private: bool m_isFinished; }; template <class OBJECT_TYPE> AbstractState<OBJECT_TYPE>::AbstractState() : AbstractFactoryObject(this) , m_isFinished(true) { } template <class OBJECT_TYPE> AbstractState<OBJECT_TYPE>::AbstractState(const AbstractBuilder& builder) : AbstractFactoryObject(this) , m_isFinished(true) { } template <class OBJECT_TYPE> AbstractState<OBJECT_TYPE>::AbstractState(const AbstractState& copy) : AbstractFactoryObject(this) , m_isFinished(copy.m_isFinished) { } template <class OBJECT_TYPE> AbstractState<OBJECT_TYPE>::~AbstractState() { } template <class OBJECT_TYPE> AbstractState<OBJECT_TYPE>& AbstractState<OBJECT_TYPE>::operator=(const AbstractState& rhs) { if (this != &rhs) { m_isFinished = rhs.m_isFinished; } return *this; } template <class OBJECT_TYPE> bool AbstractState<OBJECT_TYPE>::isFinished() const { return m_isFinished; } template <class OBJECT_TYPE> void AbstractState<OBJECT_TYPE>::enableFinished(const bool finished) { m_isFinished = finished; } template <class OBJECT_TYPE> void AbstractState<OBJECT_TYPE>::enableCanDelete(const bool enable) { AbstractFactoryObject::enableCanDelete(enable); } class Telegram { public: //the entity that sent this telegram AbstractFactoryObject* Sender; //the entity that is to receive this telegram AbstractFactoryObject* Receiver; //the message itself. These are all enumerated in the file //"MessageTypes.h" s32 Msg; //messages can be dispatched immediately or delayed for a specified amount //of time. If a delay is necessary this field is stamped with the time //the message should be dispatched. f32 DispatchTime; //any additional information that may accompany the message void* ExtraInfo; Telegram() : Sender(NULL) , Receiver(NULL) , Msg(0) , DispatchTime(0) //, //ExtraInfo(0) { } Telegram(f32 time, AbstractFactoryObject* sender, AbstractFactoryObject* receiver, s32 msg, void* info = NULL) : Sender(sender) , Receiver(receiver) , Msg(msg) , DispatchTime(time) , ExtraInfo(info) { } }; } #endif
hjc851/SourceCodePlagiarismDetectionDataset
Variant Programs/2/2-23/XingCallback.java
<gh_stars>0 import java.util.ArrayDeque; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; public class XingCallback extends Organizer { public int periodsRest = 0; public ArrayDeque<Mistake> carelessnessDipper = null; public ArrayDeque<Phase> setConvoy = null; public XingCallback() { this.setConvoy = (new ArrayDeque<>()); this.carelessnessDipper = (new ArrayDeque<>()); periodsRest = (WeekVolume); } public synchronized void bpsRetick() { List<Mistake> defect; defect = (new LinkedList<>()); for (Mistake f : carelessnessDipper) { if (f.arriveFixMonth() == this.haveCirculatingShudder()) defect.add(f); } for (Mistake responsible : defect) { carelessnessDipper.remove(responsible); substitutedIge.contributeVarlet( new Folio( responsible.catchSue().receiveCalls().peek(), responsible.catchSue().startPicture(), 0), responsible.catchSue()); if (!setConvoy.contains(responsible.catchSue())) { this.mortarProceedings(responsible.catchSue()); } } if (presentNegotiations != null) { periodsRest--; if (presentNegotiations.isEnded()) { presentNegotiations.arrangeEgressYears(this.haveCirculatingShudder()); this.realizedWork.addLast(presentNegotiations); presentNegotiations = (null); } if (periodsRest == 0 && presentNegotiations != null) { if (setConvoy.isEmpty()) { periodsRest = (WeekVolume); } else { this.mortarProceedings(presentNegotiations); presentNegotiations = (null); } } } if (presentNegotiations == null && !setConvoy.isEmpty()) { presentNegotiations = (this.availableSummons()); periodsRest = (WeekVolume); } this.endureNewRequisition(); } public synchronized void mortarProceedings(Phase methodology) { setConvoy.addLast(methodology); } public synchronized Phase availableSummons() { return setConvoy.removeFirst(); } public synchronized void endureNewRequisition() { if (this.presentNegotiations == null) { return; } while (!substitutedIge.tabAsked(this.presentNegotiations)) { this.mailedFolioLiability(); periodsRest = (WeekVolume); if (!setConvoy.isEmpty()) { presentNegotiations = (availableSummons()); } else { presentNegotiations = (null); return; } } presentNegotiations.methodSecondDecision(); } public synchronized void mailedFolioLiability() { Mistake f; f = (new Mistake(this.haveCirculatingShudder(), presentNegotiations)); carelessnessDipper.add(f); presentNegotiations.fetchMistakes().add(f); } }
InTheBlack-cn/MorePlanets
src/main/java/stevekung/mods/moreplanets/utils/blocks/BlockDoorMP.java
<gh_stars>10-100 package stevekung.mods.moreplanets.utils.blocks; import java.util.Random; import net.minecraft.block.BlockDoor; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; public class BlockDoorMP extends BlockDoor { private Item doorItem; public BlockDoorMP(String name) { super(Material.WOOD); this.setHardness(3.0F); this.setSoundType(SoundType.WOOD); this.setUnlocalizedName(name); this.setDefaultState(this.getDefaultState().withProperty(FACING, EnumFacing.NORTH).withProperty(OPEN, false).withProperty(HINGE, BlockDoorMP.EnumHingePosition.LEFT).withProperty(POWERED, false).withProperty(HALF, BlockDoorMP.EnumDoorHalf.LOWER)); } @Override public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { return new ItemStack(this.doorItem); } @Override public Item getItemDropped(IBlockState state, Random rand, int fortune) { if (!(state.getValue(HALF) == BlockDoor.EnumDoorHalf.UPPER)) { return this.doorItem; } return Items.AIR; } public void setDoorItem(Item item) { this.doorItem = item; } }
Imranr2/tp
src/test/java/ay2122s1_cs2103t_w16_2/btbb/logic/commands/client/EditClientCommandTest.java
package ay2122s1_cs2103t_w16_2.btbb.logic.commands.client; import static ay2122s1_cs2103t_w16_2.btbb.commons.core.Messages.MESSAGE_DUPLICATE_CLIENT; import static ay2122s1_cs2103t_w16_2.btbb.logic.commands.CommandTestUtil.DESC_AMY; import static ay2122s1_cs2103t_w16_2.btbb.logic.commands.CommandTestUtil.DESC_BOB; import static ay2122s1_cs2103t_w16_2.btbb.logic.commands.CommandTestUtil.VALID_NAME_BOB; import static ay2122s1_cs2103t_w16_2.btbb.logic.commands.CommandTestUtil.VALID_PHONE_BOB; import static ay2122s1_cs2103t_w16_2.btbb.logic.commands.CommandTestUtil.assertCommandFailure; import static ay2122s1_cs2103t_w16_2.btbb.logic.commands.CommandTestUtil.assertCommandSuccessWithTabChange; import static ay2122s1_cs2103t_w16_2.btbb.logic.commands.CommandTestUtil.showClientAtIndex; import static ay2122s1_cs2103t_w16_2.btbb.testutil.TypicalClients.getTypicalAddressBook; import static ay2122s1_cs2103t_w16_2.btbb.testutil.TypicalIndexes.INDEX_FIRST; import static ay2122s1_cs2103t_w16_2.btbb.testutil.TypicalIndexes.INDEX_SECOND; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import ay2122s1_cs2103t_w16_2.btbb.commons.core.Messages; import ay2122s1_cs2103t_w16_2.btbb.commons.core.index.Index; import ay2122s1_cs2103t_w16_2.btbb.exception.NotFoundException; import ay2122s1_cs2103t_w16_2.btbb.logic.descriptors.ClientDescriptor; import ay2122s1_cs2103t_w16_2.btbb.model.AddressBook; import ay2122s1_cs2103t_w16_2.btbb.model.Model; import ay2122s1_cs2103t_w16_2.btbb.model.ModelManager; import ay2122s1_cs2103t_w16_2.btbb.model.UserPrefs; import ay2122s1_cs2103t_w16_2.btbb.model.client.Client; import ay2122s1_cs2103t_w16_2.btbb.testutil.ClientBuilder; import ay2122s1_cs2103t_w16_2.btbb.testutil.ClientDescriptorBuilder; import ay2122s1_cs2103t_w16_2.btbb.ui.UiTab; /** * Contains integration tests (interaction with the Model) and unit tests for EditClientCommand. */ public class EditClientCommandTest { private Model model = new ModelManager(getTypicalAddressBook(), new UserPrefs()); @Test public void execute_allFieldsSpecifiedUnfilteredList_success() throws NotFoundException { Client editedClient = new ClientBuilder().build(); ClientDescriptor descriptor = new ClientDescriptorBuilder(editedClient).build(); EditClientCommand editClientCommand = new EditClientCommand(INDEX_FIRST, descriptor); String expectedMessage = String.format(EditClientCommand.MESSAGE_EDIT_CLIENT_SUCCESS, editedClient); Model expectedModel = new ModelManager(new AddressBook(model.getAddressBook()), new UserPrefs()); expectedModel.setClient(model.getFilteredClientList().get(0), editedClient); assertCommandSuccessWithTabChange(editClientCommand, model, expectedMessage, expectedModel, UiTab.HOME); } @Test public void execute_someFieldsSpecifiedUnfilteredList_success() throws NotFoundException { Index indexLastClient = Index.fromOneBased(model.getFilteredClientList().size()); Client lastClient = model.getFilteredClientList().get(indexLastClient.getZeroBased()); ClientBuilder clientInList = new ClientBuilder(lastClient); Client editedClient = clientInList.withName(VALID_NAME_BOB).withPhone(VALID_PHONE_BOB).build(); ClientDescriptor descriptor = new ClientDescriptorBuilder().withName(VALID_NAME_BOB) .withPhone(VALID_PHONE_BOB).build(); EditClientCommand editClientCommand = new EditClientCommand(indexLastClient, descriptor); String expectedMessage = String.format(EditClientCommand.MESSAGE_EDIT_CLIENT_SUCCESS, editedClient); Model expectedModel = new ModelManager(new AddressBook(model.getAddressBook()), new UserPrefs()); expectedModel.setClient(lastClient, editedClient); assertCommandSuccessWithTabChange(editClientCommand, model, expectedMessage, expectedModel, UiTab.HOME); } @Test public void execute_noFieldSpecifiedUnfilteredList_success() { EditClientCommand editClientCommand = new EditClientCommand(INDEX_FIRST, new ClientDescriptor()); Client editedClient = model.getFilteredClientList().get(INDEX_FIRST.getZeroBased()); String expectedMessage = String.format(EditClientCommand.MESSAGE_EDIT_CLIENT_SUCCESS, editedClient); Model expectedModel = new ModelManager(new AddressBook(model.getAddressBook()), new UserPrefs()); assertCommandSuccessWithTabChange(editClientCommand, model, expectedMessage, expectedModel, UiTab.HOME); } @Test public void execute_filteredList_success() throws NotFoundException { showClientAtIndex(model, INDEX_FIRST); Client clientInFilteredList = model.getFilteredClientList().get(INDEX_FIRST.getZeroBased()); Client editedClient = new ClientBuilder(clientInFilteredList).withName(VALID_NAME_BOB).build(); EditClientCommand editClientCommand = new EditClientCommand(INDEX_FIRST, new ClientDescriptorBuilder().withName(VALID_NAME_BOB).build()); String expectedMessage = String.format(EditClientCommand.MESSAGE_EDIT_CLIENT_SUCCESS, editedClient); Model expectedModel = new ModelManager(new AddressBook(model.getAddressBook()), new UserPrefs()); expectedModel.setClient(model.getFilteredClientList().get(0), editedClient); assertCommandSuccessWithTabChange(editClientCommand, model, expectedMessage, expectedModel, UiTab.HOME); } @Test public void execute_duplicateClientUnfilteredList_failure() { Client firstClient = model.getFilteredClientList().get(INDEX_FIRST.getZeroBased()); ClientDescriptor descriptor = new ClientDescriptorBuilder(firstClient).build(); EditClientCommand editClientCommand = new EditClientCommand(INDEX_SECOND, descriptor); assertCommandFailure(editClientCommand, model, MESSAGE_DUPLICATE_CLIENT); } @Test public void execute_duplicateClientFilteredList_failure() { showClientAtIndex(model, INDEX_FIRST); // edit client in filtered list into a duplicate in address book Client clientInList = model.getAddressBook().getClientList().get(INDEX_SECOND.getZeroBased()); EditClientCommand editClientCommand = new EditClientCommand(INDEX_FIRST, new ClientDescriptorBuilder(clientInList).build()); assertCommandFailure(editClientCommand, model, MESSAGE_DUPLICATE_CLIENT); } @Test public void execute_invalidClientIndexUnfilteredList_failure() { Index outOfBoundIndex = Index.fromOneBased(model.getFilteredClientList().size() + 1); ClientDescriptor descriptor = new ClientDescriptorBuilder().withName(VALID_NAME_BOB).build(); EditClientCommand editClientCommand = new EditClientCommand(outOfBoundIndex, descriptor); assertCommandFailure(editClientCommand, model, Messages.MESSAGE_INVALID_CLIENT_DISPLAYED_INDEX); } /** * Edit filtered list where index is larger than size of filtered list, * but smaller than size of address book */ @Test public void execute_invalidClientIndexFilteredList_failure() { showClientAtIndex(model, INDEX_FIRST); Index outOfBoundIndex = INDEX_SECOND; // ensures that outOfBoundIndex is still in bounds of address book list assertTrue(outOfBoundIndex.getZeroBased() < model.getAddressBook().getClientList().size()); EditClientCommand editClientCommand = new EditClientCommand(outOfBoundIndex, new ClientDescriptorBuilder().withName(VALID_NAME_BOB).build()); assertCommandFailure(editClientCommand, model, Messages.MESSAGE_INVALID_CLIENT_DISPLAYED_INDEX); } @Test public void equals() { final EditClientCommand standardCommand = new EditClientCommand(INDEX_FIRST, DESC_AMY); // same values -> returns true ClientDescriptor copyDescriptor = new ClientDescriptor(DESC_AMY); EditClientCommand commandWithSameValues = new EditClientCommand(INDEX_FIRST, copyDescriptor); assertTrue(standardCommand.equals(commandWithSameValues)); // same object -> returns true assertTrue(standardCommand.equals(standardCommand)); // null -> returns false assertFalse(standardCommand.equals(null)); // different types -> returns false assertFalse(standardCommand.equals(new ListClientCommand())); // different index -> returns false assertFalse(standardCommand.equals(new EditClientCommand(INDEX_SECOND, DESC_AMY))); // different descriptor -> returns false assertFalse(standardCommand.equals(new EditClientCommand(INDEX_FIRST, DESC_BOB))); } }
fusetim/fluent-scala
core/src/io/github/fluent4s/api/ResolutionError.scala
<reponame>fusetim/fluent-scala package io.github.fluent4s.api /** * Represent an error occurred during the resolution process. * @param message the description of this error */ case class ResolutionError(message: String) extends Error object ResolutionError { def NotFound(value: String): ResolutionError = ResolutionError(s"Not found: $value") def Mismatch(expected: String, got: String): ResolutionError = ResolutionError(s"Expected $expected, got $got") val Impossible: ResolutionError = ResolutionError("Impossible error. This is probably a bug.") }
babatunde-dropque/ubanew
app/models/aivideo.rb
class Aivideo < ActiveRecord::Base end
calebperelini/nzbikeaccidents
node_modules/seer/dist/index.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; // Copyright (c) 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. var isBrowser = typeof window !== 'undefined' && window.addEventListener; var timers = new Map(); /** * Ready check for Seer initialization * * @returns {Boolean} */ var isReady = function isReady() { return isBrowser && window.__SEER_INITIALIZED__; }; /** * Utility method allowing to throttle a user action based on a key and a minimun delay. * * @param key {String} A unique key * @param delay {Number} The minimal delay to throttle * @returns {Boolean} */ var throttle = function throttle(key, delay) { var time = timers.get(key); var now = Date.now(); if (time && now - time < delay) { return true; } timers.set(key, now); return false; }; var replacer = function replacer(seen) { return function (key, value) { if (value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && seen.has(value)) { return; } seen.add(value); var isArray = Object.prototype.toString.call(value).slice(8, -1).includes('Array'); if (isArray) { return Array.prototype.slice.call(value, 0, 20); } return value; }; }; /** * Low-level api leveraging window.postMessage * * @param type {String} The action type * @param payload {Any} The action payload */ var send = function send(type) { var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (!isBrowser || !isReady()) { return; } var seen = new Set(); var payload = JSON.stringify(data, replacer(seen)); try { window.postMessage({ type: type, payload: payload, source: 'seer-agent' }, '*'); } catch (e) { if (throttle('seer-log', 2E3)) { return; } console.log(e); // eslint-disable-line } }; var listeners = new Map(); var listener = function listener(message) { if (!message || !message.data || message.data.source !== 'seer-core') { return; } var _message$data = message.data, type = _message$data.type, payload = _message$data.payload; var typeListeners = listeners.get(type); if (typeListeners) { typeListeners.forEach(function (cb) { return cb(payload); }); } }; /** * Initilize window listener. There will be only one for the whole process * to prevent too many registrations. * * This method will be called automatically if you use the `listenFor` method. */ var init = function init() { if (!isBrowser || window.__SEER_LISTENER__) { return; } window.addEventListener('message', listener); window.__SEER_LISTENER__ = true; }; /** * Clean listener. Can be useful in case you want to unregister upcoming events * or liberate memory. */ var clean = function clean() { if (!isBrowser || !window.__SEER_LISTENER__) { return; } window.removeEventListener('message', listener); delete window.__SEER_LISTENER__; }; /** * Create a listener that will be called upon events of the given key. * * @param key {String} The unique tab key * @param cb {Function} A callback that will receive the message payload */ var listenFor = function listenFor(type, cb) { if (!isBrowser) { return; } if (!type || !cb) { throw new Error('Please provide a type and callback'); } if (!listeners.has(type)) { listeners.set(type, []); } if (!window.__SEER_LISTENER__) { init(); } listeners.get(type).push(cb); }; /** * Remove an identity listener * * @param cb {Function} The callback to remove */ var removeListener = function removeListener(cb) { listeners.forEach(function (typeListeners, key) { listeners.set(key, typeListeners.filter(function (l) { return l !== cb; })); }); }; /** * Creates a new indexed list. * It works by index to get O(1) accessing and performance. * * @param key {String} The key of the tab * @param data {Object} The indexed object */ var list = function list(key, data) { return send('LIST', { key: key, data: data }); }; /** * Creates an element in the indexed list, based on the itemKey. * * @param key {String} The key of the tab * @param itemKey {String} The key of the item * @param data {Any} The value of the item */ var listItem = function listItem(key, itemKey) { var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return send('LIST_ITEM', { key: key, itemKey: itemKey, data: data }); }; /** * Update an item property, can be deeply nested. * * @param key {String} The key of the tab * @param itemKey {String} The key of the item * @param path {String} The path of the variable you want to update * @param data {Object} The new value */ var updateItem = function updateItem(key, itemKey, path, data) { return send('UPDATE_ITEM', { key: key, itemKey: itemKey, path: path, data: data }); }; /** * Similar to updateItem, but allows to pass an array with {path,data} pairs for * multiple update of the same item without having to send multiple messages. * * @param key {String} The key of the tab * @param itemKey {String} The key of the item * @param array {Array} The array of updates * @param array.path {String} The path for this update * @param array.data {Object} The value of this update */ var multiUpdate = function multiUpdate(key, itemKey, array) { return send('MULTI_UPDATE_ITEM', { key: key, itemKey: itemKey, array: array }); }; /** * Remove a specific item in a specific tab. * * @param key {String} They key of the tab * @param itemKey {String} The key of the item */ var deleteItem = function deleteItem(key, itemKey) { return send('DELETE_ITEM', { key: key, itemKey: itemKey }); }; /** * Will create a log message to an item, that will be displayde with the current time. * * @param key {String} The key of the tab * @param itemKey {String} The key of the item * @param msg {String} The message to display */ var addLog = function addLog(key, itemKey, msg) { return send('ADD_LOG', { key: key, itemKey: itemKey, msg: msg }); }; exports.default = { send: send, throttle: throttle, isReady: isReady, list: list, listItem: listItem, updateItem: updateItem, multiUpdate: multiUpdate, deleteItem: deleteItem, addLog: addLog, listeners: listeners, listenFor: listenFor, removeListener: removeListener, init: init, clean: clean };
AiRanthem/OOMall_of_2-4
comment/src/test/java/xmu/oomall/comment/dao/CommentDaoTest.java
package xmu.oomall.comment.dao; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.Rollback; import org.springframework.transaction.annotation.Transactional; import xmu.oomall.comment.CommentApplication; import xmu.oomall.comment.domain.Comment; import xmu.oomall.comment.domain.CommentPo; import java.time.LocalDateTime; @SpringBootTest(classes = CommentApplication.class) @Transactional class CommentDaoTest { @Autowired private CommentDao commentDao; @Test @Rollback void getCommentsTest() { CommentPo commentPo = commentDao.findCommentById(5623412); System.out.println("Fount comment: " + commentPo); } @Test @Rollback void deleteTest() { System.out.println("Before: "); System.out.println(commentDao.findCommentById(5623412)); commentDao.deleteComment(5623412); System.out.println("After: "); System.out.println(commentDao.findCommentById(5623412)); } @Test @Rollback void saveCommentTest() { if (commentDao.findCommentById(32) != null) System.out.println("评论已存在!"); CommentPo commentPo = new CommentPo(); commentPo.setUserId(123); commentPo.setStar((short) 3); commentPo.setContent("Ok stuff!"); commentPo.setProductId(533); commentPo.setStatusCode((short) 0); Comment comment = new Comment(commentPo); LocalDateTime localDateTime = LocalDateTime.now(); comment.setGmtCreate(localDateTime); comment.setGmtModified(localDateTime); System.out.println("commentPo: " + commentPo); System.out.println("comment: " + comment); commentDao.saveComment(comment); System.out.println("new comment: " + commentDao.findCommentById(32)); } @Test @Rollback void showCommentByProductIdTest() { System.out.println(commentDao.showCommentsByProduct(5422, 0, 3)); } }
b2wads/grimorio-ui
source/components/button-upload/button-upload.stories.js
<reponame>b2wads/grimorio-ui<filename>source/components/button-upload/button-upload.stories.js import React from 'react'; import { withState } from '../../helpers/storybook'; import ButtonUpload from './index'; import Button from '../button'; import styles from './button-upload.styl'; export default { title: 'Button Upload', component: ButtonUpload, }; const printRes = (data, list, error, size) => { console.log('images: ', data, 'list:', list, 'error:', error, 'size', size); }; export const Normal = () => ( <div> <ButtonUpload onChange={printRes} showTags /> <ButtonUpload onChange={printRes} withDrop showTags /> </div> ); export const WithImageDimensions = () => ( <ButtonUpload allowedDimensions={['300x250']} formatWhiteList={['.jpg', '.jpeg', '.png']} btnText="Apenas 300x250" onChange={printRes} showTags /> ); export const WithLimit = () => ( <ButtonUpload btnText="Apenas 2 imagens" limit={2} onChange={printRes} showTags /> ); export const WithExtensionWhitelist = () => ( <ButtonUpload formatWhiteList={['.jpg', '.jpeg']} btnText="Apenas JPG e JPEG" onChange={printRes} showTags /> ); export const WithMaxFileSize = () => ( <ButtonUpload maxFileSize={100000} btnText="Até 100KB" onChange={printRes} showTags /> ); export const WithDropArea = () => ( <ButtonUpload onChange={printRes} showTags withDrop dropText="Texto custom de drop" /> ); export const WithoutTags = withState({ data: [], list: [] }, store => { const change = (data, list) => { store.set({ data, list }); }; const removeImage = (index) => { const listFiles = store.state.list.filter((_, i) => i !== index); const listData = store.state.data.filter((_, i) => i !== index); store.set({ list: listFiles, data: listData }); }; return ( <div className={styles.contentList}> {store.state.data.map((base64, index) => ( <div className={styles.wrapperImg}> <img width="150px" src={base64} /> <div> <Button className={styles.buttonRemove} onClick={() => removeImage(index)}> Remover </Button> </div> </div> ))} <br /> <ButtonUpload withDrop files={store.state.list} onChange={change} showTags={false} /> </div> ); }); export const Disabled = () => ( <div> <ButtonUpload disabled onChange={printRes} showTags /> <ButtonUpload disabled onChange={printRes} withDrop showTags /> </div> );
sanko-shoko/simplesp
sample/gl/multicam/main.cpp
<reponame>sanko-shoko/simplesp #define SP_USE_DEBUG 1 #include "simplesp.h" #include "spex/spgl.h" using namespace sp; class VoxelGUI : public BaseWindow { // camera CamParam m_cam; // view pose Pose m_view; // multi camerea poses Mem1<Pose> m_poses; Mem1<Pose> m_ests; Mem1<Vec3> m_pnts; Mem1<Pose> m_boards; int m_id; private: void help() { printf("'a' key : switch board\n"); printf("'s' key : calibration\n"); printf("\n"); } virtual void init() { help(); m_id = 0; m_cam = getCamParam(640, 480); const double distance = 1000.0; m_view = getPose(getVec3(0.0, 0.0, 3 * distance)); { const int cnum = 10; for (int i = 0; i < cnum; i++) { const Pose pose = getRotAngleX(+20.0 * SP_PI / 180.0) * getPose(getRotAngleY(i * 2 * SP_PI / cnum), getVec3(0.0, +0.4 * distance, distance)); m_poses.push(pose); } } { const int onum = 50; const double size = 200.0; for (int i = 0; i < onum; i++) { const Vec3 pos = randuVec3(size, 0.0, size) + getVec3(0.0, -1.0, 0.0); const Pose pose = invPose(getPose(invRot(getRotDirection(pos)), pos)); //const Pose pose = getPose(pos); m_boards.push(pose); if (i == 0) { print(m_poses[0] * invPose(pose)); } } } { // set marker info const int dsize[2] = { 4, 3 }; const int block = 3; const double length = 30.0; const double interval = 5.0; const Mem1<BitMarkerParam> mrks = getBitMarkerParam(0, block, length, dsize[0], dsize[1], interval); Mem1<Vec3> unit = getVec3(grid(2, 2), 0) * length; unit -= mean(unit); m_pnts.clear(); for (int i = 0; i < mrks.size(); i++) { m_pnts.push(invPose(mrks[i].offset) * unit); } } } virtual void keyFun(int key, int scancode, int action, int mods) { if (m_key[GLFW_KEY_A] == 1) { m_id++; if (m_id >= m_boards.size()) m_id = 0; } if (m_key[GLFW_KEY_S] == 1) { Mem1<Mem1<Mem1<Vec2> > > pixs; Mem1<Mem1<Mem1<Vec2> > > objs; Mem1<CamParam> cams; genDataset(cams, pixs, objs, m_boards, m_pnts); Mem1<Pose> poses; calibMultiCam(poses, cams, pixs, objs); Pose base = m_poses[0]; m_ests.clear(); for (int i = 0; i < cams.size(); i++) { m_ests.push(poses[i] * base); } } } void genDataset(Mem1<CamParam> &cams, Mem1<Mem1<Mem1<Vec2> > > &pixs, Mem1<Mem1<Mem1<Vec2> > > &objs, const Mem1<Pose> &boards, const Mem1<Vec3> &pnts) { for (int i = 0; i < m_poses.size(); i++) { CamParam cam = getCamParam(640, 480); Mem1<Mem1<Vec2> > spixs; Mem1<Mem1<Vec2> > sobjs; for (int j = 0; j < boards.size(); j++) { Mem1<Vec2> tpixs; Mem1<Vec2> tobjs; const Pose pose = m_poses[i] * invPose(boards[j]); const Vec3 nrm = pose.rot * getVec3(0.0, 0.0, 1.0); if (nrm.z > 0.3) { for (int k = 0; k < pnts.size(); k++) { const double noise = 0.5; const Vec2 pix = mulCamD(cam, prjVec(pose * pnts[k])) + randgVec2(noise, noise); tpixs.push(pix); tobjs.push(getVec2(pnts[k].x, pnts[k].y)); ///print(noise); } } spixs.push(tpixs); sobjs.push(tobjs); Mem2<Byte> img(640, 480); img.zero(); //printf("pnts %d\n", tpixs.size()); //for (int k = 0; k < tpixs.size(); k++) { // renderPoint(img, tpixs[k], BYTE(255), 1); //} } pixs.push(spixs); objs.push(sobjs); cams.push(cam); } } virtual void display() { glClearColor(0.10f, 0.12f, 0.12f, 0.00f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // render model { glLoadView3D(m_cam, m_viewPos, m_viewScale); glDisable(GL_DEPTH_TEST); { glPointSize(3.f); glLoadMatrix(m_view * invPose(m_boards[m_id])); glBegin(GL_POINTS); glColor3f(0.2f, 0.7f, 0.2f); for (int i = 0; i < m_pnts.size(); i++) { glVertex(m_pnts[i]); } glEnd(); glAxis(50.0); } // render cam { glLineWidth(2.f); for (int i = 0; i < m_poses.size(); i++) { glLoadMatrix(m_view * invPose(m_poses[i])); const Vec3 nrm = (m_poses[i] * invPose(m_boards[m_id])).rot * getVec3(0.0, 0.0, 1.0); if (nrm.z > 0.3) { glColor3d(0.5, 0.5, 0.8); } else { glColor3d(0.2, 0.2, 0.4); } glCam(m_cam, 50); } for (int i = 0; i < m_ests.size(); i++) { glLoadMatrix(m_view * invPose(m_ests[i])); glColor3d(0.5, 0.8, 0.5); glCam(m_cam, 50); } } } } virtual void mousePos(double x, double y) { controlPose(m_view, m_mouse, m_wcam, m_viewScale); } virtual void mouseScroll(double x, double y) { controlPose(m_view, m_mouse, m_wcam, m_viewScale); } }; int main(){ VoxelGUI win; win.execute("multicam", 800, 600); return 0; }
jnthn/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/findFirst/beforeFindFirstOptionalType.java
// "Replace with findFirst()" "true" import java.util.*; public class Main { public List<String> getErrors(List<String> data) { List<String> def = Collections.singletonList("Not found"); for(String s : dat<caret>a) { if(s.startsWith("xyz")) { return s.length() < 10 ? Collections.emptyList() : Arrays.asList(); } } return def; } }
Kirishikesan/haiku
src/kits/debugger/debug_info/ImageDebugLoadingStateHandlerRoster.cpp
<reponame>Kirishikesan/haiku /* * Copyright 2014, <NAME>, <EMAIL>. * Distributed under the terms of the MIT License. */ #include "ImageDebugLoadingStateHandlerRoster.h" #include <new> #include <AutoDeleter.h> #include <AutoLocker.h> #include "DwarfLoadingStateHandler.h" #include "ImageDebugInfoLoadingState.h" #include "ImageDebugLoadingStateHandler.h" #include "SpecificImageDebugInfoLoadingState.h" /*static*/ ImageDebugLoadingStateHandlerRoster* ImageDebugLoadingStateHandlerRoster::sDefaultInstance = NULL; ImageDebugLoadingStateHandlerRoster::ImageDebugLoadingStateHandlerRoster() : fLock("loading state handler roster"), fStateHandlers(20, false) { } ImageDebugLoadingStateHandlerRoster::~ImageDebugLoadingStateHandlerRoster() { for (int32 i = 0; ImageDebugLoadingStateHandler* handler = fStateHandlers.ItemAt(i); i++) { handler->ReleaseReference(); } } /*static*/ ImageDebugLoadingStateHandlerRoster* ImageDebugLoadingStateHandlerRoster::Default() { return sDefaultInstance; } /*static*/ status_t ImageDebugLoadingStateHandlerRoster::CreateDefault() { if (sDefaultInstance != NULL) return B_OK; ImageDebugLoadingStateHandlerRoster* roster = new(std::nothrow) ImageDebugLoadingStateHandlerRoster; if (roster == NULL) return B_NO_MEMORY; ObjectDeleter<ImageDebugLoadingStateHandlerRoster> rosterDeleter(roster); status_t error = roster->Init(); if (error != B_OK) return error; error = roster->RegisterDefaultHandlers(); if (error != B_OK) return error; sDefaultInstance = rosterDeleter.Detach(); return B_OK; } /*static*/ void ImageDebugLoadingStateHandlerRoster::DeleteDefault() { ImageDebugLoadingStateHandlerRoster* roster = sDefaultInstance; sDefaultInstance = NULL; delete roster; } status_t ImageDebugLoadingStateHandlerRoster::Init() { return fLock.InitCheck(); } status_t ImageDebugLoadingStateHandlerRoster::RegisterDefaultHandlers() { ImageDebugLoadingStateHandler* handler; BReference<ImageDebugLoadingStateHandler> handlerReference; handler = new(std::nothrow) DwarfLoadingStateHandler(); if (handler == NULL) return B_NO_MEMORY; handlerReference.SetTo(handler, true); if (!RegisterHandler(handler)) return B_NO_MEMORY; return B_OK; } status_t ImageDebugLoadingStateHandlerRoster::FindStateHandler( SpecificImageDebugInfoLoadingState* state, ImageDebugLoadingStateHandler*& _handler) { AutoLocker<BLocker> locker(fLock); bool found = false; ImageDebugLoadingStateHandler* handler = NULL; for (int32 i = 0; (handler = fStateHandlers.ItemAt(i)); i++) { if ((found = handler->SupportsState(state))) break; } if (!found) return B_ENTRY_NOT_FOUND; handler->AcquireReference(); _handler = handler; return B_OK; } bool ImageDebugLoadingStateHandlerRoster::RegisterHandler( ImageDebugLoadingStateHandler* handler) { if (!fStateHandlers.AddItem(handler)) return false; handler->AcquireReference(); return true; } void ImageDebugLoadingStateHandlerRoster::UnregisterHandler( ImageDebugLoadingStateHandler* handler) { if (fStateHandlers.RemoveItem(handler)) handler->ReleaseReference(); }
opencomputeproject/HWMgmt-DeviceMgr-PSME
PSME/application/src/command/heart_beat/definition/heart_beat.cpp
/*! * @section LICENSE * * @copyright * Copyright (c) 2015-2017 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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. * * @section DESCRIPTION * * @file command/heart_beat/definition/heart_beat.cpp * @brief Heart beat command definition * */ #include "psme/command/heart_beat/definition/tag.hpp" #include "psme/command/heart_beat/heart_beat.hpp" #include "configuration/configuration.hpp" #include "psme/core/agent/agent_manager.hpp" #include <chrono> using namespace psme; using namespace psme::command; using namespace std::chrono; /*! HeartBeat agent implementation */ class HeartBeat : public heart_beat::HeartBeat { public: HeartBeat() : heart_beat::HeartBeat(heart_beat::definition::TAG) { auto time_clock = steady_clock::now().time_since_epoch(); m_time_begin = TimeLive(duration_cast<seconds>(time_clock).count()); } using heart_beat::HeartBeat::execute; void execute(const Request& request, Response& response) { auto time_clock = steady_clock::now().time_since_epoch(); auto time_now = TimeLive(duration_cast<seconds>(time_clock).count()); auto agent = core::agent::AgentManager::get_instance()->get_agent(request.get_gami_id()); if(agent) { response.set_time_live(time_now - m_time_begin); } else { response.set_time_live(0); } response.set_minimum_delay(m_minimum_delay); } ~HeartBeat(); private: TimeLive m_time_begin{0}; Seconds m_minimum_delay{3}; }; HeartBeat::~HeartBeat() { } static Command::Register<HeartBeat> g;
CodingSoldier/java-learn
project/mysql-learn/multi-datasource/src/main/java/com/example/multidatasource/CommonCtrl.java
<reponame>CodingSoldier/java-learn<filename>project/mysql-learn/multi-datasource/src/main/java/com/example/multidatasource/CommonCtrl.java<gh_stars>10-100 package com.example.multidatasource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class CommonCtrl { @Autowired CommonService commonService; @GetMapping("/test01") public boolean test01(@RequestParam("msg") String msg){ boolean b = commonService.save(msg); return b; } }
cc8848/report
report-common/report-common-model/src/main/java/com/report/common/model/JsonMapper.java
package com.report.common.model; import java.io.IOException; import java.text.DateFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion; import com.fasterxml.jackson.databind.util.JSONPObject; /** * 简单封装Jackson,实现JSON String<->Java Object的Mapper. 封装不同的输出风格, * 使用不同的builder函数创建实例. * @author lishun * @version 1.0 */ public class JsonMapper { private static Logger logger = LoggerFactory.getLogger(JsonMapper.class); private ObjectMapper mapper; public JsonMapper() { this(Inclusion.NON_NULL, null, false); } public JsonMapper(Inclusion inclusion) { this(inclusion, null, false); } public JsonMapper(Inclusion inclusion, DateFormat df) { this(inclusion, df, false); } public JsonMapper(Inclusion inclusion, DateFormat df, boolean replaceNull) { mapper = new ObjectMapper(); // 设置输出时包含属性的风格 // mapper.setSerializationInclusion(inclusion); // // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性 // mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); // // 禁止使用int代表Enum的order()來反序列化Enum // mapper.configure(DeserializationConfig.Feature.FAIL_ON_NUMBERS_FOR_ENUMS, true); // 允许单引号 mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.setDateFormat(df); if (replaceNull) { // null 转换为 "" mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() { @Override public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(""); } }); } } /** * 创建输出全部属性到Json字符串的Mapper. */ public static JsonMapper buildNormalMapper() { return new JsonMapper(Inclusion.ALWAYS); } /** * 创建只输出非空属性到Json字符串的Mapper. */ public static JsonMapper buildNonNullMapper() { return new JsonMapper(Inclusion.NON_NULL); } /** * 创建只输出初始值被改变的属性到Json字符串的Mapper. */ public static JsonMapper buildNonDefaultMapper() { return new JsonMapper(Inclusion.NON_DEFAULT); } /** * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper. */ public static JsonMapper buildNonEmptyMapper() { return new JsonMapper(Inclusion.NON_EMPTY); } /** * 如果对象为Null, 返回"null". 如果集合为空集合, 返回"[]". */ public String toJson(Object object) { try { return mapper.writeValueAsString(object); } catch (IOException e) { logger.warn("write to json string error:" + object, e); return null; } } /** * 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合. * * 如需读取集合如List/Map, 且不是List<String>这种简单类型时,先使用函数constructParametricType构造类型. * * @see #constructParametricType(Class, Class...) */ public <T> T fromJson(String jsonString, Class<T> clazz) { if (StringUtils.isEmpty(jsonString)) { return null; } try { return mapper.readValue(jsonString, clazz); } catch (IOException e) { logger.warn("parse json string error:" + jsonString, e); return null; } } /** * 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合. * * 如需读取集合如List/Map, 且不是List<String>这种简单类型时,先使用函數constructParametricType构造类型. * * @see #constructParametricType(Class, Class...) */ @SuppressWarnings("unchecked") public <T> T fromJson(String jsonString, JavaType javaType) { if (StringUtils.isEmpty(jsonString)) { return null; } try { return (T) mapper.readValue(jsonString, javaType); } catch (IOException e) { logger.warn("parse json string error:" + jsonString, e); return null; } } /** * 构造泛型的Type如List<MyBean>, * 则调用constructParametricType(ArrayList.class,MyBean.class) * Map<String,MyBean>则调用(HashMap.class,String.class, MyBean.class) */ public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses) { return mapper.getTypeFactory().constructParametricType(parametrized, parameterClasses); } /** * 当JSON里只含有Bean的部分属性时,更新一个已存在Bean,只覆盖该部分的属性. */ @SuppressWarnings("unchecked") public <T> T update(T object, String jsonString) { try { return (T) mapper.readerForUpdating(object).readValue(jsonString); } catch (JsonProcessingException e) { logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e); } catch (IOException e) { logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e); } return null; } /** * 输出JSONP格式数据. */ public String toJsonP(String functionName, Object object) { return toJson(new JSONPObject(functionName, object)); } /** * 设定是否使用Enum的toString函数來读写Enum, 为False时候使用Enum的name()函数來读写Enum, 默认为False. * 注意本函数一定要在Mapper创建后, 所有的读写动作之前调用. */ public void setEnumUseToString(boolean value) { // mapper.configure(SerializationConfig.thiWRITE_ENUMS_USING_TO_STRING, value); // mapper.configure(DeserializationConfig.Feature.READ_ENUMS_USING_TO_STRING, value); } /** * 取出Mapper做进一步的设置或使用其他序列化API. */ public ObjectMapper getMapper() { return mapper; } }
GameRevision/GWLP-R
protocol/src/main/java/gwlpr/protocol/gameserver/outbound/P132_MissionMapIconType.java
<gh_stars>10-100 package gwlpr.protocol.gameserver.outbound; import gwlpr.protocol.serialization.GWMessage; /** * Auto-generated by PacketCodeGen. * */ public final class P132_MissionMapIconType extends GWMessage { private long localID; private long iconHash; @Override public short getHeader() { return 132; } public void setLocalID(long localID) { this.localID = localID; } public void setIconHash(long iconHash) { this.iconHash = iconHash; } @Override public String toString() { StringBuilder sb = new StringBuilder("P132_MissionMapIconType["); sb.append("localID=").append(this.localID).append(",iconHash=").append(this.iconHash).append("]"); return sb.toString(); } }
shadytradesman/The-Contract-Website
hgapp/characters/migrations/0004_auto_20170825_1625.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-08-25 15:25 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('characters', '0003_auto_20170711_0329'), ] operations = [ migrations.AlterField( model_name='character', name='appearance', field=models.TextField(max_length=300), ), migrations.AlterField( model_name='character', name='player', field=models.ForeignKey(default=3, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), preserve_default=False, ), ]
lovecrossyou/Puzzle
ios/Module/Home/View/RRFActivityCanonCell.h
<filename>ios/Module/Home/View/RRFActivityCanonCell.h // // RRFActivityCanonCell.h // Puzzle // // Created by huibei on 16/9/30. // Copyright © 2016年 HuiBei. All rights reserved. // #import <UIKit/UIKit.h> @class PZCommonCellModel; @interface RRFActivityCanonCell : UITableViewCell @property(nonatomic,strong)PZCommonCellModel *model; @end
qianfei11/zstack
search/src/main/java/org/zstack/zql/ast/visitors/FunctionVisitor.java
<gh_stars>100-1000 package org.zstack.zql.ast.visitors; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.zql.ASTNode; import org.zstack.header.zql.ASTVisitor; /** * Created by MaJin on 2019/6/3. */ public class FunctionVisitor implements ASTVisitor<String, ASTNode> { @Override public String visit(ASTNode node) { if (node instanceof ASTNode.Distinct) { return (String) node.accept(new DistinctVistor()); } else { throw new CloudRuntimeException(String.format("should not be here, %s", node.getClass())); } } }
mystickev/ctf-archives
DarkCTF/2020/butterfly/source/butterfly.c
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<fcntl.h> #include<unistd.h> #define HK 0x1337 char *note[0x2]; long int getnum() { char buffer[0x20]; read(0,buffer,0x18); return atoll(buffer); } void setup() { setvbuf(stdin,0,2,0); setvbuf(stdout,0,2,0); setvbuf(stderr,0,2,0); alarm(20); } void handler() { char buffer[0x100]; long int idx; note[0] = (char *)malloc(0x200); note[1] = (char *)malloc(0x200); printf("I need your name: "); read(0,buffer,0x50); puts(buffer); printf("Enter the index of the you want to write: "); idx = getnum(); if(idx < 2) { printf("Enter data: "); read(0,note[idx],0xe8); } puts("Bye"); _exit(HK); } int main() { setup(); handler(); return 0; }
DevelopWb/otgCamera
module_Base/src/main/java/com/juntai/wisdom/basecomponent/base/BaseMvpFragment.java
package com.juntai.wisdom.basecomponent.base; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import com.juntai.wisdom.basecomponent.mvp.IPresenter; import com.juntai.wisdom.basecomponent.mvp.BaseIView; import com.trello.rxlifecycle2.LifecycleTransformer; import com.trello.rxlifecycle2.android.FragmentEvent; public abstract class BaseMvpFragment<P extends IPresenter> extends BaseLazyFragment implements BaseIView { protected P mPresenter; protected abstract P createPresenter(); ProgressDialog progressDialog; @Override public void onAttach(Context context) { mPresenter = createPresenter(); if (mPresenter != null) { mPresenter.attachView(this); } super.onAttach(context); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // progressDialog = new ProgressDialog(mContext); } @Override public void onDestroyView() { super.onDestroyView(); if (mPresenter != null) { mPresenter.detachView(); } this.mPresenter = null; } @Override public void showLoading() { getBaseActivity().showLoadingDialog(getContext()); } @Override public void hideLoading() { getBaseActivity().stopLoadingDialog(); } @Override public void showMsg(String message) { } @Override public void showDefaultMsg(String msg) { } @Override public void showErrorMsg(String errorMsg) { } @Override public <T> LifecycleTransformer<T> bindToLife() { return this.bindUntilEvent(FragmentEvent.DESTROY_VIEW); } /** * 查找viewid * @param viewId * @param <V> * @return */ @Override public <V extends View> V getView(int viewId){ return mRootView.findViewById(viewId); } }
polyverse/ropoly
vendor/github.com/polyverse/masche/memaccess/memaccess_c_wrapper.go
// +build windows darwin package memaccess // #include "memaccess.h" // #cgo CFLAGS: -std=c99 import "C" import ( "fmt" "github.com/polyverse/masche/cresponse" "github.com/polyverse/masche/process" "unsafe" ) func nextMemoryRegion(p process.Process, address uintptr) (region MemoryRegion, harderror error, softerrors []error) { var isAvailable C.bool var cRegion C.memory_region_t response := C.get_next_memory_region( (C.process_handle_t)(p.Handle()), C.memory_address_t(address), &isAvailable, &cRegion) harderror, softerrors = cresponse.GetResponsesErrors(unsafe.Pointer(response)) C.response_free(response) if harderror != nil || isAvailable == false { return NoRegionAvailable, harderror, softerrors } return MemoryRegion{uintptr(cRegion.start_address), uint(cRegion.length), Access(cRegion.access), C.GoString(cRegion.kind)}, harderror, softerrors } func copyMemory(p process.Process, address uintptr, buffer []byte) (harderror error, softerrors []error) { buf := unsafe.Pointer(&buffer[0]) n := len(buffer) var bytesRead C.size_t resp := C.copy_process_memory( (C.process_handle_t)(p.Handle()), C.memory_address_t(address), C.size_t(n), buf, &bytesRead, ) harderror, softerrors = cresponse.GetResponsesErrors(unsafe.Pointer(resp)) C.response_free(resp) if harderror != nil { harderror = fmt.Errorf("Error while copying %d bytes starting at %x: %s", n, address, harderror.Error()) return } if len(buffer) != int(bytesRead) { harderror = fmt.Errorf("Could not copy %d bytes starting at %x, copyed %d", len(buffer), address, bytesRead) } return }
Grosskopf/openoffice
main/svx/source/svdraw/svdotxat.cxx
/************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <svl/style.hxx> #include <svx/svdotext.hxx> #include "svx/svditext.hxx" #include <svx/svdmodel.hxx> // fuer GetMaxObjSize und GetStyleSheetPool #include <svx/svdoutl.hxx> #include <svx/svdorect.hxx> // fuer SetDirty bei NbcAdjustTextFrameWidthAndHeight #include <svx/svdocapt.hxx> // fuer SetDirty bei NbcAdjustTextFrameWidthAndHeight #include <svx/svdetc.hxx> #include <editeng/writingmodeitem.hxx> #include <editeng/editeng.hxx> #include <editeng/eeitem.hxx> #include <editeng/flditem.hxx> #include <svx/sdtfchim.hxx> #include <editeng/editview.hxx> #include <svl/smplhint.hxx> #include <svl/whiter.hxx> #include <editeng/outlobj.hxx> #include <editeng/outliner.hxx> #include <editeng/eeitem.hxx> #include <editeng/editobj.hxx> #include <editeng/fhgtitem.hxx> #include <editeng/charscaleitem.hxx> #include <svl/style.hxx> #include <svl/itemiter.hxx> #include <editeng/lrspitem.hxx> #include <svl/itempool.hxx> #include <editeng/numitem.hxx> #include <editeng/editeng.hxx> #include <editeng/postitem.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // // @@@@@@ @@@@@ @@ @@ @@@@@@ @@@@ @@@@@ @@@@@@ // @@ @@ @@@ @@@ @@ @@ @@ @@ @@ @@ // @@ @@ @@@@@ @@ @@ @@ @@ @@ @@ // @@ @@@@ @@@ @@ @@ @@ @@@@@ @@ // @@ @@ @@@@@ @@ @@ @@ @@ @@ @@ // @@ @@ @@@ @@@ @@ @@ @@ @@ @@ @@ @@ // @@ @@@@@ @@ @@ @@ @@@@ @@@@@ @@@@ // // Attribute, StyleSheets und AutoGrow // //////////////////////////////////////////////////////////////////////////////////////////////////// FASTBOOL SdrTextObj::AdjustTextFrameWidthAndHeight(Rectangle& rR, FASTBOOL bHgt, FASTBOOL bWdt) const { if (bTextFrame && pModel!=NULL && !rR.IsEmpty()) { SdrFitToSizeType eFit=GetFitToSize(); FASTBOOL bFitToSize=(eFit==SDRTEXTFIT_PROPORTIONAL || eFit==SDRTEXTFIT_ALLLINES); FASTBOOL bWdtGrow=bWdt && IsAutoGrowWidth(); FASTBOOL bHgtGrow=bHgt && IsAutoGrowHeight(); SdrTextAniKind eAniKind=GetTextAniKind(); SdrTextAniDirection eAniDir=GetTextAniDirection(); FASTBOOL bScroll=eAniKind==SDRTEXTANI_SCROLL || eAniKind==SDRTEXTANI_ALTERNATE || eAniKind==SDRTEXTANI_SLIDE; FASTBOOL bHScroll=bScroll && (eAniDir==SDRTEXTANI_LEFT || eAniDir==SDRTEXTANI_RIGHT); FASTBOOL bVScroll=bScroll && (eAniDir==SDRTEXTANI_UP || eAniDir==SDRTEXTANI_DOWN); if (!bFitToSize && (bWdtGrow || bHgtGrow)) { Rectangle aR0(rR); long nHgt=0,nMinHgt=0,nMaxHgt=0; long nWdt=0,nMinWdt=0,nMaxWdt=0; Size aSiz(rR.GetSize()); aSiz.Width()--; aSiz.Height()--; Size aMaxSiz(100000,100000); Size aTmpSiz(pModel->GetMaxObjSize()); if (aTmpSiz.Width()!=0) aMaxSiz.Width()=aTmpSiz.Width(); if (aTmpSiz.Height()!=0) aMaxSiz.Height()=aTmpSiz.Height(); if (bWdtGrow) { nMinWdt=GetMinTextFrameWidth(); nMaxWdt=GetMaxTextFrameWidth(); if (nMaxWdt==0 || nMaxWdt>aMaxSiz.Width()) nMaxWdt=aMaxSiz.Width(); if (nMinWdt<=0) nMinWdt=1; aSiz.Width()=nMaxWdt; } if (bHgtGrow) { nMinHgt=GetMinTextFrameHeight(); nMaxHgt=GetMaxTextFrameHeight(); if (nMaxHgt==0 || nMaxHgt>aMaxSiz.Height()) nMaxHgt=aMaxSiz.Height(); if (nMinHgt<=0) nMinHgt=1; aSiz.Height()=nMaxHgt; } long nHDist=GetTextLeftDistance()+GetTextRightDistance(); long nVDist=GetTextUpperDistance()+GetTextLowerDistance(); aSiz.Width()-=nHDist; aSiz.Height()-=nVDist; if (aSiz.Width()<2) aSiz.Width()=2; // Mindestgroesse 2 if (aSiz.Height()<2) aSiz.Height()=2; // Mindestgroesse 2 // #101684# sal_Bool bInEditMode = IsInEditMode(); if(!bInEditMode) { if (bHScroll) aSiz.Width()=0x0FFFFFFF; // Laufschrift nicht umbrechen if (bVScroll) aSiz.Height()=0x0FFFFFFF; } if(pEdtOutl) { pEdtOutl->SetMaxAutoPaperSize(aSiz); if (bWdtGrow) { Size aSiz2(pEdtOutl->CalcTextSize()); nWdt=aSiz2.Width()+1; // lieber etwas Tolleranz if (bHgtGrow) nHgt=aSiz2.Height()+1; // lieber etwas Tolleranz } else { nHgt=pEdtOutl->GetTextHeight()+1; // lieber etwas Tolleranz } } else { Outliner& rOutliner=ImpGetDrawOutliner(); rOutliner.SetPaperSize(aSiz); rOutliner.SetUpdateMode(sal_True); // !!! hier sollte ich wohl auch noch mal die Optimierung mit // bPortionInfoChecked usw einbauen OutlinerParaObject* pOutlinerParaObject = GetOutlinerParaObject(); if ( pOutlinerParaObject != NULL ) { rOutliner.SetText(*pOutlinerParaObject); rOutliner.SetFixedCellHeight(((const SdrTextFixedCellHeightItem&)GetMergedItem(SDRATTR_TEXT_USEFIXEDCELLHEIGHT)).GetValue()); } if (bWdtGrow) { Size aSiz2(rOutliner.CalcTextSize()); nWdt=aSiz2.Width()+1; // lieber etwas Tolleranz if (bHgtGrow) nHgt=aSiz2.Height()+1; // lieber etwas Tolleranz } else { nHgt=rOutliner.GetTextHeight()+1; // lieber etwas Tolleranz } rOutliner.Clear(); } if (nWdt<nMinWdt) nWdt=nMinWdt; if (nWdt>nMaxWdt) nWdt=nMaxWdt; nWdt+=nHDist; if (nWdt<1) nWdt=1; // nHDist kann auch negativ sein if (nHgt<nMinHgt) nHgt=nMinHgt; if (nHgt>nMaxHgt) nHgt=nMaxHgt; nHgt+=nVDist; if (nHgt<1) nHgt=1; // nVDist kann auch negativ sein long nWdtGrow=nWdt-(rR.Right()-rR.Left()); long nHgtGrow=nHgt-(rR.Bottom()-rR.Top()); if (nWdtGrow==0) bWdtGrow=sal_False; if (nHgtGrow==0) bHgtGrow=sal_False; if (bWdtGrow || bHgtGrow) { if (bWdtGrow) { SdrTextHorzAdjust eHAdj=GetTextHorizontalAdjust(); if (eHAdj==SDRTEXTHORZADJUST_LEFT) rR.Right()+=nWdtGrow; else if (eHAdj==SDRTEXTHORZADJUST_RIGHT) rR.Left()-=nWdtGrow; else { long nWdtGrow2=nWdtGrow/2; rR.Left()-=nWdtGrow2; rR.Right()=rR.Left()+nWdt; } } if (bHgtGrow) { SdrTextVertAdjust eVAdj=GetTextVerticalAdjust(); if (eVAdj==SDRTEXTVERTADJUST_TOP) rR.Bottom()+=nHgtGrow; else if (eVAdj==SDRTEXTVERTADJUST_BOTTOM) rR.Top()-=nHgtGrow; else { long nHgtGrow2=nHgtGrow/2; rR.Top()-=nHgtGrow2; rR.Bottom()=rR.Top()+nHgt; } } if (aGeo.nDrehWink!=0) { Point aD1(rR.TopLeft()); aD1-=aR0.TopLeft(); Point aD2(aD1); RotatePoint(aD2,Point(),aGeo.nSin,aGeo.nCos); aD2-=aD1; rR.Move(aD2.X(),aD2.Y()); } return sal_True; } } } return sal_False; } FASTBOOL SdrTextObj::NbcAdjustTextFrameWidthAndHeight(FASTBOOL bHgt, FASTBOOL bWdt) { FASTBOOL bRet=AdjustTextFrameWidthAndHeight(aRect,bHgt,bWdt); if (bRet) { SetRectsDirty(); if (HAS_BASE(SdrRectObj,this)) { // mal wieder 'nen Hack ((SdrRectObj*)this)->SetXPolyDirty(); } if (HAS_BASE(SdrCaptionObj,this)) { // mal wieder 'nen Hack ((SdrCaptionObj*)this)->ImpRecalcTail(); } } return bRet; } FASTBOOL SdrTextObj::AdjustTextFrameWidthAndHeight(FASTBOOL bHgt, FASTBOOL bWdt) { Rectangle aNeuRect(aRect); FASTBOOL bRet=AdjustTextFrameWidthAndHeight(aNeuRect,bHgt,bWdt); if (bRet) { Rectangle aBoundRect0; if (pUserCall!=NULL) aBoundRect0=GetLastBoundRect(); // #110094#-14 SendRepaintBroadcast(); aRect=aNeuRect; SetRectsDirty(); if (HAS_BASE(SdrRectObj,this)) { // mal wieder 'nen Hack ((SdrRectObj*)this)->SetXPolyDirty(); } if (HAS_BASE(SdrCaptionObj,this)) { // mal wieder 'nen Hack ((SdrCaptionObj*)this)->ImpRecalcTail(); } SetChanged(); BroadcastObjectChange(); SendUserCall(SDRUSERCALL_RESIZE,aBoundRect0); } return bRet; } void SdrTextObj::ImpSetTextStyleSheetListeners() { SfxStyleSheetBasePool* pStylePool=pModel!=NULL ? pModel->GetStyleSheetPool() : NULL; if (pStylePool!=NULL) { Container aStyles(1024,64,64); OutlinerParaObject* pOutlinerParaObject = GetOutlinerParaObject(); if (pOutlinerParaObject!=NULL) { // Zunaechst werden alle im ParaObject enthaltenen StyleSheets // im Container aStyles gesammelt. Dazu wird die Family jeweils // ans Ende des StyleSheet-Namen drangehaengt. const EditTextObject& rTextObj=pOutlinerParaObject->GetTextObject(); XubString aStyleName; SfxStyleFamily eStyleFam; sal_uInt16 nParaAnz=rTextObj.GetParagraphCount(); for(sal_uInt16 nParaNum(0); nParaNum < nParaAnz; nParaNum++) { rTextObj.GetStyleSheet(nParaNum, aStyleName, eStyleFam); if(aStyleName.Len()) { XubString aFam = UniString::CreateFromInt32((sal_uInt16)eStyleFam); aFam.Expand(5); aStyleName += sal_Unicode('|'); aStyleName += aFam; sal_Bool bFnd(sal_False); sal_uInt32 nNum(aStyles.Count()); while(!bFnd && nNum > 0) { // kein StyleSheet doppelt! nNum--; bFnd = (aStyleName.Equals(*(XubString*)aStyles.GetObject(nNum))); } if(!bFnd) { aStyles.Insert(new XubString(aStyleName), CONTAINER_APPEND); } } } } // nun die Strings im Container durch StyleSheet* ersetzten sal_uIntPtr nNum=aStyles.Count(); while (nNum>0) { nNum--; XubString* pName=(XubString*)aStyles.GetObject(nNum); // UNICODE: String aFam(pName->Cut(pName->Len()-6)); String aFam = pName->Copy(0, pName->Len() - 6); aFam.Erase(0,1); aFam.EraseTrailingChars(); // UNICODE: sal_uInt16 nFam=sal_uInt16(aFam); sal_uInt16 nFam = (sal_uInt16)aFam.ToInt32(); SfxStyleFamily eFam=(SfxStyleFamily)nFam; SfxStyleSheetBase* pStyleBase=pStylePool->Find(*pName,eFam); SfxStyleSheet* pStyle=PTR_CAST(SfxStyleSheet,pStyleBase); delete pName; if (pStyle!=NULL && pStyle!=GetStyleSheet()) { aStyles.Replace(pStyle,nNum); } else { aStyles.Remove(nNum); } } // jetzt alle ueberfluessigen StyleSheets entfernen nNum=GetBroadcasterCount(); while (nNum>0) { nNum--; SfxBroadcaster* pBroadcast=GetBroadcasterJOE((sal_uInt16)nNum); SfxStyleSheet* pStyle=PTR_CAST(SfxStyleSheet,pBroadcast); if (pStyle!=NULL && pStyle!=GetStyleSheet()) { // Sonderbehandlung fuer den StyleSheet des Objekts if (aStyles.GetPos(pStyle)==CONTAINER_ENTRY_NOTFOUND) { EndListening(*pStyle); } } } // und schliesslich alle in aStyles enthaltenen StyleSheets mit den vorhandenen Broadcastern mergen nNum=aStyles.Count(); while (nNum>0) { nNum--; SfxStyleSheet* pStyle=(SfxStyleSheet*)aStyles.GetObject(nNum); // StartListening soll selbst nachsehen, ob hier nicht evtl. schon gehorcht wird StartListening(*pStyle,sal_True); } } } void SdrTextObj::NbcResizeTextAttributes(const Fraction& xFact, const Fraction& yFact) { OutlinerParaObject* pOutlinerParaObject = GetOutlinerParaObject(); if (pOutlinerParaObject!=NULL && xFact.IsValid() && yFact.IsValid()) { Fraction n100(100,1); long nX=long(xFact*n100); long nY=long(yFact*n100); if (nX<0) nX=-nX; if (nX<1) nX=1; if (nX>0xFFFF) nX=0xFFFF; if (nY<0) nY=-nY; if (nY<1) nY=1; if (nY>0xFFFF) nY=0xFFFF; if (nX!=100 || nY!=100) { // Rahmenattribute const SfxItemSet& rSet = GetObjectItemSet(); const SvxCharScaleWidthItem& rOldWdt=(SvxCharScaleWidthItem&)rSet.Get(EE_CHAR_FONTWIDTH); const SvxFontHeightItem& rOldHgt=(SvxFontHeightItem&)rSet.Get(EE_CHAR_FONTHEIGHT); // erstmal die alten Werte holen long nRelWdt=rOldWdt.GetValue(); long nAbsHgt=rOldHgt.GetHeight(); long nRelHgt=rOldHgt.GetProp(); // Relative Breite aendern nRelWdt*=nX; nRelWdt/=nY; if (nRelWdt<0) nRelWdt=-nRelWdt; // nicht negativ if (nRelWdt<=0) nRelWdt=1; // und mind. 1% if (nRelWdt>0xFFFF) nRelWdt=0xFFFF; // Absolute Hoehe aendern nAbsHgt*=nY; nAbsHgt/=100; if (nAbsHgt<0) nAbsHgt=-nAbsHgt; // nicht negativ if (nAbsHgt<=0) nAbsHgt=1; // und mind. 1 if (nAbsHgt>0xFFFF) nAbsHgt=0xFFFF; // und nun attributieren SetObjectItem(SvxCharScaleWidthItem( (sal_uInt16) nRelWdt, EE_CHAR_FONTWIDTH)); SetObjectItem(SvxFontHeightItem(nAbsHgt,(sal_uInt16)nRelHgt, EE_CHAR_FONTHEIGHT)); // Zeichen- und Absatzattribute innerhalb des OutlinerParaObjects Outliner& rOutliner=ImpGetDrawOutliner(); rOutliner.SetPaperSize(Size(LONG_MAX,LONG_MAX)); rOutliner.SetText(*pOutlinerParaObject); rOutliner.DoStretchChars((sal_uInt16)nX,(sal_uInt16)nY); OutlinerParaObject* pNewPara=rOutliner.CreateParaObject(); NbcSetOutlinerParaObject(pNewPara); rOutliner.Clear(); } } } /** #103836# iterates over the paragraphs of a given SdrObject and removes all hard set character attributes with the which ids contained in the given vector */ void SdrTextObj::RemoveOutlinerCharacterAttribs( const std::vector<sal_uInt16>& rCharWhichIds ) { sal_Int32 nText = getTextCount(); while( --nText >= 0 ) { SdrText* pText = getText( nText ); OutlinerParaObject* pOutlinerParaObject = pText ? pText->GetOutlinerParaObject() : 0; if(pOutlinerParaObject) { Outliner* pOutliner = 0; if( pEdtOutl || (pText == getActiveText()) ) pOutliner = pEdtOutl; if(!pOutliner) { pOutliner = &ImpGetDrawOutliner(); pOutliner->SetText(*pOutlinerParaObject); } ESelection aSelAll( 0, 0, 0xffff, 0xffff ); std::vector<sal_uInt16>::const_iterator aIter( rCharWhichIds.begin() ); while( aIter != rCharWhichIds.end() ) { pOutliner->RemoveAttribs( aSelAll, false, (*aIter++) ); } if(!pEdtOutl || (pText != getActiveText()) ) { const sal_uInt32 nParaCount = pOutliner->GetParagraphCount(); OutlinerParaObject* pTemp = pOutliner->CreateParaObject(0, (sal_uInt16)nParaCount); pOutliner->Clear(); NbcSetOutlinerParaObjectForText(pTemp, pText); } } } } bool SdrTextObj::HasText() const { if( pEdtOutl ) return HasEditText(); OutlinerParaObject* pOPO = GetOutlinerParaObject(); bool bHasText = false; if( pOPO ) { const EditTextObject& rETO = pOPO->GetTextObject(); sal_uInt16 nParaCount = rETO.GetParagraphCount(); if( nParaCount > 0 ) bHasText = (nParaCount > 1) || (rETO.GetText( 0 ).Len() != 0); } return bHasText; }
baidubce/baiducloud-cce-cni-driver
pkg/config/types/cnimode.go
<gh_stars>10-100 /* * Copyright (c) 2021 Baidu, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. * */ package types // ContainerNetworkMode defines container config type ContainerNetworkMode string const ( // K8sNetworkModeKubenet using kubenet K8sNetworkModeKubenet ContainerNetworkMode = "kubenet" // CCEModeRouteVeth using vpc route plus veth CCEModeRouteVeth ContainerNetworkMode = "vpc-route-veth" // CCEModeRouteIPVlan using vpc route plus ipvlan CCEModeRouteIPVlan ContainerNetworkMode = "vpc-route-ipvlan" // CCEModeRouteAutoDetect using vpc route and auto detects veth or ipvlan due to kernel version CCEModeRouteAutoDetect ContainerNetworkMode = "vpc-route-auto-detect" // CCEModeSecondaryIPVeth using vpc secondary ip plus veth CCEModeSecondaryIPVeth ContainerNetworkMode = "vpc-secondary-ip-veth" // CCEModeSecondaryIPIPVlan using vpc secondary ip plus ipvlan CCEModeSecondaryIPIPVlan ContainerNetworkMode = "vpc-secondary-ip-ipvlan" // CCEModeSecondaryIPAutoDetect using vpc secondary ip and auto detects veth or ipvlan due to kernel version CCEModeSecondaryIPAutoDetect ContainerNetworkMode = "vpc-secondary-ip-auto-detect" // CCEModeBBCSecondaryIPVeth using vpc secondary ip plus veth (BBC only) CCEModeBBCSecondaryIPVeth ContainerNetworkMode = "bbc-vpc-secondary-ip-veth" // CCEModeBBCSecondaryIPIPVlan using vpc secondary ip plus ipvlan (BBC only) CCEModeBBCSecondaryIPIPVlan ContainerNetworkMode = "bbc-vpc-secondary-ip-ipvlan" // CCEModeBBCSecondaryIPAutoDetect using vpc secondary ip and auto detects veth or ipvlan due to kernel version (BBC only) CCEModeBBCSecondaryIPAutoDetect ContainerNetworkMode = "bbc-vpc-secondary-ip-auto-detect" ) func IsCCECNIModeBasedOnVPCRoute(mode ContainerNetworkMode) bool { if mode == CCEModeRouteVeth || mode == CCEModeRouteIPVlan || mode == CCEModeRouteAutoDetect { return true } return false } func IsCCECNIModeAutoDetect(mode ContainerNetworkMode) bool { switch mode { case CCEModeRouteAutoDetect: return true case CCEModeSecondaryIPAutoDetect: return true case CCEModeBBCSecondaryIPAutoDetect: return true default: return false } } func IsCCECNIModeBasedOnBCCSecondaryIP(mode ContainerNetworkMode) bool { if mode == CCEModeSecondaryIPVeth || mode == CCEModeSecondaryIPIPVlan || mode == CCEModeSecondaryIPAutoDetect { return true } return false } func IsCCECNIModeBasedOnBBCSecondaryIP(mode ContainerNetworkMode) bool { if mode == CCEModeBBCSecondaryIPVeth || mode == CCEModeBBCSecondaryIPIPVlan || mode == CCEModeBBCSecondaryIPAutoDetect { return true } return false } func IsCCECNIModeBasedOnSecondaryIP(mode ContainerNetworkMode) bool { return IsCCECNIModeBasedOnBCCSecondaryIP(mode) || IsCCECNIModeBasedOnBBCSecondaryIP(mode) } func IsCCECNIMode(mode ContainerNetworkMode) bool { return IsCCECNIModeBasedOnVPCRoute(mode) || IsCCECNIModeBasedOnBCCSecondaryIP(mode) || IsCCECNIModeBasedOnBBCSecondaryIP(mode) } func IsKubenetMode(mode ContainerNetworkMode) bool { if mode == K8sNetworkModeKubenet { return true } return false }
gustavo978/helpful
ns-allinone-3.22/ns-3.22/src/core/model/fatal-impl.h
<filename>ns-allinone-3.22/ns-3.22/src/core/model/fatal-impl.h /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 NICTA * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: <NAME> <<EMAIL>> */ #ifndef FATAL_IMPL_H #define FATAL_IMPL_H #include <ostream> /** * \file * \ingroup fatalimpl * \brief Declaration of RegisterStream(), UnregisterStream(), and FlushStreams(). */ /** * \ingroup fatal * \defgroup fatalimpl Fatal Implementation. */ namespace ns3 { /** * \ingroup fatalimpl * \brief Implementation namespace for fatal error handlers. */ namespace FatalImpl { /** * \ingroup fatalimpl * * \brief Register a stream to be flushed on abnormal exit. * * If a \c std::terminate() call is encountered after the * stream had been registered and before it has been * unregistered, \c stream->flush() will be called. Users of * this function should ensure the stream remains valid until * it had been unregistered. * * \param stream The stream to be flushed on abnormal exit. */ void RegisterStream (std::ostream* stream); /** * \ingroup fatalimpl * * \brief Unregister a stream for flushing on abnormal exit. * * After a stream had been unregistered, \c stream->flush() * will no longer be called should abnormal termination be * encountered. * * If the stream is not registered, nothing will happen. * * \param stream The stream to be unregistered. */ void UnregisterStream (std::ostream* stream); /** * \ingroup fatalimpl * * \brief Flush all currently registered streams. * * This function iterates through each registered stream and * unregisters them. The default \c SIGSEGV handler is overridden * when this function is being executed, and will be restored * when this function returns. * * If a \c SIGSEGV is encountered (most likely due to a bad \c ostream* * being registered, or a registered \c osteam* pointing to an * \c ostream that had already been destroyed), this function will * skip the bad \c ostream* and continue to flush the next stream. * The function will then terminate raising \c SIGIOT (aka \c SIGABRT) * * DO NOT call this function until the program is ready to crash. */ void FlushStreams (void); } //FatalImpl } //ns3 #endif
mhuryanov/gitlab
ee/spec/frontend/security_configuration/components/manage_dast_profiles_spec.js
import { shallowMount } from '@vue/test-utils'; import ManageDastProfiles from 'ee/security_configuration/components/manage_dast_profiles.vue'; import { extendedWrapper } from 'helpers/vue_test_utils_helper'; import { generateFeatures } from './helpers'; describe('ManageDastProfiles component', () => { let wrapper; const createComponent = (propsData) => { wrapper = extendedWrapper(shallowMount(ManageDastProfiles, { propsData })); }; const findButton = () => wrapper.findByTestId('manage-button'); afterEach(() => { wrapper.destroy(); }); it('renders the DAST Profiles manage button', () => { const [feature] = generateFeatures(1, { configuration_path: '/foo' }); createComponent({ feature }); const button = findButton(); expect(button.text()).toBe('Manage'); expect(button.attributes('href')).toBe(feature.configuration_path); }); });
kermitdafrog8/REDasm-Loaders
chip8/assembler/chip8.cpp
#include "chip8.h" void CHIP8::renderInstruction(RDContext*, const RDRendererParams* rp) { //RDSurfaceRenderer_HexDump(rp->renderer, &rp->view, sizeof(u16)); CHIP8Instruction instruction; if(!CHIP8Decoder::decode(&rp->view, &instruction)) return; if(instruction.mnemonic.empty()) { switch(instruction.op) { case CHIP8Opcode_Copy: case CHIP8Opcode_SetI: case CHIP8Opcode_SetTime: case CHIP8Opcode_SetTone: case CHIP8Opcode_SetPitch: case CHIP8Opcode_GetTime: case CHIP8Opcode_GetKey: CHIP8::renderCopy(&instruction, rp); break; case CHIP8Opcode_Copy2: CHIP8::renderCopy2(&instruction, rp); break; case CHIP8Opcode_Add: case CHIP8Opcode_Sub: case CHIP8Opcode_And: case CHIP8Opcode_Xor: case CHIP8Opcode_Or: CHIP8::renderMath(&instruction, rp); break; default: RDRenderer_Text(rp->renderer, "???"); break; } return; } if(instruction.op == CHIP8Opcode_Return) RDRenderer_Mnemonic(rp->renderer, instruction.mnemonic.c_str(), Theme_Ret); else RDRenderer_Mnemonic(rp->renderer, instruction.mnemonic.c_str(), Theme_Default); RDRenderer_Text(rp->renderer, " "); for(size_t i = 0; i < instruction.operands.size(); i++) { const CHIP8Operand* op = &instruction.operands[i]; if(IS_TYPE(op, CHIP8Operand_Null)) break; if(i) RDRenderer_Text(rp->renderer, ", "); CHIP8::renderOperand(rp, op); } } void CHIP8::emulate(RDContext* ctx, RDEmulateResult* result) { CHIP8Instruction instruction; if(!CHIP8Decoder::decode(RDEmulateResult_GetView(result), &instruction)) return; if((instruction.opcode == 0x00EE) || (instruction.opcode == 0xF000)) RDEmulateResult_AddReturn(result); else { rd_address address = RDEmulateResult_GetAddress(result); u16 op = instruction.opcode & 0xF000; switch(op) { case 0x1000: RDEmulateResult_AddBranch(result, instruction.opcode & 0x0FFF); break; case 0x2000: RDEmulateResult_AddCall(result, instruction.opcode & 0x0FFF); break; case 0x3000: case 0x4000: case 0x5000: case 0x9000: case 0xE000: RDEmulateResult_AddBranchTrue(result, address + (sizeof(u16) * 2)); RDEmulateResult_AddBranchFalse(result, address + sizeof(u16)); break; } } RDEmulateResult_SetSize(result, sizeof(u16)); } void CHIP8::renderOperand(const RDRendererParams* rp, const CHIP8Operand* op) { switch(op->type) { case CHIP8Operand_Register: RDRenderer_Register(rp->renderer, ("$v" + std::to_string(op->reg)).c_str()); break; case CHIP8Operand_Register_I: RDRenderer_Register(rp->renderer, "$i"); break; case CHIP8Operand_Register_MI: RDRenderer_Register(rp->renderer, "$mi"); break; case CHIP8Operand_Register_KEY: RDRenderer_Register(rp->renderer, "KEY"); break; case CHIP8Operand_Register_TIME: RDRenderer_Register(rp->renderer, "TIME"); break; case CHIP8Operand_Register_TONE: RDRenderer_Register(rp->renderer, "TONE"); break; case CHIP8Operand_Register_PITCH: RDRenderer_Register(rp->renderer, "PITCH"); break; case CHIP8Operand_Register_DEQ: RDRenderer_Register(rp->renderer, "DEQ"); break; case CHIP8Operand_Register_DSP: RDRenderer_Register(rp->renderer, "DSP"); break; case CHIP8Operand_Register_RS485: RDRenderer_Register(rp->renderer, "RS485"); break; case CHIP8Operand_Register_BAUD: RDRenderer_Register(rp->renderer, "BAUD"); break; case CHIP8Operand_Constant: RDRenderer_Unsigned(rp->renderer, op->cnst); break; case CHIP8Operand_Address: RDRenderer_Reference(rp->renderer, op->addr); break; case CHIP8Operand_Register_Range: RDRenderer_Register(rp->renderer, ("$v" + std::to_string(op->reg1)).c_str()); RDRenderer_Text(rp->renderer, ":"); RDRenderer_Register(rp->renderer, ("$v" + std::to_string(op->reg2)).c_str()); break; default: RDRenderer_Text(rp->renderer, "???"); break; } } void CHIP8::renderCopy(CHIP8Instruction* instruction, const RDRendererParams* rp) { CHIP8::renderOperand(rp, &instruction->operands[0]); RDRenderer_Text(rp->renderer, " = "); CHIP8::renderOperand(rp, &instruction->operands[1]); } void CHIP8::renderCopy2(CHIP8Instruction* instruction, const RDRendererParams* rp) { CHIP8::renderOperand(rp, &instruction->operands[0]); RDRenderer_Text(rp->renderer, " = "); CHIP8::renderOperand(rp, &instruction->operands[1]); RDRenderer_Text(rp->renderer, ", "); CHIP8::renderOperand(rp, &instruction->operands[2]); } void CHIP8::renderMath(CHIP8Instruction* instruction, const RDRendererParams* rp) { CHIP8::renderOperand(rp, &instruction->operands[0]); RDRenderer_Text(rp->renderer, " = "); CHIP8::renderOperand(rp, &instruction->operands[0]); switch(instruction->op) { case CHIP8Opcode_Add: RDRenderer_Text(rp->renderer, " + "); break; case CHIP8Opcode_Sub: RDRenderer_Text(rp->renderer, " - "); break; case CHIP8Opcode_And: RDRenderer_Text(rp->renderer, " & "); break; case CHIP8Opcode_Xor: RDRenderer_Text(rp->renderer, " ^ "); break; case CHIP8Opcode_Or: RDRenderer_Text(rp->renderer, " | "); break; default: RDRenderer_Text(rp->renderer, " ??? "); break; } CHIP8::renderOperand(rp, &instruction->operands[1]); }
SiamV/React-OpenSourceProject-FullStack
client/components/SocialBlocks/WhatsApp.js
import React from 'react'; import WhatsAppImg from '../../images/whatsapp-v2.png'; import classes from './SocialBlocks.module.css' const WhatsApp = (props) => { return ( <div className={classes.wrapperImgSocial}> <a href="https://api.whatsapp.com/send?phone=5219983969285"> <img src={WhatsAppImg} alt='WhatsApp' className={classes.imgSocial}/> </a> </div> ) } export default WhatsApp;
Shostina/metacherchant
src/io/LargeKmerLoader.java
package io; import org.apache.log4j.Logger; import ru.ifmo.genetics.dna.Dna; import ru.ifmo.genetics.io.ReadersUtils; import ru.ifmo.genetics.io.sources.NamedSource; import ru.ifmo.genetics.structures.map.BigLong2ShortHashMap; import ru.ifmo.genetics.utils.NumUtils; import ru.ifmo.genetics.utils.tool.ExecutionFailedException; import ru.ifmo.genetics.utils.tool.Tool; import utils.HashFunction; import utils.PolynomialHash; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import static utils.StringUtils.normalizeDna; /** * Created by -- on 23.08.2019. */ public class LargeKmerLoader { static final int READS_WORK_RANGE_SIZE = 1 << 15; // 32 K public static HashFunction hash; static class ReadsLoadWorker extends ReadsWorker { ReadsLoadWorker(Map<String, Integer> subgraph, int k, int minDnaLen, HashFunction hasher, BigLong2ShortHashMap graph) { this.subgraph = subgraph; this.graph = graph; this.k = k; this.minDnaLen = minDnaLen; this.hasher = hasher; } final BigLong2ShortHashMap graph; final Map<String, Integer> subgraph; final int k; final int minDnaLen; final HashFunction hasher; @Override public void process(List<Dna> reads) { for (Dna dna : reads) { if (dna.length() >= minDnaLen) { for (int i = 0; i + k <= dna.length(); i++) { String key = dna.substring(i, i + k).toString(); subgraph.put(normalizeDna(key), (int) graph.get(hasher.hash(normalizeDna(key)))); } } } } } public static Map<String, Integer> loadReads(File[] files, int k, int minSeqLen, int availableProcessors, Logger logger, BigLong2ShortHashMap graph, HashFunction hasher) throws ExecutionFailedException { BigLong2ShortHashMap hm = new BigLong2ShortHashMap( (int) (Math.log(availableProcessors) / Math.log(2)) + 4, 12, true); ConcurrentMap<String, Integer> subgraph = new ConcurrentHashMap<>(); hash = hasher != null ? hasher : new PolynomialHash(); LargeKmerLoader.ReadsLoadWorker[] workers = new LargeKmerLoader.ReadsLoadWorker[availableProcessors]; for (int i = 0; i < workers.length; ++i) { workers[i] = new LargeKmerLoader.ReadsLoadWorker(subgraph, k, minSeqLen, hash, graph); } run(files, workers, hm, logger); return subgraph; } public static void run(File[] files, ReadsWorker[] workers, BigLong2ShortHashMap hmForMonitoring, Logger logger) throws ExecutionFailedException { for (File file : files) { Tool.info(logger, "Loading file " + file.getName() + "..."); NamedSource<Dna> reader = null; try { reader = ReadersUtils.readDnaLazyTrunc(file, null); } catch (IOException e) { throw new ExecutionFailedException("Failed to read from file " + file.getPath()); } ReadsDispatcher dispatcher = new ReadsDispatcher(reader, READS_WORK_RANGE_SIZE, hmForMonitoring); CountDownLatch latch = new CountDownLatch(workers.length); for (int i = 0; i < workers.length; ++i) { workers[i].setDispatcher(dispatcher); workers[i].setLatch(latch); new Thread(workers[i]).start(); } try { latch.await(); } catch (InterruptedException e) { Tool.warn(logger, "Main thread interrupted"); for (ReadsWorker worker : workers) { worker.interrupt(); } throw new ExecutionFailedException("Thread was interrupted", e); } Tool.info(logger, NumUtils.groupDigits(dispatcher.reads) + " reads added"); } } }
GerHobbelt/DOMtastic
benchmark/init.js
<filename>benchmark/init.js (function(root) { var bench = root.benchrunner; bench.libs = [ { name: 'jQuery', version: '', script: { src: 'vendor/jquery.min.js', onload: function(jQuery) { root.jQuery = (jQuery || root.jQuery).noConflict(); bench.libs[0].version = root.jQuery.fn.jquery; } } }, { name: 'Zepto', version: '1.1.3', script: { src: 'vendor/zepto.min.js' } }, { name: 'DOMtastic', version: '', script: { src: '../dist/domtastic.min.js', onload: function($) { root.$ = ($ || root.$).noConflict(); bench.libs[2].version = root.$.version; } } } ]; bench.setup.push(function() { var div = document.createElement('div'); div.id = 'container'; div.style.display = 'none'; document.body.appendChild(div); }); bench.onComplete = function(results, callback) { var data = {}, suiteNameParts, suiteGroupName, key, config = { 'Class': { key: '<KEY>', url: 'http://www.browserscope.org/user/tests/table/agt1YS1wcm9maWxlcnIRCxIEVGVzdBiAgICkvo7WCQw?v=3&layout=simple' }, 'Constructor': { key: '<KEY>', url: 'http://www.browserscope.org/user/tests/table/agt1YS1wcm9maWxlcnIRCxIEVGVzdBiAgICkyo2ECQw?v=3&layout=simple' }, 'DOM': { key: '<KEY>_Cgw', url: 'http://www.browserscope.org/user/tests/table/agt1YS1wcm9maWxlcnIRCxIEVGVzdBiAgIDk0Jv_Cgw?v=3&layout=simple' }, 'Selector': { key: '<KEY>', url: 'http://www.browserscope.org/user/tests/table/agt1YS1wcm9maWxlcnIRCxIEVGVzdBiAgICkzLXNCAw?v=3&layout=simple' } }; function log(text) { console.log(text + ''); var uiConsole = document && document.getElementById('ui-console'); if(uiConsole) { uiConsole.textContent += text + '\n'; } } function postToBrowserScope(suiteKey, browserScopeKey, data) { root._bTestResults = data; if (root.document && !root.phantom) { log('\nSending data for "' + suiteKey + '" to BrowserScope (' + config[suiteKey].url + ')'); var newScript = document.createElement('script'), firstScript = document.getElementsByTagName('script')[0]; newScript.src = 'http://www.browserscope.org/user/beacon/' + browserScopeKey; newScript.src += '?callback=browserScopeCallback'; firstScript.parentNode.insertBefore(newScript, firstScript); } else { callback(); } } root.browserScopeCallback = function browserScopeCallback() { log('✓'); callback(); }; bench.libs.forEach(function(lib) { config[lib.name] = lib.name + ' ' + lib.version; }); for(var suiteName in results) { suiteNameParts = suiteName.split('.'); suiteGroupName = suiteNameParts[0]; if(suiteGroupName in config) { data[suiteGroupName] = data[suiteGroupName] || {}; for(var lib in results[suiteName]) { key = [config[lib], suiteNameParts[1]].join(' ').trim(); data[suiteGroupName][key] = parseInt(results[suiteName][lib].hz, 10); } } } for(var suiteGroup in data) { postToBrowserScope(suiteGroup, config[suiteGroup].key, data[suiteGroup]); } } }(typeof global == 'object' && global || this));
googleapis/googleapis-gen
google/apps/alertcenter/v1beta1/google-cloud-apps-alertcenter-v1beta1-java/proto-google-cloud-apps-alertcenter-v1beta1-java/src/main/java/com/google/apps/alertcenter/v1beta1/ListAlertsResponse.java
<gh_stars>1-10 // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/apps/alertcenter/v1beta1/alertcenter.proto package com.google.apps.alertcenter.v1beta1; /** * <pre> * Response message for an alert listing request. * </pre> * * Protobuf type {@code google.apps.alertcenter.v1beta1.ListAlertsResponse} */ public final class ListAlertsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.apps.alertcenter.v1beta1.ListAlertsResponse) ListAlertsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListAlertsResponse.newBuilder() to construct. private ListAlertsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListAlertsResponse() { alerts_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new ListAlertsResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ListAlertsResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { alerts_ = new java.util.ArrayList<com.google.apps.alertcenter.v1beta1.Alert>(); mutable_bitField0_ |= 0x00000001; } alerts_.add( input.readMessage(com.google.apps.alertcenter.v1beta1.Alert.parser(), extensionRegistry)); break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); nextPageToken_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { alerts_ = java.util.Collections.unmodifiableList(alerts_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.apps.alertcenter.v1beta1.AlertCenterProto.internal_static_google_apps_alertcenter_v1beta1_ListAlertsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.apps.alertcenter.v1beta1.AlertCenterProto.internal_static_google_apps_alertcenter_v1beta1_ListAlertsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.apps.alertcenter.v1beta1.ListAlertsResponse.class, com.google.apps.alertcenter.v1beta1.ListAlertsResponse.Builder.class); } public static final int ALERTS_FIELD_NUMBER = 1; private java.util.List<com.google.apps.alertcenter.v1beta1.Alert> alerts_; /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ @java.lang.Override public java.util.List<com.google.apps.alertcenter.v1beta1.Alert> getAlertsList() { return alerts_; } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.apps.alertcenter.v1beta1.AlertOrBuilder> getAlertsOrBuilderList() { return alerts_; } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ @java.lang.Override public int getAlertsCount() { return alerts_.size(); } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ @java.lang.Override public com.google.apps.alertcenter.v1beta1.Alert getAlerts(int index) { return alerts_.get(index); } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ @java.lang.Override public com.google.apps.alertcenter.v1beta1.AlertOrBuilder getAlertsOrBuilder( int index) { return alerts_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; private volatile java.lang.Object nextPageToken_; /** * <pre> * The token for the next page. If not empty, indicates that there may be more * alerts that match the listing request; this value can be used in a * subsequent [ListAlertsRequest][google.apps.alertcenter.v1beta1.ListAlertsRequest] to get alerts continuing from last result * of the current list call. * </pre> * * <code>string next_page_token = 2;</code> * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * <pre> * The token for the next page. If not empty, indicates that there may be more * alerts that match the listing request; this value can be used in a * subsequent [ListAlertsRequest][google.apps.alertcenter.v1beta1.ListAlertsRequest] to get alerts continuing from last result * of the current list call. * </pre> * * <code>string next_page_token = 2;</code> * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < alerts_.size(); i++) { output.writeMessage(1, alerts_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < alerts_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, alerts_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.apps.alertcenter.v1beta1.ListAlertsResponse)) { return super.equals(obj); } com.google.apps.alertcenter.v1beta1.ListAlertsResponse other = (com.google.apps.alertcenter.v1beta1.ListAlertsResponse) obj; if (!getAlertsList() .equals(other.getAlertsList())) return false; if (!getNextPageToken() .equals(other.getNextPageToken())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getAlertsCount() > 0) { hash = (37 * hash) + ALERTS_FIELD_NUMBER; hash = (53 * hash) + getAlertsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.apps.alertcenter.v1beta1.ListAlertsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.alertcenter.v1beta1.ListAlertsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.alertcenter.v1beta1.ListAlertsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.alertcenter.v1beta1.ListAlertsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.alertcenter.v1beta1.ListAlertsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.alertcenter.v1beta1.ListAlertsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.alertcenter.v1beta1.ListAlertsResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.apps.alertcenter.v1beta1.ListAlertsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.apps.alertcenter.v1beta1.ListAlertsResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.apps.alertcenter.v1beta1.ListAlertsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.apps.alertcenter.v1beta1.ListAlertsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.apps.alertcenter.v1beta1.ListAlertsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.apps.alertcenter.v1beta1.ListAlertsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Response message for an alert listing request. * </pre> * * Protobuf type {@code google.apps.alertcenter.v1beta1.ListAlertsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.apps.alertcenter.v1beta1.ListAlertsResponse) com.google.apps.alertcenter.v1beta1.ListAlertsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.apps.alertcenter.v1beta1.AlertCenterProto.internal_static_google_apps_alertcenter_v1beta1_ListAlertsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.apps.alertcenter.v1beta1.AlertCenterProto.internal_static_google_apps_alertcenter_v1beta1_ListAlertsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.apps.alertcenter.v1beta1.ListAlertsResponse.class, com.google.apps.alertcenter.v1beta1.ListAlertsResponse.Builder.class); } // Construct using com.google.apps.alertcenter.v1beta1.ListAlertsResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getAlertsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); if (alertsBuilder_ == null) { alerts_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { alertsBuilder_.clear(); } nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.apps.alertcenter.v1beta1.AlertCenterProto.internal_static_google_apps_alertcenter_v1beta1_ListAlertsResponse_descriptor; } @java.lang.Override public com.google.apps.alertcenter.v1beta1.ListAlertsResponse getDefaultInstanceForType() { return com.google.apps.alertcenter.v1beta1.ListAlertsResponse.getDefaultInstance(); } @java.lang.Override public com.google.apps.alertcenter.v1beta1.ListAlertsResponse build() { com.google.apps.alertcenter.v1beta1.ListAlertsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.apps.alertcenter.v1beta1.ListAlertsResponse buildPartial() { com.google.apps.alertcenter.v1beta1.ListAlertsResponse result = new com.google.apps.alertcenter.v1beta1.ListAlertsResponse(this); int from_bitField0_ = bitField0_; if (alertsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { alerts_ = java.util.Collections.unmodifiableList(alerts_); bitField0_ = (bitField0_ & ~0x00000001); } result.alerts_ = alerts_; } else { result.alerts_ = alertsBuilder_.build(); } result.nextPageToken_ = nextPageToken_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.apps.alertcenter.v1beta1.ListAlertsResponse) { return mergeFrom((com.google.apps.alertcenter.v1beta1.ListAlertsResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.apps.alertcenter.v1beta1.ListAlertsResponse other) { if (other == com.google.apps.alertcenter.v1beta1.ListAlertsResponse.getDefaultInstance()) return this; if (alertsBuilder_ == null) { if (!other.alerts_.isEmpty()) { if (alerts_.isEmpty()) { alerts_ = other.alerts_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureAlertsIsMutable(); alerts_.addAll(other.alerts_); } onChanged(); } } else { if (!other.alerts_.isEmpty()) { if (alertsBuilder_.isEmpty()) { alertsBuilder_.dispose(); alertsBuilder_ = null; alerts_ = other.alerts_; bitField0_ = (bitField0_ & ~0x00000001); alertsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getAlertsFieldBuilder() : null; } else { alertsBuilder_.addAllMessages(other.alerts_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.apps.alertcenter.v1beta1.ListAlertsResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.apps.alertcenter.v1beta1.ListAlertsResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List<com.google.apps.alertcenter.v1beta1.Alert> alerts_ = java.util.Collections.emptyList(); private void ensureAlertsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { alerts_ = new java.util.ArrayList<com.google.apps.alertcenter.v1beta1.Alert>(alerts_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.apps.alertcenter.v1beta1.Alert, com.google.apps.alertcenter.v1beta1.Alert.Builder, com.google.apps.alertcenter.v1beta1.AlertOrBuilder> alertsBuilder_; /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public java.util.List<com.google.apps.alertcenter.v1beta1.Alert> getAlertsList() { if (alertsBuilder_ == null) { return java.util.Collections.unmodifiableList(alerts_); } else { return alertsBuilder_.getMessageList(); } } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public int getAlertsCount() { if (alertsBuilder_ == null) { return alerts_.size(); } else { return alertsBuilder_.getCount(); } } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public com.google.apps.alertcenter.v1beta1.Alert getAlerts(int index) { if (alertsBuilder_ == null) { return alerts_.get(index); } else { return alertsBuilder_.getMessage(index); } } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public Builder setAlerts( int index, com.google.apps.alertcenter.v1beta1.Alert value) { if (alertsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAlertsIsMutable(); alerts_.set(index, value); onChanged(); } else { alertsBuilder_.setMessage(index, value); } return this; } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public Builder setAlerts( int index, com.google.apps.alertcenter.v1beta1.Alert.Builder builderForValue) { if (alertsBuilder_ == null) { ensureAlertsIsMutable(); alerts_.set(index, builderForValue.build()); onChanged(); } else { alertsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public Builder addAlerts(com.google.apps.alertcenter.v1beta1.Alert value) { if (alertsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAlertsIsMutable(); alerts_.add(value); onChanged(); } else { alertsBuilder_.addMessage(value); } return this; } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public Builder addAlerts( int index, com.google.apps.alertcenter.v1beta1.Alert value) { if (alertsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAlertsIsMutable(); alerts_.add(index, value); onChanged(); } else { alertsBuilder_.addMessage(index, value); } return this; } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public Builder addAlerts( com.google.apps.alertcenter.v1beta1.Alert.Builder builderForValue) { if (alertsBuilder_ == null) { ensureAlertsIsMutable(); alerts_.add(builderForValue.build()); onChanged(); } else { alertsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public Builder addAlerts( int index, com.google.apps.alertcenter.v1beta1.Alert.Builder builderForValue) { if (alertsBuilder_ == null) { ensureAlertsIsMutable(); alerts_.add(index, builderForValue.build()); onChanged(); } else { alertsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public Builder addAllAlerts( java.lang.Iterable<? extends com.google.apps.alertcenter.v1beta1.Alert> values) { if (alertsBuilder_ == null) { ensureAlertsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, alerts_); onChanged(); } else { alertsBuilder_.addAllMessages(values); } return this; } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public Builder clearAlerts() { if (alertsBuilder_ == null) { alerts_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { alertsBuilder_.clear(); } return this; } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public Builder removeAlerts(int index) { if (alertsBuilder_ == null) { ensureAlertsIsMutable(); alerts_.remove(index); onChanged(); } else { alertsBuilder_.remove(index); } return this; } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public com.google.apps.alertcenter.v1beta1.Alert.Builder getAlertsBuilder( int index) { return getAlertsFieldBuilder().getBuilder(index); } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public com.google.apps.alertcenter.v1beta1.AlertOrBuilder getAlertsOrBuilder( int index) { if (alertsBuilder_ == null) { return alerts_.get(index); } else { return alertsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public java.util.List<? extends com.google.apps.alertcenter.v1beta1.AlertOrBuilder> getAlertsOrBuilderList() { if (alertsBuilder_ != null) { return alertsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(alerts_); } } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public com.google.apps.alertcenter.v1beta1.Alert.Builder addAlertsBuilder() { return getAlertsFieldBuilder().addBuilder( com.google.apps.alertcenter.v1beta1.Alert.getDefaultInstance()); } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public com.google.apps.alertcenter.v1beta1.Alert.Builder addAlertsBuilder( int index) { return getAlertsFieldBuilder().addBuilder( index, com.google.apps.alertcenter.v1beta1.Alert.getDefaultInstance()); } /** * <pre> * The list of alerts. * </pre> * * <code>repeated .google.apps.alertcenter.v1beta1.Alert alerts = 1;</code> */ public java.util.List<com.google.apps.alertcenter.v1beta1.Alert.Builder> getAlertsBuilderList() { return getAlertsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.apps.alertcenter.v1beta1.Alert, com.google.apps.alertcenter.v1beta1.Alert.Builder, com.google.apps.alertcenter.v1beta1.AlertOrBuilder> getAlertsFieldBuilder() { if (alertsBuilder_ == null) { alertsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.apps.alertcenter.v1beta1.Alert, com.google.apps.alertcenter.v1beta1.Alert.Builder, com.google.apps.alertcenter.v1beta1.AlertOrBuilder>( alerts_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); alerts_ = null; } return alertsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * <pre> * The token for the next page. If not empty, indicates that there may be more * alerts that match the listing request; this value can be used in a * subsequent [ListAlertsRequest][google.apps.alertcenter.v1beta1.ListAlertsRequest] to get alerts continuing from last result * of the current list call. * </pre> * * <code>string next_page_token = 2;</code> * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * The token for the next page. If not empty, indicates that there may be more * alerts that match the listing request; this value can be used in a * subsequent [ListAlertsRequest][google.apps.alertcenter.v1beta1.ListAlertsRequest] to get alerts continuing from last result * of the current list call. * </pre> * * <code>string next_page_token = 2;</code> * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * The token for the next page. If not empty, indicates that there may be more * alerts that match the listing request; this value can be used in a * subsequent [ListAlertsRequest][google.apps.alertcenter.v1beta1.ListAlertsRequest] to get alerts continuing from last result * of the current list call. * </pre> * * <code>string next_page_token = 2;</code> * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken( java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; onChanged(); return this; } /** * <pre> * The token for the next page. If not empty, indicates that there may be more * alerts that match the listing request; this value can be used in a * subsequent [ListAlertsRequest][google.apps.alertcenter.v1beta1.ListAlertsRequest] to get alerts continuing from last result * of the current list call. * </pre> * * <code>string next_page_token = 2;</code> * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); onChanged(); return this; } /** * <pre> * The token for the next page. If not empty, indicates that there may be more * alerts that match the listing request; this value can be used in a * subsequent [ListAlertsRequest][google.apps.alertcenter.v1beta1.ListAlertsRequest] to get alerts continuing from last result * of the current list call. * </pre> * * <code>string next_page_token = 2;</code> * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.apps.alertcenter.v1beta1.ListAlertsResponse) } // @@protoc_insertion_point(class_scope:google.apps.alertcenter.v1beta1.ListAlertsResponse) private static final com.google.apps.alertcenter.v1beta1.ListAlertsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.apps.alertcenter.v1beta1.ListAlertsResponse(); } public static com.google.apps.alertcenter.v1beta1.ListAlertsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListAlertsResponse> PARSER = new com.google.protobuf.AbstractParser<ListAlertsResponse>() { @java.lang.Override public ListAlertsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ListAlertsResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ListAlertsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListAlertsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.apps.alertcenter.v1beta1.ListAlertsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
alexxv/REST
src/test/java/org/rest/test/suite/SearchTestSuite.java
package org.rest.test.suite; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import org.rest.sec.persistence.service.RoleServiceSearchPersistenceIntegrationTest; import org.rest.sec.util.ConstructQueryStringUnitTest; import org.rest.sec.util.ParseQueryStringUnitTest; import org.rest.sec.web.role.RoleSearchRESTIntegrationTest; @RunWith(Suite.class) @SuiteClasses({ ParseQueryStringUnitTest.class, ConstructQueryStringUnitTest.class, RoleServiceSearchPersistenceIntegrationTest.class, RoleSearchRESTIntegrationTest.class }) public final class SearchTestSuite { // }
SaraPerezSoler/SOCIO
old/es.uam.miso.modelado/src/es/uam/app/actions/metamodels/UpdateRefType.java
<gh_stars>1-10 package es.uam.app.actions.metamodels; import es.uam.app.actions.UpdateMetamodel; import es.uam.app.projects.IsClass; import es.uam.app.projects.IsReference; import es.uam.app.projects.ecore.ClassControl; import es.uam.app.projects.ecore.ReferenceControl; import socioProjects.MetamodelProject; public class UpdateRefType extends UpdateMetamodel { private IsReference ref = null; private IsClass type = null; private int max; public UpdateRefType(MetamodelProject proj, IsReference ref, IsClass type, int max) { super(proj); this.ref = ref; this.type= type; this.max=max; } public UpdateRefType(MetamodelProject p, ReferenceControl referenceControl, ReferenceControl oldC, ReferenceControl newC) { super(p); setObject(referenceControl); setOld(oldC); setNew(newC); this.setExecute(true); } @Override public void doIt() throws Exception { if (isExecute()) { return; } ReferenceControl refControl=ref.getReferenceControl(); if (refControl == null) { throw new Exception("Problem ocurred in"+this.getClass().getName()+": the reference is not found"); } setOld(refControl.copyObject()); ClassControl typeCC= null; if (type!=null){ typeCC=type.getClassControl(); } refControl.setType(typeCC); refControl.setUpperBound(max); setNew(refControl.copyObject()); setObject(refControl); setExecute(true); } @Override public void undoIt() throws Exception { if (!isExecute() || isUndo()){ return; } ClassControl type=getProject().getClass(((ReferenceControl)getOldC()).getTypeName()); (getObject()).setType(type); getObject().setLowerBound(((ReferenceControl)getOldC()).getLowerBound()); getObject().setUpperBound(((ReferenceControl)getOldC()).getUpperBound()); setUndo(true); } @Override public void redoIt() throws Exception { if (!isExecute() || !isUndo()){ return; } ClassControl type=getProject().getClass(((ReferenceControl)getNewC()).getTypeName()); getObject().setLowerBound(((ReferenceControl)getNewC()).getLowerBound()); getObject().setUpperBound(((ReferenceControl)getNewC()).getUpperBound()); (getObject()).setType(type); setUndo(false); } @Override public ReferenceControl getObject() { return (ReferenceControl)super.getObject(); } }
hjc851/SourceCodePlagiarismDetectionDataset
Variant Programs/1/1-16/producing/VintnerPole.java
<reponame>hjc851/SourceCodePlagiarismDetectionDataset package producing; import developmentElements.ImmiscibleDisagree; import storeroom.*; public class VintnerPole extends Grower { private BroadsheetRelationRosters<ImmiscibleDisagree> basket = null; protected synchronized void provideExpectedObjet() throws StowageLootedDerogation { try { this.typicalOpposes = (this.finalGarage.nowAgenda()); } catch (StowageLootedDerogation ej) { throw ej; } } protected synchronized void stepPreviousMatterSpecialistsSpace() { this.basket.putConclusion(this.typicalOpposes); this.typicalOpposes = (null); } public VintnerPole(double hateful, double roam, Warehouses successive) { unhide(hateful, roam, null, successive); this.government = (GrowersCanton.emaciated); this.basket = (new BroadsheetRelationRosters<ImmiscibleDisagree>()); } }
spencercjh/codeLife
exam/src/exam/qihu2019/Test1.java
package exam.qihu2019; import java.util.Scanner; import java.util.regex.Pattern; public class Test1 { static Pattern NUMBER = Pattern.compile("^(-?\\d+)(\\.\\d+)?$"); static Pattern INTEGER = Pattern.compile("^(-?\\d+)$"); static int string2int(String str) { if (str == null || !NUMBER.matcher(str).matches()) { return 0; } boolean negative = false; if ('-' == str.charAt(0)) { negative = true; str = str.substring(1); } if (!INTEGER.matcher(str).matches()) { str = str.substring(0, str.indexOf('.')); } int num = 0; for (char ch : str.toCharArray()) { num = num * 10 + ch - '0'; } if (negative) { num *= -1; } return num; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int res; String _str; try { _str = in.nextLine(); } catch (Exception e) { _str = null; } res = string2int(_str); System.out.println(String.valueOf(res)); } }
niklas/Tirade
vendor/plugins/globalize2/lib/globalize/model/active_record/adapter.rb
module Globalize module Model class AttributeStash < Hash def contains?(locale, attr_name) locale = locale.to_sym self[locale] ||= {} self[locale].has_key? attr_name end def read(locale, attr_name) locale = locale.to_sym self[locale] ||= {} self[locale][attr_name] end def write(locale, attr_name, value) locale = locale.to_sym self[locale] ||= {} self[locale][attr_name] = value end end class Adapter def initialize(record) @record = record # TODO what exactly are the roles of cache and stash @cache = AttributeStash.new @stash = AttributeStash.new end def fetch(locale, attr_name) # locale = I18n.locale is_cached = @cache.contains?(locale, attr_name) is_cached ? @cache.read(locale, attr_name) : begin value = fetch_attribute locale, attr_name @cache.write locale, attr_name, value if value && value.locale == locale value end end def stash(locale, attr_name, value) @stash.write locale, attr_name, value @cache.write locale, attr_name, value end def update_translations! @stash.each do |locale, attrs| translation = @record.globalize_translations.find_or_initialize_by_locale(locale.to_s) attrs.each{|attr_name, value| translation[attr_name] = value } translation.save! end @stash.clear end # Clears the cache def clear @cache.clear @stash.clear end private def fetch_attribute(locale, attr_name) fallbacks = I18n.fallbacks[locale].map{|tag| tag.to_s}.map(&:to_sym) # If the translations were included with # :include => globalize_translations # there is no need to query them again. unless @record.globalize_translations.loaded? translations = @record.globalize_translations.by_locales(fallbacks) else translations = @record.globalize_translations end result, requested_locale = nil, locale # Walk through the fallbacks, starting with the current locale itself, and moving # to the next best choice, until we find a match. # Check the @globalize_set_translations cache first to see if we've just changed the # attribute and not saved yet. fallbacks.each do |fallback| # TODO should we be checking stash or just cache? result = @stash.read(fallback, attr_name) || begin translation = translations.detect {|tr| tr.locale == fallback } translation && translation.send(attr_name) end if result locale = fallback break end end result && Translation::Attribute.new(result, :locale => locale, :requested_locale => requested_locale) end end end end
xiayingfeng/ontop
db/rdb/src/main/java/it/unibz/inf/ontop/model/term/functionsymbol/db/impl/OracleDBFunctionSymbolFactory.java
package it.unibz.inf.ontop.model.term.functionsymbol.db.impl; import com.google.common.collect.HashBasedTable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableTable; import com.google.common.collect.Table; import com.google.inject.Inject; import it.unibz.inf.ontop.model.term.ImmutableTerm; import it.unibz.inf.ontop.model.term.TermFactory; import it.unibz.inf.ontop.model.term.functionsymbol.db.*; import it.unibz.inf.ontop.model.type.DBTermType; import it.unibz.inf.ontop.model.type.DBTypeFactory; import it.unibz.inf.ontop.model.type.RDFDatatype; import it.unibz.inf.ontop.model.type.TypeFactory; import it.unibz.inf.ontop.model.vocabulary.XSD; import java.util.UUID; import java.util.function.Function; import static it.unibz.inf.ontop.model.term.functionsymbol.db.impl.MySQLDBFunctionSymbolFactory.UUID_STR; import static it.unibz.inf.ontop.model.type.impl.DefaultSQLDBTypeFactory.DATE_STR; import static it.unibz.inf.ontop.model.type.impl.DefaultSQLDBTypeFactory.TIMESTAMP_STR; import static it.unibz.inf.ontop.model.type.impl.OracleDBTypeFactory.NUMBER_STR; import static it.unibz.inf.ontop.model.type.impl.OracleDBTypeFactory.TIMESTAMP_LOCAL_TZ_STR; public class OracleDBFunctionSymbolFactory extends AbstractSQLDBFunctionSymbolFactory { private static final String UNSUPPORTED_MSG = "Not supported by Oracle"; private static final String RANDOM_STR = "DBMS_RANDOM.VALUE"; private static final String TO_CHAR_STR = "TO_CHAR"; // Created in init() private DBFunctionSymbol dbRightFunctionSymbol; @Inject protected OracleDBFunctionSymbolFactory(TypeFactory typeFactory) { super(createOracleRegularFunctionTable(typeFactory), typeFactory); } @Override protected void init() { super.init(); dbRightFunctionSymbol = new SimpleTypedDBFunctionSymbolImpl(RIGHT_STR, 2, dbStringType, false, abstractRootDBType, ((terms, termConverter, termFactory) -> String.format("SUBSTR(%s,-1*%s)", termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1))))); } protected static ImmutableTable<String, Integer, DBFunctionSymbol> createOracleRegularFunctionTable( TypeFactory typeFactory) { DBTypeFactory dbTypeFactory = typeFactory.getDBTypeFactory(); DBTermType dbStringType = dbTypeFactory.getDBStringType(); DBTermType abstractRootDBType = dbTypeFactory.getAbstractRootDBType(); Table<String, Integer, DBFunctionSymbol> table = HashBasedTable.create( createDefaultRegularFunctionTable(typeFactory)); table.remove(RIGHT_STR, 2); DBFunctionSymbol nowFunctionSymbol = new WithoutParenthesesSimpleTypedDBFunctionSymbolImpl( CURRENT_TIMESTAMP_STR, dbTypeFactory.getDBDateTimestampType(), abstractRootDBType); table.put(CURRENT_TIMESTAMP_STR, 0, nowFunctionSymbol); // Default TO_CHAR (unknown input type) DBFunctionSymbol toChar1FunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(TO_CHAR_STR, 1, dbStringType, false, abstractRootDBType); table.put(TO_CHAR_STR, 1, toChar1FunctionSymbol); DBFunctionSymbol toChar2FunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(TO_CHAR_STR, 2, dbStringType, false, abstractRootDBType); table.put(TO_CHAR_STR, 2, toChar2FunctionSymbol); return ImmutableTable.copyOf(table); } /** * TODO: shall we alert the user when TIMESTAMP is used with a XSD.DATETIMESTAMP? */ @Override protected ImmutableTable<DBTermType, RDFDatatype, DBTypeConversionFunctionSymbol> createNormalizationTable() { Table<DBTermType, RDFDatatype, DBTypeConversionFunctionSymbol> table = HashBasedTable.create(); table.putAll(super.createNormalizationTable()); RDFDatatype xsdDatetime = typeFactory.getXsdDatetimeDatatype(); RDFDatatype xsdDatetimeStamp = typeFactory.getXsdDatetimeStampDatatype(); DBTermType timestampLTzType = dbTypeFactory.getDBTermType(TIMESTAMP_LOCAL_TZ_STR); DBTypeConversionFunctionSymbol datetimeLTZNormFunctionSymbol = createDateTimeNormFunctionSymbol(timestampLTzType); table.put(timestampLTzType, xsdDatetime, datetimeLTZNormFunctionSymbol); table.put(timestampLTzType, xsdDatetimeStamp, datetimeLTZNormFunctionSymbol); DBTermType timestampType = dbTypeFactory.getDBTermType(TIMESTAMP_STR); DBTypeConversionFunctionSymbol datetimeNormFunctionSymbol = createDateTimeNormFunctionSymbol(timestampType); table.put(timestampType, xsdDatetime, datetimeNormFunctionSymbol); // No TZ for TIMESTAMP --> incompatible with XSD.DATETIMESTAMP // Date column in Oracle does include time information, too DBTermType dbDateType = dbTypeFactory.getDBTermType(DATE_STR); DBTypeConversionFunctionSymbol datetimeNormFunctionSymbolWoTz = createDateTimeNormFunctionSymbol(dbDateType); table.put(dbDateType, xsdDatetime, datetimeNormFunctionSymbolWoTz); DBTypeConversionFunctionSymbol dateNormFunctionSymbol = new OracleDateNormFunctionSymbol(dbDateType, dbStringType); table.put(dbDateType, typeFactory.getDatatype(XSD.DATE), dateNormFunctionSymbol); // NUMBER boolean normalization RDFDatatype xsdBoolean = typeFactory.getXsdBooleanDatatype(); DBTermType numberType = dbTypeFactory.getDBTermType(NUMBER_STR); table.put(numberType, xsdBoolean, new DefaultNumberNormAsBooleanFunctionSymbol(numberType, dbStringType)); return ImmutableTable.copyOf(table); } @Override protected ImmutableTable<DBTermType, RDFDatatype, DBTypeConversionFunctionSymbol> createDenormalizationTable() { Table<DBTermType, RDFDatatype, DBTypeConversionFunctionSymbol> table = HashBasedTable.create(); table.putAll(super.createDenormalizationTable()); DBTermType dbDateType = dbTypeFactory.getDBTermType(DATE_STR); DBTypeConversionFunctionSymbol dateDenormFunctionSymbol = new OracleDateDenormFunctionSymbol(dbStringType, dbDateType); table.put(dbDateType, typeFactory.getDatatype(XSD.DATE), dateDenormFunctionSymbol); return ImmutableTable.copyOf(table); } @Override public DBFunctionSymbol getDBSubString2() { return getRegularDBFunctionSymbol(SUBSTR_STR, 2); } @Override public DBFunctionSymbol getDBSubString3() { return getRegularDBFunctionSymbol(SUBSTR_STR, 3); } @Override public DBFunctionSymbol getDBRight() { return dbRightFunctionSymbol; } @Override public DBFunctionSymbol getDBCharLength() { return getRegularDBFunctionSymbol(LENGTH_STR, 1); } @Override public NonDeterministicDBFunctionSymbol getDBRand(UUID uuid) { return new DefaultNonDeterministicNullaryFunctionSymbol(RANDOM_STR, uuid, dbDoubleType, (terms, termConverter, termFactory) -> RANDOM_STR); } @Override protected String getRandNameInDialect() { throw new UnsupportedOperationException("getRandNameInDialect() must not be called for Oracle"); } @Override protected String serializeContains(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { return String.format("(INSTR(%s,%s) > 0)", termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1))); } @Override protected String serializeStrBefore(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { String str = termConverter.apply(terms.get(0)); String before = termConverter.apply(terms.get(1)); return String.format("NVL(SUBSTR(%s,0,INSTR(%s,%s)-1),'')", str, str, before); } @Override protected String serializeStrAfter(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { String str = termConverter.apply(terms.get(0)); String after = termConverter.apply(terms.get(1)); // NB: (%s IS NULL) here is for empty strings (NULL in Oracle...) return String.format("CASE WHEN %s IS NULL THEN %s ELSE NVL(SUBSTR(%s,INSTR(%s,%s)+LENGTH(%s),SIGN(INSTR(%s,%s))*LENGTH(%s)),'') END", after, str, str, str, after, after, str, after, str); //FIXME when no match found should return empty string } @Override protected String serializeMD5(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { return String.format("LOWER(TO_CHAR(RAWTOHEX(SYS.DBMS_CRYPTO.HASH(UTL_I18N.STRING_TO_RAW(%s, 'AL32UTF8'), 2))))", termConverter.apply(terms.get(0))); } @Override protected String serializeSHA1(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { return String.format("LOWER(TO_CHAR(RAWTOHEX(SYS.DBMS_CRYPTO.HASH(UTL_I18N.STRING_TO_RAW(%s, 'AL32UTF8'), SYS.DBMS_CRYPTO.HASH_SH1))))", termConverter.apply(terms.get(0))); } @Override protected String serializeSHA256(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { return String.format("LOWER(TO_CHAR(RAWTOHEX(SYS.DBMS_CRYPTO.HASH(UTL_I18N.STRING_TO_RAW(%s, 'AL32UTF8'), SYS.DBMS_CRYPTO.HASH_SH256))))", termConverter.apply(terms.get(0))); } @Override protected String serializeSHA512(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { return String.format("LOWER(TO_CHAR(RAWTOHEX(SYS.DBMS_CRYPTO.HASH(UTL_I18N.STRING_TO_RAW(%s, 'AL32UTF8'), SYS.DBMS_CRYPTO.HASH_SH512))))", termConverter.apply(terms.get(0))); } /** * TODO: use a different implementation of the FunctionSymbol for simplifying in the presence of TIMESTAMP (has no TZ) * Currently: Oracle throws a fatal error */ @Override protected DBFunctionSymbol createTzFunctionSymbol() { return super.createTzFunctionSymbol(); } /** * TODO: reformat the number into 05:00 instead of 5:0 */ @Override protected String serializeTz(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { String str = termConverter.apply(terms.get(0)); return String.format("CASE WHEN EXTRACT(TIMEZONE_HOUR FROM %s) IS NOT NULL \n" + " THEN EXTRACT(TIMEZONE_HOUR FROM %s) || ':' || EXTRACT(TIMEZONE_MINUTE FROM %s)\n" + " ELSE NULL\n" + "END", str, str, str); } @Override protected String serializeDBRowNumber(Function<ImmutableTerm, String> converter, TermFactory termFactory) { return "ROWNUM"; } @Override protected DBConcatFunctionSymbol createNullRejectingDBConcat(int arity) { return new OracleNullRejectingDBConcatFunctionSymbol(arity, dbStringType, abstractRootDBType); } /** * Treats NULLs as empty strings */ @Override public DBConcatFunctionSymbol createDBConcatOperator(int arity) { return new NullToleratingDBConcatFunctionSymbol(CONCAT_OP_STR, arity, dbStringType, abstractRootDBType, true); } /** * Treats NULLs as empty strings */ @Override protected DBConcatFunctionSymbol createRegularDBConcat(int arity) { if (arity != 2) throw new UnsupportedOperationException("CONCAT is a binary function in Oracle. Use || instead."); return new NullToleratingDBConcatFunctionSymbol(CONCAT_STR, 2, dbStringType, abstractRootDBType, false); } @Override protected DBTypeConversionFunctionSymbol createSimpleCastFunctionSymbol(DBTermType targetType) { if (targetType.equals(dbStringType)) return createDefaultCastToStringFunctionSymbol(abstractRootDBType); return super.createSimpleCastFunctionSymbol(targetType); } /** * Made explicit, so as to enforce the use of the same character set */ @Override protected DBTypeConversionFunctionSymbol createStringToStringCastFunctionSymbol(DBTermType inputType, DBTermType targetType) { return createDefaultCastToStringFunctionSymbol(inputType); } @Override protected DBTypeConversionFunctionSymbol createIntegerToStringCastFunctionSymbol(DBTermType inputType) { return new DefaultCastIntegerToStringFunctionSymbol(inputType, dbStringType, Serializers.getRegularSerializer(TO_CHAR_STR)); } @Override protected DBTypeConversionFunctionSymbol createDefaultCastToStringFunctionSymbol(DBTermType inputType) { return new DefaultSimpleDBCastFunctionSymbol(inputType, dbStringType, Serializers.getRegularSerializer(TO_CHAR_STR)); } @Override protected DBBooleanFunctionSymbol createDBBooleanCase(int arity, boolean doOrderingMatter) { return new WrappedDBBooleanCaseFunctionSymbolImpl(arity, dbBooleanType, abstractRootDBType, doOrderingMatter); } @Override protected DBIsNullOrNotFunctionSymbol createDBIsNull(DBTermType dbBooleanType, DBTermType rootDBTermType) { return new ExpressionSensitiveSQLDBIsNullOrNotFunctionSymbolImpl(true, dbBooleanType, rootDBTermType); } @Override protected DBIsNullOrNotFunctionSymbol createDBIsNotNull(DBTermType dbBooleanType, DBTermType rootDBTermType) { return new ExpressionSensitiveSQLDBIsNullOrNotFunctionSymbolImpl(false, dbBooleanType, rootDBTermType); } /** * Overrides */ @Override protected DBTypeConversionFunctionSymbol createDateTimeNormFunctionSymbol(DBTermType dbDateTimestampType) { return new DefaultSQLTimestampISONormFunctionSymbol( dbDateTimestampType, dbStringType, (terms, converter, factory) -> serializeDateTimeNorm(dbDateTimestampType, terms, converter)); } /** * NB: In some JDBC connection settings, returns a comma instead of a period. */ protected String serializeDateTimeNorm(DBTermType dbDateTimestampType, ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter) { /* * TIMESTAMP by default does not support time zones */ if (dbDateTimestampType.equals(dbTypeFactory.getDBTermType(TIMESTAMP_STR))) { return String.format("REPLACE(REPLACE(TO_CHAR(%s,'YYYY-MM-DD HH24:MI:SSxFF'),' ','T'),',','.')", termConverter.apply(terms.get(0))); } // Timezone support else if (dbDateTimestampType.equals(dbTypeFactory.getDBTermType(DATE_STR))) { return String.format("REPLACE(REGEXP_REPLACE(TO_CHAR(CAST (%s AS TIMESTAMP WITH TIME ZONE),'YYYY-MM-DD HH24:MI:SSxFFTZH:TZM'),' ','T',1,1),',','.')", termConverter.apply(terms.get(0))); } else return String.format( "REPLACE(REPLACE(REGEXP_REPLACE(TO_CHAR(%s,'YYYY-MM-DD HH24:MI:SSxFFTZH:TZM'),' ','T',1,1),' ',''),',','.')", termConverter.apply(terms.get(0))); } @Override protected String serializeDateTimeNorm(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { throw new UnsupportedOperationException("This method should not be called for Oracle"); } @Override protected DBTypeConversionFunctionSymbol createDateTimeDenormFunctionSymbol(DBTermType timestampType) { return new OracleTimestampISODenormFunctionSymbol(timestampType, dbStringType); } @Override public NonDeterministicDBFunctionSymbol getDBUUID(UUID uuid) { return new DefaultNonDeterministicNullaryFunctionSymbol(UUID_STR, uuid, dbStringType, (terms, termConverter, termFactory) -> "LOWER(REGEXP_REPLACE(RAWTOHEX(SYS_GUID()), '([A-F0-9]{8})([A-F0-9]{4})([A-F0-9]{4})([A-F0-9]{4})([A-F0-9]{12})', '\\1-\\2-\\3-\\4-\\5'))" ); } @Override protected String getUUIDNameInDialect() { throw new UnsupportedOperationException("Do not call getUUIDNameInDialect for Oracle"); } /** * Time extension - duration arithmetic */ @Override protected String serializeWeeksBetween(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { return String.format("TRUNC(EXTRACT(DAY FROM %s - %s) / 7)", termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1)), termConverter.apply(terms.get(1)), termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1)), termConverter.apply(terms.get(0))); } @Override protected String serializeWeeksBetweenFromDate(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { return String.format("TRUNC((%s - %s)/7)", termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1))); } @Override protected String serializeDaysBetweenFromDateTime(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { return String.format("EXTRACT(DAY FROM %s - %s)", termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1))); } @Override protected String serializeDaysBetweenFromDate(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { return String.format("%s - %s", termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1))); } @Override protected String serializeHoursBetween(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { return String.format("EXTRACT(DAY FROM %s - %s) * 24 + " + "EXTRACT(HOUR FROM %s - %s)", termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1)), termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1))); } @Override protected String serializeMinutesBetween(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { return String.format("EXTRACT(DAY FROM %s - %s) * 24 * 60 + " + "EXTRACT(HOUR FROM %s - %s) * 60 + " + "EXTRACT(MINUTE FROM %s - %s)", termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1)), termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1)), termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1))); } @Override protected String serializeSecondsBetween(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { return String.format("EXTRACT(DAY FROM %s - %s) * 24 * 60 * 60 + " + "EXTRACT(HOUR FROM %s - %s) * 60 * 60 + " + "EXTRACT(MINUTE FROM %s - %s) * 60 + " + "EXTRACT(SECOND FROM %s - %s)", termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1)), termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1)), termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1)), termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1))); } @Override protected String serializeMillisBetween(ImmutableList<? extends ImmutableTerm> terms, Function<ImmutableTerm, String> termConverter, TermFactory termFactory) { return String.format("(EXTRACT(DAY FROM %s - %s) * 24 * 60 * 60 + " + "EXTRACT(HOUR FROM %s - %s) * 60 * 60 + " + "EXTRACT(MINUTE FROM %s - %s) * 60 + " + "EXTRACT(SECOND FROM %s - %s))*1000", termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1)), termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1)), termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1)), termConverter.apply(terms.get(0)), termConverter.apply(terms.get(1))); } }
tkrons/SPFlow_topdownrules
src/spn/structure/leaves/cltree/__init__.py
""" Created on October 20, 2018 @author: <NAME> """
fraqqer/Hall-Guys-CSC8503
Plugins/VulkanRendering/VulkanRenderer.h
/****************************************************************************** Class:VulkanRenderer Implements:RendererBase Author:<NAME> Description:TODO -_-_-_-_-_-_-_,------, _-_-_-_-_-_-_-| /\_/\ NYANYANYAN -_-_-_-_-_-_-~|__( ^ .^) / _-_-_-_-_-_-_-"" "" *////////////////////////////////////////////////////////////////////////////// #pragma once #include "../../Common/RendererBase.h" #ifdef _WIN32 #define VK_USE_PLATFORM_WIN32_KHR #include <Windows.h> //vulkan hpp needs this included beforehand! #include <minwindef.h> #endif #include <vulkan/vulkan.hpp> // #include "VulkanShader.h" #include "VulkanMesh.h" #include "VulkanShader.h" #include "VulkanTexture.h" #include <vector> #include <string> using std::string; namespace NCL { namespace Rendering { struct UniformData { vk::Buffer buffer; vk::MemoryAllocateInfo allocInfo; vk::DeviceMemory deviceMem; vk::DescriptorBufferInfo descriptorInfo; }; struct VulkanPipeline { vk::Pipeline pipeline; vk::PipelineLayout layout; }; class VulkanRenderer : public RendererBase { friend class VulkanMesh; friend class VulkanTexture; friend class VulkanPipelineBuilder; friend class VulkanShaderBuilder; friend class VulkanDescriptorSetLayoutBuilder; friend class VulkanRenderPassBuilder; public: VulkanRenderer(Window& window); ~VulkanRenderer(); protected: void OnWindowResize(int w, int h) override; void BeginFrame() override; void EndFrame() override; void SwapBuffers() override; void SubmitDrawCall(VulkanMesh* m, vk::CommandBuffer& to); void SetDebugName(vk::ObjectType t, uint64_t handle, const string& debugName); virtual void CompleteResize(); vk::DescriptorSet BuildDescriptorSet(vk::DescriptorSetLayout& layout); bool InitInstance(); bool InitGPUDevice(); int InitBufferChain(); bool CreateDefaultFrameBuffers(); bool InitSurface(); bool InitDeviceQueue(); void ImageTransitionBarrier(vk::CommandBuffer* buffer, vk::Image i, vk::ImageLayout oldLayout, vk::ImageLayout newLayout, vk::ImageAspectFlags aspect, vk::PipelineStageFlags srcStage, vk::PipelineStageFlags dstStage, int mipLevel = 0, int layer = 0 ); void ImageTransitionBarrier(vk::CommandBuffer* buffer, VulkanTexture* t, vk::ImageLayout oldLayout, vk::ImageLayout newLayout, vk::ImageAspectFlags aspect, vk::PipelineStageFlags srcStage, vk::PipelineStageFlags dstStage, int mipLevel = 0, int layer = 0); virtual void InitDefaultRenderPass(); virtual void InitDefaultDescriptorPool(); vk::CommandBuffer BeginCmdBuffer(); void EndCmdBufferWait(vk::CommandBuffer&buffer); vk::Fence EndCmdBuffer(vk::CommandBuffer& buffer); void DestroyCmdBuffer(vk::CommandBuffer& buffer); void BeginSetupCmdBuffer(); void EndSetupCmdBuffer(); void InitCommandPool(); void PresentScreenImage(); void InitUniformBuffer(UniformData& uniform, void* data, int dataSize); void UpdateUniformBuffer(UniformData& uniform, void* data, int dataSize); void UpdateImageDescriptor(vk::DescriptorSet& set, VulkanTexture* t, vk::Sampler sampler, int bindingNum = 0); void UpdateImageDescriptor(vk::DescriptorSet& set, VulkanTexture* t, vk::Sampler sampler, vk::ImageView, vk::ImageLayout forceLayout, int bindingNum = 0); vk::Device GetDevice() const { return device; } bool MemoryTypeFromPhysicalDeviceProps(vk::MemoryPropertyFlags requirements, uint32_t type, uint32_t& index); struct SwapChain { vk::Image image; vk::ImageView view; }; vk::DispatchLoaderDynamic* dispatcher; vk::SurfaceKHR surface; vk::Format surfaceFormat; vk::ColorSpaceKHR surfaceSpace; vk::Framebuffer* frameBuffers; uint32_t numFrameBuffers; VulkanTexture* depthBuffer; vk::SwapchainKHR swapChain; std::vector<SwapChain*> swapChainList; uint32_t currentSwap; vk::Instance instance; //API Instance vk::PhysicalDevice gpu; //GPU in use vk::Device device; //Device handle vk::PhysicalDeviceProperties deviceProperties; vk::PhysicalDeviceMemoryProperties deviceMemoryProperties; vk::PipelineCache pipelineCache; vk::DescriptorPool defaultDescriptorPool; //descriptor sets come from here! vk::CommandPool commandPool; //Source Command Buffers from here vk::CommandBuffer setupCmdBuffer; vk::CommandBuffer frameCmdBuffer; vk::RenderPass defaultRenderPass; vk::RenderPassBeginInfo defaultBeginInfo; vk::ClearValue defaultClearValues[2]; vk::Viewport defaultViewport; vk::Rect2D defaultScissor; vk::Queue deviceQueue; uint32_t gfxQueueIndex; uint32_t gfxPresentIndex; }; } }
jufeng98/b2c-master
maven-parent/b2c-spring-data-jpa/src/main/java/org/javamaster/b2c/spring/data/jpa/repository/ActorRepository.java
<filename>maven-parent/b2c-spring-data-jpa/src/main/java/org/javamaster/b2c/spring/data/jpa/repository/ActorRepository.java<gh_stars>0 package org.javamaster.b2c.spring.data.jpa.repository; import org.javamaster.b2c.spring.data.jpa.entity.Actor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Lock; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import javax.persistence.LockModeType; import java.util.List; /** * @author yudong * @date 2020/7/9 */ @Repository public interface ActorRepository extends JpaRepository<Actor, Integer> { // @Lock(LockModeType.READ) // @Transactional List<Actor> findActorByLastName(String lastName); @Query("select a from Actor a where a.firstName like :firstName") List<Actor> findByFirstNameEndsWith(@Param("firstName") String firstName); @Query(value = "select a.* from actor a where a.actor_id=?1", nativeQuery = true) Actor findByActorId(int actorId); @Query(value = "select * from actor where first_name like ?1", countQuery = "select count(*) from actor where first_name like ?1", nativeQuery = true) Page<Actor> findByFirstNameLike(String firstName, Pageable pageable); /** * spEL #{#entityName}引用@Entity上的name属性 * * @param lastName * @return */ @Query("select u from #{#entityName} u where u.lastName = ?1") List<Actor> findByLastName(String lastName); @Modifying @Transactional @Query("update Actor a set a.firstName = ?1 where a.lastName = ?2") int setFixedFirstnameFor(String firstName, String lastName); }
RyanFu/DSJAPP
ios/bc3.0/ALBBTradeSDK.framework/Headers/ALBBTradePage.h
// // ALBBTradePage.h // ALBBTrade // // Created by zhoulai on 15/10/28. // Copyright © 2015年 Alibaba. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** 页面 */ @interface ALBBTradePage : NSObject /** 地址 */ @property (nonatomic, copy) NSString *url; /** 短连接名 */ @property (nonatomic, copy) NSString *target; /** 参数 */ @property (nonatomic, copy) NSDictionary *params; /** 创建URL指定页面 @param url 地址 @return URL指定页面 */ + (instancetype)page:(NSString *)url; /** 创建短连接URL指定页面 @param target url的短连接名,SDK会自动映射 @param params 自定义参数 @return 短连接URL指定页面 */ + (instancetype)page:(NSString *)target params:(nullable NSDictionary *)params; /** 创建商品真实ID对应的详情页面 @param itemId 商品真实ID或者混淆(open)ID @param params 自定义参数 @return 详情页面 */ + (instancetype)itemDetailPage:(NSString *)itemId params:(nullable NSDictionary *)params; /** 创建优惠券页面 @param param 参数. type为shop时, param为卖家nick; type为auction时, param为商品的混淆ID. @param type 类型. 取值为shop或auction. @return 优惠券页面 */ + (instancetype)promotionsPage:(NSString *)param type:(NSString *)type; /** 创建我的购物车页面 @return 我的购物车页面 */ + (instancetype)myCartsPage; /** 创建我的订单列表页面 @param status 订单状态. 0为全部订单; 1为待付款订单; 2为待发货订单; 3为待收货订单; 4为待评价订单. @param isAllOrder 是否显示全部订单. 传YES时, 显示全部订单; 传NO时, 显示ISV的订单. @return 我的订单列表页面 */ + (instancetype)myOrdersPage:(NSInteger)status isAllOrder:(BOOL)isAllOrder; /** 创建我的卡券包页面 @return 我的卡券包页面 */ + (instancetype)myCardCouponsPage; /** * 创建店铺页面 * * @param shopId 店铺ID * @param params 自定义参数 * * @return 店铺页面 */ + (instancetype)shopPage:(nonnull NSString *)shopId params:(nullable NSDictionary *)params; @end NS_ASSUME_NONNULL_END typedef ALBBTradePage ALBBPage __attribute__((deprecated("use ALBBTradePage instead.")));
dong706/CorbaDemo
src/main/java/org/omg/hw/protection/ESwitchData_THelper.java
<filename>src/main/java/org/omg/hw/protection/ESwitchData_THelper.java package org.omg.hw.protection; /** * Generated from IDL definition of struct "ESwitchData_T" * @author JacORB IDL compiler */ public final class ESwitchData_THelper { private static org.omg.CORBA.TypeCode _type = null; public static org.omg.CORBA.TypeCode type () { if (_type == null) { _type = org.omg.CORBA.ORB.init().create_struct_tc(org.omg.hw.protection.ESwitchData_THelper.id(),"ESwitchData_T",new org.omg.CORBA.StructMember[]{new org.omg.CORBA.StructMember("eProtectionGroupType", org.omg.hw.protection.EProtectionGroupType_THelper.type(), null),new org.omg.CORBA.StructMember("eSwitchReason", org.omg.hw.protection.ESwitchReason_THelper.type(), null),new org.omg.CORBA.StructMember("ePGPName", org.omg.hw.globaldefs.NamingAttributes_THelper.type(), null),new org.omg.CORBA.StructMember("protectedE", org.omg.hw.globaldefs.NamingAttributes_THelper.type(), null),new org.omg.CORBA.StructMember("switchToE", org.omg.hw.globaldefs.NamingAttributes_THelper.type(), null),new org.omg.CORBA.StructMember("additionalInfo", org.omg.hw.globaldefs.NVSList_THelper.type(), null)}); } return _type; } public static void insert (final org.omg.CORBA.Any any, final org.omg.hw.protection.ESwitchData_T s) { any.type(type()); write( any.create_output_stream(),s); } public static org.omg.hw.protection.ESwitchData_T extract (final org.omg.CORBA.Any any) { return read(any.create_input_stream()); } public static String id() { return "IDL:mtnm.tmforum.org/protection/ESwitchData_T:1.0"; } public static org.omg.hw.protection.ESwitchData_T read (final org.omg.CORBA.portable.InputStream in) { org.omg.hw.protection.ESwitchData_T result = new org.omg.hw.protection.ESwitchData_T(); result.eProtectionGroupType=in.read_string(); result.eSwitchReason=in.read_string(); result.ePGPName = org.omg.hw.globaldefs.NVSList_THelper.read(in); result.protectedE = org.omg.hw.globaldefs.NVSList_THelper.read(in); result.switchToE = org.omg.hw.globaldefs.NVSList_THelper.read(in); result.additionalInfo = org.omg.hw.globaldefs.NVSList_THelper.read(in); return result; } public static void write (final org.omg.CORBA.portable.OutputStream out, final org.omg.hw.protection.ESwitchData_T s) { out.write_string(s.eProtectionGroupType); out.write_string(s.eSwitchReason); org.omg.hw.globaldefs.NVSList_THelper.write(out,s.ePGPName); org.omg.hw.globaldefs.NVSList_THelper.write(out,s.protectedE); org.omg.hw.globaldefs.NVSList_THelper.write(out,s.switchToE); org.omg.hw.globaldefs.NVSList_THelper.write(out,s.additionalInfo); } }
ShamsAnsari/cardsagainstai
server/src/utils/config.js
<gh_stars>1-10 require('dotenv').config(); const { PORT } = process.env; const { GOOGLE_CLIENT_ID } = process.env; const { GOOGLE_CLIENT_SECRET } = process.env; const { GITHUB_CLIENT_ID } = process.env; const { GITHUB_CLIENT_SECRET } = process.env; const { TWITTER_CLIENT_ID } = process.env; const { TWITTER_CLIENT_SECRET } = process.env; const { POSTGRES_PORT } = process.env; const { POSTGRES_USER } = process.env; const { POSTGRES_PASSWORD } = process.env; const { HOST } = process.env; const { DATABASE_NAME } = process.env; module.exports = { PORT, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, TWITTER_CLIENT_ID, TWITTER_CLIENT_SECRET, POSTGRES_PASSWORD, POSTGRES_USER, POSTGRES_PORT, HOST, DATABASE_NAME, };
Yoann-Vie/esgi-hearthstone
tests/utils_tests/test_module/another_good_module.py
from . import site content = 'Another Good Module' site._registry.update({ 'lorem': 'ipsum', })
404name/lightcloud-community
lightcloud/lightcloud-web/src/main/java/com/juelunn/lightcloud/module/system/controller/LogController.java
<filename>lightcloud/lightcloud-web/src/main/java/com/juelunn/lightcloud/module/system/controller/LogController.java package com.juelunn.lightcloud.module.system.controller; import com.juelunn.common.dto.OperationLogDTO; import com.juelunn.common.vo.ConditionVO; import com.juelunn.common.vo.PageResult; import com.juelunn.lightcloud.module.system.service.OperationLogService; import com.juelunn.common.vo.Result; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * 日志控制器 * * @author CTGU_LLZ(404name) * @date 2021/07/27 */ @Api(tags = "日志模块") @RestController public class LogController { @Autowired private OperationLogService operationLogService; /** * 查看操作日志 * * @param conditionVO 条件 * @return {@link Result<OperationLogDTO>} 日志列表 */ @ApiOperation(value = "查看操作日志") @GetMapping("/admin/operation/logs") public Result<PageResult<OperationLogDTO>> listOperationLogs(ConditionVO conditionVO) { return Result.ok(operationLogService.listOperationLogs(conditionVO)); } /** * 删除操作日志 * * @param logIdList 日志id列表 * @return {@link Result<>} */ @ApiOperation(value = "删除操作日志") @DeleteMapping("/admin/operation/logs") public Result<?> deleteOperationLogs(@RequestBody List<Integer> logIdList) { operationLogService.removeByIds(logIdList); return Result.ok(); } }
svp-dev/mgsim
arch/dev/Display.h
<filename>arch/dev/Display.h // -*- c++ -*- #ifndef DISPLAY_H #define DISPLAY_H #include <arch/IOMessageInterface.h> #include <sim/kernel.h> #include <sim/storage.h> #include <sim/config.h> #include <sim/sampling.h> namespace Simulator { struct SDLContext; class Display : public Object { class ControlInterface; class FrameBufferInterface : public IIOMessageClient, public Object { IOMessageInterface& m_ioif; IODeviceID m_devid; friend class ControlInterface; Display& GetDisplay() { return *dynamic_cast<Display*>(GetParent()); } public: FrameBufferInterface(const std::string& name, Display& parent, IOMessageInterface& ioif, IODeviceID devid); friend class Display; bool OnReadRequestReceived(IODeviceID from, MemAddr address, MemSize size) override; StorageTraceSet GetReadRequestTraces() const override; bool OnWriteRequestReceived(IODeviceID from, MemAddr address, const IOData& data) override; StorageTraceSet GetWriteRequestTraces() const override; void GetDeviceIdentity(IODeviceIdentification& id) const override; const std::string& GetIODeviceName() const override; }; class ControlInterface : public IIOMessageClient, public Object { IOMessageInterface& m_ioif; std::vector<uint32_t> m_control; IODeviceID m_devid; DefineStateVariable(unsigned, key); Display& GetDisplay() { return *dynamic_cast<Display*>(GetParent()); } public: ControlInterface(const std::string& name, Display& parent, IOMessageInterface& ioif, IODeviceID devid); friend class Display; bool OnReadRequestReceived(IODeviceID from, MemAddr address, MemSize size) override; StorageTraceSet GetReadRequestTraces() const override; bool OnWriteRequestReceived(IODeviceID from, MemAddr address, const IOData& data) override; StorageTraceSet GetWriteRequestTraces() const override; void GetDeviceIdentity(IODeviceIdentification& id) const override; const std::string& GetIODeviceName() const override; }; ControlInterface m_ctlinterface; FrameBufferInterface m_fbinterface; unsigned int m_max_screen_h; unsigned int m_max_screen_w; bool m_video_memory_updated; bool m_logical_screen_resized; bool m_logical_screen_updated; bool m_window_resized; std::vector<uint8_t> m_video_memory; std::vector<uint32_t> m_logical_screen_pixels; bool m_sdl_enabled; SDLContext* m_sdl_context; DefineStateVariable(unsigned int, logical_width); DefineStateVariable(unsigned int, logical_height); DefineStateVariable(uint32_t, command_offset); DefineStateVariable(float, scalex); DefineStateVariable(float, scaley); friend class ControlInterface; friend class FrameBufferInterface; public: Display(const std::string& name, Object& parent, IOMessageInterface& iobus, IODeviceID ctldevid, IODeviceID fbdevid); Display(const Display&) = delete; Display& operator=(const Display&) = delete; ~Display(); protected: // Resize the logical screen and its framebuffer // (m_logical_screen_pixels) The logical screen defines the // coordinate system for command lists in video memory. void ResizeLogicalScreen(unsigned w, unsigned h, bool erase); // Paint m_video_memory into m_logical_screen_pixels. void PrepareLogicalScreen(); // Dump the logical screen pixels to file/stream void DumpLogicalScreen(unsigned key, int stream, bool gen_timestamp); // Perform the rendering pipeline to the screen void Show(); // Change/update the rendering scaling factor // set = true -> change m_scalex/m_scaley to specified factors; // set = false -> multiply m_scalex/m_scaly by specified factors. void SetWindowScale(double sx, double sy, bool set); // ResetRatio: set x/y to the same scale. void EqualizeWindowScale(); // Resize the render window, set m_need_redraw to true, call RenderLogicalScreen. void SetWindowSize(unsigned int w, unsigned int h); // Change/update the window caption void ResetWindowCaption() const; // Reset: force re-creating windows, renderer, etc (used by // DisplayManager below) void ResetDisplay(); // CloseWindow: delete window and renderer void CloseWindow(); friend class DisplayManager; }; class DisplayManager { public: // RegisterDisplay/UnregisterDisplay: register/unregister a // display instance that may be connected to a SDL window and // thus receive key or window resize events. void RegisterDisplay(Display *disp); void UnregisterDisplay(Display *disp); // GetMaxWindowSize: retrieve the largest possible resolution // for a window. void GetMaxWindowSize(unsigned& w, unsigned& h); // OnCycle(): only call CheckEvents (which is expensive) every // m_refreshDelay cycles. Called by Kernel::Step(). void OnCycle(CycleNo cycle) { if (m_lastUpdate + m_refreshDelay > cycle) return; m_lastUpdate = cycle; CheckEvents(); } // CheckEvents: poll the SDL event queue and dispatch events // to the appropriate display. Used by OnCycle and CommandLineReader::ReadLineHook. void CheckEvents(void); // GetRefreshDelay: accessor for the refresh delay. Used by // individual Displays to generate their window caption. unsigned GetRefreshDelay() const { return m_refreshDelay; } // IsSDLInitialized: used by displays to decide whether SDL can be used bool IsSDLInitialized() const { return m_sdl_initialized; } // ResetDisplays: reset all enabled displays; ie re-create // their SDL window and render context and redraw. Should be // used after deserializing a simulation state. void ResetDisplays() const; // Singleton methods static void CreateManagerIfNotExists(Config& cfg); static DisplayManager* GetManager() { return g_singleton; } protected: bool m_sdl_initialized; ///< Whether SDL is available unsigned m_refreshDelay_orig; ///< Initial refresh delay from config unsigned m_refreshDelay; ///< Current refresh delay as set by user CycleNo m_lastUpdate; ///< Cycle number of last check std::vector<Display*> m_displays; ///< Currently registered Display instances static DisplayManager* g_singleton; ///< Singleton instance // Constructor, used by CreateManagerIfNotExists. DisplayManager(unsigned refreshDelay); }; } #endif
seongwon-kang/common-tags
src/testUtils/index.test.js
<reponame>seongwon-kang/common-tags import fs from 'fs'; import path from 'path'; import mm from 'micromatch'; const observe = ['*', '!index.js', '!index.test.js']; const context = {}; beforeEach(() => { context.modules = mm(fs.readdirSync(__dirname), observe); }); function requireModule(module) { return require(path.join(__dirname, module)); } test('test utils exports all the right modules directly', () => { const modules = context.modules; expect.assertions(modules.length); modules.forEach((module) => { expect(requireModule(module)).toBeDefined(); }); }); test('test utils exports all the right modules as props', () => { const modules = context.modules; expect.assertions(modules.length); modules.forEach((module) => { expect(require('./index')).toHaveProperty(module, requireModule(module)); }); });
AnthonyCapirchio/golem
add.go
<reponame>AnthonyCapirchio/golem<gh_stars>0 package main import ( "errors" "flag" "fmt" "github.com/4nth0/golem/internal/command" ) func addCmd() command.Command { fs := flag.NewFlagSet("golem add", flag.ExitOnError) return command.Command{ FlagSet: fs, Handler: func(args []string) error { fs.Parse(args) return Add(args) }, } } func Add(args []string) (err error) { if len(args) < 2 { return errors.New("NOT ENOUGH ARGMUENTS") } switch args[1] { case "http": fmt.Println("Create new http service ...") default: return errors.New("UNKONWN COMMAND") } return nil }
xayo001/file-transform-kit
file-transform-kit-server/src/main/java/com/tal/file/transform/controller/processor/ImageProcessor.java
<gh_stars>10-100 package com.tal.file.transform.controller.processor; import com.tal.file.transform.entity.Audio; import com.tal.file.transform.entity.Image; import com.tal.file.transform.image.ImageTask; import com.tal.file.transform.image.ImageTasks; import com.tal.file.transform.controller.image.ImageCore; import com.tal.file.transform.controller.image.ImageJobs; import com.tal.file.transform.controller.image.ImageSize; import com.tal.file.transform.common.FilenameUtils; import com.tal.file.transform.common.StringUtils; import com.tal.file.transform.common.mime.Mime; import com.tal.file.transform.common.mime.MimeUtils; import com.tal.file.transform.common.storage.StorageFile; import com.tal.file.transform.common.storage.StorageFileNamer; import com.tal.file.transform.common.storage.StorageZone; import com.tal.file.transform.controller.result.UploadResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; @Component public class ImageProcessor extends DefaultProcessor { protected static final Logger log = LoggerFactory.getLogger(ImageProcessor.class); private final static int JOB_OPTIMIZE = 1; private final static int JOB_SCALE = 2; private final static int JOB_SPECIFIC = 4; private final static int JOB_ALL = JOB_OPTIMIZE | JOB_SCALE | JOB_SPECIFIC; private final static int JOB_ALL_WITHOUT_OPTIMIZE = JOB_SCALE | JOB_SPECIFIC; private final static int JOB_SAVE_ONLY = 8; @Autowired ImageTasks imageTasks; @Override public UploadResult<Image> process(String clientId, List<File> files, StorageZone zone, StorageFileNamer fileNamer) { UploadResult<Image> r = new UploadResult<Image>(); ImageJobs jobs = new ImageJobs(zone); List<ImageTask> tasks = imageTasks.find(clientId); for(int i = 0; i < files.size(); i ++) { File file = files.get(i); // liujt, 2020.8.8 // 鉴于png的压缩率不高的原因,强制将png转换成jpeg格式,使最终生成的文件更小,确保下载速度 // 注:这个修改主要是因为掌门iOS版上传直播大列表图片时,png文件过大导致直播大列表打开太慢 String fileName = file.getName(); String fileExts = FilenameUtils.getExt(fileName); String filePath = "", bizName = ""; int jobType = JOB_ALL; // liujt, 2020.5.19 // 当上传的图片没有后缀时,给定默认后缀名 if(StringUtils.isBlank(fileExts)) { fileExts = ".jpeg"; fileName += fileExts; } if (imageTasks.findPaths(clientId) || Objects.isNull(fileNamer.getFilePath())) { filePath = fileNamer.bename(clientId + "/image", fileName); } else { filePath = fileNamer.getFilePath() + fileName; } Image image = new Image(); image.setName(fileName); r.addFile(image); BufferedImage img = null; Mime mime = MimeUtils.find(fileExts); StorageFile storFile = zone.create(filePath); try { InputStream inputStream = new FileInputStream(file); img = ImageIO.read(inputStream); storFile.write(inputStream, mime); image.setUrl(storFile.getUrl()); file.delete(); } catch (IOException e) { log.error(e.getMessage()); } switch(jobType) { case JOB_ALL: case JOB_ALL_WITHOUT_OPTIMIZE: // 默认保存自身 jobs.add(img, filePath, ImageCore.KEY_SELF, mime); if(tasks != null) { ImageCore ic = new ImageCore(); for(ImageTask task : tasks) { int w = img.getWidth(), h = img.getHeight(); BufferedImage t = null; switch(ImageCore.getOp(task.getOperate())) { case ImageCore.OPERATE_OPTIMIZE: bizName = ImageCore.KEY_OPTIMIZE; if((jobType & JOB_OPTIMIZE) == JOB_OPTIMIZE) { ImageSize limit = task.getLimitSize(); if(limit != null && limit.getWidth() > 0 && limit.getHeight() > 0) { t = ic.optimize(img, w, h, limit.getWidth(), limit.getHeight()); } else { t = ic.optimize(img); } } else { t = img; } break; case ImageCore.OPERATE_SCALE: int minW = task.getMinSize().getWidth(), minH = task.getMinSize().getHeight(); int maxW = task.getMaxSize().getWidth(), maxH = task.getMaxSize().getHeight(); bizName = String.format(ImageCore.KEY_SCALE, minW, minH, maxW, maxH); t = ic.scale(img, w, h, minW, minH, maxW, maxH); break; case ImageCore.OPERATE_SELF_SCALE: int selfW = task.getSize().getWidth(), selfH = task.getSize().getHeight(); bizName = String.format(ImageCore.KEY_SELF, selfW, selfH); t = ic.specific(img, w, h, selfW, selfH); break; case ImageCore.OPERATE_SPECIFIC: int specW = task.getSize().getWidth(), specH = task.getSize().getHeight(); bizName = String.format(ImageCore.KEY_SPECIFIC, specW, specH); t = ic.specific(img, w, h, specW, specH); break; default: break; } jobs.add(t, filePath, bizName, mime); } } break; case JOB_SAVE_ONLY: jobs.add(img, filePath, bizName, mime); ImageCore ic = new ImageCore(); // liujt, 2020.8.11 // 根据缩略图生成更小尺寸的缩略图 Pattern specP = Pattern.compile("_r(\\d+)x(\\d+)$"); Matcher specM = specP.matcher(bizName); if(specM.find() && tasks != null) { int w = StringUtils.toInt(specM.group(1)), h = StringUtils.toInt(specM.group(2)); double scale = (double)w / (double)h; for(ImageTask task : tasks) { if(ImageCore.getOp(task.getOperate()) == ImageCore.OPERATE_SPECIFIC) { int specW = task.getSize().getWidth(), specH = task.getSize().getHeight(); double specScale = (double)specW / (double)specH; if(scale == specScale && specW < w && specH < h) { BufferedImage bi = ic.specific(img, specW, specH); bizName = String.format(ImageCore.KEY_SPECIFIC, specW, specH); jobs.add(bi, filePath, bizName, mime); } } } } break; default: break; } } jobs.commit(); return r; } }
ereslibre/oneinfra
internal/app/oi/cluster/version.go
<filename>internal/app/oi/cluster/version.go /** * Copyright 2020 <NAME> <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package cluster import ( "github.com/oneinfra/oneinfra/internal/pkg/cluster" "github.com/oneinfra/oneinfra/internal/pkg/component" "github.com/oneinfra/oneinfra/internal/pkg/infra" "github.com/oneinfra/oneinfra/internal/pkg/manifests" ) // KubernetesVersion returns the Kubernetes version for the given // cluster func KubernetesVersion(clusterName string) (string, error) { var kubernetesVersion string err := manifests.WithStdinResourcesSilent( func(_ infra.HypervisorMap, clusters cluster.Map, _ component.List) error { return manifests.WithNamedCluster(clusterName, clusters, func(cluster *cluster.Cluster) error { kubernetesVersion = cluster.KubernetesVersion return nil }) }, ) return kubernetesVersion, err }
gazeti/aleph
aleph/views/leads_api.py
from flask import Blueprint, request from apikit import obj_or_404, jsonify, request_data from werkzeug.exceptions import BadRequest from aleph.model import Collection, EntityIdentity from aleph.search import QueryState from aleph.search.leads import leads_query from aleph.logic import update_entity, update_lead from aleph.events import log_event from aleph.views.util import get_entity blueprint = Blueprint('leads_api', __name__) @blueprint.route('/api/1/collections/<int:collection_id>/leads', methods=['GET']) def index(collection_id): collection = obj_or_404(Collection.by_id(collection_id)) request.authz.require(request.authz.collection_read(collection)) state = QueryState(request.args, request.authz) results = leads_query(collection_id, state) return jsonify(results) @blueprint.route('/api/1/collections/<int:collection_id>/leads', methods=['POST', 'PUT']) def update(collection_id): collection = obj_or_404(Collection.by_id(collection_id)) request.authz.require(request.authz.collection_write(collection)) data = request_data() entity, obj = get_entity(data.get('entity_id'), request.authz.WRITE) if obj.collection_id != collection_id: raise BadRequest("Entity does not belong to collection.") match, _ = get_entity(data.get('match_id'), request.authz.READ) judgement = data.get('judgement') if judgement not in EntityIdentity.JUDGEMENTS: raise BadRequest("Invalid judgement.") update_lead(entity, match, judgement, judge=request.authz.role) log_event(request) update_entity(obj) return jsonify({'status': 'ok'})
ryntckr/openapilint
lib/rules/path-style.js
<filename>lib/rules/path-style.js 'use strict'; const { List } = require('immutable'); const constants = require('../constants'); const RuleFailure = require('../RuleFailure'); /** * Checks the path element for compliance. A path element is anything between the forward slashes. * * @param {Object} pathElement The path element being checked. * @param {Object} caseOption The expected case of the path element. * @param {Object} pathKey The entire path key used for logging errors. * @param {Object} errorList The local list of errors. */ function checkPathElement(pathElement, caseOption, pathKey, errorList) { if (pathElement === '') { errorList.push(new RuleFailure({ location: `paths.${pathKey}`, hint: 'Must not have empty path elements' })); } else if (pathElement.match(constants.reValidPathTemplateParam)) { // found a valid template id. Stop checking. } else if (!pathElement.match(constants.caseStyles[caseOption])) { errorList.push(new RuleFailure({ location: `paths.${pathKey}`, hint: `"${pathElement}" does not comply with case: "${caseOption}"` })); } } const rule = { description: 'enforce paths that conform to spec, and to a specified input case style', validate(options, schema) { if (!options || !options.case || Object.keys(constants.caseStyles).indexOf(options.case) === -1) { throw new Error('Invalid config specified'); } const errorList = []; if (schema.paths) { Object.keys(schema.paths).forEach((pathKey) => { if (pathKey === '/') { // a path of "/" is ok. return; } let trimmedPath = pathKey; if (!pathKey.startsWith('/')) { errorList.push(new RuleFailure({ location: `paths.${pathKey}`, hint: 'Missing a leading slash' })); } else { trimmedPath = trimmedPath.substr(1);// trim off first slash. } if (pathKey.endsWith('/')) { errorList.push(new RuleFailure({ location: `paths.${pathKey}`, hint: 'Must not have a trailing slash' })); trimmedPath = trimmedPath.slice(0, -1); // trim off last slash } // now check the trimmedPath for the other problems. const splitPath = trimmedPath.split('/'); splitPath.forEach((pathElement) => { checkPathElement(pathElement, options.case, pathKey, errorList); }); }); } return new List(errorList); } }; module.exports = rule;
nining/bither-android
bither-android/src/net/bither/runnable/FancyQrCodeThread.java
<gh_stars>100-1000 /* * Copyright 2014 http://Bither.net * * 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 net.bither.runnable; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import net.bither.preference.AppSharedPreference; import net.bither.qrcode.Qr; import net.bither.ui.base.listener.IGetAvatarListener; import net.bither.util.ImageManageUtil; import net.bither.util.ThreadUtil; import net.bither.util.UIUtil; public class FancyQrCodeThread extends Thread { public static interface FancyQrCodeListener { public void generated(Bitmap bmp); } public static final float AvatarSizeRate = 0.24f; public static final int MarginSize = UIUtil.dip2pix(16); private FancyQrCodeListener listener; private String content; private int size; private int fgColor = Color.BLACK; private int bgColor = Color.WHITE; private boolean addAvatar; public FancyQrCodeThread(String content, int size, int fgColor, int bgColor, FancyQrCodeListener listener) { this(content, size, fgColor, bgColor, listener, true); } public FancyQrCodeThread(String content, int size, int fgColor, int bgColor, FancyQrCodeListener listener, boolean addAvatar) { this.content = content; this.listener = listener; this.size = size; this.fgColor = fgColor; this.bgColor = bgColor; this.addAvatar = addAvatar; } @Override public void run() { final Bitmap qrCode = Qr.bitmap(content, size, fgColor, bgColor, MarginSize); final int qrCodeSize = Math.min(qrCode.getWidth(), qrCode.getHeight()); if (addAvatar && AppSharedPreference.getInstance().hasUserAvatar()) { ImageManageUtil.getAvatarForFancyQrCode(new IGetAvatarListener() { @Override public void success(Bitmap bit) { if (bit != null) { Canvas c = new Canvas(qrCode); int avatarSize = (int) (qrCodeSize * AvatarSizeRate); int avaterOffset = (qrCodeSize - avatarSize) / 2; Paint paint = new Paint(); paint.setAntiAlias(true); c.drawBitmap(bit, null, new Rect(avaterOffset, avaterOffset, avaterOffset + avatarSize, avaterOffset + avatarSize), paint); } } @Override public void fileNoExist() { } }); } if (listener != null) { ThreadUtil.runOnMainThread(new Runnable() { @Override public void run() { listener.generated(qrCode); } }); } } }
bkreider/link
vendor/github.com/Soulou/errgo-rollbar/errgo_rollbar.go
package errgorollbar import ( "strings" "github.com/rollbar/rollbar-go" "gopkg.in/errgo.v1" ) // Rollbar package expect such error: // type CauseStacker interface { // error // Cause() error // Stack() Stack // } var ( _ rollbar.CauseStacker = wrappedError{} ) type wrappedError struct { err error msg string skip int } func (err wrappedError) Error() string { return err.msg } func Wrap(msg string, err error, skip int) wrappedError { return wrappedError{msg: msg, err: err, skip: skip} } func (err wrappedError) Cause() error { return err.err } func (werr wrappedError) Stack() rollbar.Stack { stack := rollbar.Stack{} err := werr.err for err != nil { if errgoErr, ok := err.(*errgo.Err); !ok { break } else { frame := rollbar.Frame{ Filename: errgoErr.File, Line: errgoErr.Line, } stack = append([]rollbar.Frame{frame}, stack...) err = errgoErr.Underlying() } } // The result is the concatenation of the stack given by the current // execution flow and the stack determined by the pkg/errors error // Plus we ignore all the intermediate frames from rollbar lib which // is adding something around 4 levels of depth. rawStack := rollbar.BuildStack(werr.skip + 2) execStack := rollbar.Stack{} for _, frame := range rawStack { if !strings.Contains(frame.Filename, "rollbar/rollbar-go") { execStack = append(execStack, frame) } } return append(stack, execStack...) }
onap/archive-ncomp-openstack
ncomp-openstack-model/src/main/xcore-gen/org/openecomp/ncomp/openstack/compute/impl/OpenstackRequestNewServerImpl.java
<reponame>onap/archive-ncomp-openstack<filename>ncomp-openstack-model/src/main/xcore-gen/org/openecomp/ncomp/openstack/compute/impl/OpenstackRequestNewServerImpl.java<gh_stars>0 /*- * ============LICENSE_START========================================== * OPENECOMP - DCAE * =================================================================== * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. * =================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ */ /** */ package org.openecomp.ncomp.openstack.compute.impl; import org.openecomp.ncomp.openstack.compute.ComputePackage; import org.openecomp.ncomp.openstack.compute.OpenstackRequestNewServer; import org.openecomp.ncomp.openstack.core.VirtualMachineType; import org.openecomp.ncomp.openstack.core.impl.OpenStackRequestImpl; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EDataTypeEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Openstack Request New Server</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.openecomp.ncomp.openstack.compute.impl.OpenstackRequestNewServerImpl#getName <em>Name</em>}</li> * <li>{@link org.openecomp.ncomp.openstack.compute.impl.OpenstackRequestNewServerImpl#getHypervisor <em>Hypervisor</em>}</li> * <li>{@link org.openecomp.ncomp.openstack.compute.impl.OpenstackRequestNewServerImpl#getUser <em>User</em>}</li> * <li>{@link org.openecomp.ncomp.openstack.compute.impl.OpenstackRequestNewServerImpl#getNetworks <em>Networks</em>}</li> * <li>{@link org.openecomp.ncomp.openstack.compute.impl.OpenstackRequestNewServerImpl#getPorts <em>Ports</em>}</li> * <li>{@link org.openecomp.ncomp.openstack.compute.impl.OpenstackRequestNewServerImpl#getUser_data <em>User data</em>}</li> * <li>{@link org.openecomp.ncomp.openstack.compute.impl.OpenstackRequestNewServerImpl#getFloatingIp <em>Floating Ip</em>}</li> * <li>{@link org.openecomp.ncomp.openstack.compute.impl.OpenstackRequestNewServerImpl#getVmType <em>Vm Type</em>}</li> * </ul> * * @generated */ public class OpenstackRequestNewServerImpl extends OpenStackRequestImpl implements OpenstackRequestNewServer { /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The default value of the '{@link #getHypervisor() <em>Hypervisor</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getHypervisor() * @generated * @ordered */ protected static final String HYPERVISOR_EDEFAULT = null; /** * The cached value of the '{@link #getHypervisor() <em>Hypervisor</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getHypervisor() * @generated * @ordered */ protected String hypervisor = HYPERVISOR_EDEFAULT; /** * The default value of the '{@link #getUser() <em>User</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUser() * @generated * @ordered */ protected static final String USER_EDEFAULT = null; /** * The cached value of the '{@link #getUser() <em>User</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUser() * @generated * @ordered */ protected String user = USER_EDEFAULT; /** * The cached value of the '{@link #getNetworks() <em>Networks</em>}' attribute list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getNetworks() * @generated * @ordered */ protected EList<String> networks; /** * The cached value of the '{@link #getPorts() <em>Ports</em>}' attribute list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPorts() * @generated * @ordered */ protected EList<String> ports; /** * The default value of the '{@link #getUser_data() <em>User data</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUser_data() * @generated * @ordered */ protected static final String USER_DATA_EDEFAULT = null; /** * The cached value of the '{@link #getUser_data() <em>User data</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUser_data() * @generated * @ordered */ protected String user_data = USER_DATA_EDEFAULT; /** * The default value of the '{@link #getFloatingIp() <em>Floating Ip</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFloatingIp() * @generated * @ordered */ protected static final String FLOATING_IP_EDEFAULT = null; /** * The cached value of the '{@link #getFloatingIp() <em>Floating Ip</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFloatingIp() * @generated * @ordered */ protected String floatingIp = FLOATING_IP_EDEFAULT; /** * The cached value of the '{@link #getVmType() <em>Vm Type</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getVmType() * @generated * @ordered */ protected VirtualMachineType vmType; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected OpenstackRequestNewServerImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ComputePackage.Literals.OPENSTACK_REQUEST_NEW_SERVER; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__NAME, oldName, name)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getHypervisor() { return hypervisor; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setHypervisor(String newHypervisor) { String oldHypervisor = hypervisor; hypervisor = newHypervisor; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__HYPERVISOR, oldHypervisor, hypervisor)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getUser() { return user; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setUser(String newUser) { String oldUser = user; user = newUser; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__USER, oldUser, user)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<String> getNetworks() { if (networks == null) { networks = new EDataTypeEList<String>(String.class, this, ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__NETWORKS); } return networks; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<String> getPorts() { if (ports == null) { ports = new EDataTypeEList<String>(String.class, this, ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__PORTS); } return ports; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getUser_data() { return user_data; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setUser_data(String newUser_data) { String oldUser_data = user_data; user_data = newUser_data; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__USER_DATA, oldUser_data, user_data)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getFloatingIp() { return floatingIp; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFloatingIp(String newFloatingIp) { String oldFloatingIp = floatingIp; floatingIp = newFloatingIp; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__FLOATING_IP, oldFloatingIp, floatingIp)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public VirtualMachineType getVmType() { return vmType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetVmType(VirtualMachineType newVmType, NotificationChain msgs) { VirtualMachineType oldVmType = vmType; vmType = newVmType; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__VM_TYPE, oldVmType, newVmType); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setVmType(VirtualMachineType newVmType) { if (newVmType != vmType) { NotificationChain msgs = null; if (vmType != null) msgs = ((InternalEObject)vmType).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__VM_TYPE, null, msgs); if (newVmType != null) msgs = ((InternalEObject)newVmType).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__VM_TYPE, null, msgs); msgs = basicSetVmType(newVmType, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__VM_TYPE, newVmType, newVmType)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__VM_TYPE: return basicSetVmType(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__NAME: return getName(); case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__HYPERVISOR: return getHypervisor(); case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__USER: return getUser(); case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__NETWORKS: return getNetworks(); case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__PORTS: return getPorts(); case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__USER_DATA: return getUser_data(); case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__FLOATING_IP: return getFloatingIp(); case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__VM_TYPE: return getVmType(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__NAME: setName((String)newValue); return; case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__HYPERVISOR: setHypervisor((String)newValue); return; case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__USER: setUser((String)newValue); return; case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__NETWORKS: getNetworks().clear(); getNetworks().addAll((Collection<? extends String>)newValue); return; case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__PORTS: getPorts().clear(); getPorts().addAll((Collection<? extends String>)newValue); return; case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__USER_DATA: setUser_data((String)newValue); return; case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__FLOATING_IP: setFloatingIp((String)newValue); return; case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__VM_TYPE: setVmType((VirtualMachineType)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__NAME: setName(NAME_EDEFAULT); return; case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__HYPERVISOR: setHypervisor(HYPERVISOR_EDEFAULT); return; case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__USER: setUser(USER_EDEFAULT); return; case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__NETWORKS: getNetworks().clear(); return; case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__PORTS: getPorts().clear(); return; case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__USER_DATA: setUser_data(USER_DATA_EDEFAULT); return; case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__FLOATING_IP: setFloatingIp(FLOATING_IP_EDEFAULT); return; case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__VM_TYPE: setVmType((VirtualMachineType)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__HYPERVISOR: return HYPERVISOR_EDEFAULT == null ? hypervisor != null : !HYPERVISOR_EDEFAULT.equals(hypervisor); case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__USER: return USER_EDEFAULT == null ? user != null : !USER_EDEFAULT.equals(user); case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__NETWORKS: return networks != null && !networks.isEmpty(); case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__PORTS: return ports != null && !ports.isEmpty(); case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__USER_DATA: return USER_DATA_EDEFAULT == null ? user_data != null : !USER_DATA_EDEFAULT.equals(user_data); case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__FLOATING_IP: return FLOATING_IP_EDEFAULT == null ? floatingIp != null : !FLOATING_IP_EDEFAULT.equals(floatingIp); case ComputePackage.OPENSTACK_REQUEST_NEW_SERVER__VM_TYPE: return vmType != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (name: "); result.append(name); result.append(", hypervisor: "); result.append(hypervisor); result.append(", user: "); result.append(user); result.append(", networks: "); result.append(networks); result.append(", ports: "); result.append(ports); result.append(", user_data: "); result.append(user_data); result.append(", floatingIp: "); result.append(floatingIp); result.append(')'); return result.toString(); } } //OpenstackRequestNewServerImpl
wachunga/ui-demo
apps/styleguide/config/validateStyleguideConfig.js
<filename>apps/styleguide/config/validateStyleguideConfig.js<gh_stars>1-10 const fs = require('fs'); const getConfig = require('react-styleguidist/scripts/config'); // eslint-disable-line import/no-extraneous-dependencies function validateConfigSection(config) { if (config.content) { if (!fs.existsSync(config.content)) { throw new Error(`no style guide content found at path ${config.content} for section ${config.name}`); } } if (config.components) { const componentPaths = config.components(); componentPaths.forEach(componentPath => { if (!fs.existsSync(componentPath)) { throw new Error(`no style guide component found at path ${componentPath} for section ${config.name}`); } }); } if (config.sections) { config.sections.map(validateConfigSection); } } try { const config = getConfig(); // validates config only contains known properties etc config.sections.map(validateConfigSection); } catch (err) { console.error(err); process.exit(1); }
juui/juui.org
src/server/index.js
<reponame>juui/juui.org 'use strict'; const Hapi = require('hapi'); const ip = require('ip'); const bluebird = require('bluebird'); const coroutine = bluebird.coroutine; const mongoose = require('mongoose'); ////////////////////////////////////////////////// const settings = require('./config/index'); const prePlugins = require('./config/plugins/pre/index'); const postPlugins = require('./config/plugins/post/index'); const routes = require('./config/routes'); let server = {}; ////////////////////////////////////////////////// coroutine(activateServer)() .catch((error)=> { console.error(error); }); ////////////////////////////////////////////////// function* activateServer() { createServer(); setupConnections(); yield setupPlugins(); setupRoutes(); startServer(); } ////////////////////////////////////////////////// function createServer() { server = new Hapi.Server(settings); } function setupConnections() { server.connection( { port: process.env.PORT || 3008, labels: 'api', routes: { files: { relativeTo: __dirname + '/../clients/', }, cors: true } } ); } function setupPlugins() { return new Promise((resolve, reject)=> { server.register(prePlugins, function (error) { if (error) { reject(error); } else { server.register(postPlugins, function (error) { if (error) { reject(error); } else { resolve(); } }); } }); }); } function setupRoutes() { let api = server.select('api'); api.route(routes); api.views({ engines: { 'html': { module: require('handlebars') }, 'pug': { module: require('pug') } }, path: __dirname + '/../clients/', compileOptions: {}, isCached: false }); } function startServer() { server.start((err) => { if (err) { throw err; } else { console.log('Server running at:', ip.address() + ':' + (process.env.PORT || 3008)); } }); }
RainSpace-CN/Easy-tools
src/main/java/cn/rainspace/easytools/utils/Const.java
<filename>src/main/java/cn/rainspace/easytools/utils/Const.java package cn.rainspace.easytools.utils; public class Const { public final static String MOD_ID = "easytools"; }
best08618/asylo
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/pr48722.c
/* PR middle-end/48722 */ /* { dg-do compile } */ /* { dg-options "-Os -mno-push-args" } */ extern long long a; extern int b; void bar (int, long long); void foo (void) { bar (a > 0x85, b); }
thanusiv/Climby-Climb
app/src/main/java/com/game/thanu/gameapp/AnimationManager.java
package com.game.thanu.gameapp; import android.graphics.Canvas; import android.graphics.Rect; class AnimationManager { private Animation[] animations; private int animationIndex = 0; AnimationManager(Animation[] animations) { this.animations = animations; } void playAnim(int index) { for (int i = 0; i < animations.length; i++) { if (i == index) { if (!animations[index].isPlaying()) animations[i].play(); } else animations[i].stop(); } animationIndex = index; } public void draw(Canvas canvas, Rect rect) { if (animations[animationIndex].isPlaying()) animations[animationIndex].draw(canvas, rect); } public void update() { if (animations[animationIndex].isPlaying()) animations[animationIndex].update(); } }
meinac/odf_core
lib/odf_core/element/office/styles.rb
module OdfCore module Element module Office class Styles < AbstractElement XML_ELEMENT_NAME = 'office:styles' CHILDREN = [ "draw:fill-image", "draw:gradient", "draw:hatch", "draw:marker", "draw:opacity", "draw:stroke-dash", "number:boolean-style", "number:currency-style", "number:date-style", "number:number-style", "number:percentage-style", "number:text-style", "number:time-style", "style:default-page-layout", "style:default-style", "style:presentation-page-layout", "style:style", "svg:linearGradient", "svg:radialGradient", "table:table-template", "text:bibliography-configuration", "text:linenumbering-configuration", "text:list-style", "text:notes-configuration", "text:outline-style", ].freeze ATTRIBUTES = [].freeze end end end end
BartekCK/RestaurantAPI
src/main/java/com/restaurant/utility/constants/ExceptionMessages.java
package com.restaurant.utility.constants; import lombok.AccessLevel; import lombok.AllArgsConstructor; @AllArgsConstructor(access = AccessLevel.PRIVATE) public class ExceptionMessages { public static final String DISH_NOT_FOUND = "Dish with opinionId %s not found"; public static final String RESTAURANT_NOT_FOUND = "Restaurant with id %s not found"; public static final String OPINION_SIZE_MESSAGE = "Opinion should have less than 300 signs"; public static final String TABLE_NOT_FOUND = "Table %s not found"; public static final String USER_NOT_FOUND = "User with id %s not found"; public static final String OPINION_NOT_FOUND = "Opinion with id %s not found"; }
vimalcvs/MaterialX
app/src/main/java/com/material/components/activity/bottomnavigation/BottomNavigationBasic.java
<filename>app/src/main/java/com/material/components/activity/bottomnavigation/BottomNavigationBasic.java package com.material.components.activity.bottomnavigation; import android.os.Bundle; import androidx.annotation.NonNull; import com.google.android.material.bottomnavigation.BottomNavigationView; import androidx.core.widget.NestedScrollView; import androidx.appcompat.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.material.components.R; import com.material.components.utils.Tools; public class BottomNavigationBasic extends AppCompatActivity { private TextView mTextMessage; private BottomNavigationView navigation; private View search_bar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bottom_navigation_basic); initComponent(); } private void initComponent() { search_bar = (View) findViewById(R.id.search_bar); mTextMessage = (TextView) findViewById(R.id.search_text); navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_recent: mTextMessage.setText(item.getTitle()); return true; case R.id.navigation_favorites: mTextMessage.setText(item.getTitle()); return true; case R.id.navigation_nearby: mTextMessage.setText(item.getTitle()); return true; } return false; } }); NestedScrollView nested_content = (NestedScrollView) findViewById(R.id.nested_scroll_view); nested_content.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() { @Override public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { if (scrollY < oldScrollY) { // up animateNavigation(false); animateSearchBar(false); } if (scrollY > oldScrollY) { // down animateNavigation(true); animateSearchBar(true); } } }); // display image Tools.displayImageOriginal(this, (ImageView) findViewById(R.id.image_1), R.drawable.image_8); Tools.displayImageOriginal(this, (ImageView) findViewById(R.id.image_2), R.drawable.image_9); Tools.displayImageOriginal(this, (ImageView) findViewById(R.id.image_3), R.drawable.image_15); Tools.displayImageOriginal(this, (ImageView) findViewById(R.id.image_4), R.drawable.image_14); Tools.displayImageOriginal(this, (ImageView) findViewById(R.id.image_5), R.drawable.image_12); Tools.displayImageOriginal(this, (ImageView) findViewById(R.id.image_6), R.drawable.image_2); Tools.displayImageOriginal(this, (ImageView) findViewById(R.id.image_7), R.drawable.image_5); ((ImageButton) findViewById(R.id.bt_menu)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); Tools.setSystemBarColor(this, R.color.grey_5); Tools.setSystemBarLight(this); } boolean isNavigationHide = false; private void animateNavigation(final boolean hide) { if (isNavigationHide && hide || !isNavigationHide && !hide) return; isNavigationHide = hide; int moveY = hide ? (2 * navigation.getHeight()) : 0; navigation.animate().translationY(moveY).setStartDelay(100).setDuration(300).start(); } boolean isSearchBarHide = false; private void animateSearchBar(final boolean hide) { if (isSearchBarHide && hide || !isSearchBarHide && !hide) return; isSearchBarHide = hide; int moveY = hide ? -(2 * search_bar.getHeight()) : 0; search_bar.animate().translationY(moveY).setStartDelay(100).setDuration(300).start(); } }
ye1088/uni-app
src/platforms/h5/service/api/device/network-info.js
const { invokeCallbackHandler: invoke } = UniServiceJSBridge const callbackIds = [] function changeHandler () { const { networkType } = getNetworkType() callbackIds.forEach(callbackId => { invoke(callbackId, { errMsg: 'onNetworkStatusChange:ok', isConnected: networkType !== 'none', networkType }) }) } export function onNetworkStatusChange (callbackId) { const connection = navigator.connection || navigator.webkitConnection callbackIds.push(callbackId) if (connection) { connection.addEventListener('change', changeHandler) } else { window.addEventListener('offline', changeHandler) window.addEventListener('online', changeHandler) } } export function getNetworkType () { const connection = navigator.connection || navigator.webkitConnection let networkType = 'unknown' if (connection) { networkType = connection.type if (networkType === 'cellular' && connection.effectiveType) { networkType = connection.effectiveType.replace('slow-', '') } else if (!['none', 'wifi'].includes(networkType)) { networkType = 'unknown' } } else if (navigator.onLine === false) { networkType = 'none' } return { errMsg: 'getNetworkType:ok', networkType } }
adamlau/knife-xenserver
vendor/fog/lib/fog/rackspace/requests/compute/get_server_details.rb
module Fog module Compute class Rackspace class Real # Get details about a server # # ==== Parameters # * server_id<~Integer> - Id of server to get details for # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'server'<~Hash>: # * 'addresses'<~Hash>: # * 'public'<~Array> - public address strings # * 'private'<~Array> - private address strings # * 'flavorId'<~Integer> - Id of servers current flavor # * 'hostId'<~String> # * 'id'<~Integer> - Id of server # * 'imageId'<~Integer> - Id of image used to boot server # * 'metadata'<~Hash> - metadata # * 'name<~String> - Name of server # * 'progress'<~Integer> - Progress through current status # * 'status'<~String> - Current server status def get_server_details(server_id) request( :expects => [200, 203], :method => 'GET', :path => "servers/#{server_id}.json" ) end end class Mock def get_server_details(server_id) response = Excon::Response.new if server = list_servers_detail.body['servers'].detect {|_| _['id'] == server_id} response.status = [200, 203][rand(1)] response.body = { 'server' => server } response else raise Fog::Compute::Rackspace::NotFound end end end end end end
dragonrider7225/JavaUtil
src/util/function/CharSupplier.java
package util.function; /** * A supplier of characters. */ @FunctionalInterface public interface CharSupplier { /** * @return a character */ char get(); }
CMPUT301F18T13/HealthTracker
app/src/main/java/com/example/healthtracker/Activities/AddGeoLocationActivity.java
package com.example.healthtracker.Activities; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.example.healthtracker.R; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import java.io.IOException; import java.util.List; public class AddGeoLocationActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; private String CurrentLocation; private Double Lat; private Double Lon; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_geo_location); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /* * Search for a location by address. */ public void onMapSearch(View view) { EditText locationSearch = findViewById(R.id.editText); String location = locationSearch.getText().toString(); List<Address> addressList = null; if (location != null && !location.equals("")) { try { Geocoder geocoder = new Geocoder(this); addressList = geocoder.getFromLocationName(location, 1); //Log.d("array",addressList.toString()); if (!addressList.isEmpty()) { Address address = addressList.get(0); String city = address.getLocality(); String state = address.getAdminArea(); String country = address.getCountryName(); String postalCode = address.getPostalCode(); CurrentLocation = city + " " + state + " " + country + " " + postalCode; Lat = address.getLatitude(); Lon = address.getLongitude(); String Locality = address.getLocality(); Toast.makeText(getApplicationContext(), Locality, Toast.LENGTH_SHORT).show(); //LatLng LatLng = new LatLng(address.getLatitude(), address.getLongitude()); goToLocation(address.getLatitude(), address.getLongitude()); } else { String no_address = "No address found"; Toast.makeText(getApplicationContext(), no_address, Toast.LENGTH_SHORT).show(); } } catch (IOException e) { e.printStackTrace(); } //mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); } } @Override /* * Override the onMapReady method in order to set what will apear when the map is initiated. */ public void onMapReady(GoogleMap googleMap) { mMap = googleMap; /* // Add a marker in Sydney and move the camera LatLng sydney = new LatLng(27.700769, 85.300140); mMap.addMarker(new MarkerOptions().position(sydney).title("Marke")); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } mMap.setMyLocationEnabled(true);*/ String location = "University of Alberta"; List<Address> addressList = null; Geocoder geocoder = new Geocoder(this); try { addressList = geocoder.getFromLocationName(location, 1); } catch (IOException e) { e.printStackTrace(); } if (addressList != null) { Address address = addressList.get(0); String city = address.getLocality(); String state = address.getAdminArea(); String country = address.getCountryName(); String postalCode = address.getPostalCode(); CurrentLocation = city + " " + state + " " + country + " " + postalCode; Lat = address.getLatitude(); Lon = address.getLongitude(); String Locality = address.getLocality(); Toast.makeText(getApplicationContext(), Locality, Toast.LENGTH_SHORT).show(); goToLocation(address.getLatitude(), address.getLongitude()); } //goToLocation(27.700769, 85.300140, 15); } private void goToLocation(double latitude, double longitude) { LatLng LatLng = new LatLng(latitude, longitude); CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LatLng, 15); mMap.addMarker(new MarkerOptions().position(LatLng).title("Marker")); mMap.moveCamera(update); } public void onBackPressed() { Intent intent = new Intent(); intent.putExtra("result", CurrentLocation); AddGeoLocationActivity.this.setResult(0, intent); AddGeoLocationActivity.this.finish(); } public void Save_current(View view) { Intent intent = new Intent(); intent.putExtra("Lat", Lat); intent.putExtra("Lon", Lon); AddGeoLocationActivity.this.setResult(1, intent); AddGeoLocationActivity.this.finish(); } }
phistuck/sensu-go
vendor/github.com/ugorji/go/codec/binc.go
<filename>vendor/github.com/ugorji/go/codec/binc.go // Copyright (c) 2012-2015 <NAME>. All rights reserved. // Use of this source code is governed by a MIT license found in the LICENSE file. package codec import ( "math" "reflect" "time" ) const bincDoPrune = true // No longer needed. Needed before as C lib did not support pruning. // vd as low 4 bits (there are 16 slots) const ( bincVdSpecial byte = iota bincVdPosInt bincVdNegInt bincVdFloat bincVdString bincVdByteArray bincVdArray bincVdMap bincVdTimestamp bincVdSmallInt bincVdUnicodeOther bincVdSymbol bincVdDecimal _ // open slot _ // open slot bincVdCustomExt = 0x0f ) const ( bincSpNil byte = iota bincSpFalse bincSpTrue bincSpNan bincSpPosInf bincSpNegInf bincSpZeroFloat bincSpZero bincSpNegOne ) const ( bincFlBin16 byte = iota bincFlBin32 _ // bincFlBin32e bincFlBin64 _ // bincFlBin64e // others not currently supported ) type bincEncDriver struct { e *Encoder w encWriter m map[string]uint16 // symbols b [scratchByteArrayLen]byte s uint16 // symbols sequencer // encNoSeparator encDriverNoopContainerWriter noBuiltInTypes } // func (e *bincEncDriver) IsBuiltinType(rt uintptr) bool { // return rt == timeTypId // } func (e *bincEncDriver) EncodeNil() { e.w.writen1(bincVdSpecial<<4 | bincSpNil) } // func (e *bincEncDriver) EncodeBuiltin(rt uintptr, v interface{}) { // if rt == timeTypId { // e.EncodeTime(v.(time.Time)) // return // } // e.e.errorf("binc error encoding builtin: expect time.Time, received %T", v) // } func (e *bincEncDriver) EncodeTime(t time.Time) { if t.IsZero() { e.EncodeNil() } else { bs := encodeTime(t) e.w.writen1(bincVdTimestamp<<4 | uint8(len(bs))) e.w.writeb(bs) } } func (e *bincEncDriver) EncodeBool(b bool) { if b { e.w.writen1(bincVdSpecial<<4 | bincSpTrue) } else { e.w.writen1(bincVdSpecial<<4 | bincSpFalse) } } func (e *bincEncDriver) EncodeFloat32(f float32) { if f == 0 { e.w.writen1(bincVdSpecial<<4 | bincSpZeroFloat) return } e.w.writen1(bincVdFloat<<4 | bincFlBin32) bigenHelper{e.b[:4], e.w}.writeUint32(math.Float32bits(f)) } func (e *bincEncDriver) EncodeFloat64(f float64) { if f == 0 { e.w.writen1(bincVdSpecial<<4 | bincSpZeroFloat) return } bigen.PutUint64(e.b[:8], math.Float64bits(f)) if bincDoPrune { i := 7 for ; i >= 0 && (e.b[i] == 0); i-- { } i++ if i <= 6 { e.w.writen1(bincVdFloat<<4 | 0x8 | bincFlBin64) e.w.writen1(byte(i)) e.w.writeb(e.b[:i]) return } } e.w.writen1(bincVdFloat<<4 | bincFlBin64) e.w.writeb(e.b[:8]) } func (e *bincEncDriver) encIntegerPrune(bd byte, pos bool, v uint64, lim uint8) { if lim == 4 { bigen.PutUint32(e.b[:lim], uint32(v)) } else { bigen.PutUint64(e.b[:lim], v) } if bincDoPrune { i := pruneSignExt(e.b[:lim], pos) e.w.writen1(bd | lim - 1 - byte(i)) e.w.writeb(e.b[i:lim]) } else { e.w.writen1(bd | lim - 1) e.w.writeb(e.b[:lim]) } } func (e *bincEncDriver) EncodeInt(v int64) { const nbd byte = bincVdNegInt << 4 if v >= 0 { e.encUint(bincVdPosInt<<4, true, uint64(v)) } else if v == -1 { e.w.writen1(bincVdSpecial<<4 | bincSpNegOne) } else { e.encUint(bincVdNegInt<<4, false, uint64(-v)) } } func (e *bincEncDriver) EncodeUint(v uint64) { e.encUint(bincVdPosInt<<4, true, v) } func (e *bincEncDriver) encUint(bd byte, pos bool, v uint64) { if v == 0 { e.w.writen1(bincVdSpecial<<4 | bincSpZero) } else if pos && v >= 1 && v <= 16 { e.w.writen1(bincVdSmallInt<<4 | byte(v-1)) } else if v <= math.MaxUint8 { e.w.writen2(bd|0x0, byte(v)) } else if v <= math.MaxUint16 { e.w.writen1(bd | 0x01) bigenHelper{e.b[:2], e.w}.writeUint16(uint16(v)) } else if v <= math.MaxUint32 { e.encIntegerPrune(bd, pos, v, 4) } else { e.encIntegerPrune(bd, pos, v, 8) } } func (e *bincEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, _ *Encoder) { bs := ext.WriteExt(rv) if bs == nil { e.EncodeNil() return } e.encodeExtPreamble(uint8(xtag), len(bs)) e.w.writeb(bs) } func (e *bincEncDriver) EncodeRawExt(re *RawExt, _ *Encoder) { e.encodeExtPreamble(uint8(re.Tag), len(re.Data)) e.w.writeb(re.Data) } func (e *bincEncDriver) encodeExtPreamble(xtag byte, length int) { e.encLen(bincVdCustomExt<<4, uint64(length)) e.w.writen1(xtag) } func (e *bincEncDriver) WriteArrayStart(length int) { e.encLen(bincVdArray<<4, uint64(length)) } func (e *bincEncDriver) WriteMapStart(length int) { e.encLen(bincVdMap<<4, uint64(length)) } func (e *bincEncDriver) EncodeString(c charEncoding, v string) { l := uint64(len(v)) e.encBytesLen(c, l) if l > 0 { e.w.writestr(v) } } func (e *bincEncDriver) EncodeSymbol(v string) { // if WriteSymbolsNoRefs { // e.encodeString(cUTF8, v) // return // } //symbols only offer benefit when string length > 1. //This is because strings with length 1 take only 2 bytes to store //(bd with embedded length, and single byte for string val). l := len(v) if l == 0 { e.encBytesLen(cUTF8, 0) return } else if l == 1 { e.encBytesLen(cUTF8, 1) e.w.writen1(v[0]) return } if e.m == nil { e.m = make(map[string]uint16, 16) } ui, ok := e.m[v] if ok { if ui <= math.MaxUint8 { e.w.writen2(bincVdSymbol<<4, byte(ui)) } else { e.w.writen1(bincVdSymbol<<4 | 0x8) bigenHelper{e.b[:2], e.w}.writeUint16(ui) } } else { e.s++ ui = e.s //ui = uint16(atomic.AddUint32(&e.s, 1)) e.m[v] = ui var lenprec uint8 if l <= math.MaxUint8 { // lenprec = 0 } else if l <= math.MaxUint16 { lenprec = 1 } else if int64(l) <= math.MaxUint32 { lenprec = 2 } else { lenprec = 3 } if ui <= math.MaxUint8 { e.w.writen2(bincVdSymbol<<4|0x0|0x4|lenprec, byte(ui)) } else { e.w.writen1(bincVdSymbol<<4 | 0x8 | 0x4 | lenprec) bigenHelper{e.b[:2], e.w}.writeUint16(ui) } if lenprec == 0 { e.w.writen1(byte(l)) } else if lenprec == 1 { bigenHelper{e.b[:2], e.w}.writeUint16(uint16(l)) } else if lenprec == 2 { bigenHelper{e.b[:4], e.w}.writeUint32(uint32(l)) } else { bigenHelper{e.b[:8], e.w}.writeUint64(uint64(l)) } e.w.writestr(v) } } func (e *bincEncDriver) EncodeStringBytes(c charEncoding, v []byte) { if v == nil { e.EncodeNil() return } l := uint64(len(v)) e.encBytesLen(c, l) if l > 0 { e.w.writeb(v) } } func (e *bincEncDriver) encBytesLen(c charEncoding, length uint64) { //TODO: support bincUnicodeOther (for now, just use string or bytearray) if c == cRAW { e.encLen(bincVdByteArray<<4, length) } else { e.encLen(bincVdString<<4, length) } } func (e *bincEncDriver) encLen(bd byte, l uint64) { if l < 12 { e.w.writen1(bd | uint8(l+4)) } else { e.encLenNumber(bd, l) } } func (e *bincEncDriver) encLenNumber(bd byte, v uint64) { if v <= math.MaxUint8 { e.w.writen2(bd, byte(v)) } else if v <= math.MaxUint16 { e.w.writen1(bd | 0x01) bigenHelper{e.b[:2], e.w}.writeUint16(uint16(v)) } else if v <= math.MaxUint32 { e.w.writen1(bd | 0x02) bigenHelper{e.b[:4], e.w}.writeUint32(uint32(v)) } else { e.w.writen1(bd | 0x03) bigenHelper{e.b[:8], e.w}.writeUint64(uint64(v)) } } //------------------------------------ type bincDecSymbol struct { s string b []byte i uint16 } type bincDecDriver struct { d *Decoder h *BincHandle r decReader br bool // bytes reader bdRead bool bd byte vd byte vs byte // noStreamingCodec // decNoSeparator b [scratchByteArrayLen]byte // linear searching on this slice is ok, // because we typically expect < 32 symbols in each stream. s []bincDecSymbol decDriverNoopContainerReader noBuiltInTypes } func (d *bincDecDriver) readNextBd() { d.bd = d.r.readn1() d.vd = d.bd >> 4 d.vs = d.bd & 0x0f d.bdRead = true } func (d *bincDecDriver) uncacheRead() { if d.bdRead { d.r.unreadn1() d.bdRead = false } } func (d *bincDecDriver) ContainerType() (vt valueType) { if !d.bdRead { d.readNextBd() } if d.vd == bincVdSpecial && d.vs == bincSpNil { return valueTypeNil } else if d.vd == bincVdByteArray { return valueTypeBytes } else if d.vd == bincVdString { return valueTypeString } else if d.vd == bincVdArray { return valueTypeArray } else if d.vd == bincVdMap { return valueTypeMap } // else { // d.d.errorf("isContainerType: unsupported parameter: %v", vt) // } return valueTypeUnset } func (d *bincDecDriver) TryDecodeAsNil() bool { if !d.bdRead { d.readNextBd() } if d.bd == bincVdSpecial<<4|bincSpNil { d.bdRead = false return true } return false } // func (d *bincDecDriver) IsBuiltinType(rt uintptr) bool { // return rt == timeTypId // } func (d *bincDecDriver) DecodeTime() (t time.Time) { if !d.bdRead { d.readNextBd() } if d.bd == bincVdSpecial<<4|bincSpNil { d.bdRead = false return } if d.vd != bincVdTimestamp { d.d.errorf("Invalid d.vd. Expecting 0x%x. Received: 0x%x", bincVdTimestamp, d.vd) return } t, err := decodeTime(d.r.readx(int(d.vs))) if err != nil { panic(err) } d.bdRead = false return } // func (d *bincDecDriver) DecodeBuiltin(rt uintptr, v interface{}) { // if rt == timeTypId { // var vt = v.(*time.Time) // *vt = d.DecodeTime() // return // } // d.d.errorf("binc error decoding builtin: expect *time.Time, received %T", v) // } func (d *bincDecDriver) decFloatPre(vs, defaultLen byte) { if vs&0x8 == 0 { d.r.readb(d.b[0:defaultLen]) } else { l := d.r.readn1() if l > 8 { d.d.errorf("At most 8 bytes used to represent float. Received: %v bytes", l) return } for i := l; i < 8; i++ { d.b[i] = 0 } d.r.readb(d.b[0:l]) } } func (d *bincDecDriver) decFloat() (f float64) { //if true { f = math.Float64frombits(bigen.Uint64(d.r.readx(8))); break; } if x := d.vs & 0x7; x == bincFlBin32 { d.decFloatPre(d.vs, 4) f = float64(math.Float32frombits(bigen.Uint32(d.b[0:4]))) } else if x == bincFlBin64 { d.decFloatPre(d.vs, 8) f = math.Float64frombits(bigen.Uint64(d.b[0:8])) } else { d.d.errorf("only float32 and float64 are supported. d.vd: 0x%x, d.vs: 0x%x", d.vd, d.vs) return } return } func (d *bincDecDriver) decUint() (v uint64) { // need to inline the code (interface conversion and type assertion expensive) switch d.vs { case 0: v = uint64(d.r.readn1()) case 1: d.r.readb(d.b[6:8]) v = uint64(bigen.Uint16(d.b[6:8])) case 2: d.b[4] = 0 d.r.readb(d.b[5:8]) v = uint64(bigen.Uint32(d.b[4:8])) case 3: d.r.readb(d.b[4:8]) v = uint64(bigen.Uint32(d.b[4:8])) case 4, 5, 6: lim := int(7 - d.vs) d.r.readb(d.b[lim:8]) for i := 0; i < lim; i++ { d.b[i] = 0 } v = uint64(bigen.Uint64(d.b[:8])) case 7: d.r.readb(d.b[:8]) v = uint64(bigen.Uint64(d.b[:8])) default: d.d.errorf("unsigned integers with greater than 64 bits of precision not supported") return } return } func (d *bincDecDriver) decCheckInteger() (ui uint64, neg bool) { if !d.bdRead { d.readNextBd() } vd, vs := d.vd, d.vs if vd == bincVdPosInt { ui = d.decUint() } else if vd == bincVdNegInt { ui = d.decUint() neg = true } else if vd == bincVdSmallInt { ui = uint64(d.vs) + 1 } else if vd == bincVdSpecial { if vs == bincSpZero { //i = 0 } else if vs == bincSpNegOne { neg = true ui = 1 } else { d.d.errorf("numeric decode fails for special value: d.vs: 0x%x", d.vs) return } } else { d.d.errorf("number can only be decoded from uint or int values. d.bd: 0x%x, d.vd: 0x%x", d.bd, d.vd) return } return } func (d *bincDecDriver) DecodeInt(bitsize uint8) (i int64) { ui, neg := d.decCheckInteger() i, overflow := chkOvf.SignedInt(ui) if overflow { d.d.errorf("simple: overflow converting %v to signed integer", ui) return } if neg { i = -i } if chkOvf.Int(i, bitsize) { d.d.errorf("binc: overflow integer: %v for num bits: %v", i, bitsize) return } d.bdRead = false return } func (d *bincDecDriver) DecodeUint(bitsize uint8) (ui uint64) { ui, neg := d.decCheckInteger() if neg { d.d.errorf("Assigning negative signed value to unsigned type") return } if chkOvf.Uint(ui, bitsize) { d.d.errorf("binc: overflow integer: %v", ui) return } d.bdRead = false return } func (d *bincDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) { if !d.bdRead { d.readNextBd() } vd, vs := d.vd, d.vs if vd == bincVdSpecial { d.bdRead = false if vs == bincSpNan { return math.NaN() } else if vs == bincSpPosInf { return math.Inf(1) } else if vs == bincSpZeroFloat || vs == bincSpZero { return } else if vs == bincSpNegInf { return math.Inf(-1) } else { d.d.errorf("Invalid d.vs decoding float where d.vd=bincVdSpecial: %v", d.vs) return } } else if vd == bincVdFloat { f = d.decFloat() } else { f = float64(d.DecodeInt(64)) } if chkOverflow32 && chkOvf.Float32(f) { d.d.errorf("binc: float32 overflow: %v", f) return } d.bdRead = false return } // bool can be decoded from bool only (single byte). func (d *bincDecDriver) DecodeBool() (b bool) { if !d.bdRead { d.readNextBd() } if bd := d.bd; bd == (bincVdSpecial | bincSpFalse) { // b = false } else if bd == (bincVdSpecial | bincSpTrue) { b = true } else { d.d.errorf("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd) return } d.bdRead = false return } func (d *bincDecDriver) ReadMapStart() (length int) { if !d.bdRead { d.readNextBd() } if d.vd != bincVdMap { d.d.errorf("Invalid d.vd for map. Expecting 0x%x. Got: 0x%x", bincVdMap, d.vd) return } length = d.decLen() d.bdRead = false return } func (d *bincDecDriver) ReadArrayStart() (length int) { if !d.bdRead { d.readNextBd() } if d.vd != bincVdArray { d.d.errorf("Invalid d.vd for array. Expecting 0x%x. Got: 0x%x", bincVdArray, d.vd) return } length = d.decLen() d.bdRead = false return } func (d *bincDecDriver) decLen() int { if d.vs > 3 { return int(d.vs - 4) } return int(d.decLenNumber()) } func (d *bincDecDriver) decLenNumber() (v uint64) { if x := d.vs; x == 0 { v = uint64(d.r.readn1()) } else if x == 1 { d.r.readb(d.b[6:8]) v = uint64(bigen.Uint16(d.b[6:8])) } else if x == 2 { d.r.readb(d.b[4:8]) v = uint64(bigen.Uint32(d.b[4:8])) } else { d.r.readb(d.b[:8]) v = bigen.Uint64(d.b[:8]) } return } func (d *bincDecDriver) decStringAndBytes(bs []byte, withString, zerocopy bool) (bs2 []byte, s string) { if !d.bdRead { d.readNextBd() } if d.bd == bincVdSpecial<<4|bincSpNil { d.bdRead = false return } var slen = -1 // var ok bool switch d.vd { case bincVdString, bincVdByteArray: slen = d.decLen() if zerocopy { if d.br { bs2 = d.r.readx(slen) } else if len(bs) == 0 { bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, d.b[:]) } else { bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, bs) } } else { bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, bs) } if withString { s = string(bs2) } case bincVdSymbol: // zerocopy doesn't apply for symbols, // as the values must be stored in a table for later use. // //from vs: extract numSymbolBytes, containsStringVal, strLenPrecision, //extract symbol //if containsStringVal, read it and put in map //else look in map for string value var symbol uint16 vs := d.vs if vs&0x8 == 0 { symbol = uint16(d.r.readn1()) } else { symbol = uint16(bigen.Uint16(d.r.readx(2))) } if d.s == nil { d.s = make([]bincDecSymbol, 0, 16) } if vs&0x4 == 0 { for i := range d.s { j := &d.s[i] if j.i == symbol { bs2 = j.b if withString { if j.s == "" && bs2 != nil { j.s = string(bs2) } s = j.s } break } } } else { switch vs & 0x3 { case 0: slen = int(d.r.readn1()) case 1: slen = int(bigen.Uint16(d.r.readx(2))) case 2: slen = int(bigen.Uint32(d.r.readx(4))) case 3: slen = int(bigen.Uint64(d.r.readx(8))) } // since using symbols, do not store any part of // the parameter bs in the map, as it might be a shared buffer. // bs2 = decByteSlice(d.r, slen, bs) bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, nil) if withString { s = string(bs2) } d.s = append(d.s, bincDecSymbol{i: symbol, s: s, b: bs2}) } default: d.d.errorf("Invalid d.vd. Expecting string:0x%x, bytearray:0x%x or symbol: 0x%x. Got: 0x%x", bincVdString, bincVdByteArray, bincVdSymbol, d.vd) return } d.bdRead = false return } func (d *bincDecDriver) DecodeString() (s string) { // DecodeBytes does not accommodate symbols, whose impl stores string version in map. // Use decStringAndBytes directly. // return string(d.DecodeBytes(d.b[:], true, true)) _, s = d.decStringAndBytes(d.b[:], true, true) return } func (d *bincDecDriver) DecodeStringAsBytes() (s []byte) { s, _ = d.decStringAndBytes(d.b[:], false, true) return } func (d *bincDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) { if !d.bdRead { d.readNextBd() } if d.bd == bincVdSpecial<<4|bincSpNil { d.bdRead = false return nil } // check if an "array" of uint8's (see ContainerType for how to infer if an array) if d.vd == bincVdArray { bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d) return } var clen int if d.vd == bincVdString || d.vd == bincVdByteArray { clen = d.decLen() } else { d.d.errorf("Invalid d.vd for bytes. Expecting string:0x%x or bytearray:0x%x. Got: 0x%x", bincVdString, bincVdByteArray, d.vd) return } d.bdRead = false if zerocopy { if d.br { return d.r.readx(clen) } else if len(bs) == 0 { bs = d.b[:] } } return decByteSlice(d.r, clen, d.d.h.MaxInitLen, bs) } func (d *bincDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) { if xtag > 0xff { d.d.errorf("decodeExt: tag must be <= 0xff; got: %v", xtag) return } realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag)) realxtag = uint64(realxtag1) if ext == nil { re := rv.(*RawExt) re.Tag = realxtag re.Data = detachZeroCopyBytes(d.br, re.Data, xbs) } else { ext.ReadExt(rv, xbs) } return } func (d *bincDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) { if !d.bdRead { d.readNextBd() } if d.vd == bincVdCustomExt { l := d.decLen() xtag = d.r.readn1() if verifyTag && xtag != tag { d.d.errorf("Wrong extension tag. Got %b. Expecting: %v", xtag, tag) return } xbs = d.r.readx(l) } else if d.vd == bincVdByteArray { xbs = d.DecodeBytes(nil, true) } else { d.d.errorf("Invalid d.vd for extensions (Expecting extensions or byte array). Got: 0x%x", d.vd) return } d.bdRead = false return } func (d *bincDecDriver) DecodeNaked() { if !d.bdRead { d.readNextBd() } n := d.d.n var decodeFurther bool switch d.vd { case bincVdSpecial: switch d.vs { case bincSpNil: n.v = valueTypeNil case bincSpFalse: n.v = valueTypeBool n.b = false case bincSpTrue: n.v = valueTypeBool n.b = true case bincSpNan: n.v = valueTypeFloat n.f = math.NaN() case bincSpPosInf: n.v = valueTypeFloat n.f = math.Inf(1) case bincSpNegInf: n.v = valueTypeFloat n.f = math.Inf(-1) case bincSpZeroFloat: n.v = valueTypeFloat n.f = float64(0) case bincSpZero: n.v = valueTypeUint n.u = uint64(0) // int8(0) case bincSpNegOne: n.v = valueTypeInt n.i = int64(-1) // int8(-1) default: d.d.errorf("decodeNaked: Unrecognized special value 0x%x", d.vs) } case bincVdSmallInt: n.v = valueTypeUint n.u = uint64(int8(d.vs)) + 1 // int8(d.vs) + 1 case bincVdPosInt: n.v = valueTypeUint n.u = d.decUint() case bincVdNegInt: n.v = valueTypeInt n.i = -(int64(d.decUint())) case bincVdFloat: n.v = valueTypeFloat n.f = d.decFloat() case bincVdSymbol: n.v = valueTypeSymbol n.s = d.DecodeString() case bincVdString: n.v = valueTypeString n.s = d.DecodeString() case bincVdByteArray: n.v = valueTypeBytes n.l = d.DecodeBytes(nil, false) case bincVdTimestamp: n.v = valueTypeTime tt, err := decodeTime(d.r.readx(int(d.vs))) if err != nil { panic(err) } n.t = tt case bincVdCustomExt: n.v = valueTypeExt l := d.decLen() n.u = uint64(d.r.readn1()) n.l = d.r.readx(l) case bincVdArray: n.v = valueTypeArray decodeFurther = true case bincVdMap: n.v = valueTypeMap decodeFurther = true default: d.d.errorf("decodeNaked: Unrecognized d.vd: 0x%x", d.vd) } if !decodeFurther { d.bdRead = false } if n.v == valueTypeUint && d.h.SignedInteger { n.v = valueTypeInt n.i = int64(n.u) } return } //------------------------------------ //BincHandle is a Handle for the Binc Schema-Free Encoding Format //defined at https://github.com/ugorji/binc . // //BincHandle currently supports all Binc features with the following EXCEPTIONS: // - only integers up to 64 bits of precision are supported. // big integers are unsupported. // - Only IEEE 754 binary32 and binary64 floats are supported (ie Go float32 and float64 types). // extended precision and decimal IEEE 754 floats are unsupported. // - Only UTF-8 strings supported. // Unicode_Other Binc types (UTF16, UTF32) are currently unsupported. // //Note that these EXCEPTIONS are temporary and full support is possible and may happen soon. type BincHandle struct { BasicHandle binaryEncodingType noElemSeparators } // SetBytesExt sets an extension func (h *BincHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) { return h.SetExt(rt, tag, &setExtWrapper{b: ext}) } func (h *BincHandle) newEncDriver(e *Encoder) encDriver { return &bincEncDriver{e: e, w: e.w} } func (h *BincHandle) newDecDriver(d *Decoder) decDriver { return &bincDecDriver{d: d, h: h, r: d.r, br: d.bytes} } // // IsBuiltinType returns true for time.Time, else false. // // only time.Time is builtin. // func (h *BincHandle) IsBuiltinType(rt uintptr) bool { // return rt == timeTypId // } func (e *bincEncDriver) reset() { e.w = e.e.w e.s = 0 e.m = nil } func (d *bincDecDriver) reset() { d.r, d.br = d.d.r, d.d.bytes d.s = nil d.bd, d.bdRead, d.vd, d.vs = 0, false, 0, 0 } var _ decDriver = (*bincDecDriver)(nil) var _ encDriver = (*bincEncDriver)(nil)
Maruf-Tuhin/Online_Judge
solved-lightOj/1088.cpp
#include <stdio.h> #include <string.h> #include <algorithm> #include <math.h> using namespace std; long arr[100010]; int bsearch(int v,int l, int h) { int mid; while(h>=l) { mid=ceil((h+l)/2.0); if(arr[mid]==v) return mid; else if(arr[mid]<v) l=mid+1; else h=mid-1; } return h; } main() { int i,j,t,T,n,q,x,y,sum; scanf("%d",&T); for(t=1;t<=T;t++) { scanf("%d %d",&n,&q); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } printf("Case %d:\n",t); while(q--) { scanf("%d %d",&x,&y); i=bsearch(x,0,n-1); if(i<0) i=0; else if(arr[i]<x) i++; j=bsearch(y,0,n-1); sum=j-i+1; if(sum>0) printf("%d\n",sum); else printf("0\n"); } } return 0; }
dev-senior-com-br/senior-sam-java
src/main/java/br/com/senior/sam/portaria/pojos/EmailRecord.java
<filename>src/main/java/br/com/senior/sam/portaria/pojos/EmailRecord.java package br.com.senior.sam.portaria.pojos; public class EmailRecord { /** * ID */ public Long id; /** * Email Preferencial */ public Boolean preferential; /** * Endereço do email */ public String email; public EmailRecord() { } /** * This constructor allows initialization of all fields, required and optional. */ public EmailRecord(Long id, Boolean preferential, String email) { this.id = id; this.preferential = preferential; this.email = email; } /** * This convenience constructor allows initialization of all required fields. */ public EmailRecord(Long id, String email) { this.id = id; this.email = email; } }
jjk1492/WebCheckers
src/main/java/com/webcheckers/model/Position.java
package com.webcheckers.model; import static com.webcheckers.model.Board.COLS; import static com.webcheckers.model.Board.ROWS; /** * Position class in the model tier * @author <NAME> */ public class Position { private final int row; private final int cell; /** * constructs a Position object * @param row int from 0 to 7 * @param cell int 0 to 7 */ public Position(int row, int cell) { this.row = row; this.cell = cell; } /** * gets the corresponding position if the board were rotated 180 degrees * @return inverted Position */ public Position getInverse() { return new Position( ROWS - 1 - row, COLS - 1 - cell ); } /** * @return row */ public int getRow(){ return row; } /** * @return cell */ public int getCell() { return cell; } @Override public String toString() { return "(" + row + "," + cell + ")"; } }
CoolBitX-Technology/coolwallet-ios
CoolWallet/CwKeychain.h
// // CwKeychain.h // CoolWallet // // Created by 鄭斐文 on 2015/12/9. // Copyright © 2015年 MAC-BRYAN. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreBitcoin/BTCKeychain.h> #import <CoreBitcoin/BTCKey.h> typedef NS_ENUM (NSInteger, CwKeychainType) { CwKeyChainExternal = 0x00, CwKeyChainInternal = 0x01 }; @interface CwKeychain : BTCKeychain @property (readonly) NSString *hexPublicKey; @property (readonly) NSString *hexChainCode; @property (readonly) NSNumber *keyChainId; @property (readonly) NSNumber *currentKeyIndex; /** init keychain * @param publicKey 64 bytes hex string * @param chainCode 32 bytes hex string * @param keychainType CwKeyChainExternal/CwKeyChainInternal */ - (id) initWithPublicKey:(NSString*)publicKey ChainCode:(NSString *)chainCode KeychainId:(CwKeychainType)keychainType; -(BTCKey *) getAddressAtIndex:(int)index; -(BTCKey *) genNextAddress; -(NSData *) getPublicKeyAtIndex:(int)index; @end
dermidgen/graphdb.js
src/query/query-payload.js
<gh_stars>10-100 const QueryContentType = require('../http/query-content-type'); /** * Base class from which all query payload classes derives. Successors must * implement {@link #validateParams} and {@link #getSupportedContentTypes}. * * @abstract * @class * @author <NAME> * @author <NAME> */ class QueryPayload { /** * Does basic initialization. */ constructor() { this.payload = {}; this.contentType = null; } /** * @param {boolean} [inference] Specifies whether inferred statements should * be included in the query evaluation. * @return {QueryPayload} */ setInference(inference) { if (typeof inference !== 'boolean') { throw new Error('Inference must be a boolean!'); } this.payload.infer = inference; return this; } /** * @param {number} [timeout] Specifies a maximum query execution time, in * whole seconds. * @return {QueryPayload} */ setTimeout(timeout) { if (typeof timeout !== 'number') { throw new Error('Timeout must be a number!'); } this.payload.timeout = timeout; return this; } /** * An optional parameter which is used for defining the request Content-Type. * * @param {string} [contentType] One of the supported content types for given * operation. * @return {QueryPayload} */ setContentType(contentType) { const supportedTypes = this.getSupportedContentTypes(); if (typeof contentType !== 'string' || supportedTypes.indexOf(contentType) === -1) { throw new Error(`Content type must be one of ${supportedTypes}!`); } this.contentType = contentType; return this; } /** * @return {string} content type which was populated in this payload. */ getContentType() { return this.contentType; } /** * Serializes all query parameters populated in the payload. Only parameters * which are present will be returned. * * Mandatory and dependent parameters are validated and errors are thrown if * necessary. * * @return {string} a serialized payload which holds all available query * parameters in this payload object. */ getParams() { // when contentType is 'x-www-form-urlencoded', then all parameters should // be considered if (this.getContentType() === QueryContentType.X_WWW_FORM_URLENCODED) { const isValid = this.validateParams(); return isValid && this.serialize(this.payload); } const query = this.getQuery(); if (!query) { throw new Error('Parameter query is mandatory!'); } return query; } /** * Utility method which serializes a single level json object to properly * encoded string that can be used in a request. * * @protected * @param {Object} data object which holds request parameter key:value pairs. * @return {string} provided object serialized and encoded to string. */ serialize(data) { return Object.entries(data) .filter((x) => x[1] !== undefined) .map((x) => `${encodeURIComponent(x[0])}=${encodeURIComponent(x[1])}`) .join('&'); } /** * Must be implemented in successors. * * Validates payload for mandatory and invalid parameters. * * @abstract * @protected * * @return {boolean} <code>true</code> if parameters are valid and * <code>false</code> otherwise. */ validateParams() { return false; } /** * Must be implemented in successors and should return a list with supported * content types. * @abstract * @protected * * @return {Array<string>} */ getSupportedContentTypes() { return []; } } module.exports = QueryPayload;
emanuelaguna/rakm
app/services/location/jhu.py
"""app.services.location.jhu.py""" import csv from datetime import datetime from asyncache import cached from cachetools import TTLCache from ...coordinates import Coordinates from ...location import TimelinedLocation from ...timeline import Timeline from ...utils import countries from ...utils import date as date_util from ...utils import httputils from . import LocationService class JhuLocationService(LocationService): """ Service for retrieving locations from Johns Hopkins CSSE (https://github.com/CSSEGISandData/COVID-19). """ async def get_all(self): # Get the locations. locations = await get_locations() return locations async def get(self, loc_id): # pylint: disable=arguments-differ # Get location at the index equal to provided id. locations = await self.get_all() return locations[loc_id] # --------------------------------------------------------------- # Base URL for fetching category. BASE_URL = ( "https://raw.githubusercontent.com/CSSEGISandData/2019-nCoV/master/csse_covid_19_data/csse_covid_19_time_series/" ) @cached(cache=TTLCache(maxsize=1024, ttl=3600)) async def get_category(category): """ Retrieves the data for the provided category. The data is cached for 1 hour. :returns: The data for category. :rtype: dict """ # Adhere to category naming standard. category = category.lower() # URL to request data from. url = BASE_URL + "time_series_covid19_%s_global.csv" % category # Request the data async with httputils.CLIENT_SESSION.get(url) as response: text = await response.text() # Parse the CSV. data = list(csv.DictReader(text.splitlines())) # The normalized locations. locations = [] for item in data: # Filter out all the dates. dates = dict(filter(lambda element: date_util.is_date(element[0]), item.items())) # Make location history from dates. history = {date: int(amount or 0) for date, amount in dates.items()} # Country for this location. country = item["Country/Region"] # Latest data insert value. latest = list(history.values())[-1] # Normalize the item and append to locations. locations.append( { # General info. "country": country, "country_code": countries.country_code(country), "province": item["Province/State"], # Coordinates. "coordinates": {"lat": item["Lat"], "long": item["Long"],}, # History. "history": history, # Latest statistic. "latest": int(latest or 0), } ) # Latest total. latest = sum(map(lambda location: location["latest"], locations)) # Return the final data. return { "locations": locations, "latest": latest, "last_updated": datetime.utcnow().isoformat() + "Z", "source": "https://github.com/ExpDev07/coronavirus-tracker-api", } @cached(cache=TTLCache(maxsize=1024, ttl=3600)) async def get_locations(): """ Retrieves the locations from the categories. The locations are cached for 1 hour. :returns: The locations. :rtype: List[Location] """ # Get all of the data categories locations. confirmed = await get_category("confirmed") deaths = await get_category("deaths") # recovered = await get_category("recovered") locations_confirmed = confirmed["locations"] locations_deaths = deaths["locations"] # locations_recovered = recovered["locations"] # Final locations to return. locations = [] # Go through locations. for index, location in enumerate(locations_confirmed): # Get the timelines. timelines = { "confirmed": locations_confirmed[index]["history"], "deaths": locations_deaths[index]["history"], # 'recovered' : locations_recovered[index]['history'], } # Grab coordinates. coordinates = location["coordinates"] # Create location (supporting timelines) and append. locations.append( TimelinedLocation( # General info. index, location["country"], location["province"], # Coordinates. Coordinates(coordinates["lat"], coordinates["long"]), # Last update. datetime.utcnow().isoformat() + "Z", # Timelines (parse dates as ISO). { "confirmed": Timeline( { datetime.strptime(date, "%m/%d/%y").isoformat() + "Z": amount for date, amount in timelines["confirmed"].items() } ), "deaths": Timeline( { datetime.strptime(date, "%m/%d/%y").isoformat() + "Z": amount for date, amount in timelines["deaths"].items() } ), "recovered": Timeline({}), }, ) ) # Finally, return the locations. return locations
bytesparadise/libasciidoctor
testsupport/table_of_contents_matcher_test.go
<gh_stars>0 package testsupport_test import ( "fmt" "github.com/bytesparadise/libasciidoc/pkg/types" "github.com/bytesparadise/libasciidoc/testsupport" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("document fragments matcher", func() { // given expected := &types.TableOfContents{ Sections: []*types.ToCSection{ { Title: "root", }, }, } matcher := testsupport.MatchTableOfContents(expected) It("should match", func() { // given actual := &types.TableOfContents{ Sections: []*types.ToCSection{ { Title: "root", }, }, } // when result, err := matcher.Match(actual) // then Expect(err).ToNot(HaveOccurred()) Expect(result).To(BeTrue()) }) It("should not match", func() { // given actual := &types.TableOfContents{ Sections: []*types.ToCSection{ { Title: "something else", }, }, } // when result, err := matcher.Match(actual) // then Expect(err).ToNot(HaveOccurred()) Expect(result).To(BeFalse()) diffs := cmp.Diff(expected, actual, cmpopts.IgnoreUnexported(types.TableOfContents{})) Expect(matcher.FailureMessage(actual)).To(Equal(fmt.Sprintf("expected table of contents to match:\n%s", diffs))) Expect(matcher.NegatedFailureMessage(actual)).To(Equal(fmt.Sprintf("expected table of contents not to match:\n%s", diffs))) }) It("should return error when invalid type is input", func() { // when result, err := matcher.Match(1) // then Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("MatchDocumentFragment matcher expects a *types.TableOfContents (actual: int)")) Expect(result).To(BeFalse()) }) })
lastweek/source-freebsd
src/sys/dev/bhnd/nvram/bhnd_nvram_store_subr.c
/*- * Copyright (c) 2015-2016 <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any * redistribution must be conditioned upon including a substantially * similar Disclaimer requirement for further binary redistribution. * * NO WARRANTY * 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 NONINFRINGEMENT, MERCHANTIBILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include <sys/param.h> #include <sys/hash.h> #include <sys/queue.h> #ifdef _KERNEL #include <sys/ctype.h> #include <sys/systm.h> #include <machine/_inttypes.h> #else /* !_KERNEL */ #include <ctype.h> #include <errno.h> #include <inttypes.h> #include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #endif /* _KERNEL */ #include "bhnd_nvram_private.h" #include "bhnd_nvram_datavar.h" #include "bhnd_nvram_storevar.h" static int bhnd_nvstore_idx_cmp(void *ctx, const void *lhs, const void *rhs); /** * Allocate and initialize a new path instance. * * The caller is responsible for deallocating the instance via * bhnd_nvstore_path_free(). * * @param path_str The path's canonical string representation. * @param path_len The length of @p path_str. * * @retval non-NULL success * @retval NULL if allocation fails. */ bhnd_nvstore_path * bhnd_nvstore_path_new(const char *path_str, size_t path_len) { bhnd_nvstore_path *path; /* Allocate new entry */ path = bhnd_nv_malloc(sizeof(*path)); if (path == NULL) return (NULL); path->index = NULL; path->num_vars = 0; path->pending = bhnd_nvram_plist_new(); if (path->pending == NULL) goto failed; path->path_str = bhnd_nv_strndup(path_str, path_len); if (path->path_str == NULL) goto failed; return (path); failed: if (path->pending != NULL) bhnd_nvram_plist_release(path->pending); if (path->path_str != NULL) bhnd_nv_free(path->path_str); bhnd_nv_free(path); return (NULL); } /** * Free an NVRAM path instance, releasing all associated resources. */ void bhnd_nvstore_path_free(struct bhnd_nvstore_path *path) { /* Free the per-path index */ if (path->index != NULL) bhnd_nvstore_index_free(path->index); bhnd_nvram_plist_release(path->pending); bhnd_nv_free(path->path_str); bhnd_nv_free(path); } /** * Allocate and initialize a new index instance with @p capacity. * * The caller is responsible for deallocating the instance via * bhnd_nvstore_index_free(). * * @param capacity The maximum number of variables to be indexed. * * @retval non-NULL success * @retval NULL if allocation fails. */ bhnd_nvstore_index * bhnd_nvstore_index_new(size_t capacity) { bhnd_nvstore_index *index; size_t bytes; /* Allocate and populate variable index */ bytes = sizeof(struct bhnd_nvstore_index) + (sizeof(void *) * capacity); index = bhnd_nv_malloc(bytes); if (index == NULL) { BHND_NV_LOG("error allocating %zu byte index\n", bytes); return (NULL); } index->count = 0; index->capacity = capacity; return (index); } /** * Free an index instance, releasing all associated resources. * * @param index An index instance previously allocated via * bhnd_nvstore_index_new(). */ void bhnd_nvstore_index_free(bhnd_nvstore_index *index) { bhnd_nv_free(index); } /** * Append a new NVRAM variable's @p cookiep value to @p index. * * After one or more append requests, the index must be prepared via * bhnd_nvstore_index_prepare() before any indexed lookups are performed. * * @param sc The NVRAM store from which NVRAM values will be queried. * @param index The index to be modified. * @param cookiep The cookiep value (as provided by the backing NVRAM * data instance of @p sc) to be included in @p index. * * @retval 0 success * @retval ENOMEM if appending an additional entry would exceed the * capacity of @p index. */ int bhnd_nvstore_index_append(struct bhnd_nvram_store *sc, bhnd_nvstore_index *index, void *cookiep) { BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); if (index->count >= index->capacity) return (ENOMEM); index->cookiep[index->count] = cookiep; index->count++; return (0); } /* sort function for bhnd_nvstore_index_prepare() */ static int bhnd_nvstore_idx_cmp(void *ctx, const void *lhs, const void *rhs) { struct bhnd_nvram_store *sc; void *l_cookiep, *r_cookiep; const char *l_str, *r_str; const char *l_name, *r_name; int order; sc = ctx; l_cookiep = *(void * const *)lhs; r_cookiep = *(void * const *)rhs; BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); /* Fetch string pointers from the cookiep values */ l_str = bhnd_nvram_data_getvar_name(sc->data, l_cookiep); r_str = bhnd_nvram_data_getvar_name(sc->data, r_cookiep); /* Trim device path prefixes */ if (sc->data_caps & BHND_NVRAM_DATA_CAP_DEVPATHS) { l_name = bhnd_nvram_trim_path_name(l_str); r_name = bhnd_nvram_trim_path_name(r_str); } else { l_name = l_str; r_name = r_str; } /* Perform comparison */ order = strcmp(l_name, r_name); if (order != 0 || lhs == rhs) return (order); /* If the backing data incorrectly contains variables with duplicate * names, we need a sort order that provides stable behavior. * * Since Broadcom's own code varies wildly on this question, we just * use a simple precedence rule: The first declaration of a variable * takes precedence. */ return (bhnd_nvram_data_getvar_order(sc->data, l_cookiep, r_cookiep)); } /** * Prepare @p index for querying via bhnd_nvstore_index_lookup(). * * After one or more append requests, the index must be prepared via * bhnd_nvstore_index_prepare() before any indexed lookups are performed. * * @param sc The NVRAM store from which NVRAM values will be queried. * @param index The index to be prepared. * * @retval 0 success * @retval non-zero if preparing @p index otherwise fails, a regular unix * error code will be returned. */ int bhnd_nvstore_index_prepare(struct bhnd_nvram_store *sc, bhnd_nvstore_index *index) { BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); /* Sort the index table */ qsort_r(index->cookiep, index->count, sizeof(index->cookiep[0]), sc, bhnd_nvstore_idx_cmp); return (0); } /** * Return a borrowed reference to the root path node. * * @param sc The NVRAM store. */ bhnd_nvstore_path * bhnd_nvstore_get_root_path(struct bhnd_nvram_store *sc) { BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); return (sc->root_path); } /** * Return true if @p path is the root path node. * * @param sc The NVRAM store. * @param path The path to query. */ bool bhnd_nvstore_is_root_path(struct bhnd_nvram_store *sc, bhnd_nvstore_path *path) { BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); return (sc->root_path == path); } /** * Return the update entry matching @p name in @p path, or NULL if no entry * found. * * @param sc The NVRAM store. * @param path The path to query. * @param name The NVRAM variable name to search for in @p path's update list. * * @retval non-NULL success * @retval NULL if @p name is not found in @p path. */ bhnd_nvram_prop * bhnd_nvstore_path_get_update(struct bhnd_nvram_store *sc, bhnd_nvstore_path *path, const char *name) { BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); return (bhnd_nvram_plist_get_prop(path->pending, name)); } /** * Register or remove an update record for @p name in @p path. * * @param sc The NVRAM store. * @param path The path to be modified. * @param name The path-relative variable name to be modified. * @param value The new value. A value of BHND_NVRAM_TYPE_NULL denotes deletion. * * @retval 0 success * @retval ENOMEM if allocation fails. * @retval ENOENT if @p name is unknown. * @retval EINVAL if @p value is NULL, and deletion of @p is not * supported. * @retval EINVAL if @p value cannot be converted to a supported value * type. */ int bhnd_nvstore_path_register_update(struct bhnd_nvram_store *sc, bhnd_nvstore_path *path, const char *name, bhnd_nvram_val *value) { bhnd_nvram_val *prop_val; const char *full_name; void *cookiep; char *namebuf; int error; bool nvram_committed; namebuf = NULL; prop_val = NULL; /* Determine whether the variable is currently defined in the * backing NVRAM data, and derive its full path-prefixed name */ nvram_committed = false; cookiep = bhnd_nvstore_path_data_lookup(sc, path, name); if (cookiep != NULL) { /* Variable is defined in the backing data */ nvram_committed = true; /* Use the existing variable name */ full_name = bhnd_nvram_data_getvar_name(sc->data, cookiep); } else if (path == sc->root_path) { /* No prefix required for root path */ full_name = name; } else { bhnd_nvstore_alias *alias; int len; /* New variable is being set; we need to determine the * appropriate path prefix */ alias = bhnd_nvstore_find_alias(sc, path->path_str); if (alias != NULL) { /* Use <alias>:name */ len = bhnd_nv_asprintf(&namebuf, "%lu:%s", alias->alias, name); } else { /* Use path/name */ len = bhnd_nv_asprintf(&namebuf, "%s/%s", path->path_str, name); } if (len < 0) return (ENOMEM); full_name = namebuf; } /* Allow the data store to filter the NVRAM operation */ if (bhnd_nvram_val_type(value) == BHND_NVRAM_TYPE_NULL) { error = bhnd_nvram_data_filter_unsetvar(sc->data, full_name); if (error) { BHND_NV_LOG("cannot unset property %s: %d\n", full_name, error); goto cleanup; } if ((prop_val = bhnd_nvram_val_copy(value)) == NULL) { error = ENOMEM; goto cleanup; } } else { error = bhnd_nvram_data_filter_setvar(sc->data, full_name, value, &prop_val); if (error) { BHND_NV_LOG("cannot set property %s: %d\n", full_name, error); goto cleanup; } } /* Add relative variable name to the per-path update list */ if (bhnd_nvram_val_type(value) == BHND_NVRAM_TYPE_NULL && !nvram_committed) { /* This is a deletion request for a variable not defined in * out backing store; we can simply remove the corresponding * update entry. */ bhnd_nvram_plist_remove(path->pending, name); } else { /* Update or append a pending update entry */ error = bhnd_nvram_plist_replace_val(path->pending, name, prop_val); if (error) goto cleanup; } /* Success */ error = 0; cleanup: if (namebuf != NULL) bhnd_nv_free(namebuf); if (prop_val != NULL) bhnd_nvram_val_release(prop_val); return (error); } /** * Iterate over all variable cookiep values retrievable from the backing * data store in @p path. * * @warning Pending updates in @p path are ignored by this function. * * @param sc The NVRAM store. * @param path The NVRAM path to be iterated. * @param[in,out] indexp A pointer to an opaque indexp value previously * returned by bhnd_nvstore_path_data_next(), or a * NULL value to begin iteration. * * @return Returns the next variable name, or NULL if there are no more * variables defined in @p path. */ void * bhnd_nvstore_path_data_next(struct bhnd_nvram_store *sc, bhnd_nvstore_path *path, void **indexp) { void **index_ref; BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); /* No index */ if (path->index == NULL) { /* An index is required for all non-empty, non-root path * instances */ BHND_NV_ASSERT(bhnd_nvstore_is_root_path(sc, path), ("missing index for non-root path %s", path->path_str)); /* Iterate NVRAM data directly, using the NVRAM data's cookiep * value as our indexp context */ if ((bhnd_nvram_data_next(sc->data, indexp)) == NULL) return (NULL); return (*indexp); } /* Empty index */ if (path->index->count == 0) return (NULL); if (*indexp == NULL) { /* First index entry */ index_ref = &path->index->cookiep[0]; } else { size_t idxpos; /* Advance to next index entry */ index_ref = *indexp; index_ref++; /* Hit end of index? */ BHND_NV_ASSERT(index_ref > path->index->cookiep, ("invalid indexp")); idxpos = (index_ref - path->index->cookiep); if (idxpos >= path->index->count) return (NULL); } /* Provide new index position */ *indexp = index_ref; /* Return the data's cookiep value */ return (*index_ref); } /** * Perform an lookup of @p name in the backing NVRAM data for @p path, * returning the associated cookiep value, or NULL if the variable is not found * in the backing NVRAM data. * * @warning Pending updates in @p path are ignored by this function. * * @param sc The NVRAM store from which NVRAM values will be queried. * @param path The path to be queried. * @param name The variable name to be queried. * * @retval non-NULL success * @retval NULL if @p name is not found in @p index. */ void * bhnd_nvstore_path_data_lookup(struct bhnd_nvram_store *sc, bhnd_nvstore_path *path, const char *name) { BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); /* No index */ if (path->index == NULL) { /* An index is required for all non-empty, non-root path * instances */ BHND_NV_ASSERT(bhnd_nvstore_is_root_path(sc, path), ("missing index for non-root path %s", path->path_str)); /* Look up directly in NVRAM data */ return (bhnd_nvram_data_find(sc->data, name)); } /* Otherwise, delegate to an index-based lookup */ return (bhnd_nvstore_index_lookup(sc, path->index, name)); } /** * Perform an index lookup of @p name, returning the associated cookiep * value, or NULL if the variable does not exist. * * @param sc The NVRAM store from which NVRAM values will be queried. * @param index The index to be queried. * @param name The variable name to be queried. * * @retval non-NULL success * @retval NULL if @p name is not found in @p index. */ void * bhnd_nvstore_index_lookup(struct bhnd_nvram_store *sc, bhnd_nvstore_index *index, const char *name) { void *cookiep; const char *indexed_name; size_t min, mid, max; uint32_t data_caps; int order; BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); BHND_NV_ASSERT(index != NULL, ("NULL index")); /* * Locate the requested variable using a binary search. */ if (index->count == 0) return (NULL); data_caps = sc->data_caps; min = 0; max = index->count - 1; while (max >= min) { /* Select midpoint */ mid = (min + max) / 2; cookiep = index->cookiep[mid]; /* Fetch variable name */ indexed_name = bhnd_nvram_data_getvar_name(sc->data, cookiep); /* Trim any path prefix */ if (data_caps & BHND_NVRAM_DATA_CAP_DEVPATHS) indexed_name = bhnd_nvram_trim_path_name(indexed_name); /* Determine which side of the partition to search */ order = strcmp(indexed_name, name); if (order < 0) { /* Search upper partition */ min = mid + 1; } else if (order > 0) { /* Search (non-empty) lower partition */ if (mid == 0) break; max = mid - 1; } else if (order == 0) { size_t idx; /* * Match found. * * If this happens to be a key with multiple definitions * in the backing store, we need to find the entry with * the highest declaration precedence. * * Duplicates are sorted in order of descending * precedence; to find the highest precedence entry, * we search backwards through the index. */ idx = mid; while (idx > 0) { void *dup_cookiep; const char *dup_name; /* Fetch preceding index entry */ idx--; dup_cookiep = index->cookiep[idx]; dup_name = bhnd_nvram_data_getvar_name(sc->data, dup_cookiep); /* Trim any path prefix */ if (data_caps & BHND_NVRAM_DATA_CAP_DEVPATHS) { dup_name = bhnd_nvram_trim_path_name( dup_name); } /* If no match, current cookiep is the variable * definition with the highest precedence */ if (strcmp(indexed_name, dup_name) != 0) return (cookiep); /* Otherwise, prefer this earlier definition, * and keep searching for a higher-precedence * definitions */ cookiep = dup_cookiep; } return (cookiep); } } /* Not found */ return (NULL); } /** * Return the device path entry registered for @p path, if any. * * @param sc The NVRAM store to be queried. * @param path The device path to search for. * @param path_len The length of @p path. * * @retval non-NULL if found. * @retval NULL if not found. */ bhnd_nvstore_path * bhnd_nvstore_get_path(struct bhnd_nvram_store *sc, const char *path, size_t path_len) { bhnd_nvstore_path_list *plist; bhnd_nvstore_path *p; uint32_t h; BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); /* Use hash lookup */ h = hash32_strn(path, path_len, HASHINIT); plist = &sc->paths[h % nitems(sc->paths)]; LIST_FOREACH(p, plist, np_link) { /* Check for prefix match */ if (strncmp(p->path_str, path, path_len) != 0) continue; /* Check for complete match */ if (strnlen(path, path_len) != strlen(p->path_str)) continue; return (p); } /* Not found */ return (NULL); } /** * Resolve @p aval to its corresponding device path entry, if any. * * @param sc The NVRAM store to be queried. * @param aval The device path alias value to search for. * * @retval non-NULL if found. * @retval NULL if not found. */ bhnd_nvstore_path * bhnd_nvstore_resolve_path_alias(struct bhnd_nvram_store *sc, u_long aval) { bhnd_nvstore_alias *alias; BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); /* Fetch alias entry */ if ((alias = bhnd_nvstore_get_alias(sc, aval)) == NULL) return (NULL); return (alias->path); } /** * Register a device path entry for the path referenced by variable name * @p info, if any. * * @param sc The NVRAM store to be updated. * @param info The NVRAM variable name info. * @param cookiep The NVRAM variable's cookiep value. * * @retval 0 if the path was successfully registered, or an identical * path or alias entry exists. * @retval EEXIST if a conflicting entry already exists for the path or * alias referenced by @p info. * @retval ENOENT if @p info contains a dangling alias reference. * @retval EINVAL if @p info contains an unsupported bhnd_nvstore_var_type * and bhnd_nvstore_path_type combination. * @retval ENOMEM if allocation fails. */ int bhnd_nvstore_var_register_path(struct bhnd_nvram_store *sc, bhnd_nvstore_name_info *info, void *cookiep) { switch (info->type) { case BHND_NVSTORE_VAR: /* Variable */ switch (info->path_type) { case BHND_NVSTORE_PATH_STRING: /* Variable contains a full path string * (pci/1/1/varname); register the path */ return (bhnd_nvstore_register_path(sc, info->path.str.value, info->path.str.value_len)); case BHND_NVSTORE_PATH_ALIAS: /* Variable contains an alias reference (0:varname). * There's no path to register */ return (0); } BHND_NV_PANIC("unsupported path type %d", info->path_type); break; case BHND_NVSTORE_ALIAS_DECL: /* Alias declaration */ return (bhnd_nvstore_register_alias(sc, info, cookiep)); } BHND_NV_PANIC("unsupported var type %d", info->type); } /** * Resolve the device path entry referenced by @p info. * * @param sc The NVRAM store to be updated. * @param info Variable name information descriptor containing * the path or path alias to be resolved. * * @retval non-NULL if found. * @retval NULL if not found. */ bhnd_nvstore_path * bhnd_nvstore_var_get_path(struct bhnd_nvram_store *sc, bhnd_nvstore_name_info *info) { switch (info->path_type) { case BHND_NVSTORE_PATH_STRING: return (bhnd_nvstore_get_path(sc, info->path.str.value, info->path.str.value_len)); case BHND_NVSTORE_PATH_ALIAS: return (bhnd_nvstore_resolve_path_alias(sc, info->path.alias.value)); } BHND_NV_PANIC("unsupported path type %d", info->path_type); } /** * Return the device path alias entry registered for @p alias_val, if any. * * @param sc The NVRAM store to be queried. * @param alias_val The alias value to search for. * * @retval non-NULL if found. * @retval NULL if not found. */ bhnd_nvstore_alias * bhnd_nvstore_get_alias(struct bhnd_nvram_store *sc, u_long alias_val) { bhnd_nvstore_alias_list *alist; bhnd_nvstore_alias *alias; BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); /* Can use hash lookup */ alist = &sc->aliases[alias_val % nitems(sc->aliases)]; LIST_FOREACH(alias, alist, na_link) { if (alias->alias == alias_val) return (alias); } /* Not found */ return (NULL); } /** * Return the device path alias entry registered for @p path, if any. * * @param sc The NVRAM store to be queried. * @param path The alias path to search for. * * @retval non-NULL if found. * @retval NULL if not found. */ bhnd_nvstore_alias * bhnd_nvstore_find_alias(struct bhnd_nvram_store *sc, const char *path) { bhnd_nvstore_alias *alias; BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); /* Have to scan the full table */ for (size_t i = 0; i < nitems(sc->aliases); i++) { LIST_FOREACH(alias, &sc->aliases[i], na_link) { if (strcmp(alias->path->path_str, path) == 0) return (alias); } } /* Not found */ return (NULL); } /** * Register a device path entry for @p path. * * @param sc The NVRAM store to be updated. * @param path_str The absolute device path string. * @param path_len The length of @p path_str. * * @retval 0 if the path was successfully registered, or an identical * path/alias entry already exists. * @retval ENOMEM if allocation fails. */ int bhnd_nvstore_register_path(struct bhnd_nvram_store *sc, const char *path_str, size_t path_len) { bhnd_nvstore_path_list *plist; bhnd_nvstore_path *path; uint32_t h; BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); /* Already exists? */ if (bhnd_nvstore_get_path(sc, path_str, path_len) != NULL) return (0); /* Can't represent more than SIZE_MAX paths */ if (sc->num_paths == SIZE_MAX) return (ENOMEM); /* Allocate new entry */ path = bhnd_nvstore_path_new(path_str, path_len); if (path == NULL) return (ENOMEM); /* Insert in path hash table */ h = hash32_str(path->path_str, HASHINIT); plist = &sc->paths[h % nitems(sc->paths)]; LIST_INSERT_HEAD(plist, path, np_link); /* Increment path count */ sc->num_paths++; return (0); } /** * Register a device path alias for an NVRAM 'devpathX' variable. * * The path value for the alias will be fetched from the backing NVRAM data. * * @param sc The NVRAM store to be updated. * @param info The NVRAM variable name info. * @param cookiep The NVRAM variable's cookiep value. * * @retval 0 if the alias was successfully registered, or an * identical alias entry exists. * @retval EEXIST if a conflicting alias or path entry already exists. * @retval EINVAL if @p info is not a BHND_NVSTORE_ALIAS_DECL or does * not contain a BHND_NVSTORE_PATH_ALIAS entry. * @retval ENOMEM if allocation fails. */ int bhnd_nvstore_register_alias(struct bhnd_nvram_store *sc, const bhnd_nvstore_name_info *info, void *cookiep) { bhnd_nvstore_alias_list *alist; bhnd_nvstore_alias *alias; bhnd_nvstore_path *path; char *path_str; size_t path_len; int error; BHND_NVSTORE_LOCK_ASSERT(sc, MA_OWNED); path_str = NULL; alias = NULL; /* Can't represent more than SIZE_MAX aliases */ if (sc->num_aliases == SIZE_MAX) return (ENOMEM); /* Must be an alias declaration */ if (info->type != BHND_NVSTORE_ALIAS_DECL) return (EINVAL); if (info->path_type != BHND_NVSTORE_PATH_ALIAS) return (EINVAL); /* Fetch the devpath variable's value length */ error = bhnd_nvram_data_getvar(sc->data, cookiep, NULL, &path_len, BHND_NVRAM_TYPE_STRING); if (error) return (ENOMEM); /* Allocate path string buffer */ if ((path_str = bhnd_nv_malloc(path_len)) == NULL) return (ENOMEM); /* Decode to our new buffer */ error = bhnd_nvram_data_getvar(sc->data, cookiep, path_str, &path_len, BHND_NVRAM_TYPE_STRING); if (error) goto failed; /* Trim trailing '/' character(s) from the path length */ path_len = strnlen(path_str, path_len); while (path_len > 0 && path_str[path_len-1] == '/') { path_str[path_len-1] = '\0'; path_len--; } /* Is a conflicting alias entry already registered for this alias * value? */ alias = bhnd_nvstore_get_alias(sc, info->path.alias.value); if (alias != NULL) { if (alias->cookiep != cookiep || strcmp(alias->path->path_str, path_str) != 0) { error = EEXIST; goto failed; } } /* Is a conflicting entry already registered for the alias path? */ if ((alias = bhnd_nvstore_find_alias(sc, path_str)) != NULL) { if (alias->alias != info->path.alias.value || alias->cookiep != cookiep || strcmp(alias->path->path_str, path_str) != 0) { error = EEXIST; goto failed; } } /* Get (or register) the target path entry */ path = bhnd_nvstore_get_path(sc, path_str, path_len); if (path == NULL) { error = bhnd_nvstore_register_path(sc, path_str, path_len); if (error) goto failed; path = bhnd_nvstore_get_path(sc, path_str, path_len); BHND_NV_ASSERT(path != NULL, ("missing registered path")); } /* Allocate alias entry */ alias = bhnd_nv_calloc(1, sizeof(*alias)); if (alias == NULL) { error = ENOMEM; goto failed; } alias->path = path; alias->cookiep = cookiep; alias->alias = info->path.alias.value; /* Insert in alias hash table */ alist = &sc->aliases[alias->alias % nitems(sc->aliases)]; LIST_INSERT_HEAD(alist, alias, na_link); /* Increment alias count */ sc->num_aliases++; bhnd_nv_free(path_str); return (0); failed: if (path_str != NULL) bhnd_nv_free(path_str); if (alias != NULL) bhnd_nv_free(alias); return (error); } /** * If @p child is equal to or a child path of @p parent, return a pointer to * @p child's path component(s) relative to @p parent; otherwise, return NULL. */ const char * bhnd_nvstore_parse_relpath(const char *parent, const char *child) { size_t prefix_len; /* All paths have an implicit leading '/'; this allows us to treat * our manufactured root path of "/" as a prefix to all NVRAM-defined * paths (which do not necessarily include a leading '/' */ if (*parent == '/') parent++; if (*child == '/') child++; /* Is parent a prefix of child? */ prefix_len = strlen(parent); if (strncmp(parent, child, prefix_len) != 0) return (NULL); /* A zero-length prefix matches everything */ if (prefix_len == 0) return (child); /* Is child equal to parent? */ if (child[prefix_len] == '\0') return (child + prefix_len); /* Is child actually a child of parent? */ if (child[prefix_len] == '/') return (child + prefix_len + 1); /* No match (e.g. parent=/foo..., child=/fooo...) */ return (NULL); } /** * Parse a raw NVRAM variable name and return its @p entry_type, its * type-specific @p prefix (e.g. '0:', 'pci/1/1', 'devpath'), and its * type-specific @p suffix (e.g. 'varname', '0'). * * @param name The NVRAM variable name to be parsed. This * value must remain valid for the lifetime of * @p info. * @param type The NVRAM name type -- either INTERNAL for names * parsed from backing NVRAM data, or EXTERNAL for * names provided by external NVRAM store clients. * @param data_caps The backing NVRAM data capabilities * (see bhnd_nvram_data_caps()). * @param[out] info On success, the parsed variable name info. * * @retval 0 success * @retval non-zero if parsing @p name otherwise fails, a regular unix * error code will be returned. */ int bhnd_nvstore_parse_name_info(const char *name, bhnd_nvstore_name_type type, uint32_t data_caps, bhnd_nvstore_name_info *info) { const char *p; char *endp; /* Skip path parsing? */ if (data_caps & BHND_NVRAM_DATA_CAP_DEVPATHS) { /* devpath declaration? (devpath0=pci/1/1) */ if (strncmp(name, "devpath", strlen("devpath")) == 0) { u_long alias; /* Perform standard validation on the relative * variable name */ if (type != BHND_NVSTORE_NAME_INTERNAL && !bhnd_nvram_validate_name(name)) { return (ENOENT); } /* Parse alias value that should follow a 'devpath' * prefix */ p = name + strlen("devpath"); alias = strtoul(p, &endp, 10); if (endp != p && *endp == '\0') { info->type = BHND_NVSTORE_ALIAS_DECL; info->path_type = BHND_NVSTORE_PATH_ALIAS; info->name = name; info->path.alias.value = alias; return (0); } } /* device aliased variable? (0:varname) */ if (bhnd_nv_isdigit(*name)) { u_long alias; /* Parse '0:' alias prefix */ alias = strtoul(name, &endp, 10); if (endp != name && *endp == ':') { /* Perform standard validation on the relative * variable name */ if (type != BHND_NVSTORE_NAME_INTERNAL && !bhnd_nvram_validate_name(name)) { return (ENOENT); } info->type = BHND_NVSTORE_VAR; info->path_type = BHND_NVSTORE_PATH_ALIAS; /* name follows 0: prefix */ info->name = endp + 1; info->path.alias.value = alias; return (0); } } /* device variable? (pci/1/1/varname) */ if ((p = strrchr(name, '/')) != NULL) { const char *path, *relative_name; size_t path_len; /* Determine the path length; 'p' points at the last * path separator in 'name' */ path_len = p - name; path = name; /* The relative variable name directly follows the * final path separator '/' */ relative_name = path + path_len + 1; /* Now that we calculated the name offset, exclude all * trailing '/' characters from the path length */ while (path_len > 0 && path[path_len-1] == '/') path_len--; /* Perform standard validation on the relative * variable name */ if (type != BHND_NVSTORE_NAME_INTERNAL && !bhnd_nvram_validate_name(relative_name)) { return (ENOENT); } /* Initialize result with pointers into the name * buffer */ info->type = BHND_NVSTORE_VAR; info->path_type = BHND_NVSTORE_PATH_STRING; info->name = relative_name; info->path.str.value = path; info->path.str.value_len = path_len; return (0); } } /* If all other parsing fails, the result is a simple variable with * an implicit path of "/" */ if (type != BHND_NVSTORE_NAME_INTERNAL && !bhnd_nvram_validate_name(name)) { /* Invalid relative name */ return (ENOENT); } info->type = BHND_NVSTORE_VAR; info->path_type = BHND_NVSTORE_PATH_STRING; info->name = name; info->path.str.value = BHND_NVSTORE_ROOT_PATH; info->path.str.value_len = BHND_NVSTORE_ROOT_PATH_LEN; return (0); }
ww362034710/Gannt
gannt/lib/Gantt/column/EventModeColumn.js
<reponame>ww362034710/Gannt<filename>gannt/lib/Gantt/column/EventModeColumn.js import CheckColumn from '../../Grid/column/CheckColumn.js'; import ColumnStore from '../../Grid/data/ColumnStore.js'; /** * A column that displays (and allows user to update) the task's * {@link Gantt.model.TaskModel#field-manuallyScheduled manuallyScheduled} field. * * This column uses a {@link Core.widget.Checkbox checkbox} as its editor, and it is not intended to be changed. * * @extends Grid/column/CheckColumn * @classType eventmode */ export default class EventModeColumn extends CheckColumn { static get type() { return 'eventmode'; } static get isGanttColumn() { return true; } static get defaults() { return { field : 'manuallyScheduled', align : 'left', text : 'L{Event mode}' }; } constructor(config, store) { super(...arguments); this.internalCellCls = 'b-eventmode-cell'; } renderer({ value, cellElement, column, isExport }) { super.renderer(...arguments); if (isExport) { return this.renderText(value); } else { if (cellElement.widget) { cellElement.widget.text = this.renderText(value); } } } onCheckboxChange({ source, checked }) { super.onCheckboxChange(...arguments); source.text = this.renderText(checked); } renderText(value) { return value ? this.L('L{Manual}') : this.L('L{Auto}'); } } ColumnStore.registerColumnType(EventModeColumn);
NickBethune/bullet-core
src/test/java/com/yahoo/bullet/common/ValidatorTest.java
/* * Copyright 2017, Yahoo Inc. * Licensed under the terms of the Apache License, Version 2.0. * See the LICENSE file associated with the project for terms. */ package com.yahoo.bullet.common; import com.yahoo.bullet.common.Validator.Entry; import com.yahoo.bullet.common.Validator.Relationship; import com.yahoo.bullet.common.Validator.State; import com.yahoo.bullet.pubsub.MockPubSub; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.BiPredicate; import java.util.function.Predicate; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; public class ValidatorTest { private BulletConfig empty; @BeforeMethod public void setup() { empty = new BulletConfig(); empty.clear(); } @Test public void testDefaultEntry() { Validator validator = new Validator(); Entry entry = validator.define("foo"); empty.set("foo", "bar"); entry.normalize(empty); Assert.assertEquals(empty.get("foo"), "bar"); Assert.assertNull(entry.getDefaultValue()); } @Test public void testEntryDefaulting() { Validator validator = new Validator(); Entry entry = validator.define("foo").checkIf(Validator::isNotNull).defaultTo("baz").castTo(Validator::asString); Assert.assertNull(empty.get("foo")); entry.normalize(empty); Assert.assertEquals(empty.get("foo"), "baz"); Assert.assertEquals(entry.getDefaultValue(), "baz"); // Check to see if type conversion is done for default of the non-final type. entry.defaultTo(1); Assert.assertEquals(entry.getDefaultValue(), "1"); } @Test public void testEntryCasting() { Validator validator = new Validator(); Entry entry = validator.define("foo").castTo(Validator::asInt); empty.set("foo", 1.035f); entry.normalize(empty); Assert.assertEquals(empty.get("foo").getClass(), Integer.class); Assert.assertEquals(empty.get("foo"), 1); } @Test public void testEntryMultipleChecks() { Validator validator = new Validator(); Entry entry = validator.define("foo") .checkIf(Validator::isNotNull) .checkIf(Validator.isIn("baz", "bar")) .defaultTo("qux"); Assert.assertNull(empty.get("foo")); entry.normalize(empty); Assert.assertEquals(empty.get("foo"), "qux"); empty.set("foo", "baz"); entry.normalize(empty); Assert.assertEquals(empty.get("foo"), "baz"); empty.set("foo", "bar"); entry.normalize(empty); Assert.assertEquals(empty.get("foo"), "bar"); empty.set("foo", "foo"); entry.normalize(empty); Assert.assertEquals(empty.get("foo"), "qux"); } @Test public void testEntryUnless() { Validator validator = new Validator(); // foo should be 1 or 2, defaults 1L and is casted to String UNLESS it is already "1" Entry entry = validator.define("foo") .checkIf(Validator::isNotNull) .checkIf(Validator.isIn(1L, 2L)) .defaultTo(1L) .castTo(Objects::toString) .unless("1"::equals); Assert.assertNull(empty.get("foo")); entry.normalize(empty); Assert.assertEquals(empty.get("foo"), "1"); empty.set("foo", 1L); entry.normalize(empty); Assert.assertEquals(empty.get("foo"), "1"); empty.set("foo", 2L); entry.normalize(empty); Assert.assertEquals(empty.get("foo"), "2"); String original = "1"; empty.set("foo", "1"); entry.normalize(empty); Assert.assertEquals(empty.get("foo"), "1"); // This is the SAME string Assert.assertTrue(empty.get("foo") == original); } @Test(expectedExceptions = IllegalStateException.class) public void testEntryFailing() { Validator validator = new Validator(); Entry entry = validator.define("foo") .checkIf(Validator::isNotNull) .checkIf(Validator.isIn("baz", "bar")) .orFail(); empty.set("foo", "qux"); entry.normalize(empty); } @Test public void testIsNotNull() { Assert.assertTrue(Validator.isNotNull("foo")); Assert.assertFalse(Validator.isNotNull(null)); } @Test public void testIsTrue() { Assert.assertFalse(Validator.isTrue("foo")); Assert.assertFalse(Validator.isTrue(null)); Assert.assertFalse(Validator.isTrue(false)); Assert.assertTrue(Validator.isTrue(true)); } @Test public void testIsFalse() { Assert.assertFalse(Validator.isFalse("foo")); Assert.assertFalse(Validator.isFalse(null)); Assert.assertFalse(Validator.isFalse(true)); Assert.assertTrue(Validator.isFalse(false)); } @Test public void testisType() { Assert.assertTrue(Validator.isType("foo", String.class)); Assert.assertTrue(Validator.isType(1, Integer.class)); Assert.assertTrue(Validator.isType(1L, Long.class)); Assert.assertTrue(Validator.isType(asList("foo", "bar"), List.class)); Assert.assertTrue(Validator.isType(singletonMap("foo", "bar"), Map.class)); Assert.assertFalse(Validator.isType(0, Float.class)); } @Test public void testIsBoolean() { Assert.assertTrue(Validator.isBoolean(true)); Assert.assertTrue(Validator.isBoolean(false)); Assert.assertFalse(Validator.isBoolean("foo")); } @Test public void testIsString() { Assert.assertTrue(Validator.isString("foo")); Assert.assertFalse(Validator.isString(null)); Assert.assertFalse(Validator.isString(1.0)); } @Test public void testIsFloat() { Assert.assertTrue(Validator.isFloat(1.34)); Assert.assertTrue(Validator.isFloat(1.34f)); Assert.assertFalse(Validator.isFloat(2)); } @Test public void testIsInt() { Assert.assertTrue(Validator.isInt(1)); Assert.assertTrue(Validator.isInt(3L)); Assert.assertFalse(Validator.isInt(2.3)); } @Test public void testIsNumber() { Assert.assertTrue(Validator.isNumber(1.3)); Assert.assertTrue(Validator.isNumber(1)); Assert.assertTrue(Validator.isNumber(42L)); Assert.assertTrue(Validator.isNumber(4.2f)); Assert.assertFalse(Validator.isNumber("foo")); } @Test public void testIsPositive() { Assert.assertTrue(Validator.isPositive(2.4)); Assert.assertTrue(Validator.isPositive(2)); Assert.assertTrue(Validator.isPositive(0.02)); Assert.assertFalse(Validator.isPositive(-0.3)); } @Test public void testIsPositiveInt() { Assert.assertTrue(Validator.isPositiveInt(1)); Assert.assertTrue(Validator.isPositiveInt(2L)); Assert.assertFalse(Validator.isPositiveInt(0.3)); Assert.assertFalse(Validator.isPositiveInt(0L)); Assert.assertFalse(Validator.isPositiveInt(0)); Assert.assertFalse(Validator.isPositiveInt(-10)); Assert.assertFalse(Validator.isPositiveInt(-10.3)); } @Test public void testIsPowerOfTwo() { Assert.assertTrue(Validator.isPowerOfTwo(1)); Assert.assertTrue(Validator.isPowerOfTwo(2)); Assert.assertTrue(Validator.isPowerOfTwo(4)); Assert.assertTrue(Validator.isPowerOfTwo(16384)); Assert.assertFalse(Validator.isPowerOfTwo(3)); Assert.assertFalse(Validator.isPowerOfTwo(2.0)); Assert.assertFalse(Validator.isPowerOfTwo(-4)); } @Test public void testIsNonEmptyList() { Assert.assertTrue(Validator.isNonEmptyList(asList(0))); Assert.assertTrue(Validator.isNonEmptyList(asList(0, 1))); Assert.assertTrue(Validator.isNonEmptyList(asList("string"))); Assert.assertFalse(Validator.isNonEmptyList("string")); Assert.assertFalse(Validator.isNonEmptyList(null)); Assert.assertFalse(Validator.isNonEmptyList(emptyList())); } @Test public void testIsNonEmptyMap() { Assert.assertTrue(Validator.isNonEmptyMap(singletonMap(0, null))); Assert.assertTrue(Validator.isNonEmptyMap(singletonMap(0, 1))); Assert.assertTrue(Validator.isNonEmptyMap(singletonMap("string", "string"))); Assert.assertFalse(Validator.isNonEmptyMap(null)); Assert.assertFalse(Validator.isNonEmptyMap(emptyMap())); } @Test public void testIsMap() { Assert.assertTrue(Validator.isMap(singletonMap("foo", "bar"))); Assert.assertFalse(Validator.isMap("foo")); } @SuppressWarnings("unchecked") @Test public void testIsIn() { Assert.assertTrue(Validator.isIn("foo", "bar", "baz", "qux").test("foo")); Assert.assertTrue(Validator.isIn("foo", "bar", "baz", "qux").test("qux")); Assert.assertFalse(Validator.isIn("foo", "bar", "baz", "qux").test("f")); Assert.assertFalse(Validator.isIn("foo", "bar", "baz", "qux").test(1.0)); Assert.assertTrue(Validator.isIn(asList("foo", "bar"), asList("baz", "qux")).test(asList("foo", "bar"))); Assert.assertTrue(Validator.isIn(asList("foo", "bar"), asList("baz", "qux")).test(asList("baz", "qux"))); Assert.assertFalse(Validator.isIn(asList("foo", "bar"), asList("baz", "qux")).test(singletonList("baz"))); Assert.assertFalse(Validator.isIn(asList("foo", "bar"), asList("baz", "qux")).test(singletonList("foo"))); Assert.assertFalse(Validator.isIn(asList("foo", "bar"), asList("baz", "qux")).test(null)); Assert.assertFalse(Validator.isIn(asList("foo", "bar"), asList("baz", "qux")).test("foo")); } @Test public void testIsInRange() { Assert.assertTrue(Validator.isInRange(-1, 2.0).test(-1)); Assert.assertTrue(Validator.isInRange(-1, 2.0).test(0)); Assert.assertTrue(Validator.isInRange(-1, 2.0).test(2.0)); Assert.assertTrue(Validator.isInRange(-1.0, 2.0).test(0.1)); Assert.assertTrue(Validator.isInRange(-1.0, 2.0).test(0.0f)); Assert.assertTrue(Validator.isInRange(-1.0, 2.0).test(1L)); Assert.assertFalse(Validator.isInRange(-1, 2.0).test("0")); Assert.assertFalse(Validator.isInRange(-1, 2.0).test(-1.1)); Assert.assertFalse(Validator.isInRange(-1, 2.0).test(2.1)); Assert.assertFalse(Validator.isInRange(-1, 2.0).test(null)); } @Test public void testIsAtleastNTimes() { BiPredicate<Object, Object> isAtleastTwice = Validator.isAtleastNTimes(2.0); Assert.assertTrue(isAtleastTwice.test(2L, 1L)); Assert.assertTrue(isAtleastTwice.test(3L, 1L)); Assert.assertFalse(isAtleastTwice.test(0L, 1L)); BiPredicate<Object, Object> isAtleastThrice = Validator.isAtleastNTimes(3.0); Assert.assertFalse(isAtleastThrice.test(2.0, 1L)); Assert.assertTrue(isAtleastThrice.test(3.0, 1L)); Assert.assertTrue(isAtleastThrice.test(4.0, 1L)); Assert.assertFalse(isAtleastThrice.test(0.1, 1L)); } @Test public void testIntegerConversion() { Assert.assertEquals(Validator.asInt(3.4), 3); Assert.assertEquals(Validator.asInt(3), 3); Assert.assertEquals(Validator.asInt(3L), 3); Assert.assertEquals(Validator.asInt(3.4f), 3); } @Test(expectedExceptions = ClassCastException.class) public void testIntegerConversionFailure() { Validator.asInt("foo"); } @Test public void testFloatConversion() { Assert.assertEquals(Validator.asFloat(3.0), 3.0f); Assert.assertEquals(Validator.asFloat(3), 3.0f); Assert.assertEquals(Validator.asFloat(3L), 3.0f); Assert.assertEquals(Validator.asFloat(3.0f), 3.0f); } @Test(expectedExceptions = ClassCastException.class) public void testFloatConversionFailure() { Validator.asFloat("foo"); } @Test public void testDoubleConversion() { Assert.assertEquals(Validator.asDouble(3.0), 3.0); Assert.assertEquals(Validator.asDouble(3), 3.0); Assert.assertEquals(Validator.asDouble(3L), 3.0); Assert.assertEquals(Validator.asDouble(3.0f), 3.0); } @Test(expectedExceptions = ClassCastException.class) public void testDoubleConversionFailure() { Validator.asDouble("foo"); } @Test public void testStringConversion() { Assert.assertEquals(Validator.asString("foo"), "foo"); Assert.assertEquals(Validator.asString(1.0), "1.0"); Assert.assertEquals(Validator.asString(asList("foo", "bar")), asList("foo", "bar").toString()); } @Test(expectedExceptions = NullPointerException.class) public void testStringConversionFailure() { Validator.asString(null); } @Test(expectedExceptions = NullPointerException.class) public void testRelationshipWithoutEntry() { Validator validator = new Validator(); validator.relate("Won't be created", "foo", "bar"); } @Test public void testRelationshipDefaulting() { Validator validator = new Validator(); validator.define("foo"); validator.define("bar"); Relationship relation = validator.relate("Test", "foo", "bar"); // Nothing happens empty.set("foo", 0.2); empty.set("bar", "baz"); relation.normalize(empty); Assert.assertEquals(empty.get("foo"), 0.2); Assert.assertEquals(empty.get("bar"), "baz"); } @Test public void testRelationshipFailureUsingEntryDefaults() { Validator validator = new Validator(); validator.define("foo").defaultTo(0); validator.define("bar").defaultTo(42); Relationship relation = validator.relate("Test", "foo", "bar").checkIf(Validator::isGreaterOrEqual); empty.set("foo", -1L); empty.set("bar", 0.2); relation.normalize(empty); Assert.assertEquals(empty.get("foo"), 0); Assert.assertEquals(empty.get("bar"), 42); empty.set("foo", 42); empty.set("bar", 4.2); relation.normalize(empty); Assert.assertEquals(empty.get("foo"), 42); Assert.assertEquals(empty.get("bar"), 4.2); } @Test public void testRelationshipWithMultipleChecks() { Validator validator = new Validator(); validator.define("foo").defaultTo(42); validator.define("bar").defaultTo(11).castTo(Validator::asDouble); Relationship relation = validator.relate("Test", "foo", "bar").checkIf(Validator::isGreaterOrEqual) .checkIf((a, b) -> ((Number) b).intValue() > 10); empty.set("foo", -1L); empty.set("bar", 0.2); relation.normalize(empty); Assert.assertEquals(empty.get("foo"), 42); Assert.assertEquals(empty.get("bar"), 11.0); empty.set("foo", 42); empty.set("bar", 4.2); relation.normalize(empty); Assert.assertEquals(empty.get("foo"), 42); Assert.assertEquals(empty.get("bar"), 11.0); empty.set("foo", 42); empty.set("bar", 40.3); relation.normalize(empty); Assert.assertEquals(empty.get("foo"), 42); Assert.assertEquals(empty.get("bar"), 40.3); } @Test public void testRelationshipFailureUsesCustomDefaults() { Validator validator = new Validator(); validator.define("foo").defaultTo(0); validator.define("bar").defaultTo(42); Relationship relation = validator.relate("Test", "foo", "bar").checkIf(Validator::isGreaterOrEqual); relation.orElseUse("qux", "norf"); empty.set("foo", 42); empty.set("bar", 4.2); relation.normalize(empty); Assert.assertEquals(empty.get("foo"), 42); Assert.assertEquals(empty.get("bar"), 4.2); empty.set("foo", -1L); empty.set("bar", 0.2); relation.normalize(empty); Assert.assertEquals(empty.get("foo"), "qux"); Assert.assertEquals(empty.get("bar"), "norf"); } @Test(expectedExceptions = IllegalStateException.class) public void testRelationshipFailureFailsOut() { Validator validator = new Validator(); validator.define("foo").defaultTo(0); validator.define("bar").defaultTo(42); Relationship relation = validator.relate("Test", "foo", "bar").checkIf(Validator::isGreaterOrEqual); relation.orFail(); empty.set("foo", -1L); empty.set("bar", 0.2); relation.normalize(empty); } @Test(expectedExceptions = NullPointerException.class) public void testStateWithoutEntry() { Validator validator = new Validator(); validator.evaluate("Test", "foo", "bar", "baz"); } @Test public void testStateDefaulting() { Validator validator = new Validator(); validator.define("foo").defaultTo(42); validator.define("bar").defaultTo(11).castTo(Validator::asDouble); validator.define("baz").defaultTo(true).checkIf(Validator::isBoolean); validator.evaluate("Test", "foo", "bar", "baz").checkIf(o -> false); empty.set("foo", 22); empty.set("bar", -1.4); empty.set("baz", false); validator.validate(empty); Assert.assertEquals(empty.get("foo"), 42); Assert.assertEquals(empty.get("bar"), 11.0); Assert.assertEquals(empty.get("baz"), true); } @Test public void testStateMultipleChecks() { Validator validator = new Validator(); validator.define("foo").defaultTo(42); validator.define("bar").defaultTo(11).castTo(Validator::asDouble); validator.define("baz").defaultTo(true).checkIf(Validator::isBoolean); validator.evaluate("Test", "foo", "bar", "baz") .checkIf((o) -> o.get(0).equals("1") && o.get(1).equals(2.0) && o.get(2).equals(false)) .checkIf((o) -> Double.valueOf(o.get(0).toString()) >= 0.0); empty.set("foo", "1"); empty.set("bar", 2.0); empty.set("baz", false); validator.validate(empty); Assert.assertEquals(empty.get("foo"), "1"); Assert.assertEquals(empty.get("bar"), 2.0); Assert.assertEquals(empty.get("baz"), false); } @Test(expectedExceptions = IllegalStateException.class) public void testStateCheckFailureErrorsOut() { Validator validator = new Validator(); validator.define("foo").defaultTo(42); validator.define("bar").defaultTo(11).castTo(Validator::asDouble); validator.define("baz").defaultTo(true).checkIf(Validator::isBoolean); validator.evaluate("Test", "foo", "bar", "baz") .checkIf((o) -> false) .orFail(); empty.set("foo", 22); empty.set("bar", -1.4); empty.set("baz", false); validator.validate(empty); } @Test public void testCopyingPreservesOriginal() { Validator validator = new Validator(); Set<Long> whitelist = new HashSet<>(); validator.define("foo").checkIf(whitelist::contains).defaultTo(0L); empty.set("foo", -1L); validator.validate(empty); // Defaults to 0 since -1 is not in the whitelist Assert.assertEquals(empty.get("foo"), 0L); // Allow -1 through whitelist.add(-1L); empty.set("foo", -1L); validator.validate(empty); Assert.assertEquals(empty.get("foo"), -1L); Validator copy = validator.copy(); empty.set("foo", 10L); copy.validate(empty); Assert.assertEquals(empty.get("foo"), 0L); empty.set("foo", -1L); copy.validate(empty); Assert.assertEquals(empty.get("foo"), -1L); // Whitelist 1 and -1 whitelist.add(1L); // Add a new check to the original Entry Entry original = validator.getEntries().get("foo"); original.checkIf((o) -> ((long) o > 0L)); // Will default since -1 is not > 0 empty.set("foo", -1L); validator.validate(empty); Assert.assertEquals(empty.get("foo"), 0L); // Will not default since it does not have the same check anymore empty.set("foo", -1L); copy.validate(empty); Assert.assertEquals(empty.get("foo"), -1L); } @Test public void testCopyingDoesNotDeepCopy() { Validator validator = new Validator(); Set<Long> whitelist = new HashSet<>(); validator.define("foo").checkIf(whitelist::contains).defaultTo(0); validator.define("bar").defaultTo(42); validator.define("baz").defaultTo(false); Relationship relation = validator.relate("Test", "foo", "bar").checkIf(Validator::isGreaterOrEqual); relation.orElseUse("qux", "norf"); State state = validator.evaluate("Test", "foo", "bar", "baz").checkIf(o -> true); empty.set("foo", -1L); empty.set("bar", -1.4); empty.set("baz", true); validator.validate(empty); // Defaults to 0 since -1 is not in the whitelist Assert.assertEquals(empty.get("foo"), 0); Assert.assertEquals(empty.get("bar"), -1.4); Assert.assertEquals(empty.get("baz"), true); // Allow -1 through whitelist.add(-1L); empty.set("foo", -1L); empty.set("bar", -1.4); empty.set("baz", false); validator.validate(empty); Assert.assertEquals(empty.get("foo"), -1L); Assert.assertEquals(empty.get("bar"), -1.4); Assert.assertEquals(empty.get("baz"), false); Validator copy = validator.copy(); // The copy also has the shallow copy of contains since -1 goes through empty.set("foo", -1L); empty.set("bar", -1.4); empty.set("baz", false); copy.validate(empty); Assert.assertEquals(empty.get("foo"), -1L); Assert.assertEquals(empty.get("bar"), -1.4); Assert.assertEquals(empty.get("baz"), false); // Removing the white whitelist.clear(); copy.validate(empty); Assert.assertEquals(empty.get("foo"), 0); Assert.assertEquals(empty.get("bar"), -1.4); Assert.assertEquals(empty.get("baz"), false); // Changing the state to fail, doesn't change the copy state.checkIf(o -> false); state.orFail(); copy.validate(empty); Assert.assertEquals(empty.get("foo"), 0); Assert.assertEquals(empty.get("bar"), -1.4); Assert.assertEquals(empty.get("baz"), false); } @Test public void testIsListOfType() { Predicate<Object> stringChecker = Validator.isListOfType(String.class); Assert.assertFalse(stringChecker.test(null)); Assert.assertFalse(stringChecker.test(emptyList())); Assert.assertTrue(stringChecker.test(singletonList("a"))); Assert.assertTrue(stringChecker.test(asList("a", "b"))); Assert.assertFalse(stringChecker.test(singletonList(1))); Assert.assertFalse(stringChecker.test(asList(1, 2))); } @Test public void testIsMapOfType() { Predicate<Object> stringIntegerChecker = Validator.isMapOfType(String.class, Integer.class); Assert.assertFalse(stringIntegerChecker.test(null)); Assert.assertFalse(stringIntegerChecker.test(emptyMap())); Assert.assertTrue(stringIntegerChecker.test(singletonMap("a", 1))); Map<String, Integer> mapA = new HashMap<>(); mapA.put("a", 1); mapA.put("b", 2); Assert.assertTrue(stringIntegerChecker.test(mapA)); Assert.assertFalse(stringIntegerChecker.test(singletonMap("a", 1.0))); Assert.assertFalse(stringIntegerChecker.test(singletonMap("a", "1"))); Assert.assertFalse(stringIntegerChecker.test(singletonMap("a", "1"))); Map<Object, Object> mapB = new HashMap<>(); mapB.put("a", 1); mapB.put("b", "2"); Assert.assertFalse(stringIntegerChecker.test(mapB)); } @Test public void testIsClassName() { Assert.assertTrue(Validator.isClassName(Validator.class.getName())); Assert.assertTrue(Validator.isClassName(MockPubSub.class.getName())); Assert.assertFalse(Validator.isClassName("fake.class.path.foo")); Assert.assertFalse(Validator.isClassName(null)); Assert.assertFalse(Validator.isClassName(asList("foo", "bar"))); } @Test public void testHasMinimumListSize() { Predicate<Object> hasThreeOrMore = Validator.hasMinimumListSize(3); Assert.assertFalse(hasThreeOrMore.test(null)); Assert.assertFalse(hasThreeOrMore.test(emptyList())); Assert.assertFalse(hasThreeOrMore.test(singletonList("a"))); Assert.assertFalse(hasThreeOrMore.test(asList("a", "b"))); Assert.assertTrue(hasThreeOrMore.test(asList("a", "b", "c"))); Assert.assertTrue(hasThreeOrMore.test(asList("a", "b", "c", "d"))); Assert.assertTrue(hasThreeOrMore.test(asList(1, 2, 3, 4))); Assert.assertFalse(hasThreeOrMore.test(asList(1, 2))); Assert.assertTrue(Validator.hasMinimumListSize(0).test(emptyList())); } @Test public void testHasMaximumListSize() { Predicate<Object> hasThreeOrLess = Validator.hasMaximumListSize(3); Assert.assertFalse(hasThreeOrLess.test(null)); Assert.assertTrue(hasThreeOrLess.test(emptyList())); Assert.assertTrue(hasThreeOrLess.test(singletonList("a"))); Assert.assertTrue(hasThreeOrLess.test(asList("a", "b"))); Assert.assertTrue(hasThreeOrLess.test(asList("a", "b", "c"))); Assert.assertFalse(hasThreeOrLess.test(asList("a", "b", "c", "d"))); Assert.assertTrue(hasThreeOrLess.test(asList(1, 2))); Assert.assertTrue(Validator.hasMaximumListSize(0).test(emptyList())); } @Test public void testIsImplied() { Assert.assertTrue(Validator.isImplied(true, true)); Assert.assertTrue(Validator.isImplied(false, true)); Assert.assertTrue(Validator.isImplied(false, false)); Assert.assertFalse(Validator.isImplied(true, false)); } @Test public void testANDing() { Predicate<Object> notNullAndNotEmptyList = Validator.and(Objects::nonNull, a -> !(((List) a).isEmpty())); Assert.assertFalse(notNullAndNotEmptyList.test(null)); Assert.assertFalse(notNullAndNotEmptyList.test(emptyList())); Assert.assertTrue(notNullAndNotEmptyList.test(singletonList("a"))); } @Test public void testORing() { Predicate<Object> nullOrEmptyList = Validator.or(Objects::isNull, a -> ((List) a).isEmpty()); Assert.assertTrue(nullOrEmptyList.test(null)); Assert.assertTrue(nullOrEmptyList.test(emptyList())); Assert.assertFalse(nullOrEmptyList.test(singletonList("a"))); } @Test public void testNOTing() { Predicate<Object> isNotNull = Validator.not(Validator::isNull); Assert.assertTrue(isNotNull.test("a")); Assert.assertFalse(isNotNull.test(null)); } @Test public void testIfTrueThenCheck() { BiPredicate<Object, Object> isEnabledAndCheck = Validator.ifTrueThenCheck(Validator::isList); Assert.assertTrue(isEnabledAndCheck.test(true, emptyList())); Assert.assertTrue(isEnabledAndCheck.test(false, null)); Assert.assertTrue(isEnabledAndCheck.test(false, null)); Assert.assertFalse(isEnabledAndCheck.test(true, 8)); } @Test public void testIsImpliedBy() { BiPredicate<Object, Object> isEnabledAndCheck = Validator.isImpliedBy(Validator::isTrue, Validator::isList); Assert.assertTrue(isEnabledAndCheck.test(true, emptyList())); Assert.assertTrue(isEnabledAndCheck.test(false, null)); Assert.assertTrue(isEnabledAndCheck.test(false, null)); Assert.assertFalse(isEnabledAndCheck.test(true, 8)); } }
ndrwksr/StructureGrader
src/test/java/edu/test/proj2/Interface1.java
package edu.test.proj2; import edu.test.annotations.TestAnnotation1; @TestAnnotation1 public interface Interface1 { void method(Object arg); }
T-binson/fullStack
node/node1/express/server-cookie.js
<gh_stars>0 const express = require('express'); const cookieParser = require('cookie-parser'); let server = express(); server.listen(8080); server.use(cookieParser(['shhsoelsheo' ])); server.get('/', (req, res, next) => { console.log(req.cookies); console.log(req.signedCookies); res.cookie('pass', <PASSWORD>, { //domain //expires: date //maxAge: int //path //secrect: true signed: true }); res.end(); });
daiyaanarfeen/kospeech
test/test_deepspeech2_recognize.py
# Copyright (c) 2020, <NAME>. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from kospeech.models import DeepSpeech2 batch_size = 3 sequence_length = 14321 dimension = 80 cuda = torch.cuda.is_available() device = torch.device('cuda' if cuda else 'cpu') inputs = torch.rand(batch_size, sequence_length, dimension).to(device) # BxTxD input_lengths = torch.LongTensor([14321, 14300, 13000]).to(device) print("Deep Speech 2 Model Test..") model = DeepSpeech2(num_classes=10, input_dim=dimension).to(device) output = model.recognize(inputs, input_lengths) print(output) print(output.size())
ivychen/databass-public
databass/ops/join.py
<filename>databass/ops/join.py from ..baseops import * from ..exprs import * from ..db import Database from ..schema import * from ..tuples import * from ..util import cache, OBTuple from itertools import chain class From(NaryOp): """ Logical FROM operator. Optimizer will expand it into a join tree """ def __init__(self, cs, predicates): super(From, self).__init__(cs) self.predicates = predicates def to_str(self, ctx): name = "From(%s)" % " and ".join(map(str, self.predicates)) with ctx.indent(name): for c in self.cs: c.to_str(ctx) class Join(BinaryOp): pass class ThetaJoin(Join): """ Theta Join is tuple-nested loops join """ def __init__(self, l, r, cond=Literal(True)): """ @l left (outer) subplan of the join @r right (inner) subplan of the join @cond an Expr object whose output will be interpreted as a boolean """ super(ThetaJoin, self).__init__(l, r) self.cond = cond def __iter__(self): # initialize a single intermediate tuple irow = ListTuple(self.schema, []) for lrow in self.l: for rrow in self.r: # populate intermediate tuple with values irow.row[:len(lrow.row)] = lrow.row irow.row[len(lrow.row):] = rrow.row if self.cond(irow): yield irow def __str__(self): return "THETAJOIN(ON %s)" % (str(self.cond))
bitwize/rscheme
packages/threads/manager/synch.h
<reponame>bitwize/rscheme /* returns 0 on success, else -ERRNO, i.e.,: -EPIPE : mailbox is closed */ int ksend_mailbox( obj mbox, obj item ); /* append to queue */ int ksend_mailbox_pre( obj mbox, obj item ); /* prepend onto queue */ int close_mailbox( obj mbox, obj leave ); void krelease_joiners( obj thr ); void kthread_unqueue_suspend( obj thr );
caliber11/Love-Field
tests/schema/table_builder_test.js
/** * @license * Copyright 2015 The Lovefield Project Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ goog.setTestOnly(); goog.require('goog.testing.jsunit'); goog.require('lf.Order'); goog.require('lf.Row'); goog.require('lf.Type'); goog.require('lf.schema.TableBuilder'); goog.require('lf.structs.set'); goog.require('lf.testing.util'); function testThrows_DuplicateColumn() { // 503: Name {0} is already defined. lf.testing.util.assertThrowsError(503, function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('col', lf.Type.STRING). addColumn('col', lf.Type.STRING); }); } function testThrows_InvalidNullable() { // Testing single column primary key. // 545: Primary key column {0} can't be marked as nullable, lf.testing.util.assertThrowsError(545, function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('id', lf.Type.STRING). addPrimaryKey(['id']). addNullable(['id']); tableBuilder.getSchema(); }); // Testing multi column primary key. lf.testing.util.assertThrowsError(545, function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('id1', lf.Type.STRING). addColumn('id2', lf.Type.STRING). addNullable(['id2']). addPrimaryKey(['id1', 'id2']); tableBuilder.getSchema(); }); } function testThrows_NonIndexableColumns() { // 509: Attempt to index table {0} on non-indexable column {1}. lf.testing.util.assertThrowsError(509, function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('object', lf.Type.OBJECT). addPrimaryKey(['object']); }); lf.testing.util.assertThrowsError(509, function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('arraybuffer', lf.Type.ARRAY_BUFFER). addIndex('idx_arraybuffer', ['arraybuffer']); }); } function testThrows_CrossColumnPkWithAutoInc() { // 505: Can not use autoIncrement with a cross-column primary key. lf.testing.util.assertThrowsError(505, function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('id1', lf.Type.INTEGER). addColumn('id2', lf.Type.INTEGER). addPrimaryKey([ {'name': 'id1', 'autoIncrement': true}, {'name': 'id2', 'autoIncrement': true} ]); }); } function testThrows_NonIntegerPkWithAutoInc() { // 504: Can not use autoIncrement with a non-integer primary key. lf.testing.util.assertThrowsError(504, function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('id', lf.Type.STRING). addPrimaryKey([{'name': 'id', 'autoIncrement': true}]); }); } function testThrows_InValidFKLocalColName() { // 540: Foreign key {0} has invalid reference syntax. lf.testing.util.assertThrowsError(540, function() { var tableBuilder = new lf.schema.TableBuilder('FkTable1'); tableBuilder. addColumn('employeeId', lf.Type.STRING). addForeignKey('fkemployeeId', { local: 'employeeId1', ref: 'Employee.id' }); }); } function testThrows_DuplicateIndexName() { // 503: Name FkTableDupIndex.fkemployeeId is already defined. // Callincg addForeignKey first, addIndex second. lf.testing.util.assertThrowsError(503, function() { var tableBuilder = new lf.schema.TableBuilder('FkTableDupIndex'); tableBuilder. addColumn('employeeId', lf.Type.INTEGER). addForeignKey('fkemployeeId', { local: 'employeeId', ref: 'Employee.id' }). addIndex('fkemployeeId', ['employeeId'], true, lf.Order.ASC); }); // 503: Name FkTableDupIndex.fkemployeeId is already defined. // Callincg addIndex first, addForeignKey second. lf.testing.util.assertThrowsError(503, function() { var tableBuilder = new lf.schema.TableBuilder('FkTableDupIndex'); tableBuilder. addColumn('employeeId', lf.Type.INTEGER). addIndex('fkemployeeId', ['employeeId'], true, lf.Order.ASC). addForeignKey('fkemployeeId', { local: 'employeeId', ref: 'Employee.id' }); }); } function testThrows_IndexColumnConstraintNameConflict() { // 546: Indices/constraints/columns can't re-use the table name {0}, lf.testing.util.assertThrowsError(546, function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('id', lf.Type.INTEGER). addIndex('Table', ['id']); }); lf.testing.util.assertThrowsError(546, function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('id', lf.Type.INTEGER). addUnique('Table', ['id']); }); lf.testing.util.assertThrowsError(546, function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder.addColumn('Table', lf.Type.INTEGER); }); } function testThrows_ColumnBothPkAndFk() { // 543: Foreign key {0}. A primary key column can't also be a foreign key // child column. lf.testing.util.assertThrowsError(543, function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('id', lf.Type.STRING). addPrimaryKey(['id']). addForeignKey('fk_id', { local: 'id', ref: 'OtherTable.id', }); return tableBuilder.getSchema(); }); } function testThrows_PrimaryKeyDuplicateIndex() { // 544: Duplicate primary key index found at {0}, // Testing single column primary key. lf.testing.util.assertThrowsError(544, function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('id', lf.Type.STRING). addPrimaryKey(['id']). addIndex('idx_id', ['id'], false, lf.Order.ASC); return tableBuilder.getSchema(); }); // Testing multi column primary key. lf.testing.util.assertThrowsError(544, function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('id1', lf.Type.STRING). addColumn('id2', lf.Type.STRING). addPrimaryKey(['id1', 'id2']). addIndex('idx_id', ['id1', 'id2']); return tableBuilder.getSchema(); }); } function testIsUnique_CrossColumnPk() { var getSchema = function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('id1', lf.Type.NUMBER). addColumn('id2', lf.Type.NUMBER). addColumn('email', lf.Type.STRING). addColumn('maxSalary', lf.Type.NUMBER). addPrimaryKey(['id1', 'id2']); return tableBuilder.getSchema(); }; var tableSchema = getSchema(); assertFalse(tableSchema['id1'].isUnique()); assertFalse(tableSchema['id2'].isUnique()); } function testAddDuplicateIndexOnFK() { var getSchema = function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('employeeId', lf.Type.INTEGER). addForeignKey('fkemployeeId', { local: 'employeeId', ref: 'Employee.id' }). addIndex('idx_employeeId', ['employeeId'], false, lf.Order.ASC); return tableBuilder.getSchema(); }; var indexNames = lf.structs.set.create(); getSchema().getIndices().forEach( function(index) { indexNames.add(index.name); }); assertTrue(indexNames.has('fkemployeeId')); assertTrue(indexNames.has('idx_employeeId')); } function testFkChildColumnIndex_Unique() { // Case1: addUnique called before addForeignKey. var getSchema1 = function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('employeeId', lf.Type.INTEGER). addUnique('uq_employeeId', ['employeeId']). addForeignKey('fkEmployeeId', { local: 'employeeId', ref: 'Employee.id' }); return tableBuilder.getSchema(); }; var fkIndexSchema = getSchema1()['employeeId'].getIndices()[1]; assertEquals('fkEmployeeId', fkIndexSchema.name); assertTrue(fkIndexSchema.isUnique); // Case2: addUnique called after addForeignKey. var getSchema2 = function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('employeeId', lf.Type.INTEGER). addForeignKey('fkEmployeeId', { local: 'employeeId', ref: 'Employee.id' }). addUnique('uq_employeeId', ['employeeId']); return tableBuilder.getSchema(); }; fkIndexSchema = getSchema2()['employeeId'].getIndices()[0]; assertEquals('fkEmployeeId', fkIndexSchema.name); assertTrue(fkIndexSchema.isUnique); } function testFkChildColumnIndex_NonUnique() { // Case: Foreign key child column is not unique. var getSchema = function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('employeeId', lf.Type.INTEGER). addForeignKey('fkEmployeeId', { local: 'employeeId', ref: 'Employee.id' }); return tableBuilder.getSchema(); }; var fkIndexSchema = getSchema()['employeeId'].getIndices()[0]; assertEquals('fkEmployeeId', fkIndexSchema.name); assertFalse(fkIndexSchema.isUnique); } /** * Tests that the generated createRow() function produces the correct default * values for each column, based on the column's type and whether the column is * nullable by default. */ function testCreateRow_DefaultValues() { var getSchema = function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('integer', lf.Type.INTEGER). addColumn('number', lf.Type.NUMBER). addColumn('string', lf.Type.STRING). addColumn('boolean', lf.Type.BOOLEAN). addColumn('datetime', lf.Type.DATE_TIME). addColumn('arraybuffer', lf.Type.ARRAY_BUFFER). addColumn('object', lf.Type.OBJECT); return tableBuilder.getSchema(); }; var tableSchema = getSchema(); var row = tableSchema.createRow(); assertTrue(row instanceof lf.Row); var payload = row.payload(); assertNull(payload['arraybuffer']); assertFalse(payload['boolean']); assertEquals(0, payload['datetime'].getTime()); assertEquals(0, payload['integer']); assertEquals(0, payload['number']); assertNull(payload['object']); assertEquals('', payload['string']); } function testCreateRow_DefaultValues_Nullable() { var getSchema = function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('integer', lf.Type.INTEGER). addColumn('number', lf.Type.NUMBER). addColumn('string', lf.Type.STRING). addColumn('boolean', lf.Type.BOOLEAN). addColumn('datetime', lf.Type.DATE_TIME). addColumn('arraybuffer', lf.Type.ARRAY_BUFFER). addColumn('object', lf.Type.OBJECT). addNullable([ 'integer', 'number', 'string', 'boolean', 'datetime', 'arraybuffer', 'object' ]); return tableBuilder.getSchema(); }; var tableSchema = getSchema(); var row = tableSchema.createRow(); assertTrue(row instanceof lf.Row); var expectedPayload = { integer: null, number: null, string: null, boolean: null, datetime: null, arraybuffer: null, object: null }; assertObjectEquals(expectedPayload, row.payload()); } /** * Tests that keyOfIndex() method returns the expected keys, for the case of * single column indices. */ function testKeyOfIndex_SingleKey() { var getSchema = function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('datetime', lf.Type.DATE_TIME). addColumn('integer', lf.Type.INTEGER). addColumn('number', lf.Type.NUMBER). addColumn('string', lf.Type.STRING). addIndex('idx_datetime', ['datetime']). addIndex('idx_integer', ['integer']). addIndex('idx_number', ['number']). addIndex('idx_string', ['string']); return tableBuilder.getSchema(); }; var tableSchema = getSchema(); var row = tableSchema.createRow({ 'datetime': new Date(999), 'integer': 2, 'number': 3, 'string': 'bar' }); assertEquals(999, row.keyOfIndex('Table.idx_datetime')); assertEquals(2, row.keyOfIndex('Table.idx_integer')); assertEquals(3, row.keyOfIndex('Table.idx_number')); assertEquals('bar', row.keyOfIndex('Table.idx_string')); assertEquals(row.id(), row.keyOfIndex('Table.#')); } /** * Tests that keyOfIndex() is correctly handling nullable fields. */ function testKeyOfIndex_NullableField() { var getSchema = function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('datetime', lf.Type.DATE_TIME). addColumn('integer', lf.Type.INTEGER). addColumn('number', lf.Type.NUMBER). addColumn('string', lf.Type.STRING). addColumn('boolean', lf.Type.BOOLEAN). addNullable(['datetime', 'integer', 'number', 'string', 'boolean']). addIndex('idx_datetime', ['datetime']). addIndex('idx_integer', ['integer']). addIndex('idx_number', ['number']). addIndex('idx_string', ['string']). addIndex('idx_boolean', ['boolean']); return tableBuilder.getSchema(); }; var tableSchema = getSchema(); var row = tableSchema.createRow(); tableSchema.getIndices().forEach(function(indexSchema) { assertNull(row.keyOfIndex(indexSchema.getNormalizedName())); }); } /** * Tests that keyOfIndex() method returns the expected keys, for the case of * cross-column indices. */ function testKeyOfIndex_CrossColumnKey() { var getSchema = function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('datetime', lf.Type.DATE_TIME). addColumn('integer', lf.Type.INTEGER). addColumn('number', lf.Type.NUMBER). addColumn('string', lf.Type.STRING). addColumn('boolean', lf.Type.BOOLEAN). addPrimaryKey(['string', 'integer']). addIndex('idx_NumberInteger', ['number', 'integer']). addIndex('idx_NumberIntegerString', ['number', 'integer', 'string']). addIndex('idb_DateTimeString', ['datetime', 'string']). addIndex('idb_BooleanString', ['boolean', 'string']); return tableBuilder.getSchema(); }; var tableSchema = getSchema(); var row = tableSchema.createRow({ 'boolean': true, 'datetime': new Date(999), 'integer': 2, 'number': 3, 'string': 'bar' }); assertEquals(row.id(), row.keyOfIndex(tableSchema.getRowIdIndexName())); var indices = tableSchema.getIndices(); var pkIndexSchema = indices[0]; assertArrayEquals( ['bar', 2], row.keyOfIndex(pkIndexSchema.getNormalizedName())); var numberStringIndexSchema = indices[1]; assertArrayEquals( [3, 2], row.keyOfIndex(numberStringIndexSchema.getNormalizedName())); var numberIntegerStringIndexSchema = indices[2]; assertArrayEquals( [3, 2, 'bar'], row.keyOfIndex(numberIntegerStringIndexSchema.getNormalizedName())); var dateTimeStringIndexSchema = indices[3]; assertArrayEquals( [999, 'bar'], row.keyOfIndex(dateTimeStringIndexSchema.getNormalizedName())); var booleanStringIndexSchema = indices[4]; assertArrayEquals( [1, 'bar'], row.keyOfIndex(booleanStringIndexSchema.getNormalizedName())); } function testSerialization() { var getSchema = function() { var tableBuilder = new lf.schema.TableBuilder('Table'); tableBuilder. addColumn('number', lf.Type.NUMBER). addColumn('string', lf.Type.STRING). addColumn('arraybuffer', lf.Type.ARRAY_BUFFER). addColumn('datetime', lf.Type.DATE_TIME). addColumn('object', lf.Type.OBJECT). addNullable(['datetime']); return tableBuilder.getSchema(); }; var tableSchema = getSchema(); var row = tableSchema.createRow({ number: 1, string: 'bar', arraybuffer: null }); var expected = { number: 1, string: 'bar', arraybuffer: null, object: null, datetime: null }; assertObjectEquals(expected, row.toDbPayload()); assertObjectEquals( expected, tableSchema.deserializeRow(row.serialize()).payload()); }
cfogelberg/postgres-fiddle
src/client/js/app/config.js
<gh_stars>0 // NO LOGGING IN THIS FILE define(function(require) { 'use strict'; var config = { logger: { root: { js: { conf: { level: 'warn', // configure.py: js appenders: ['console'] } }, events_logger: { conf: { level: 'warn', // configure.py: events_logger appenders: ['console'] } } } } }; return config; });
yukaida/cook_native
app/src/main/java/com/ebanswers/kitchendiary/bean/Topics/Topics.java
<filename>app/src/main/java/com/ebanswers/kitchendiary/bean/Topics/Topics.java<gh_stars>0 /** * Copyright 2019 bejson.com */ package com.ebanswers.kitchendiary.bean.Topics; import java.util.List; /** * Auto-generated: 2019-12-02 19:41:53 * * @author bejson.com (<EMAIL>) * @website http://www.bejson.com/java2pojo/ */ public class Topics { private int code; private List<NormalTopics> data; private List<LastTopics> lastTopics; public void setCode(int code) { this.code = code; } public int getCode() { return code; } public void setData(List<NormalTopics> data) { this.data = data; } public List<NormalTopics> getData() { return data; } public void setLastTopics(List<LastTopics> lastTopics) { this.lastTopics = lastTopics; } public List<LastTopics> getLastTopics() { return lastTopics; } }
alexanderbock/inviwo
include/inviwo/core/processors/processorwidgetfactoryobject.h
<gh_stars>100-1000 /********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015-2021 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. 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. * *********************************************************************************/ #pragma once #include <inviwo/core/common/inviwocoredefine.h> #include <inviwo/core/processors/processor.h> #include <inviwo/core/processors/processortraits.h> #include <string> #include <memory> namespace inviwo { class ProcessorWidget; class IVW_CORE_API ProcessorWidgetFactoryObject { public: ProcessorWidgetFactoryObject(const std::string& processorClassIdentifier); virtual ~ProcessorWidgetFactoryObject(); virtual std::unique_ptr<ProcessorWidget> create(Processor* p) = 0; const std::string& getClassIdentifier() const { return classIdentifier_; } private: std::string classIdentifier_; }; template <typename T, typename ProcessorType> class ProcessorWidgetFactoryObjectTemplate : public ProcessorWidgetFactoryObject { public: ProcessorWidgetFactoryObjectTemplate() : ProcessorWidgetFactoryObject( ProcessorTraits<ProcessorType>::getProcessorInfo().classIdentifier) {} virtual ~ProcessorWidgetFactoryObjectTemplate() = default; virtual std::unique_ptr<ProcessorWidget> create(Processor* p) override { return std::make_unique<T>(p); } }; } // namespace inviwo
duckie/boson
src/boson/src/internal/routine.cc
#include "internal/routine.h" #include <cassert> #include "exception.h" #include "internal/thread.h" #include "syscalls.h" #include "semaphore.h" #include "logger.h" namespace boson { namespace internal { namespace detail { void resume_routine(transfer_t transfered_context) { thread* this_thread = current_thread(); this_thread->context() = transfered_context; routine* current_routine = this_thread->running_routine(); current_routine->status_ = routine_status::running; (*current_routine->func_)(); current_routine->status_ = routine_status::finished; jump_fcontext(this_thread->context().fctx, nullptr); } } // class routine; routine::~routine() { deallocate(stack_); } void routine::start_event_round() { // Clean previous events //previous_events_.clear(); //std::swap(previous_events_, events_); events_.clear(); // Create new event pointer current_ptr_ = routine_local_ptr_t(std::unique_ptr<routine>(this)); } void routine::add_semaphore_wait(semaphore* sema) { events_.emplace_back(waited_event{event_type::sema_wait, routine_sema_event_data{sema,0,0}}); auto slot_index = thread_->register_semaphore_wait(routine_slot{current_ptr_,events_.size()-1}); events_.back().data.get<routine_sema_event_data>().index = sema->write(thread_, slot_index); events_.back().data.get<routine_sema_event_data>().slot_index = slot_index; int result = sema->counter_.fetch_add(1,std::memory_order_release); if (0 <= result) { sema->pop_a_waiter(thread_); } } void routine::add_timer(routine_time_point date) { events_.emplace_back(waited_event{event_type::timer, routine_timer_event_data{std::move(date),nullptr}}); auto& event = events_.back(); event.data.get<routine_timer_event_data>().neighbor_timers = &thread_->register_timer(event.data.get<routine_timer_event_data>().date, routine_slot{current_ptr_,events_.size()-1}); } void routine::add_read(int fd) { events_.emplace_back(waited_event{event_type::io_read, routine_io_event{fd, -1, fd_status::unknown, fd_status::unknown}}); thread_->register_read(fd, routine_slot{current_ptr_, events_.size() - 1}); } void routine::add_write(int fd) { events_.emplace_back(waited_event{event_type::io_write, routine_io_event{fd, -1, fd_status::unknown, fd_status::unknown}}); thread_->register_write(fd, routine_slot{current_ptr_, events_.size() - 1}); } size_t routine::commit_event_round() { status_ = routine_status::wait_events; thread_->context() = jump_fcontext(thread_->context().fctx, nullptr); return happened_index_; } void routine::cancel_event_round() { // Invalidate other events for (auto& other : events_) { switch (other.type) { case event_type::none: break; case event_type::timer: { auto& data = other.data.get<routine_timer_event_data>(); --data.neighbor_timers->nb_active; } break; case event_type::io_read: --thread_->nb_suspended_routines_; break; case event_type::io_write: --thread_->nb_suspended_routines_; break; case event_type::sema_wait: { --thread_->nb_suspended_routines_; // Remove it from the queue in which it is stored auto sema = other.data.get<routine_sema_event_data>().sema; if (sema->free(other.data.get<routine_sema_event_data>().index)) { // If was in the queue, then free the thread slot thread_->unregister_expired_slot(other.data.get<routine_sema_event_data>().slot_index); } } break; case event_type::sema_closed: assert(false); break; } } current_ptr_->release(); current_ptr_.invalidate_all(); events_.clear(); //std::swap(previous_events_, events_); } void routine::set_as_semaphore_event_candidate(std::size_t index) { status_ = routine_status::sema_event_candidate; thread_->schedule_routine(routine_slot{current_ptr_,index}); } bool routine::event_is_a_fd_wait(std::size_t index, int fd) { if (index < events_.size()) { auto& event = events_[index]; if (event.type == event_type::io_read || event.type == event_type::io_write) { return (fd == event.data.get<routine_io_event>().fd); } } return false; } bool routine::event_happened(std::size_t index, event_status status) { auto& event = events_[index]; happened_rc_ = 0; switch (event.type) { case event_type::none: break; case event_type::timer: happened_type_ = event_type::timer; happened_rc_ = -ETIMEDOUT; break; case event_type::io_read: case event_type::io_write: happened_type_ = event.type; happened_rc_ = status; --thread_->nb_suspended_routines_; break; case event_type::sema_wait: { --thread_->nb_suspended_routines_; auto sema = event.data.get<routine_sema_event_data>().sema; thread_->unregister_expired_slot(event.data.get<routine_sema_event_data>().slot_index); int result = sema->counter_.fetch_sub(1,std::memory_order_acquire); if (semaphore::disabling_threshold < result) { sema->counter_.fetch_add(1,std::memory_order_relaxed); happened_type_ = event_type::sema_closed; } else if (result <= 0) { // failed candidacy // do not invalidate pointers of other events // do not change the routine status // do not invalidate event slot in the thread auto slot_index = thread_->register_semaphore_wait(routine_slot{current_ptr_, index}); event.data.get<routine_sema_event_data>().index = sema->write(thread_, slot_index); result = sema->counter_.fetch_add(1, std::memory_order_release); if (0 <= result) { sema->pop_a_waiter(thread_); } return false; } else { happened_type_ = event_type::sema_wait; } } break; case event_type::sema_closed: assert(false); break; } // invalidate other events for (auto& other : events_) { if (&other != &event) { switch (other.type) { case event_type::none: break; case event_type::timer: { auto& data = other.data.get<routine_timer_event_data>(); --data.neighbor_timers->nb_active; } break; case event_type::io_read: --thread_->nb_suspended_routines_; break; case event_type::io_write: --thread_->nb_suspended_routines_; break; case event_type::sema_wait: { --thread_->nb_suspended_routines_; // remove it from the queue in which it is stored auto sema = other.data.get<routine_sema_event_data>().sema; if (sema->free(other.data.get<routine_sema_event_data>().index)) { // if was in the queue, then free the thread slot thread_->unregister_expired_slot(other.data.get<routine_sema_event_data>().slot_index); } } break; case event_type::sema_closed: assert(false); break; } } } if (happened_type_ == event_type::sema_wait || happened_type_ == event_type::sema_closed) { status_ = routine_status::yielding; current_ptr_->release(); // in this particular case, the scheduler gets back routine ownership current_ptr_.invalidate_all(); happened_index_ = index; return true; } else if (happened_type_ != event_type::none) { //if (happened_type_ == event_type::timer) //thread_->scheduled_routines_.emplace_front(routine_slot{routine_local_ptr_t(std::unique_ptr<routine>(current_ptr_->release())),0}); //else status_ = routine_status::yielding; happened_index_ = index; thread_->schedule_routine(routine_slot{routine_local_ptr_t(std::unique_ptr<routine>(current_ptr_->release())),0}); current_ptr_.invalidate_all(); return true; } return false; } void routine::close_fd(int fd) { thread_->unregister_fd(fd); } void routine::resume(thread* managing_thread) { thread_ = managing_thread; switch (status_) { case routine_status::is_new: { context_.fctx = make_fcontext(stack_.sp, stack_.size, detail::resume_routine); context_ = jump_fcontext(context_.fctx, nullptr); break; } case routine_status::yielding: { context_ = jump_fcontext(context_.fctx, nullptr); break; } default: // Not supposed to happen boson::debug::log("Routine has status {}.", static_cast<int>(status_)); assert(false); break; } // Manage the queue requests while (context_.data && status_ == routine_status::running) { in_context_function* func = static_cast<in_context_function*>(context_.data); (*func)(thread_); context_ = jump_fcontext(context_.fctx, nullptr); } } std::size_t routine::get_stack_offset(void* pointer) { return reinterpret_cast<char*>(stack_.sp) - reinterpret_cast<char*>(pointer); } } // namespace internal } // namespace boson
abueide/mage
Mage.Sets/src/mage/cards/k/KotoseTheSilentSpider.java
package mage.cards.k; import mage.MageInt; import mage.MageObjectReference; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.condition.Condition; import mage.abilities.effects.OneShotEffect; import mage.cards.*; import mage.constants.*; import mage.filter.FilterCard; import mage.filter.predicate.Predicates; import mage.filter.predicate.mageobject.NamePredicate; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.stack.Spell; import mage.players.Player; import mage.target.common.TargetCardInGraveyard; import mage.target.common.TargetCardInHand; import mage.target.common.TargetCardInLibrary; import mage.target.common.TargetCardInOpponentsGraveyard; import mage.util.CardUtil; import mage.watchers.Watcher; import java.util.*; import java.util.stream.Collectors; /** * @author TheElk801 */ public final class KotoseTheSilentSpider extends CardImpl { private static final FilterCard filter = new FilterCard("card other than a basic land card in an opponent's graveyard"); static { filter.add(Predicates.not(Predicates.and( CardType.LAND.getPredicate(), SuperType.BASIC.getPredicate() ))); } public KotoseTheSilentSpider(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{U}{B}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.NINJA); this.power = new MageInt(4); this.toughness = new MageInt(4); // When Kotose, Silent Spider enters the battlefield, exile target card in an opponent's graveyard other than a basic land card. Search that player's graveyard, hand, and library for any number of cards with the same name as that card and exile them. For as long as you control Kotose, you may play one of the exiled cards, and you may spend mana as though it were mana of any color to cast it. Ability ability = new EntersBattlefieldTriggeredAbility(new KotoseTheSilentSpiderEffect()); ability.addTarget(new TargetCardInOpponentsGraveyard(filter)); this.addAbility(ability, new KotoseTheSilentSpiderWatcher()); } private KotoseTheSilentSpider(final KotoseTheSilentSpider card) { super(card); } @Override public KotoseTheSilentSpider copy() { return new KotoseTheSilentSpider(this); } } class KotoseTheSilentSpiderEffect extends OneShotEffect { public KotoseTheSilentSpiderEffect() { super(Outcome.Exile); this.staticText = "exile target card other than a basic land card from an opponent's graveyard. " + "Search that player's graveyard, hand, and library for any number of cards with the same name " + "as that card and exile them. Then that player shuffles. For as long as you control {this}, you may " + "play one of the exiled cards, and you may spend mana as though it were mana of any color to cast it"; } public KotoseTheSilentSpiderEffect(final KotoseTheSilentSpiderEffect effect) { super(effect); } @Override public KotoseTheSilentSpiderEffect copy() { return new KotoseTheSilentSpiderEffect(this); } @Override public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); Card card = game.getCard(getTargetPointer().getFirst(game, source)); if (controller == null || card == null) { return false; } Player opponent = game.getPlayer(card.getOwnerId()); if (opponent == null) { return false; } UUID exileId = CardUtil.getExileZoneId(game, source); String exileName = CardUtil.getSourceName(game, source); controller.moveCardsToExile(card, source, game, true, exileId, exileName); Cards cards = new CardsImpl(); FilterCard filter = new FilterCard("cards named " + card.getName() + " from " + opponent.getName() + "'s graveyard"); filter.add(new NamePredicate(card.getName())); TargetCardInGraveyard targetCardInGraveyard = new TargetCardInGraveyard(0, Integer.MAX_VALUE, filter); controller.choose(outcome, opponent.getGraveyard(), targetCardInGraveyard, game); cards.addAll(targetCardInGraveyard.getTargets()); filter.setMessage("cards named " + card.getName() + " from " + opponent.getName() + "'s hand"); TargetCardInHand targetCardInHand = new TargetCardInHand(0, Integer.MAX_VALUE, filter); controller.choose(outcome, opponent.getHand(), targetCardInHand, game); cards.addAll(targetCardInHand.getTargets()); filter.setMessage("cards named " + card.getName() + " from " + opponent.getName() + "'s library"); TargetCardInLibrary target = new TargetCardInLibrary(0, Integer.MAX_VALUE, filter); controller.searchLibrary(target, source, game, opponent.getId()); target.getTargets() .stream() .map(cardId -> opponent.getLibrary().getCard(cardId, game)) .forEach(cards::add); Set<Card> cardSet = cards.getCards(game); controller.moveCardsToExile(cardSet, source, game, true, exileId, exileName); opponent.shuffleLibrary(source, game); cardSet.add(card); if (cardSet.isEmpty() || source.getSourcePermanentIfItStillExists(game) == null) { return true; } KotoseTheSilentSpiderWatcher.addCards(source, cardSet, game); for (Card exiledCard : cardSet) { CardUtil.makeCardPlayable( game, source, exiledCard, Duration.WhileControlled, true, null, new KotoseTheSilentSpiderCondition(exiledCard, game) ); } return true; } } class KotoseTheSilentSpiderCondition implements Condition { private final MageObjectReference mor; KotoseTheSilentSpiderCondition(Card card, Game game) { this.mor = new MageObjectReference(card, game); } @Override public boolean apply(Game game, Ability source) { return KotoseTheSilentSpiderWatcher.checkCard(game, source, mor); } } class KotoseTheSilentSpiderWatcher extends Watcher { private final Map<MageObjectReference, Set<Set<MageObjectReference>>> morMap = new HashMap<>(); public KotoseTheSilentSpiderWatcher() { super(WatcherScope.GAME); } @Override public void watch(GameEvent event, Game game) { if (event.getType() == GameEvent.EventType.CLEANUP_STEP_POST) { morMap.entrySet().removeIf(e -> !e.getKey().zoneCounterIsCurrent(game)); morMap.values() .stream() .flatMap(Collection::stream) .map(set -> set.removeIf(mor -> !mor.zoneCounterIsCurrent(game))); morMap.values().removeIf(Set::isEmpty); return; } if (event.getType() != GameEvent.EventType.SPELL_CAST || event.getAdditionalReference() == null) { return; } Spell spell = game.getSpell(event.getTargetId()); if (spell == null) { return; } morMap.getOrDefault( event.getAdditionalReference().getApprovingMageObjectReference(), Collections.emptySet() ).removeIf(set -> set .stream() .anyMatch(mor -> mor.getSourceId().equals(spell.getMainCard().getId()) && mor.getZoneChangeCounter() + 1 == spell.getZoneChangeCounter(game))); } static void addCards(Ability source, Set<Card> cards, Game game) { game.getState() .getWatcher(KotoseTheSilentSpiderWatcher.class) .morMap .computeIfAbsent(new MageObjectReference(source), x -> new HashSet<>()) .add(cards .stream() .map(card -> new MageObjectReference(card, game)) .collect(Collectors.toSet())); } static boolean checkCard(Game game, Ability source, MageObjectReference mor) { return game.getState() .getWatcher(KotoseTheSilentSpiderWatcher.class) .morMap .getOrDefault(new MageObjectReference(source), Collections.emptySet()) .stream() .flatMap(Collection::stream) .anyMatch(mor::equals); } }
edidada/transformer-playground
transformer-processors/src/test/resources/me/lotabout/processor/typecheck/DifferentPrimitiveA.java
<reponame>edidada/transformer-playground package me.lotabout.processor.typecheck; import me.lotabout.annotation.Transformer; @Transformer(to = {DifferentPrimitiveB.class}) public class DifferentPrimitiveA { int fieldA; public int getFieldA() { return fieldA; } public void setFieldA(int fieldA) { this.fieldA = fieldA; } }
fduminy/intellij-community
jetCheck/src/org/jetbrains/jetCheck/GeneratorException.java
<filename>jetCheck/src/org/jetbrains/jetCheck/GeneratorException.java package org.jetbrains.jetCheck; /** * @author peter */ public class GeneratorException extends RuntimeException { GeneratorException(Iteration<?> iteration, Throwable cause) { super("Exception while generating data, " + iteration.printSeeds(), cause); } }
vortex-17/awesome-golang-algorithm
leetcode/201-300/0283.Move-Zeroes/Solution_test.go
<reponame>vortex-17/awesome-golang-algorithm<gh_stars>1-10 package Solution import ( "reflect" "strconv" "testing" ) func TestMoveZeroes(t *testing.T) { cases := []struct { name string inputs []int expects []int }{ {"test case 1", []int{0, 1, 0, 3, 12}, []int{1, 3, 12, 0, 0}}, } for _, testcase := range cases { t.Run(testcase.name, func(t *testing.T) { result := moveZeroes(testcase.inputs) if !reflect.DeepEqual(result, testcase.expects) { t.Fatalf("expected: %v, but got: %v, with input: %v ", testcase.expects, result, testcase.inputs) } }) } } func TestMoveZeroes2(t *testing.T) { cases := []struct { name string inputs []int expects []int }{ {"TestCase", []int{0, 1, 0, 3, 12}, []int{1, 3, 12, 0, 0}}, {"TestCase", []int{0}, []int{0}}, {"TestCase", []int{1}, []int{1}}, } for i, testcase := range cases { t.Run(testcase.name+" "+strconv.Itoa(i), func(t *testing.T) { result := moveZeroes2(testcase.inputs) if !reflect.DeepEqual(result, testcase.expects) { t.Fatalf("expected: %v, but got: %v, with input: %v ", testcase.expects, result, testcase.inputs) } }) } }
rbarzic/MAGICAL
thirdparty/wnlib/acc/mem/wnmemn.c
<reponame>rbarzic/MAGICAL<gh_stars>0 /********************************************************************** wn_initialize_group_for_no_free(group) local ptr alloc_piece(size,group) local ptr free_piece(p,group) local void verify_group(group) local int memory_used_in_group(group) **********************************************************************/ /**************************************************************************** COPYRIGHT NOTICE: The source code in this directory is provided free of charge to anyone who wants it. It is in the public domain and therefore may be used by anybody for any purpose. It is provided "AS IS" with no warranty of any kind whatsoever. For further details see the README files in the wnlib parent directory. AUTHOR: <NAME> ****************************************************************************/ #include <stdio.h> #include "wnlib.h" #include "wnmax.h" #include "wnasrt.h" #include "wnmem.h" #define PAD_BEGIN_MAGIC (2111222111) #define PAD_END_MAGIC (1222111222) typedef struct pad_type_struct *pad_type; struct pad_type_struct { unsigned begin_magic; pad_type next; unsigned end_magic; }; /* the following type is the same as the above but its size is 8-aligned */ union pad_type_8aligned_union { struct pad_type_struct p; double d; }; extern bool wn_gp_fill_flag,wn_gp_pad_flag,wn_gp_trap_address_flag; extern ptr wn_gp_trap_address_address; extern ptr wn_system_alloc(int); local void get_more_memory(int size,wn_memgp group) { wn_mem_block block; int size_to_get,size_to_alloc; if(group->current_block != NULL) { group->current_block->leftover += group->block_mem_left; } size_to_get = wn_max(size, group->block_size); /* we add in 4 here in case we have to realign the block_ptr */ size_to_alloc = size_to_get + 4 + sizeof(struct wn_mem_block_struct); block = (wn_mem_block)wn_system_alloc(size_to_alloc); wn_assert(sizeof(ptr) < 8 || !(((long unsigned) block) & 7)); block->next = group->current_block; group->current_block = block; block->leftover = 0; block->size = size_to_alloc; group->block_ptr = WN_MEM_BLOCK_MEMORY(block); group->block_end_ptr = (ptr)((char*)block + size_to_alloc); group->block_mem_left = (char *) group->block_end_ptr - /**/ (char *) group->block_ptr; /* make sure block_ptr is 8 bit aligned. (Note under valgrind on linux, ** malloc sometimes returns non 8-byte aligned segments.) */ if ((unsigned long)group->block_ptr & 0x7) { group->block_ptr = (ptr) ((char *)group->block_ptr + 4); group->block_mem_left -= 4; block->leftover += 4; } wn_assert(!((unsigned long)group->block_ptr & 0x7)); wn_assert(!((unsigned long)group->block_end_ptr & 0x3)); wn_assert(group->block_mem_left >= size_to_get); } /* get_more_memory */ local void fill_pad(pad_type pad,wn_memgp group) { pad->begin_magic = PAD_BEGIN_MAGIC; pad->end_magic = PAD_END_MAGIC; pad->next = (pad_type)(group->pad_list); group->pad_list = (ptr)pad; } local ptr alloc_piece(int size,wn_memgp group) { int old_size; ptr ret; old_size = size; if(wn_gp_pad_flag) { size += sizeof(union pad_type_8aligned_union); } if(size >= group->block_mem_left) { get_more_memory(size,group); } if (size & 0x7) /* 4-aligned -- get from end */ { group->block_end_ptr = (ptr) ((char *)group->block_end_ptr - size); ret = group->block_end_ptr; } else /* 8-aligned -- get from start */ { ret = group->block_ptr; group->block_ptr = (ptr) ((char *)group->block_ptr + size); } group->block_mem_left -= size; group->mem_used += old_size; if(wn_gp_pad_flag) { fill_pad((pad_type)((char *)ret + old_size), group); } if(wn_gp_trap_address_flag) { if(ret == wn_gp_trap_address_address) { fprintf(stderr,"address found.\n"); wn_assert_notreached(); } } wn_assert(!(((long unsigned) ret) & 3)); wn_assert( (((long unsigned) size) & 7) || !(((long unsigned) ret) & 7)); return(ret); } /* alloc_piece */ /*ARGSUSED*/ local void free_piece(ptr p,wn_memgp group) { } local void verify_pad(pad_type pad) { wn_assert(pad->begin_magic == PAD_BEGIN_MAGIC); wn_assert(pad->end_magic == PAD_END_MAGIC); } local void verify_pad_list(pad_type pad_list) { pad_type pad; for(pad=pad_list;pad != NULL;pad=pad->next) { verify_pad(pad); } } local void verify_group(wn_memgp group) { if (group->current_block) { wn_assert(group->block_mem_left >= 0); wn_assert(group->block_mem_left == (char *) group->block_end_ptr - /**/ (char *) group->block_ptr); } wn_assert(*group->plast == group); wn_assert(group->mem_used >= 0); if(wn_gp_pad_flag) { verify_pad_list((pad_type)(group->pad_list)); } } void wn_initialize_group_for_no_free(wn_memgp group) { group->pverify_group = (verify_group); group->pfree_piece = (free_piece); group->palloc_piece = (alloc_piece); }