text:
Q: SyntaxError: Unexpected end of JSON input when trying to query transaction details from the hyperledger 2.2 I am trying to run a rewards example on .hyperledger 2.2. The contract is successfully packaged and deployed. I was also able to run the application successfully and enroll admin and user.
Chaincode successfully deployed :
Committed chaincode definition for chaincode 'customerloyalty' on channel 'mychannel':
Version: 1.0, Sequence: 1, Endorsement Plugin: escc, Validation Plugin: vscc, Approvals: [Org1MSP: true, Org2MSP: true]
Query chaincode definition successful on peer0.org2 on channel 'mychannel'

Enroll admin successfully :

Wallet path: ../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet
Successfully enrolled admin user "admin" and imported it into the wallet

was able to successfully register user :
app running on port: 8000
Using param - firstname: Test lastname: User email: test@example.com phonenumber: 111-111-1111 accountNumber: 123456 cardId: 123
Valid Entries
Wallet path: ../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet
Successfully registered and enrolled admin user 123 and imported it into the wallet
admin user admin disconnected

Submit Create Member transaction.
createMemberResponse:
{
  accountNumber: '123456',
  firstName: 'Test',
  lastName: 'User',
  email: 'test@example.com',
  phoneNumber: '111-111-1111',
  points: 0
}

Get member state
memberResponse.parse_response:
{
  accountNumber: '123456',
  firstName: 'Test',
  lastName: 'User',
  email: 'test@example.com',
  phoneNumber: '111-111-1111',
  points: 0
}
memberData using param -  accountNumber: 123456 cardId: 123
Wallet path: ../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet

Get member state
{
  accountNumber: '123456',
  firstName: 'Test',
  lastName: 'User',
  email: 'test@example.com',
  phoneNumber: '111-111-1111',
  points: 0
}
Wallet path: ../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet

However, when I try to get transaction information in the app I get the following error with no response from peers :
Get use points transactions state for member 123456
2023-01-05T21:28:46.042Z - error: [Transaction]: Error: No valid responses from any peers. Errors:
    peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    at newEndorsementError (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12)
    at getResponsePayload (/../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23)
    at Transaction.submit (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:255:28)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.usePointsTransactionsInfo (../fabric-samples/asset-transfer-basic/application-customerloyalty/network/network.js:592:41)
Error: No valid responses from any peers. Errors:
    peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    at newEndorsementError (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12)
    at getResponsePayload (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23)
    at Transaction.submit (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:255:28)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.usePointsTransactionsInfo (../fabric-samples/asset-transfer-basic/application-customerloyalty/network/network.js:592:41) {
  responses: [
    {
      version: 0,
      timestamp: null,
      response: [Object],
      payload: <Buffer >,
      endorsement: null,
      connection: [Object],
      peer: 'peer0.org1.example.com:7051'
    },
    {
      version: 0,
      timestamp: null,
      response: [Object],
      payload: <Buffer >,
      endorsement: null,
      connection: [Object],
      peer: 'peer0.org2.example.com:9051'
    }
  ],
  errors: []
}
Wallet path: ../fabric-samples/asset-transfer-basic/application-customerloyalty/wallet

Get earn points transactions state for member 123456
2023-01-05T21:28:46.192Z - error: [Transaction]: Error: No valid responses from any peers. Errors:
    peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    at newEndorsementError (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12)
    at getResponsePayload (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23)
    at Transaction.submit (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:255:28)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.earnPointsTransactionsInfo (../fabric-samples/asset-transfer-basic/application-customerloyalty/network/network.js:545:25)
Error: No valid responses from any peers. Errors:
    peer=peer0.org1.example.com:7051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    peer=peer0.org2.example.com:9051, status=500, message=error in simulation: transaction returned with failure: SyntaxError: Unexpected end of JSON input
    at newEndorsementError (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:74:12)
    at getResponsePayload (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:41:23)
    at Transaction.submit (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/fabric-network/lib/transaction.js:255:28)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.earnPointsTransactionsInfo (../fabric-samples/asset-transfer-basic/application-customerloyalty/network/network.js:545:25) {
  responses: [
    {
      version: 0,
      timestamp: null,
      response: [Object],
      payload: <Buffer >,
      endorsement: null,
      connection: [Object],
      peer: 'peer0.org1.example.com:7051'
    },
    {
      version: 0,
      timestamp: null,
      response: [Object],
      payload: <Buffer >,
      endorsement: null,
      connection: [Object],
      peer: 'peer0.org2.example.com:9051'
    }
  ],
  errors: []
}
node:internal/errors:484
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:393:5)
    at ServerResponse.setHeader (node:_http_outgoing:644:11)
    at ServerResponse.header (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (../fabric-samples/asset-transfer-basic/application-customerloyalty/node_modules/express/lib/response.js:278:15)
    at ../fabric-samples/asset-transfer-basic/application-customerloyalty/app.js:278:37
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

the above log indicates that json syntax is not correct in network.js file both invoking submitTransaction function. excerpt from Network.js file is :
  /*
  * Get all EarnPoints transactions data
  * @param {String} cardId Card id to connect to network
  */
    earnPointsTransactionsInfo: async function (cardId, userType, userId) {

        // Create a new file system based wallet for managing identities.
        const walletPath = path.join(process.cwd(), '/wallet');
        const wallet = await Wallets.newFileSystemWallet(walletPath);
        console.log(`Wallet path: ${walletPath}`);

        try {
            // Create a new gateway for connecting to our peer node.
            const gateway2 = new Gateway();
            await gateway2.connect(ccp, { wallet, identity: cardId, discovery: gatewayDiscovery });

            // Get the network (channel) our contract is deployed to.
            const network = await gateway2.getNetwork('mychannel');

            // Get the contract from the network.
            const contract = network.getContract('customerloyalty');

            console.log(`\nGet earn points transactions state for ${userType} ${userId}`);
            //for debug only
            console.log(await contract.submitTransaction('EarnPointsTransactionsInfo', 'userType', 'userId'));
            //
            let earnPointsTransactions = await contract.submitTransaction('EarnPointsTransactionsInfo', userType, userId);
            //for debug only
            console.log(await contract.submitTransaction('EarnPointsTransactionsInfo', userType, userId));
            //
            earnPointsTransactions = JSON.parse(earnPointsTransactions.toString());
            console.log(earnPointsTransactions);

            // Disconnect from the gateway.
            await gateway2.disconnect();

            return earnPointsTransactions;
        }
        catch(err) {
            //print and return error
            console.log(err);
            let error = {};
            error.error = err.message;
            return error;
        }

    },

    usePointsTransactionsInfo: async function (cardId, userType, userId) {

        // Create a new file system based wallet for managing identities.
        const walletPath = path.join(process.cwd(), '/wallet');
        const wallet = await Wallets.newFileSystemWallet(walletPath);
        console.log(`Wallet path: ${walletPath}`);

        try {
            // Create a new gateway for connecting to our peer node.
            const gateway2 = new Gateway();
            await gateway2.connect(ccp, { wallet, identity: cardId, discovery: gatewayDiscovery });

            // Get the network (channel) our contract is deployed to.
            const network = await gateway2.getNetwork('mychannel');

            // Get the contract from the network.
            const contract = network.getContract('customerloyalty');

            console.log(`\nGet use points transactions state for ${userType} ${userId}`);
            let usePointsTransactions = await contract.submitTransaction('UsePointsTransactionsInfo',userType, userId);
            usePointsTransactions = JSON.parse(usePointsTransactions.toString());
            console.log(usePointsTransactions);

            // Disconnect from the gateway.
            await gateway2.disconnect();

            return usePointsTransactions;
        }

I have tried to check logs from the peer using docker logs <container name> :
2023-01-05 22:28:46 2023-01-05T21:28:46.023Z error [c-api:contracts-spi/chaincodefromcontract.js]     [mychannel-fedc897c] SyntaxError: Unexpected end of JSON input
2023-01-05 22:28:46 2023-01-05T21:28:46.033Z error [c-api:lib/handler.js]                             [mychannel-fedc897c] Calling chaincode Invoke() returned error response [SyntaxError: Unexpected end of JSON input
2023-01-05 22:28:46     at JSON.parse (<anonymous>)
2023-01-05 22:28:46     at CustomerLoyalty.UsePointsTransactionsInfo (/usr/local/src/lib/customerloyalty.js:110:29)
2023-01-05 22:28:46     at processTicksAndRejections (node:internal/process/task_queues:96:5)
2023-01-05 22:28:46     at async ChaincodeFromContract.invokeFunctionality (/usr/local/src/node_modules/fabric-shim/lib/contract-spi/chaincodefromcontract.js:378:32)
2023-01-05 22:28:46     at async handleMessage (/usr/local/src/node_modules/fabric-shim/lib/handler.js:602:24)]. Sending ERROR message back to peer
2023-01-05 22:28:46 2023-01-05T21:28:46.181Z error [c-api:contracts-spi/chaincodefromcontract.js]     [mychannel-644303c3] SyntaxError: Unexpected end of JSON input
2023-01-05 22:28:46 2023-01-05T21:28:46.184Z error [c-api:lib/handler.js]                             [mychannel-644303c3] Calling chaincode Invoke() returned error response [SyntaxError: Unexpected end of JSON input
2023-01-05 22:28:46     at JSON.parse (<anonymous>)
2023-01-05 22:28:46     at CustomerLoyalty.EarnPointsTransactionsInfo (/usr/local/src/lib/customerloyalty.js:89:29)
2023-01-05 22:28:46     at processTicksAndRejections (node:internal/process/task_queues:96:5)
2023-01-05 22:28:46     at async ChaincodeFromContract.invokeFunctionality (/usr/local/src/node_modules/fabric-shim/lib/contract-spi/chaincodefromcontract.js:378:32)
2023-01-05 22:28:46     at async handleMessage (/usr/local/src/node_modules/fabric-shim/lib/handler.js:602:24)]. Sending ERROR message back to peer
2023-01-05 22:32:51 2023-01-05T21:32:51.616Z info [c-api:lib/handler.js]                              [mychannel-68bdfcd2] Calling chaincode Invoke() succeeded. Sending COMPLETED message back to peer
2023-01-05 22:32:53 2023-01-05T21:32:53.977Z error [c-api:contracts-spi/chaincodefromcontract.js]     [mychannel-7f185a49] SyntaxError: Unexpected end of JSON input
2023-01-05 22:32:53 2023-01-05T21:32:53.989Z error [c-api:lib/handler.js]                             [mychannel-7f185a49] Calling chaincode Invoke() returned error response [SyntaxError: Unexpected end of JSON input
2023-01-05 22:32:53     at JSON.parse (<anonymous>)
2023-01-05 22:32:53     at CustomerLoyalty.UsePointsTransactionsInfo (/usr/local/src/lib/customerloyalty.js:110:29)
2023-01-05 22:32:53     at processTicksAndRejections (node:internal/process/task_queues:96:5)
2023-01-05 22:32:53     at async ChaincodeFromContract.invokeFunctionality (/usr/local/src/node_modules/fabric-shim/lib/contract-spi/chaincodefromcontract.js:378:32)
2023-01-05 22:32:53     at async handleMessage (/usr/local/src/node_modules/fabric-shim/lib/handler.js:602:24)]. Sending ERROR message back to peer
2023-01-05 22:32:54 2023-01-05T21:32:54.195Z error [c-api:contracts-spi/chaincodefromcontract.js]     [mychannel-44d04ba9] SyntaxError: Unexpected end of JSON input
2023-01-05 22:32:54 2023-01-05T21:32:54.197Z error [c-api:lib/handler.js]                             [mychannel-44d04ba9] Calling chaincode Invoke() returned error response [SyntaxError: Unexpected end of JSON input
2023-01-05 22:32:54     at JSON.parse (<anonymous>)
2023-01-05 22:32:54     at CustomerLoyalty.EarnPointsTransactionsInfo (/usr/local/src/lib/customerloyalty.js:89:29)
2023-01-05 22:32:54     at processTicksAndRejections (node:internal/process/task_queues:96:5)
2023-01-05 22:32:54     at async ChaincodeFromContract.invokeFunctionality (/usr/local/src/node_modules/fabric-shim/lib/contract-spi/chaincodefromcontract.js:378:32)
2023-01-05 22:32:54     at async handleMessage (/usr/local/src/node_modules/fabric-shim/lib/handler.js:602:24)]. Sending ERROR message back to peer

Here is the smart contract script customerloyalty.js :
'use strict';

const { Contract } = require('fabric-contract-api'); const allPartnersKey = 'all-partners'; const earnPointsTransactionsKey = 'earn-points-transactions'; const usePointsTransactionsKey = 'use-points-transactions';

class CustomerLoyalty extends Contract {
// Init function executed when the ledger is instantiated
async instantiate(ctx) {
    console.info('============= START : Initialize Ledger ===========');

    await ctx.stub.putState('instantiate', Buffer.from('INIT-LEDGER'));
    await ctx.stub.putState(allPartnersKey, Buffer.from(JSON.stringify([])));
    await ctx.stub.putState(earnPointsTransactionsKey, Buffer.from(JSON.stringify([])));
    await ctx.stub.putState(usePointsTransactionsKey, Buffer.from(JSON.stringify([])));

    console.info('============= END : Initialize Ledger ===========');
}

// Add a member on the ledger
async CreateMember(ctx, member) {
    member = JSON.parse(member);

    await ctx.stub.putState(member.accountNumber, Buffer.from(JSON.stringify(member)));

    return JSON.stringify(member);
}

// Add a partner on the ledger, and add it to the all-partners list
async CreatePartner(ctx, partner) {
    partner = JSON.parse(partner);

    await ctx.stub.putState(partner.id, Buffer.from(JSON.stringify(partner)));

    let allPartners = await ctx.stub.getState(allPartnersKey);
    allPartners = JSON.parse(allPartners);
    allPartners.push(partner);
    await ctx.stub.putState(allPartnersKey, Buffer.from(JSON.stringify(allPartners)));

    return JSON.stringify(partner);
}

// Record a transaction where a member earns points
async EarnPoints(ctx, earnPoints) {
    earnPoints = JSON.parse(earnPoints);
    earnPoints.timestamp = new Date((ctx.stub.txTimestamp.seconds.low*1000)).toGMTString();
    earnPoints.transactionId = ctx.stub.txId;

    let member = await ctx.stub.getState(earnPoints.member);
    member = JSON.parse(member);
    member.points += earnPoints.points;
    await ctx.stub.putState(earnPoints.member, Buffer.from(JSON.stringify(member)));

    let earnPointsTransactions = await ctx.stub.getState(earnPointsTransactionsKey);
    earnPointsTransactions = JSON.parse(earnPointsTransactions);
    earnPointsTransactions.push(earnPoints);
    await ctx.stub.putState(earnPointsTransactionsKey, Buffer.from(JSON.stringify(earnPointsTransactions)));

    return JSON.stringify(earnPoints);
}

// Record a transaction where a member redeems points
async UsePoints(ctx, usePoints) {
    usePoints = JSON.parse(usePoints);
    usePoints.timestamp = new Date((ctx.stub.txTimestamp.seconds.low*1000)).toGMTString();
    usePoints.transactionId = ctx.stub.txId;

    let member = await ctx.stub.getState(usePoints.member);
    member = JSON.parse(member);
    if (member.points < usePoints.points) {
        throw new Error('Member does not have sufficient points');
    }
    member.points -= usePoints.points;
    await ctx.stub.putState(usePoints.member, Buffer.from(JSON.stringify(member)));

    let usePointsTransactions = await ctx.stub.getState(usePointsTransactionsKey);
    usePointsTransactions = JSON.parse(usePointsTransactions);
    usePointsTransactions.push(usePoints);
    await ctx.stub.putState(usePointsTransactionsKey, Buffer.from(JSON.stringify(usePointsTransactions)));

    return JSON.stringify(usePoints);
}

// Get earn points transactions of the particular member or partner
async EarnPointsTransactionsInfo(ctx, userType, userId) {
    let transactions = await ctx.stub.getState(earnPointsTransactionsKey);
    transactions = JSON.parse(transactions);
    let userTransactions = [];

    for (let transaction of transactions) {
        if (userType === 'member') {
            if (transaction.member === userId) {
                userTransactions.push(transaction);
            }
        } else if (userType === 'partner') {
            if (transaction.partner === userId) {
                userTransactions.push(transaction);
            }
        }
    }

    return JSON.stringify(userTransactions);
}

// Get use points transactions of the particular member or partner
async UsePointsTransactionsInfo(ctx, userType, userId) {
    let transactions = await ctx.stub.getState(usePointsTransactionsKey);
    transactions = JSON.parse(transactions);
    let userTransactions = [];

    for (let transaction of transactions) {
        if (userType === 'member') {
            if (transaction.member === userId) {
                userTransactions.push(transaction);
            }
        } else if (userType === 'partner') {
            if (transaction.partner === userId) {
                userTransactions.push(transaction);
            }
        }
    }

    return JSON.stringify(userTransactions);
}

// get the state from key
async GetState(ctx, key) {
    let data = await ctx.stub.getState(key);

    let jsonData = JSON.parse(data.toString());
    return JSON.stringify(jsonData);
}

module.exports = CustomerLoyalty;`

it seems that there is an syntax error with json.stringify. I don't know what to do next, or how to solve this. Any ideas?

A: I suspect that you have never invoked your instantiate transaction function and so the earnPointsTransactionsKey ledger key contains no data:
% node --eval="JSON.parse(Buffer.from(''))"

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)

Rather than relying on an initialize transaction to set effectively empty initial state, you might consider a helper function in your smart contract, something like this:
async getEarnPointsTransactions(ctx) {
    const data = await ctx.stub.getState(earnPointsTransactionsKey);
    if (!data || data.length === 0) {
        return [];
    }

    return JSON.parse(data);
}

Also consider that all of your transactions that update the ledger are modifying the value of the earnPointsTransactionsKey ledger key. This is going to introduce contention as load increases and you are likely to experience MVCC_READ_CONFLICT failures as transactions concurrently update this state. These failures can be mitigated by implementing submit retry logic in your client application. You might consider different implementation approaches, such as:

*

*using composite keys to partition the data.

*using key history to read data associated with previous transactions.

A: This error message is indicating that the headers for an HTTP response have already been sent to the client and cannot be modified. This typically occurs when a response has already been sent to the client and an attempt is made to send another response. The specific location in the code where this error is being thrown is at "ServerResponse.header" in the "response.js" file in the "express" library, and the specific function that is causing the issue is "register" in "UserController.js" at line 60.


text:
Q: Cross-browser word-break - doesn't work in Opera 12 I have this css class for word-break in long texts without spaces.
    .wrapword{
        white-space: -moz-pre-wrap !important;  /* Mozilla, since 1999 */
        white-space: -o-pre-wrap;    /* Opera 7 */
        white-space: pre-wrap;       /* css-3 */
        word-wrap: break-word;       /* Internet Explorer 5.5+ */
        word-break: break-all;
        white-space: normal;
    }

Works for firefix 27, chrome 33, IE 10 and midori 0.43, but not for opera 12.
Any suggestions. I am not a css ninja ...

A: As of Opera 13 your CSS works, see http://caniuse.com/word-break. But there is no support for this rule in Opera 12.
The better solution would be hypenation. But this works even less via CSS, see http://caniuse.com/css-hyphens.
So my best guess: You may want to use Javascript like https://code.google.com/p/hyphenator/ to add hyphens to your text.

redpajama_set_name: RedPajamaStackExchange


text:
Q: NSPanel loses focus although being modal I have a strange problem with one of my NSPanels. Starting up my application, I use a simple panel with only an NSTextField and an NSButton to get the player's name. Working on some other stuff on my application, all of a sudden the panel does not get focused any longer when starting the app. The button does work, though, but the text field refuses to be focused and take any input.
Any ideas are appreciated.
Cheers,
Living

A: I found the solution myself, shame on me.
For the NSPanel, I had deselected "Title Bar" in the Appearance section of the Attribute Inspector. Unchecked, the panel does not have a title bar and thus cannot get the focus.
Checking it again, everything works as expected :-)


text:
Q: IBM connections API update event I'm trying to update event created in community.
Here is the atom xml I send to the server:
<?xml version="1.0" encoding="UTF-8"?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns:snx="http://www.ibm.com/xmlns/prod/sn" xmlns:thr="http://purl.org/syndication/thread/1.0">
   <id>urn:lsid:ibm.com:calendar:event:0eff8fdf-4e5c-48be-be9b-ff700b274576</id>
   <snx:eventInstUuid>0eff8fdf-4e5c-48be-be9b-ff700b274576</snx:eventInstUuid>
   <title type="text">Test event</title>
   <snx:location>Event location</snx:location>
   <snx:startDate>2015-10-22T14:00:00.000+03</snx:startDate>
   <snx:endDate>2015-10-22T15:00:00.000+03</snx:endDate>
   <snx:allday>0</snx:allday>
   <category scheme="http://www.ibm.com/xmlns/prod/sn/type" term="event-instance"/>
   <content type="html">Event description</content>
</entry>

The problem is it updates all fields that allow update. But startDate and endDate are updated as there is no timezone offset info. It means if I set startDate to 14:00, it actually sets time to 14:00 minus 3 hours.
What I'm doing wrong?

A: the connections code can parse the '+03' only if you write it as '+03:00' (the timezone, unless you set it to 'Z' for UTC) needs to have 6 characters)


text:
Q: Find streak in a row in Excel I have thousands of rows in Excel. In six columns I have percentage values.
For example: [68%][92%][72%][109%][55%][86%]
In these rows I would like to find the longest streak, from the RIGHT, of values that are below or higher than 100%
[68%][92%][72%][109%][55%][86%]     Streak is 2 below 100% -> Below 2
[62%][101%][43%][65%][78%][111%]   Streak is 1 above 100% -> Above 1
[89%][108%][55%][114%][111%][120%] Streak is 3 above 100% -> Above 3
[---][---][---][---][147%][154%]        Streak is 2 above 100% -> Above 2
[---][---][---][---][---][45%]        Streak is 1 below 100% -> Below 1
[116%][58%][89%][66%][33%][74%]     Streak is 5 below 100% -> Below 5
Didn't quite find what I was looking for in "Calculate current streak in Excel row"
Calculate current streak in Excel row
COUNTIF($KJ2341:$KO2341;"<1")
This gives me the total number that are below 1 but I only look for streak from right.
Can you help please?

A: I assumed you want to group any that are exactly 100% with the above group. If that is not the case, please specifically state how you want that handled.
Here is one method, assuming the sixth column always has the defining entry:
Note that if your data starts in columns other than A, modification to the formula may be required
Edit: Formula changed to handle partially filled rows
=IF(F1>=1,"Above ","Below ") &  IFERROR(COLUMNS($A:$F)- LOOKUP(2,1/IF(F1>=1,A1:F1<1,A1:F1>=1),COLUMN($A:$F)),COUNT(A1:F1))

If the sixth column is not always the last entry, formula solution still possible; but easier if you have Office 365.

*

*F1 > 1 determines if we are looking for a streak of aboves or belows

*A1:F1>1 (or <=1) creates an array of appropriate {TRUE,FALSE} depending on meeting the condition.

*1/(the array) changes it to an array of {1,DIV/O}

*LOOKUP(2,the_array,array of column_numbers) returns the column number matching the last TRUE in the original array we set up.

*Then it's just simple subtraction, with an IFERROR to handle the situation where there is only a single entry in the streak.

*If the formula returns an error, then it will be the case that all entries are the same (or blank); so we can just use a slightly different formula in the event of an error.


text:
Q: High Charts Dynamic Series I was trying to implement High Charts.
But Series is dynamic.
$(function () {
$('#container').highcharts({
    chart: {
        type: 'column'
    },
    title: {
        text: 'Monthly Average Rainfall'
    },
    subtitle: {
        text: 'Source: WorldClimate.com'
    },
    xAxis: {
        categories: [
            'Jan',
            'Feb',
            'Mar',
            'Apr',
            'May',
            'Jun',
            'Jul',
            'Aug',
            'Sep',
            'Oct',
            'Nov',
            'Dec'
        ],
        crosshair: true
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Rainfall (mm)'
        }
    },
    tooltip: {
        headerFormat: '{point.key}
',
        pointFormat: '
{series.name}: 	' +
            '{point.y:.1f} mm
',
        footerFormat: '
',
        shared: true,
        useHTML: true
    },
    plotOptions: {
        column: {
            pointPadding: 0.2,
            borderWidth: 0
        }
    },
    series: [{
        name: 'Tokyo',
        data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]

    }, {
        name: 'New York',
        data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3]

    }, {
        name: 'London',
        data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2]

    }, {
        name: 'Berlin',
        data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1]

    }]
});
});

What if the Series is completely dynamic and Tokyo,New York,London,Berlin
is a part of list
How can I iterate and add the series name and data dynamically.


text:
Q: compact convex problem Would you please help me in how to show that:
If $T : X \to Y$ is a continuous linear map between two locally convex spaces and $K \subset X$ is compact convex, then:

*

*The continuous image of compact convex space is a compact convex.

*If $y$ ia an extreme point of $T(K)$,  then $\exists$  $x \in X$ an extreme in $K$ such that $Tx =y$
Thank you,
Saba

A: The first point is obvious:

*

*Compactness is preserved by continuous maps so $T(K)$ is compact.

*Convexity is preserved by linear maps, so $T(K)$ is convex.

As for the second point, we need to know a bit more, I think.
First of all, I assume that your definition of locally convex includes Hausdorff, otherwise there are silly counterexamples (see right at the end of the answer).
The idea is the following: If $y \in T(K)$ is extremal then $F = \{x \in K\,:\,T(x) = y\}$ is a face of $K$ and by the Kreĭn-Mil'mans theorem every face contains an extremal point. If you know what a face is and just want to see see why $F$ is a face, you can ignore the next section and jump right to the claim afterwards.
Also, I overlooked the homework tag, so maybe I shouldn't have given all away below, stop reading now if you want to think for yourself.

Let me elaborate on this:
Recall that a face $F$ of a convex set $K$ is a non-empty and closed subset of $K$ with the following property: If $x,y \in K$ are any points for which there is $0 \lt \alpha \lt 1$ such that $(1-\alpha)x + \alpha y \in F$ then we must have $x,y \in F$ already. (Think of the faces of a cube, for example).
Let me sketch the proof of Kreĭn-Mil'man's theorem which states:

If $K$ is a compact convex set in a locally convex space, then it is the closed convex hulls of its extremal points.

Proof:

*

*For $x \in K$ the set $\{x\}$ is a face if and only if $x$ is extremal.

*If $\phi: X \to \mathbb{R}$ is a continuous linear functional and $F \subset K$ is a face, then $\{x \in F\,:\,\phi(x) \text{ is minimal}\}$ is a face again.

*Order the faces of $K$ by reverse inclusion. The intersection of a chain of faces is a face, thus every face contains a minimal face by Zorn's lemma.

*Combine 2. and Hahn-Banach to see that a minimal face cannot contain more than one point.

Taking 3. and 4. together we see that we have proved what we need for solving the exercise.

Every face of a compact convex set contains an extremal point.

Since it would be a pity to stop here, let me finish the argument for Kreĭn-Mil'man:
Since $K$ is a face of itself, there is at least one extremal point. If the closed convex hull $C$ of the extremal points were not all of $K$ then there were a point $z$ and a continuous linar functional $\phi$ such that $\phi(z) \lt \phi(c)$ for all $c \in C$. But by applying 2. to $\phi$ we find a face disjoint from all extremal points, a contradiction.

Claim: If $y \in T(K)$ is extremal, then $F = \{x \in K\,:\,T(x) = y\}$ is a face.

In particular, $F$ contains an extremal point by what I just said.
Proof of the claim: Obviously, $F$ is closed and non-empty. If $F$ were not a face, there would be $x_0,x_1 \in K \smallsetminus F$ and $0 \lt \alpha \lt 1$ such that $(1-\alpha)x_{0} + \alpha x_1 \in F$, so $(1-\alpha) T(x_0) + \alpha T(x_1) = y$, but $T(x_{0}) \neq y \neq T(x_1)$, so $y$ is not extremal, a contradiction.

To see that we need to assume at least that $X$ is Hausdorff, let $X = \mathbb{R}^2$ with the semi-norm $|(x,y)| = |x|$ and let $Y = \mathbb{R}$ with the usual topology. Let $T: X \to \mathbb{R}$ be projection on the first coordinate, $T(x,y) = x$. This map is continuous and obviously the $y$-axis $K$ in $X$ is compact and convex and contains no extremal point. However, $T(K) = \{0\}$ and the point $\{0\}$ is extremal. By construction there is no extremal point in $K$ contradicting the exercise.

A: I think you will find this easier if you recall that "convex" can be defined in terms of inequalities and that the linear map will preserve those features.


text:
Q: How to load a ramdisk now? latest kernels have made ramdisk modules:
CONFIG_BLK_DEV_RAM=m
Which is the module and where to find it.
Is loadable during boot from initramfs ?
I had root on software RAID1 with SSD and Ramdisk (/dev/ram1)
with write-mostly on SSD.
CONFIG_BLK_DEV_RAM in original kernel is boolean, now is module ?!?!
Any rationale for this change ?
Thank You

A: The block ramdisk module is called brd and can be loaded as follows:
sudo modprobe brd rd_size=100000

where rd_size is the number of blocks. After this step you have a device /dev/ram0 that you can put a filesystem on:
sudo mkfs /dev/ram0

and mount.

A: Another option for a RAM Disks is zram. When you place a file onto a zram RAM disk, the file gets quickly compressed during the transfer and it is transparently decompress during the retrieval. This can be helpful in circumstances where your system doesn't quite have the amount of RAM you desire for your RAM disk.
Here's how to create a zram RAM disk:
Make a folder to which you will mount your RAM disk:
sudo mkdir /tmp/ramdisk

Change the ownership of that folder, so your user will have full access to the RAM disk when we later mount it:
sudo chown -R yourUserName:yourGroupName /tmp/ramdisk

Make the folder immutable so you don't ever accidentally fill up your  OS partition with data intended for the RAM disk:
sudo chattr +i /tmp/ramdisk

Load the zram module:
sudo modprobe zram

Create a 1GB ram disk:
sudo zramctl --find --size 1G

The command above will output the device path of the RAM disk you've created. It will most likely be /dev/zram0, and that's what we'll assume going forward.
Format the RAM disk to EXT4:
sudo mke2fs -t ext4 -O ^has_journal -L "zram device" /dev/zram0

Mount the RAM disk to the immutable mount point folder we created:
sudo mount /dev/zram0 /tmp/ramdisk

Now you should be able to move files to and from the RAM disk located at /tmp/ramdisk/.
If you're done playing with it, unmount it:
sudo umount /tmp/ramdisk/

Lastly, lets destroy the RAM disk and free up any memory it was using:
sudo zramctl --reset /dev/zram0

If you also want to remove the the folder /tmp/ramdisk, first make it mutable:
sudo chattr -i /tmp/ramdisk

Now you can delete the folder:
rm -rf /tmp/ramdisk


text:
Q: Typescript tsconfig to exclude some source files I am trying to get Typescript to exclude certain files when compiling. However it doesn't seem to want to exclude them.
Here is my tsconfig.json
{
  "ref": "master",
  "path": "typings",
  "compilerOptions": {
    "module": "amd",
    "target": "es5",
    "declaration": true,
    "sourceMap": true,
    "outDir": "build/src"
  },
  "exclude": [
    "node_modules",
    "typings/global",
    "typings/index.d.ts",
    "./src/subClassA.ts"
  ],
  "files": [
    "./src/entry.ts"
  ]
}

It seems to be excluding the node_modules and typings. However the compiled code, still includes subClassA.
I would have expected the compiled code to not have any of the code from subClassA, however it does.

A: From the documentation:

Any files that are referenced by files included via the "files" or
  "include" properties are also included. Similarly, if a file B.ts is
  referenced by another file A.ts, then B.ts cannot be excluded unless
  the referencing file A.ts is also specified in the "exclude" list.

If your ./src/entry.ts file or any dependency of ./src/entry.ts uses ./src/subClassA.ts somewhere, then ./src/subClassA.ts cannot be excluded unless ./src/entry.ts is excluded too.
Related discussion: https://github.com/Microsoft/TypeScript/issues/7432


text:
Q: API Websocket doesn't accept ws:// over http:// I have this ionic app, that has some pages which are dependent on websockets. And for some time it used the Stomp.over() thing to connect, but It started to give me tons of problems, so I found this @stomp/rx-stomp dependency, but this guy only accepts ws://localhost... as the websocket url... And my API simply won't work with the ws annotation... only http. Here's my WebSocket config on my spring api:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket-easy-marine").setAllowedOrigins("*").withSockJS().setWebSocketEnabled(true);
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker(new String[] { "/send-panel", "/sling-changed", "/wash-engine-changed", "/contract-changed", "/news", "/movement-changed" });
        registry.setApplicationDestinationPrefixes("/app");
    }

}

And in my pom.xml I'm using this guy:
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

Spring is running the 1.5.10.RELEASE version...


text:
Q: Not able to input any Excel formulas in BIP Excel Template I am trying to build a report using Oracle BI Publisher Excel Template. However, I also want use few excel formulas in that to enhance more functionalities. But I am unable to do that. When the report is getting executed, the formulas are getting lost. Any support would be well appreciated
I am trying to build a report using Oracle BI Publisher Excel Template. However, I also want use few excel formulas in that to enhance more functionalities. But I am unable to do that. When the report is getting executed, the formulas are getting lost. Any support would be well appreciated


text:
Q: Explanation of a lisp code I start studying Lisp and I find a code on the book as example but I do not understand what is it for. Are you able to help me understanding that? I don't know if it is the right place to do it. Thanks everyone
(defun compress (l1)
  (cond ((null (cdr l1)) '())
        (t (accumula (car l1) 1 (cdr l1)))))

(defun accumula (val acc lst)
  (cond ((null lst) (cons (comp-list val acc) nil))
        ((eq val (car lst)) (accumula val (1+ acc) (cdr lst)))
        (t (cons (comp-list val acc) (accumula (car lst) 1 (cdr lst))))))

(defun comp-list (val acc)
  (if (> acc 1) (list acc val) val))

A: It's a compression function, of the Run Length Encoding variety.
(compress '(3 3 4 3 3 2 1 1 1 1 0))

will yield
((2 3) 4 (2 3) 2 (4 1) 0)

where the first number in each sublist is the number of times the second number repeats in the original sequence.
It doesn't look like much from the example, but for long sequences where numbers repeat a lot, you can get significant savings in storage costs.

A: This is an answer to problem 13 in The 99 Lisp problems (L99). It has a bug:
(compress '(a))
; ==> nil

The correct result would have been (a).


text:
Q: Request Wait Time is steady in IIS (ASP.NET) I'm monitoring my application health in SolarWinds, the strange thing I'm noticing that the Request Wait Time Counter is steady. It is not changing for quite a few hours even though there are no requests in the queue and also the Requests/Sec is not that much. Is there any specific reason for the same? What can be the possible reason?

A: Request Wait Time
The number of milliseconds that the most recent request waited in the queue for processing.
https://msdn.microsoft.com/en-us/library/fxk122b4.aspx
In other words: This value should remain the same until IIS processes another request.
Credit: https://serverfault.com/a/579180


text:
Q: Is the result $|\text{rank(AB)}-\text{rank(BA)}| \le \text{min}(\text{rank}(A),\text{rank}(B))$ Is the result $|\text{rank(AB)}-\text{rank(BA)}| \le \text{min}(\text{rank}(A),\text{rank}(B))$ true for all $n*n$ matrices $A,B$.
I only know the result that $\text{rank(AB)} \le \text{min(rank(A),rank(B))}$

A: Yes. Your desired inequality is a consequence of the one you mentioned. In other words, it follows from the fact that the ranks of both $AB$ and $BA$ are non-negative integers at most equal to that minimum.


text:
Q: NSTimer After User Leaves App I am creating an iOS app in Objective C. I don't want to pay for a server, but I want to create a reward system so that every 3 hours the user is rewarded with "coins" when they enter the app. For example, if a user exits the app at 1pm and re-enters the app at 5pm, a reward will be ready. However I want this to carry over even if the app is not running in the background.
Is this possible?

A: Maybe not a timer here, but save users' exit time through NSUserDefaults, and then whenever users re-enter the app, compare the exit time with the current time to see if the gap is 3 hours.
For example, in viewWillDisappear()
You might save the exit time through:
NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: "exitTime")

And in viewDidLoad(), you could extract the exit time through
NSUserDefaults.standardUserDefaults().objectForKey("exitTime")

A: In your AppDelegate , you can save exit date time to NSUserDefaults
when below function did called

func applicationWillTerminate(application: UIApplication)
func applicationDidEnterBackground(application: UIApplication)

when user enter foreground, you can compare exit time with current time and give some coins
but this way have some problem
if user edited iPhone's date or time in setting , can get a log of coins
but if you use server , you can compare date correctly
there are some idea to solve this problem without server
how about save current time or date periodically ?
this is usecase

*

*user edit iphone's time to 3 hour after

*user enter app

*user get coins

*user edit iphone's time to 3 hour before

*user lose coins and some item

if currentdate is earlier then saved currentdate then you have to take coins because that is invalid coins
how about my idea?


text:
Q: Getting user behavior on the Android Phone (App History, Browse History etc) Is it possible to get the user behavior on the phone (for example Alpesh has an Android phone and he uses multiple apps, browser YouTube etc). Whatever he is doing on the phone I want to get all those things from behind (which apps he has installed, which app he opens and what he search on the phone, All these data I want to get programmatically so what all can be get in android).
For now I am aware that installed apps list can be get easily but I want to get usage history and what he do all on mobile.

A: This is not a code solution, but an answer to your question, so you can get start some where.
In my opinion your question title are asking about two things.

(part 1) Getting User Behavior on the Android Phone (part 2)(App History, Browse
  History etc)

1- First part Getting User Behavior on the Android Phone:
There is a concept called context awareness. Short described; it is about gathering different information from the phone, like light sensor, motion sensor, sound, location or even user behavior etc. and depending on your app requirement and the gathered information:

*

*You could send these information over cloud data store for statically usage

*You could make your phone doing (behavior) different things depending on location, motion or what ever.

*etc.

For context awareness it is an open area for pervasive computing research. And it is not just few lines of code to write, it is typically a complete solution depending on requirement. Example I have built a context awareness  application to gather noise collected by phones from different locations for research purpose inspired from this framework, but I am pretty sure you can find other frameworks or even build your own, as I did in my case.
The mentioned framework has some examples.
2- The second part is about App History, Browse History etc.:
This is possible, but you still need to build a peace of software (App) to collect all these information (logs) from the phone. Hereafter you can make phone act on different conditions and/or again send it over a RESTful API over cloud service data store, there is no limit for it.
The problem is, there is no thing out of the box for your requirement. Even if you find frameworks you still need to research it and further work on it.
You can find different examples for your requirement, like to collect browser history, you can find SO question here:
Get browser history and search result in android
Or get list of installed application:
How to get a list of installed android applications and pick one to run
My point here is you need to solve small goals at a time and put your knowledge together at the end.
Both 1 and 2 can also be related to each other, depending on your achievement.
Conclusion

*

*Make a goal to your project.

*Define the main requirements and tasks of your project.

*Research your options (Technology, Cost, Target Audience, What data I can or I should not collect, what is possible to collect, what is the limits, Privacy issues etc.).

*Split your project in small assets and try to solve small problems/goals.

*Finally you would be able to put the puzzles together and build your final application

A:
but i want to get usage history and what he do all on mobile

This is not possible and shouldn't ever be possible.  Each app is sandboxed by Android so apps cannot inspect what other apps are doing.  Think about it, you wouldn't want apps to be able to intercept private information such as banking details.

A: Every app is isolated from the other ones. Unless you develop a system signed app, you will not be able to gather all that data.
What you could do is to develop your own Android Rom where you then develop your data collection the exact way you want. Then you need to distribute your rom, which is another story...


text:
Q: How to efficiently save a large pandas.Dataframe with million even billion rows with no error? How to save a large Dataframe to disk with good reading speed?
I have a large datasets (youtube 8M), now I have extract the raw data to dict. And I want to save it as dataframe for reading by index with pytorch dataset.
For concrete, the validate data seems like this:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1112356 entries, 0 to 1112355
Data columns (total 4 columns):
id            1112356 non-null object
mean_rgb      1112356 non-null object
mean_audio    1112356 non-null object
label         1112356 non-null object
dtypes: object(4)
memory usage: 42.4+ MB

The dtypes is listed below:
id : str
mean_rgb : numpy.ndarray
mean_audio : numpy.ndarray
label :  numpy.ndarray

I want to save it to disk, for the purpose that I could efficiently read it.
First, I used the hdf5 with pd.to_hdf(), but I got an OverFlowError.
And then, I turn to csv with successful saving. However, when I read data from this .csv, I get a corrupt dataframe. Where the rows is greatly more than 1112356.
Finally, I saved the dataframe to csv with chunksize=1000, the reading result is still wrong with 2842137 rows as well as more confusing inner data.
RangeIndex: 2842137 entries, 0 to 2842136
Data columns (total 1 columns):
widwmean_rgbwmean_audiowlabel    object
dtypes: object(1)
memory usage: 21.7+ MB

A: Joblib and klepto python packages might help you.
On other hand, you do chunking store at-max you can in one chunk while storing and load iteratively and merge at the end.


text:
Q: SELECT COUNT(DISTINCT v)) performance Simple question. How can I rewrite a query like this:
SELECT a.name, MAX(b.value), MIN (b.value), COUNT(DISTINCT(b.value))
FROM tableA a
LEFT JOIN tableB b
       ON a.type = b.type
WHERE b.value IS NOT NULL
GROUP BY a.name

So that it doesn't run dog-slow on a big-but-not-massive sized table? (let's say 1 million rows). Or would it be possible to do some other 'magic trick' on the database to make that query run quickly?
Normalising the data further is out of the question in this particular case :)
Bit of additional information as requested
Ideally, the solution would work for both MySQL and MS SQL Server 2008, although SQL Server is definitely the priority of those.
The two tables should look like this:
Table A:
    type INT NOT NULL PRIMARY KEY
    name VARCHAR(500

Table B:
    idTableC INT NOT NULL
    type INT NOT NULL
    value VARCHAR (50)

Table C:
    idTableC INT NOT NULL PRIMARY KEY
    ...

So generally, we want to go say: for each item in table C, get all items in table B with their type, specified in table A.
However, it is also necessary to be able to say: for every 'type' in table A, get a summary of information associated with it in table B. It's this second case that this question's concerned with :)

A: You can use non-clustered indexes on foreign keys, I mean 2 index on [A.Type] and [B.Type] also you can have two other indexes on the columns in select [A.Name], [B.value]
So that everything that your query needs is in an index.

A: Unsure which database you are using but you could ensure there is an index on the foreign key tableA.type and additionally an index on tableB.type which contains tableB.value. That way SQL won't need to go back to the data page to get the value and can simply retrieve it from the index. You should be careful with this as if it's a large value it could slow your index down.


text:
Q: In Perl Windows, how do you replace everything after a word? I'm new to Perl and I'd like to replace a text from this
<!-- kv3 encoding:text:version{e21c7f3c-8a33-41c5-9977-a76d3a32aa0d} format:generic:version{aafc65d8-7a5a-4e01-bd8d-3ac118422503} -->
{
    _class = "CParticleSystemDefinition"
    m_bShouldHitboxesFallbackToRenderBounds = false
    m_nMaxParticles = 1
    m_nInitialParticles = 1
    m_flConstantRadius = 15.000000
    m_ConstantColor =
    [
        255,
        0,
        0,
        255,
    ]
    m_nConstantSequenceNumber = 8
    m_nConstantSequenceNumber1 = 7
    m_Renderers =
    [

        {
            _class = "C_OP_RenderSprites"
            m_nSequenceCombineMode = "SEQUENCE_COMBINE_MODE_USE_SEQUENCE_0"
            m_bMod2X = true
            m_bDisableZBuffering = true
            m_hTexture = resource:"materials/particle/particle_modulate_01.vtex"
            m_nOrientationType = 2
        },
    ]
}

To this.
<!-- kv3 encoding:text:version{e21c7f3c-8a33-41c5-9977-a76d3a32aa0d} format:generic:version{aafc65d8-7a5a-4e01-bd8d-3ac118422503} -->
{
    _class = "CParticleSystemDefinition"
}

This is the command I've been using:

perl -pi.bak -e "s/CParticleSystemDefinition"/CParticleSystemDefinition"\n}/g;"
"C:\Folder\File.vpcf"

and it has been producing this result for me
<!-- kv3 encoding:text:version{e21c7f3c-8a33-41c5-9977-a76d3a32aa0d} format:generic:version{aafc65d8-7a5a-4e01-bd8d-3ac118422503} -->
{
    _class = "CParticleSystemDefinition"
}
    m_bShouldHitboxesFallbackToRenderBounds = false
    m_nMaxParticles = 1
    m_nInitialParticles = 1
    m_flConstantRadius = 15.000000
    m_ConstantColor =
    [
        255,
        0,
        0,
        255,
    ]
    m_nConstantSequenceNumber = 8
    m_nConstantSequenceNumber1 = 7
    m_Renderers =
    [

        {
            _class = "C_OP_RenderSprites"
            m_nSequenceCombineMode = "SEQUENCE_COMBINE_MODE_USE_SEQUENCE_0"
            m_bMod2X = true
            m_bDisableZBuffering = true
            m_hTexture = resource:"materials/particle/particle_modulate_01.vtex"
            m_nOrientationType = 2
        },
    ]
}

So, how do I make it so that replacing something deletes everything that comes after it?
I'd also like to keep the command on a single line.

A:
how do I make it so that replacing something deletes everything that comes after it?

Need to match all that after it, as well, but leave it out in the replacement
perl -0777 -pi.bak -we"s/CParticleSystemDefinition\x22\K.*/\n}/s" file

Explanation

*

*With -p the program (between "") is applied to a line at a time. So to match multiple lines at once, as needed here, we need to read the whole file into a string, what -0777 does; then our "line" to which the code is applied is the whole file.  See Command switches in perlrun

*Here we still need to enable . to match newlines as well, what it normally doesn't, with the /s modifier.  See Modifiers in perlre

*Since " delimit the program text in Windows I use \x22 (hex) for the " character in code. (In my tests on Linux escaping it with \" didn't work but it may work on Windows, what I can't test now.)

*The \K drops ("forgets") all matches previous to that point, so they are not consumed from the string; so we don't have to re-enter them in the replacement part. Thus only the following .* is replaced, with \n}, so removed apart from the needed newline and the closing delimiter.  See \K in perlre
See the tutorial perlretut

A question came up of how to pass a list of files to this command-line program in Windows, like *.vpcf that one would do in Unix world (all files that end with .vpcf).
That is a question of Windows shell(s), and is not a simple matter with cmd.exe in Windows, but it is with PowerShell. So that's one way to go, to use PowerShell.
On the other hand, one can have a Perl program do that -- pass it a pattern to build the filenames from, like the extension, and have it build a filelist, read, edit and write back the files.  Then that program will be a bit more involved than the one-liner above but still rather basic.
Here is a shortcut, to still keep it as a short command-line program ("one-liner")
perl -wE'@ARGV = glob qq($ARGV[0]); $^I = qq(.bak); while (<>) { s/.../.../s; print }' *.vpcf

(same regex as above)
Comments

*

*The filelist is built using glob from what is passed to the program when it is invoked (first argument in its @ARGV array), then that is assigned to @ARGV (for <> later)

*To emulate -i.bak one can use $^I variable

*The while (<>) takes a line from each file listed in @ARGV.  (Normally these are things from the command-line but now we explicitly assigned to @ARGV.)  See <> operator

*I use qq operator for double quotes since " is a delimiter on Windows command-line
(I cannot test on Windows right now)


text:
Q: Browser code and beautifulsoup collection different I try to parse soccerstand front page soccer matches and fail because the items I get with BeautifulSoup are really different from what I see in browser.
My code is simple at the moment:
import urllib.request
from bs4 import BeautifulSoup

with urllib.request.urlopen('https://soccerstand.com/') as response:
    url_data = response.read()

soup = BeautifulSoup(url_data, 'html.parser')
print(soup.find_all('div.event__match'))

So I tried this and this failed. When I checked soup variable it turned out not to contain such divs at all, so what I get with BS is different from what I see by inspecting code on the website.
What's the reason for that? Is there any workaround?


text:
Q: can not retrieve the array value I want to collect the elements of my address table in table format but impossible. this is what I get in my console
{…}

"-LsMm5EeM0DavWwNweBc": Object { adresse: "njkbj", commune: "Marcory", nom: "jjbjkb,", … }

"-LsMmBCOHZzkVL_LUwiQ": Object { adresse: "bjb", commune: "Marcory", nom: "bjhbhjh", … }

<prototype>: Object { … }

page for service
 adresses: Adresse [] = [];
  adresseSubject = new Subject<Adresse[]>();

  constructor() { }

  emitAdresse(){
    this.adresseSubject.next(this.adresses);
  }

  getAdresse(){
    firebase.database().ref('adresse/' + firebase.auth().currentUser.uid )
      .on('value', (data)=>{
        this.adresses = data.val() ? data.val() : [];
        console.log();
        this.emitAdresse();
      });
  }

page for Page ts
adresses : Adresse[];
  adresseSubscription: Subscription;

  constructor(private adresseService: AdresseService,  private router: Router) {}

  ngOnInit(){
    this.adresseSubscription = this.adresseService.adresseSubject.subscribe(
      (adresses: Adresse[]) => {
        this.adresses = adresses;
      }
    );
    this.adresseService.getAdresse();
    this.adresseService.emitAdresse();
  }

Thanks you

A: In your Page Component adresses is going to be an Object and not an Array. So in order to make this work, you can use the keyvalue pipe with an *ngFor
Here, give this a try:

    {{ item.adresse }}

A: What you are getting is an object, not an array. So you have the option to use keyvalue pipe like in other answer (with a small correction), or actually create an array from the response.
Here's using keyvalue:

    {{ item.value.adresse }}

Or then you create an array from the response:
adressArray = [];

getAdresse(){
  firebase.database().ref('adresse/' + firebase.auth().currentUser.uid )
    .on('value', (data) => {
       for (let key in data.val()) {
         this.adressArray.push({key, ...data.val()[key]})
       }
    });
}

With that you get an array of objects, where each object would look like:
{"key":"-LsMm5EeM0DavWwNweBc","adresse":"njkbj","commune":"Marcory","nom":"jjbjkb"}

Which you can then iterate like:

    {{item.adresse}}

Here's a STACKBLITZ with both options: DEMO


text:
Q: Cannot see the full image with a fixed position on safari
I have created a navbar using HTML and CSS. It works perfectly on IE, Opera, and Chrome.

However, on Safari the logo seems to be cut off. All I did was to add the position fixed to the logo to make the logo stick to the top of the page when the user scrolls down the page.

My HTML:

            ffff

            01283 575 671
            Join Now

            Facilties
            Timetable
            Blog

            The Team
            Events
            Contact Us

My CSS:
body{
  margin:0;
}

#nav {
        z-index: 999;
    }

    .left-container,
    .center-container,
    .right-container {
        position: absolute;
        display: inline-block;
        margin: 0;
        padding: 0;
        width: calc(50% - 125px);
    }

    .left-container {
        left: 0;
        height: 50px;
        overflow: hidden;
    }

    .left-container span {
        margin: auto;
        left: 0;
        right: 0;
        position: absolute;
    }

    .center-container {
        width: 250px;
        height: 115px;
        z-index: 2;
        left: 0;
        right: 0;
        margin: auto;
    }

    .right-container {
        right: 0;
        height: 50px;
        overflow: hidden;
    }

    .right-container span:last-child {
        background: #081F2D;
        width: 40%;
        float: right;
    }

    .right-container span:last-child a {
        color: #FFDE00;
    }

    .left-right-container {
        background: #FFDE00;
        height: inherit;
    }

    .left-container span,
    .right-container span {
        padding: 15px 15px;
        font-weight: 500;
        text-transform: uppercase;
        width: 59%;
        display: inline-block;
    }

    .left-container span a,
    .right-container span a {
        display: block;
        color: #081F2D;
        text-decoration: none;
        text-align: center;
        font-size: 17px;
    }

    #top-bar {
        float: left;
        -webkit-border-radius: 5px;
        -moz-border-radius: 5px;
        border-radius: 0px;
        overflow: hidden;
        width: 100%;
        min-width: 650px;
        min-height: 50px;
        position: fixed;
        z-index: 999;
    }

    .nav-bg {
        width: 100%;
        position: absolute;
        top: 50px;
        height: 50px;
        z-index: 2;
            margin-top: -1px;
    }

    .left-right-nav {
        background-color: #EEEEEE;
        height: inherit;
    }

    .left-nav,
    .left-nav-2,
    .center-nav,
    .right-nav {
        position: fixed;
        display: inline-block;
        width: calc(50% - 125px);
    }

    .left-nav,
    .left-nav-2{
        left: 0;
    }

    .center-nav {
        width: 250px;
        height: 50px;
        z-index: 1;
        left: 0;
        right: 0;
        margin: auto;
    }

    .right-nav {
        right: 0;
    }

    /*.left-nav:after, .right-nav:after {
  content: '';
  display: inline-block;
  width: 100%;
}*/
    .left-nav div,
    .left-nav-2 div,
    .left-nav-2 div,
    .right-nav div {
        margin: auto;
        left: 0;
        right: 0;
        position: absolute;
        background-color: #EEEEEE;
        text-align: right;
        margin-left: -20px;
    }

    .left-nav-2 div{
        background-color: #FFDE00;
    }

    .left-nav div span {}

    .right-nav div span {
        float: left;
    }

    .left-nav div span,
    .left-nav-2 div span,
    .right-nav div span {
        display: inline-block;
    }

    .left-nav span a,
    .left-nav-2 span a,
    .right-nav span a {
        padding: 15px 40px;
        display: block;
        font-size: 1rem;
        text-align: center;
        color: #081F2D;
        text-transform: uppercase;
        font-weight: 600;
        text-decoration: none;
        background-color: #EEEEEE;
    }

    }

The codepen to my problem is https://codepen.io/anon/pen/xymdmP

A: Try adding position: fixed; and -webkit-transform: translate3d(0, 0, 0); instead of on image tag style.
https://codepen.io/anon/pen/MPZPPy
Thanks


text:
Q: Do not generate blazor css isolation suffix for :root variables A blazor component with css isolation (MyComponent.razor.css) can define variables like so:
.my-component {
  --width: 5rem;
  --padding: 2px;
}

That would be scoped to the component: it will be unusable anywhere else.
One could also do this:
:root {
  --mc-width: 5rem;
  --mc-padding: 2px;
}

But although one would expect that to be available to other components too, it won't - because it will be rendered with a css isolation suffix, e.g. :root[d-b3a7ca5e3a].
That doesn't work well with UI libraries.
For example, bootstrap has styles scoped to a particular widget (e.g. accordion, menu, tabs), and styles scoped globally (:root). Root styles are useful so that your code can take widgets' properties into account in your layout.
A workaround is to redefine everything in a global app.css (thus avoiding the css isolation suffix); but that creates duplication, and one loses encapsulation.
Can I generate :root styles with css isolation, but without the isolation suffix?


text:
Q: Are finite-dimensional normed spaces injective? A Banach space $X$ is said to be injective if every linear continuous $T:Y\to X$, with $Y\subseteq Z$ Banach spaces, has a linear continuous extension $T^*:Z\to X$ with the same operator-norm.
My question is: is every finite-dimensional normed space $X$ injective?
All examples I know are infinite-dimensional and besides they're not so simple.
Any hint? Thank you.


text:
Q: NEAT function taking forever to execute I'm trying to use the NEAT library but unfortunately one of the lines is taking forever to execute (I waited 2 hrs and it had not completed)
Here is the code:
config = neat.config.Config(neat.DefaultGenome,neat.DefaultReproduction,
neat.DefaultSpeciesSet, neat.DefaultStagnation,
config_path)

p = neat.Population(config)

p=neat.Population(config) is the line taking forever to execute.
The file in config_path is this one:
file
Can anyone help?


text:
Q: ElasticSearch document script sorting I've a query that return a score NULL.
{
  "query": {
    "match_all": {}
  },
  "sort": {
    "_script": {
      "script": "doc['price'].value * doc['sales.quarter'].value",
      "type": "number",
      "order": "desc"
    }
  },
  "size": 15,
  "from": 0
}

I want to get 15th best sales and this query returns a _score equals to NULL
Do you know why this happen ?

A: I've found a solution:
Custom score query !
{
  "query": {
    "custom_score": {
      "query": {
        "match_all": {}
      },
      "script": "doc['sales.quarter'].value * doc['price'].value"
    }
  },
  "size": 15,
  "from": 0
}


text:
Q: Why does newline come before space in the output of hexdump? Using hexdump, printing these characters in the "canonical" format gives the output that I expect, while the default format throws me off.
$ echo " " |hexdump                  # Reversed?
0000000 0a20
0000002

$ echo -n " " |hexdump               # Ok, fair enough.
0000000 0020

$ echo  " " |hexdump -C              # Canonical
00000000  20 0a                      | .|
00000002

With a different string, such as "123", the output is even more confusing:
$ echo  "123" |hexdump
0000000 3231 0a33
0000004

The output here does not seem "reversed", but rather it is shuffled. What (briefly) is going on here?

A: The default format is 16-bit little-endian unsigned ints.
The manual page of hexdump explains the default format as well:
 -x  Two-byte hexadecimal display.  Display the input offset in hexadecimal,
     followed  by eight  space-separated, four-column, zero-filled, two-byte
     quantities of input data, in hexadecimal, per line.

  (...)

  If  no format strings are specified, the default display is equivalent to
  specifying the -x option.


text:
Q: QGIS Browser application I have installed QGIS 3.2 in Windows & Ubuntu OS for the first time. 'Late comer of course'.
I cannot find the usual "standalone" QGIS Browser application installed. However, I can access QGIS Browser panel within QGIS Desktop - no problem.
Does QGIS 3 comes with 'standalone" QGIS Browser application and, if so, how do I access it?


text:
Q: How can I pass data from one page to another in PHP and Javascript without from? How can I pass data from one page to another page in PHP using Javascript without from?
In my blog have a post comment with email Id
and this is routing using foreach loop
problem occur when get email id and comment
how can i do this? plz help

A: you can make use of client side cookie for this. one page you create cookie and on second page read that cookie.

A: I guess that what you dislike with forms is the page reloading on the client side.
If that is the case then you can use ajax requests (maybe with the help of a framework like jQuery, or pure javascript with the xmlHTTPRequest()).
Alternatively you can use cookies, but it's not what they really are for.
If you don't mind the page reloading, you can also use HTTP GET requests with javascript :
location.assign("http://www.my_site.com/index.php?param1=value1&param2=value2");

A: You can also store data in Web storage if the data doesn't necessarily need to be processed in PHP.
You will need to have a backup system in cookies though for the older browsers that do not support his.


text:
Q: Docker, rabbitMQ and pike connection refused I am trying to connect to rabbitMQ from inside docker, using docker-compose. There are no problems connecting to the "image: rabbitmq:3-management" from a program running outside the container.
There are no passwords set or anything.
After looking a bit more at the error message it seems like pika tries to connect with IPv6 instead of IPv4. Looking at the documentation I can't figure out a way to connect with IPv4.
Failure happens on
self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))

Error log
rabbitMQ_1  | 2020-12-09 12:41:42.332 [info] <0.685.0> Ready to start client connection listeners
rabbitMQ_1  | 2020-12-09 12:41:42.333 [info] <0.988.0> started TCP listener on [::]:5672
listener_1  | ERROR:pika.adapters.utils.io_services_utils:Socket failed to connect: <socket.socket fd=9, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6, laddr=('127.0.0.1', 36782)>; error=111 (Connection refused)
listener_1  | ERROR:pika.adapters.utils.connection_workflow:TCP Connection attempt failed: ConnectionRefusedError(111, 'Connection refused'); dest=(<AddressFamily.AF_INET: 2>, <SocketKind.SOCK_STREAM: 1>, 6, '', ('127.0.0.1', 5672))
listener_1  | ERROR:pika.adapters.utils.connection_workflow:AMQPConnector - reporting failure: AMQPConnectorSocketConnectError: ConnectionRefusedError(111, 'Connection refused')
listener_1  | ERROR:pika.adapters.utils.io_services_utils:<socket.socket fd=9, family=AddressFamily.AF_INET6, type=SocketKind.SOCK_STREAM, proto=6, laddr=('::', 0, 0, 0)>.connect(('::1', 5672, 0, 0)) failed: OSError(99, 'Cannot assign requested address')
listener_1  | ERROR:pika.adapters.utils.connection_workflow:TCP Connection attempt failed: OSError(99, 'Cannot assign requested address'); dest=(<AddressFamily.AF_INET6: 10>, <SocketKind.SOCK_STREAM: 1>, 6, '', ('::1', 5672, 0, 0))
listener_1  | ERROR:pika.adapters.utils.connection_workflow:AMQPConnector - reporting failure: AMQPConnectorSocketConnectError: OSError(99, 'Cannot assign requested address')
listener_1  | ERROR:pika.adapters.utils.connection_workflow:AMQP connection workflow failed: AMQPConnectionWorkflowFailed: 2 exceptions in all; last exception - AMQPConnectorSocketConnectError: OSError(99, 'Cannot assign requested address'); first exception - AMQPConnectorSocketConnectError: ConnectionRefusedError(111, 'Connection refused').
listener_1  | ERROR:pika.adapters.utils.connection_workflow:AMQPConnectionWorkflow - reporting failure: AMQPConnectionWorkflowFailed: 2 exceptions in all; last exception - AMQPConnectorSocketConnectError: OSError(99, 'Cannot assign requested address'); first exception - AMQPConnectorSocketConnectError: ConnectionRefusedError(111, 'Connection refused')
listener_1  | ERROR:pika.adapters.blocking_connection:Connection workflow failed: AMQPConnectionWorkflowFailed: 2 exceptions in all; last exception - AMQPConnectorSocketConnectError: OSError(99, 'Cannot assign requested address'); first exception - AMQPConnectorSocketConnectError: ConnectionRefusedError(111, 'Connection refused')
listener_1  | ERROR:pika.adapters.blocking_connection:Error in _create_connection().
listener_1  | Traceback (most recent call last):
listener_1  |   File "/usr/local/lib/python3.8/site-packages/pika/adapters/blocking_connection.py", line 450, in _create_connection
listener_1  |     raise self._reap_last_connection_workflow_error(error)
listener_1  | pika.exceptions.AMQPConnectionError

docker-compose.yml
version: '3'
services:
  rabbitMQ:
    image: rabbitmq:3-management
    ports:
      - "15672:15672"
      - "5672:5672"
  login:
    build:
      context: .
      dockerfile: Dockerfile.login
    restart: on-failure
  listener:
    build:
      context: .
      dockerfile: Dockerfile.listener
    restart: on-failure

A: The docker-compose does not setup a localhost network. This means that each service has there own name. In this case the host should be changed.
self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))

should be changed to

self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='rabbitMQ'))


text:
Q: How to draw route from A to B through multiple points on GoogleMaps? Imagine I want to go from A to B through 3 waypoints. I have this code, which forms the Google Maps direction URL:
fun getMapsApiDirectionsUrl(): String {
    val origin = "origin=" + currentLocation.latitude + "," + currentLocation.longitude;
    val waypoints = "waypoints=optimize:true|" + loc1.latitude + "," + loc1.longitude + "|" + loc2.latitude + "," + loc2.longitude + "|" + loc3.latitude + "," + loc3.longitude
    val destination = "destination=" + loc4.latitude + "," + loc4.longitude
    val sensor = "sensor=false"
    val key = "key="+API_KEY;
    val params = "$origin&$waypoints&$destination&$sensor&$key"
    val output = "json"

    val url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params
    System.out.println("map url: "+url)
    return url
}

Opening the URL on browser gave this:

{    "routes" : [],    "status" : "ZERO_RESULTS" }

But if I only use 1 waypoint (instead of 3 like shown above), the direction will be displayed in 1 big JSON correctly, like this:

{    "geocoded_waypoints" : [
{
"geocoder_status" : "OK",
"place_id" : "ChIJH87yjIXxaS4R5_ww8ZCufeo",
"types" : [ "clothing_store", "establishment", "point_of_interest", "store" ]
},
{
"geocoder_status" : "OK",
"place_id" : "ChIJ1wVXzIDxaS4RkyUYgf3ZV0c",
"types" : [ "street_address" ]
},
{
"geocoder_status" : "OK",
"place_id" : "ChIJrfOSGBXxaS4Ro595K_5ClCg",
"types" : [ "establishment", "hospital", "point_of_interest" ]
}    ],    "routes" : [
{
"bounds" : {
"northeast" : {
"lat" : -6.2399232,
"lng" : 106.8161445
},
"southwest" : {
"lat" : -6.2684858,
"lng" : 106.7929824
}
},
"copyrights" : "Map data ©2019 Google",
"legs" : [
{
"distance" : {
"text" : "1.2 km",
"value" : 1205
},
"duration" : {
"text" : "4 mins",
"value" : 254
},
"end_address" : "Jl. Kemang Raya No.54, RT.8/RW.2, Bangka, Kec. Mampang Prpt., Kota Jakarta Selatan, Daerah Khusus
Ibukota Jakarta 12730, Indonesia",
"end_location" : {
"lat" : -6.263443499999999,
"lng" : 106.8160131....

So does it mean I can only use 1 waypoint?

A: There is no way from origin to destination via waypoints set. The second URL:
https://maps.googleapis.com/maps/api/directions/json?origin=-6.2684059,106.8103103&waypoints=optimize:true%7C-6.263459,106.815903%7C-6.240607,106.792831%7C-6.240607,106.792831&destination=-6.235759,6.823277&sensor=false&key=<YOUR_KEY>
contains unreachable destination destination=-6.235759,6.823277 in Atlantic Ocean. Probably destination should be 106.823277 instead of  6.823277 : destination=-6.235759,106.823277 if all the positions should refer to valid locations in Jakarta. So, double check code, that compose URL for Directions API request.


text:
Q: MySQL wildcard return only matches with hyphen and number In my database I have the following rows which will increment if it's a duplicate:
foo
foo-1
foo-2
foo-3
f
f-1
f-2
f-3
bar
bar-1
I want to query the db and get the last f-#. I've tried using the LIKE operator below:
SELECT * FROM links WHERE slug LIKE '$slug%' ORDER BY timestamp DESC LIMIT 1";

My Problem
If $slug == f it returns foo-3 rather than f-3. Is there a better way to use the % wildcard?

A: SELECT *
FROM links
WHERE slug LIKE '$slug-%' OR slug = '$slug'
ORDER BY timestamp DESC
LIMIT 1

The alternative, if you didn't want to do an OR, would be to use a REGEXP match. However, you might give up the ability to use an index for the query if you do that.


text:
Q: Can I change the inner structure of objects in a HashTable while iterating over it? Like, the title says. Can I change the inner structure of objects in a HashTable while iterating over its keys? I know I cant change the Map itself, or at least that it is risky to do so, but despite google searches I haven't found any clear or simple answer as to whether or not it is ok to change the attributes of the objects themselves in the hashmap. My gut feeling says no, since this would probably change the hash, but it would be good to know for certain. I am also interested in replacing the value for the keys while iterating over them. Is this possible?
Apologies if this has been answered a lot of times before.
To be short, will these two methods work as expected?
public class Manager {

private Hashtable<MyClassA, BufferedImage> ht1;
private Hashtable<MyClassB, JSlider> ht2;

private Image method1() {
    for(MyClassB mcb: ht2.keySet()){
       mcb.calculateStuff(ht2.get(mcb).getValue());
       //CalculateStuff() doesnt change anything, but if it takes long, the JSliders might be
       //changed by the user or a timer, resulting in a new hashCode(), and potentially problems.
    }
}

private void method2(){
   for(MyClassA mca: ht1.keySet()){
       mca.changeInnerStructureOfA(); //Changes the fields of the object mca.
       ht1.put(mca.calculateNewImage());
   }
}

A: It is not allowed to mutate keys of a hash-based container in any situation, not only while iterating over the container. The reason for this is that any mutation that changes the value of hash function leaves your container in an invalid state, when the hashed key is sitting in the hash bucket that does not correspond to the key's hash value.
This is the reason behind a strong recommendation of using only immutable classes as keys in hash-based containers.

I am also interested in replacing the value for the keys while iterating over them. Is this possible?

No, this is not possible. In order to replace a key in a container with another key you need to remove the item first, and then re-insert it back with the new key. This, however, would trigger concurrent modification exception.
If you need to replace a significant number of keys, the best approach would be making a new hash container, and populate it with key-vale pairs as you iterate the original container.
If you need to replace only a small number of keys, make a list of objects describing the change (old key, new key, value), populate the list as you iterate then original container, and then walk the list of changes to make the alterations to the original container.


text:
Q: How to make each cell of a UItableView to be 2 different buttons? I have a UITableView and want to separate each cell in two buttons, one will be the thumbnail and the other the rest of the cell as usually, so it have to fire 2 different didSelectRowAtIndexPath methods depending on which button was pressed, how can I do that? Thank you

A: Use tag for UIbutton selector method

A: what is understand from your question is that you have two buttons in each cell in the uitableview , and you want two different actions when any button is pressed , so you neded to implement two different actions for each button it is straight forward , also check this tutorial on how to implement a custom uitableviewcell


text:
Q: java MockRestServiceServer escape characters in url In our project we're using external system with quite unusual REST API.
It contains square brackets in the url:
api/v1/series?match[]=up

Now we want to test our own REST api and just to mock this external system's responses.
So we're using MockRestServiceServer object in our unit tests.
    mockServer = MockRestServiceServer.createServer(restTemplate);
    mockServer.expect(ExpectedCount.manyTimes(), requestTo(UriComponentsBuilder.fromHttpUrl(prometheusURL + "series?match[]=up")
            .build().toUri()))
            .andExpect(method(HttpMethod.GET))
            .andRespond(withSuccess(promResponseMetricUpInfo, MediaType.APPLICATION_JSON));

Inside our Service we just call this external API as
restTemplate.getForObject(prometheusURL + "series?match[]=up", ResponseObjectForSeries.class);

But as a result we have the following error:
java.lang.AssertionError: Unexpected request expected:<http://localhost:9090/api/v1/series?match[]=up> but was:<http://localhost:9090/api/v1/series?match%5B%5D=up>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.web.client.match.MockRestRequestMatchers$5.match(MockRestRequestMatchers.java:121) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.web.client.DefaultRequestExpectation.match(DefaultRequestExpectation.java:84) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.web.client.SimpleRequestExpectationManager.validateRequestInternal(SimpleRequestExpectationManager.java:55) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.web.client.AbstractRequestExpectationManager.validateRequest(AbstractRequestExpectationManager.java:75) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.web.client.MockRestServiceServer$MockClientHttpRequestFactory$1.executeInternal(MockRestServiceServer.java:289) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.mock.http.client.MockClientHttpRequest.execute(MockClientHttpRequest.java:94) ~[spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:652) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]

How can we escape these square brackets?
I tried to use backslashes or %5B%5D explicity in the test. But it doesn't help.

A: This problem resolved using
URLEncoder.encode()

in tests


text:
Q: Setprecision in a loop struct movie{
    int week;
    int month;
    int year;
    int rating;
};

In the loop below, I am trying to print out all the information in the vector of struct and I only want decimals in the ratings but this makes it so that there are decimals in all lines after the first iteration.
for(int i = 0; i < info.size(); i++) {
    cout << info.at(i).week << endl;
    cout << info.at(i).month << endl;
    cout << info.at(i).year << endl;
    cout << fixed << setprecision(2) << info.at(i).rating << endl;
}

Anyone know how I can fix this?
Also, if I'm not using pointers and haven't allocated dynamic memory, is it still possible to have memory leaks?

A: It's tedious but you can save and restore the formatting flags
for(int i = 0; i < info.size(); i++) {
    cout << info.at(i).week << endl;
    cout << info.at(i).month << endl;
    cout << info.at(i).year << endl;
    ios_base::fmt_flags save = cout.flags();
    cout << fixed << setprecision(2) << info.at(i).rating << endl;
    cout.flags(save);
}


text:
Q: trying to check user input to my array I am completely new to Java and I am trying to get the user input to check my array for valid input and continue code and if it's not valid to repeat until I get valid input.
public class Cheesecake {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        float biteSize = 3;
        float small = 9;
        float large = 12;
        String chosenSize;
        double pricePerInch = 0;
        double total = 0;
        String[] chooseSizes = {"bite size", "small", "large"};
        String[] chooseFlavors = {"plain", "strawberry", "raspberry", "caramel", "chocolate"} ;

        Scanner scnr = new Scanner(System.in);

        System.out.println("Flavors to choose from: plain, strawberry, raspberry, caramel, chocolate.");        //giving user flavor list

        /*System.out.println("Please choose flavor:");

        flavors = scnr.nextLine();*/

        String flavors;
        while (true) {
            System.out.println("Please choose flavor:");
            flavors = scnr.nextLine();
            if (flavors.equals(chooseFlavors))
                break;
            else
                System.out.println("Please choose from flavors above.");

A: You have to check each index of the array with your flavors. (Should probably rename to userFlavor).
String[] chooseFlavors = {"plain", "strawberry", "raspberry", "caramel", "chocolate"};
...

boolean flavorFound = false;
while (!flavorFound) { // Loop until flavorFound is true
  System.out.println("Please choose flavor:");
  userFlavor = scnr.nextLine();

  for(int i = 0; i < chooseFlavors.length; i++) { // Loop from 0 to choosFlavors.length
      if(userFlavor.equals(chooseFlavors[i]) { // Compare user input to flavor at index i
          System.out.println(userFlavor + " found at index " + i);
          flavorFound = true; // This is the flag to break out of while loop
          break; // Only breaks out of for loop
      } else {
          System.out.println("Please choose from flavors above.");
      }
  }

}


text:
Q: Fetching data from server through Redux (Action & Reducer) fails to store the data in the State I'm trying to fetch data through Redux (with actions & reducers) and store it in a ReactTable
Here is the Table :
// MisleadLeadsTable
import React from "react";
import "react-table-v6/react-table.css";
import ReactTable from "react-table-v6";
import { connect } from "react-redux";
import {
  getLeadsNotValid,
  updateSpecificNotValidLead
} from "../../actions/leads";
import Spinner from "../layout/Spinner";

class MisleadLeadsTable extends React.Component {
  constructor(props) {
    super();
    const { getLeadsNotValid } = props;
    // Going to get data from the Server
    // Call the Action and use the Reducer
    getLeadsNotValid();

    // Later put the data in the state
    this.state = {
      data: []
    };
    this.renderEditable = this.renderEditable.bind(this);
  }

  componentDidMount() {
    // TODO
    const { leadsNotValid } = this.props;
    this.setState({
      data: leadsNotValid
    });
  }

  // Edit the cells
  renderEditable(cellInfo) {
    return (

 {
          const data = [...this.state.data];
          data[cellInfo.index][cellInfo.column.id] = e.target.innerHTML;
          this.setState({ data });
        }}
        dangerouslySetInnerHTML={{
          __html: this.state.data[cellInfo.index][cellInfo.column.id]
        }}
      />
    );
  }

  render() {
    // loading data or not
    const { loadingData } = this.props;

    // This "data" should hold the fetched data from the server
    const { data } = this.state;
    return (

        {loadingData ? (
          <Spinner />
        ) : (

            <ReactTable
              data={data}
              columns={[
                {
                  Header: "Business Name",
                  accessor: "BusinessName"
                  // Cell: this.renderEditable
                }
              ]}
              defaultPageSize={10}
              className="-striped -highlight"
            />

        )}

    );
  }
}

const mapStateToProps = state => ({
  loadingData: state.leadReducer.loadingData,
  leadsNotValid: state.leadReducer.leadsNotValid
});

const mapDispatchToProps = { getLeadsNotValid, updateSpecificNotValidLead };

export default connect(mapStateToProps, mapDispatchToProps)(MisleadLeadsTable);

However when I try to store the data in the State (in componentDidMount) it always comes back empty , and when the table is being rendered it gets an empty array.
It is crucial to store the data in the State because I'm trying to implement an editable table.
The data is stored in leadsNotValid , and if I do :
<ReactTable
  data={leadsNotValid}          // Notice !! Changed this
  columns={[
    {
      Header: "Business Name",
      accessor: "BusinessName"
      // Cell: this.renderEditable
    }
  ]}
  defaultPageSize={10}
  className="-striped -highlight"
/>

Then the data is presented successfully to the user , however it's not in the State of the component.
How can I put the leadsNotValid in the State using setState ?
Here are the Action & Reducer if it's needed (THEY WORK GREAT !) :
Action :
import axios from "axios";
import {
  REQUEST_LEADS_NOT_VALID,
  REQUEST_LEADS_NOT_VALID_SUCCESS,
  UPDATED_SUCCESSFULLY_A_NOT_VALID_LEAD_THAT_NOW_IS_VALID,
  UPDATE_A_SINGLE_NOT_VALID_LEAD
} from "./types";

export const updateSpecificNotValidLead = updatedLead => async dispatch => {
  dispatch({
    type: UPDATE_A_SINGLE_NOT_VALID_LEAD
  });

  const config = {
    headers: {
      "Content-Type": "application/json"
    }
  };
  const body = JSON.stringify({ updatedLead });

  const res = await axios.post(
    ".......API/Something1/....",
    body,
    config
  );

  if (res !== null && res.data !== null) {
    dispatch({
      type: UPDATED_SUCCESSFULLY_A_NOT_VALID_LEAD_THAT_NOW_IS_VALID
    });
  }
};

export const getLeadsNotValid = () => async dispatch => {
  dispatch({
    type: REQUEST_LEADS_NOT_VALID
  });

  const res = await axios.get(".......API/Something2/....");
  if (res !== null && res.data !== null) {
    dispatch({
      type: REQUEST_LEADS_NOT_VALID_SUCCESS,
      payload: res.data
    });
  }
};

Reducer :
import {
  GET_MAIN_LEADS_SUCCESS,
  REQUEST_MAIN_LEADS,
  RELOAD_DATA_MAIN_LEADS_TABLE,
  REQUEST_LEADS_NOT_VALID,
  REQUEST_LEADS_NOT_VALID_SUCCESS,
  UPDATE_A_SINGLE_NOT_VALID_LEAD,
  UPDATED_SUCCESSFULLY_A_NOT_VALID_LEAD_THAT_NOW_IS_VALID
} from "../actions/types";

const initialState = {
  mainLeadsClients: [],
  loadingData: null, // general loader
  reloadMainLeadTable: 0,
  reloadMisleadTable: 0,
  leadsNotValid: []
};

export default function(state = initialState, action) {
  const { type, payload } = action;
  switch (type) {
    case REQUEST_LEADS_NOT_VALID:
      return {
        ...state,
        loadingData: true
      };

    case REQUEST_LEADS_NOT_VALID_SUCCESS:
      return {
        ...state,
        loadingData: false,
        leadsNotValid: payload
      };
    case UPDATE_A_SINGLE_NOT_VALID_LEAD:
      return {
        ...state,
        loadingData: true
      };
    case UPDATED_SUCCESSFULLY_A_NOT_VALID_LEAD_THAT_NOW_IS_VALID:
      return {
        ...state,
        reloadMisleadTable: state.reloadMisleadTable + 1,
        loadingData: false
      };

    // ... more

    default:
      return state;
  }
}

A: You may have to write super(props) instead of super() in order to access props in the constructor.


text:
Q: Follow mouse on hover using animate Jquery I'm trying to achieve this mousemove effect over the images.The images seem like it's following my mouse,I'm trying to follow it and so far this. I tried this example https://jsfiddle.net/lesson8/SYwba/. But I'm stuck on combining it with my current fiddle.
This is my desired output.Like the images is following the mouse. Output

$('.animated').hover(
    function() {
        $('.animated').animate({
            marginTop:20
        });
    },
    function() {
        $('.animated').animate({
            marginTop:10
        });
    }
);

Also tried this:

$(document).mousemove(function(e) {
    $('.logo').offset({
        left: e.pageX,
        top: e.pageY + 20
    });
});

A: The logic is actually quite simple: what you want to do is to offset the image away from its original position based on the relative position of the cursor in the document/viewport. We will need to perform all this calculations in the mousemove event on document.
$(document).on('mousemove', function(e) {...});

Also, this means that you will need some following information:

*

*determine the maximum offset you want the image to be moved from its original position

*the viewport width and height

*the mouse/cursor position relative to viewport height—that will give us a range of [0, 1]

*transform that range to [-1, 1], since negative values are used to move to the top/left and positive values used to move to the bottom/right

*use CSS3 transform to move the image

Step-by-step guide
1. Determine maximum offset
Let's say we want to restrict the movement to ±30px. We can define them as:
// Maximum offset for image
var maxDeltaX = 30,
    maxDeltaY = 30;

2. Get viewport dimensions
Viewport dimensions can be accessed by document.documentElement.clientWidth/clientHeight:
// Get viewport dimensions
var viewportWidth = document.documentElement.clientWidth,
    viewportHeight = document.documentElement.clientHeight;

3 and 4. Get the relative position of the cursor to the viewport
The key here is to calculate the relative position of the cursor to the viewport. First, we get the fraction of the mouse/cursor coordinates to the viewport, which will give us a range of [0, 1]. However, we need to transform this into [-1, 1], so that we can calculate left/top movement (using negative values) and bottom/right movement (using positive values). The arithmetic transformation from [0, 1] to [-1, 1] is simply multiplying to 2 (so you get [0, 2]) and minus 1 (then you get [-1, 1]):
// Get relative mouse positions to viewport
var mouseX = e.pageX / viewportWidth * 2 - 1,
    mouseY = e.pageY / viewportHeight * 2 - 1;

5. Use CSS3 transform to position your image
This is the most straight forward part. The amount to translate is simply mouseX × maxDeltaX and the same along the y-axis. We pass these values into transform: translate(<x>px, <y>px):
// Calculate how much to transform the image
var translateX = mouseX * maxDeltaX,
    translateY = mouseY * maxDeltaY;
$('.animated').css('transform', 'translate('+translateX+'px, '+translateY+'px)');

Working example
See proof-of-concept below:

// Settings
// Maximum offset for image
var maxDeltaX = 30,
    maxDeltaY = 30;

// Bind mousemove event to document
$(document).on('mousemove', function(e) {

  // Get viewport dimensions
  var viewportWidth = document.documentElement.clientWidth,
      viewportHeight = document.documentElement.clientHeight;

  // Get relative mouse positions to viewport
  // Original range: [0, 1]
  // Should be in the range of -1 to 1, since we want to move left/right
  // Transform by multipling by 2 and minus 1
  // Output range: [-1, 1]
  var mouseX = e.pageX / viewportWidth * 2 - 1,
      mouseY = e.pageY / viewportHeight * 2 - 1;

  // Calculate how much to transform the image
  var translateX = mouseX * maxDeltaX,
      translateY = mouseY * maxDeltaY;
  $('.animated').css('transform', 'translate('+translateX+'px, '+translateY+'px)');

});

A: Try binding hover event to only div or  some container in which you want to move the image instead of image itself.
$('.wrapper-div').hover();

A: I'll just give you a hint

$('.animated').mousemove(
  function(ev) {
    document.getElementById("MouseCoord").innerHTML = ev.clientX + ':' + ev.clientY;
  }
);

window.addEventListener("load", function() {
  var rect = document.getElementById("container").getBoundingClientRect();
  // .toFixed(0) only remove decimal part for a nice display
  document.getElementById("BoxSize").innerHTML =
    "Box is at (" + rect.left.toFixed(0) + ";" + rect.top.toFixed(0) + ")" +
    " with size " + rect.width.toFixed(0) + "x" + rect.height.toFixed(0);
});
#container {
  width: 400px;
  height: 200px;
  border: .1px solid;
}

-

-


text:
Q: Redirect to different assigned pages if username and password correct Please I need help regarding a PHP error, I want to redirect to different pages with form login input here since I do not how to know how to make an admin backend to redirect users to different pages via database, Here is my PHP
SCRIPT
// Redirect to different page
<?php $userid = $_POST['userid'];
    $userpass = $_POST['password'];

    if (strcmp($userid, "3495062250") && strcmp($password, "12smith00") ) {
    header('location: account-dashboard/client_349506_2243/index.html');

   } else{ header('location: error.html'); } ?>

A: Please check below code.
You did mistakes.

*

*In if condition you have used $password instead of $userpass

*You can simply compare the string using equal operator in PHP
$userid = $_POST['userid'];
$userpass = $_POST['password'];
if ($userid = "3495062250" && $userpass == "12smith00") {
    header('location: account-dashboard/client_349506_2243/index.html');
} else {
    header('location: error.html');
}


text:
Q: Query Regarding Stream Provider in Flutter I'm currently trying out Stream Providers for noticing changes in Cloud Firestore Database and getting new data on change.
This is how I have created the Stream Provider :
child: StreamProvider.value(value: _firestoreAPI.getProjectsFromStream(_savedUser.user.name),child: PrimaryScene(toggleAnimation)),

As I am not able to call the provider from initstate ....Hence I'm calling is inside build :
_projectListSnapshotFromStream = Provider.of<QuerySnapshot>(context);

I have a doubt that if I rebuild the Widget containing the above call in its build function, will it charge me a read everytime I build that Widget because I called the provider? Or will it only charge a read when there is a change noticed in the database ?
Stream Definition :
Stream<QuerySnapshot> getProjectsFromStream(String username){
    return databaseReference.collection("Projects").where("Members",arrayContains: username).snapshots();
  }

Thankyou in advance for answering.

A: will only count as read if you receive a new document from firestore


text:
Q: Concat-stream callback does not call Here is code
concat = require('concat-stream');
const writable = concat(cb);

let reversedData = ''

function cb(data) {
    reversedData = data.toString().split('').reverse().join('');
    process.stdout.write(reversedData)
}

process.stdin.pipe(writable);

It's just taking input but not giving output. What's wrong ?
Edit : This question is same as Why isn't concat-stream working with process.stdin.pipe()? but  answer is not sufficient for me because i don't know how to do as he said in answer. How to close input stream ?

A: It doesn't make sense to use concat-stream with process.stdin because concat-stream expects the readable stream to end at some point, but process.stdin doesn't end.
It would make more sense to just use a normal Transform stream:
const { pipeline, Transform } = require('stream');
const { StringDecoder } = require('string_decoder');

const decoder = new StringDecoder();

// Transfrom stream which reverses input
const reverse = new Transform({
    transform(chunk, encoding, callback) {
        // Convert input from buffer to string
        chunk = decoder.write(chunk).trim();

        // Reverse string
        chunk = chunk.split('').reverse().join('');

        // Return result
        callback(null, chunk);
    }
});

// Pipe console input into transform stream then into console output
pipeline(process.stdin, reverse, process.stdout, err => {
    throw err;
});

*

*I have used pipeline() instead of .pipe() so that an error handler can be added to the end in case an error occurs.

*StringDecoder is used to convert the buffer received from process.stdin to a UTF-8 string.

*.trim() is used on the end of decoder.write(chunk).trim() in order to remove the newline at the end of the decoded string.