text:
Q: How to decrease value inside object nested in an array using Node.js and MongoDB/Mongoose Using moongoose for Node.js, I'm trying to go through each object in the "STEPS" array and decrease the stepid by 1.  Using this schema below:
"appid": 1,
"steps": [
            {
                "name": "step4",
                "stepid": 4,
            },
            {
                "name": "step5",
                "stepid": 5,
            }
         ],
"appname": "myapp"

Here's how I tried is using .update:
app.db.models.myApps.update(
        {'appid': 1, 'steps.stepid': { $gt: 3 }},
        { $inc: { 'steps.$.stepid': -1 } },
    { multi: true }
);

But I can't seem to get it to work correctly.  I was able to play around with the code and get it to update but it would only update 1 of the objects in the array, whereas I would like it to go through each object in the array and decrease by 1.
Should I break it out and first use find and then update?  The old dev in me says to do a for loop but I know that's not the right way to do it with node.
Any help or suggestions are greatly appreciated! Thanks!

A: Unfortunately this appears to be an issue with mongodb which does not support it.
Per: How to Update Multiple Array Elements in mongodb
And here: https://jira.mongodb.org/browse/SERVER-1243
For now a workaround would be this:
function convertDirectMessages(id, cb) {
    Conversation.collection.update(
        {'messages.context': 'direct'},
        {$set:{'messages.$.context': {type:'direct'}}},
        {safe:true, multi:true},
        function(err, updated) {
            if (err) return cb(err);
            if (updated) return convertDirectMessages(id, cb);
            cb();
        }
    );
}
convertDirectMessages(posted._id, this);


text:
Q: Set C# Button Style to another Button when hovered / clicked / unhovered How would I make two buttons appear the same when one is hovered over?
Picture of the buttons I want to be shown are here:
http://i.stack.imgur.com/b4P6B.png

How would I make the button with the green image in the center appear as the same style (colors, borders, etc...) when the Sign On one has been hovered over / clicked?
I'm using Windows Forms.

A: This can be done using event handlers on mouse over/out, but frankly the right choice is to make a usercontrol containing both buttons and use that instead of the two...

A: Simply add handler for MouseEnter event on your "sign on" button - all you have to do in this very handler then, is changing second button's styles (implementing MouseLeave might be useful too - to revert second button to it's original style).
Code sample:
this.ButtonSignOn.MouseEnter += this.ChangeOtherButton;
this.ButtonSingOn.MouseLeave += this.RevertOtherButtonChanges;

// later on
private void ChangeOtherButton(object sender, EventArgs e)
{
    this.OtherButton.ForeColor = Colors.Red;
    this.OtherButton.BackColor = Color.Blue;
    // more styling ...
}

// mostly same stuff when reverting changes

You could refactor those 2 handlers into one, and simply passing colors, fonts and other styles as you go... but this should be enough anyways.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change the color into red if the value that from database is unpaid or 0(in binary)? I just wanted to change the color of the text here if the status is unpaid.
$query = mysql_query("SELECT * FROM bill_record");

while($row = mysql_fetch_array($query)){
      echo $row['bill_id'];
      echo "
".$row['status']."
"; // Status has a paid and unpaid
}

A: I would add an else statement or paid values:
if ($row['status'] == 'unpaid') {
    echo "
".$row['status']."
";
} else {
    echo "
".$row['status']."
";
}

A: <?php

$query = mysql_query("SELECT * FROM bill_record");

while($row = mysql_fetch_array($query)) {

  echo $row['bill_id'];

  if ($row['status'] == 'unpaid') {
    echo "
".$row['status']."
";
  }

}


text:
Q: I want to make draggable div only with one area I have draggable div with saving positions to database... I am moving picture but can I make only one area where i can click and move div or it need to be  whole div? Because Now i can click anywhere on div and move it  and I want to click on only one spot for moving div...

A: if you are using jqueryui draggable,then you can use handle option.
check the documentation

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

handle


text:
Q: Excel changes cell formula I work with an Excel file approx. 10,000 rows on each of 12 sheets. This file is used quite a bit to pull data from (i.e. sorted, filtered, changed manually) but I never tamper with the columns that contain the formulae.
Over the past couple of weeks I've been noticing that some of the reference values within the cells have been changing. The only reason I saw this is because excel gracefully points out when a formula is different from the ones above and below it (with the small green arrows). Up to this point I've just gone and click "Restore to column formula".
Example:
=IFERROR(IF(G148/E148>100%,100%,G148/E148),"")
had been changed to,
=IFERROR(IF(G157/E157>100%,100%,G157/E157),"")
while still in Row 148.
Now this isn't a large pain to go and change all the values, its typically < 100 values. But I'm fearing the day this turns into over 9000 values.
My goal is to find out the root cause of this problem and nullify it from continuing to happen. I am using Excel 2010.
EDIT: This is an example of the problem I'm speaking about. The reference rows should continue in order, but you'll notice row 337, 341, and 345 have all changed to different rows (209, 224, 158 respectively).

A: Answered my own question.
I tried to replicate the problem instead of waiting for it to happen again and I found that this was occuring because I was filtering data in the table, and then sorting it. The reason numbers are so random is that the filter would grab only a handful of rows from thousands, and then sorting it would change the cell reference.
With that being said, I believe this post is now a copy of the following: How do I sort a table in Excel if it has cell references in it?

A: One way to get around this, is to use Excel's built in tables feature. With this much data it may not be feasible, but one benefit, is that when you have a formula it doesn't reference the row number, it instead just has the formula use the data in the same row as the formula.
Not very clear. Let's try again
I have a table
col1    col2    col3
1       2
2       4

in col3 I want a sum of the items of the same row in col1 and col2.
Without the table feature in Excel I would have the following formulas in the table
=A2+B2
=A3+B3

With the table feature in Excel the formula looks like this.
=[col1]+[col2]
=[col1]+[col2]

The formula is the same for all rows, and the table knows to use the same row of data.


text:
Q: Getting error in Nodemailer if recipient email is wrong I am sending an email With Nodemailer SMTP
Its working fine if email account is valid / existing, But getting an 500 error when entering email address whic is not exist.
I know it is not sending because email not exist but need to handle errors
I have also tried tls: {rejectUnauthorized: false}, but getting same issue
I am using Custom SMTP not using Gmail SMTP
My code is as below:
let transporter = nodemailer.createTransport({
                host: 'smtp.myhost.de',
                port: 587,
                auth: {
                  user: 'CUSTOM_SMTP_EMAIL', // generated ethereal user
                  pass: 'CUSTOM_SMTP_PASS' // generated ethereal password
                },
                secure:false,
                requireTLS: false,
                tls: {rejectUnauthorized: false},
                debug:true
              });

let info = await transporter.sendMail({
                from: sails.config.custom.appName+ SENDER_EMAIL, // sender address
                to: inputs.email, // list of receivers
                subject: "My email subject ", // Subject line
                text: "Verify Email Address "+inputs.email, // plain text body
                html: html // html body
              },function(err) {
                console.log('email sent');

                if (err){
                    console.log( 'err->>>>>>>>>>>>>', err);
                    return exits.success('error');

                } else {
                   console.log('success');
                   return exits.success('success');
                }
              });

I am not able to return return exits.success('error'); because of 500 error.
Getting below error
err->>>>>>>>>>>>>
{ Error: Can't send mail - all recipients were rejected: 552 5.2.2 host gmail-smtp-in.l.google.com [2a00:1450:400c:c09::1a] said: The email account that you tried to reach is over quota. Please direct the recipient to https://support.google.com/mail/?p=OverQuotaPerm q13si8918761wrn.204 - gsmtp (H-QUOTA)
    at SMTPConnection._formatError (/var/www/html/node_modules/nodemailer/lib/smtp-connection/index.js:784:19)
    at SMTPConnection._actionRCPT (/var/www/html/node_modules/nodemailer/lib/smtp-connection/index.js:1613:28)
    at SMTPConnection._responseActions.push.str (/var/www/html/node_modules/nodemailer/lib/smtp-connection/index.js:1566:30)
    at SMTPConnection._processResponse (/var/www/html/node_modules/nodemailer/lib/smtp-connection/index.js:942:20)
    at SMTPConnection._onData (/var/www/html/node_modules/nodemailer/lib/smtp-connection/index.js:749:14)
    at TLSSocket.SMTPConnection._onSocketData.chunk (/var/www/html/node_modules/nodemailer/lib/smtp-connection/index.js:195:44)
    at emitOne (events.js:116:13)
    at TLSSocket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at TLSSocket.Readable.push (_stream_readable.js:208:10)
    at TLSWrap.onread (net.js:607:20)
  code: 'EENVELOPE',
  response: '552 5.2.2 host gmail-smtp-in.l.google.com [2a00:1450:400c:c09::1a] said: The email account that you tried to reach is over quota. Please direct the recipient to https://support.google.com/mail/?p=OverQuotaPerm q13si8918761wrn.204 - gsmtp (H-QUOTA)',
  responseCode: 552,
  command: 'RCPT TO',
  rejected: [ 'jay@gmail.com' ],
  rejectedErrors:
   [ { Error: Recipient command failed: 552 5.2.2 host gmail-smtp-in.l.google.com [2a00:1450:400c:c09::1a] said: The email account that you tried to reach is over quota. Please direct the recipient to https://support.google.com/mail/?p=OverQuotaPerm q13si8918761wrn.204 - gsmtp (H-QUOTA)
    at SMTPConnection._formatError (/var/www/html/node_modules/nodemailer/lib/smtp-connection/index.js:784:19)
    at SMTPConnection._actionRCPT (/var/www/html/node_modules/nodemailer/lib/smtp-connection/index.js:1599:24)
    at SMTPConnection._responseActions.push.str (/var/www/html/node_modules/nodemailer/lib/smtp-connection/index.js:1566:30)
    at SMTPConnection._processResponse (/var/www/html/node_modules/nodemailer/lib/smtp-connection/index.js:942:20)
    at SMTPConnection._onData (/var/www/html/node_modules/nodemailer/lib/smtp-connection/index.js:749:14)
    at TLSSocket.SMTPConnection._onSocketData.chunk (/var/www/html/node_modules/nodemailer/lib/smtp-connection/index.js:195:44)
    at emitOne (events.js:116:13)
    at TLSSocket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at TLSSocket.Readable.push (_stream_readable.js:208:10)
    at TLSWrap.onread (net.js:607:20)
       code: 'EENVELOPE',
       response: '552 5.2.2 host gmail-smtp-in.l.google.com [2a00:1450:400c:c09::1a] said: The email account that you tried to reach is over quota. Please direct the recipient to https://support.google.com/mail/?p=OverQuotaPerm q13si8918761wrn.204 - gsmtp (H-QUOTA)',
       responseCode: 552,
       command: 'RCPT TO',
       recipient: 'jay@gmail.com' } ] }

A: If callback is not passed as a second argument to sendMail, it returns a promise that can be awaited:
let info = await transporter.sendMail({
    from: sails.config.custom.appName+ SENDER_EMAIL, // sender address
    to: inputs.email, // list of receivers
    subject: "My email subject ", // Subject line
    text: "Verify Email Address "+inputs.email, // plain text body
    html: html // html body
}).then(() => {
    console.log('success');
    return exits.success('success');
}).catch((err) => {
    console.log( 'err->>>>>>>>>>>>>', err);
    return exits.success('error');
});

console.log(info);


text:
Q: Laravel Test Cases I am using Laravel 5.3 and for testing purpose, I have created a folder called "Helpers" is "app" folder. In "Helpers" folder, there is a file named credentials.php where I will declare some strings then I will use it later. Credentials.php looks like
`
<?php

namespace App\Helpers;

class Credential
{

}
`

In the 'tests' folder there is folder called 'links' and in this folder there is file called something.php and it looks like
<?php

use App\Helpers\Credential;

class something extends TestCase
{
}

and its working correctly...Problem arising when I am trying to put the "helpers" folder from "app" to "tests" folder. I dont want to put the "Helper" folder in "app" directory. I have changed namespace and other things, nothing works. I am new to laravel and seeking your help and suggestion.

A: Update Composer.json and add files key in autoload section.
"autoload": {
    "files": [
        "tests/helpers.php"
    ],
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},

After Adding this, run the following command.
composer dump-autoload


text:
Q: How to make my own "const data" unmodifiable? I had a trouble with my own const attribute. I could not protect my const data completely because of functions. Functions can modify everything.
const reference is an awful thing because it requires an address; if it's an address of a const variable, most likely the variable data still can be changed or modified. My data is writeable. The parser cannot prevent (ignore) this kind of code because it's totally legal in C++.
scanf("%d", &const_var);

How to lock my data and make my const data unmodifiable (or unwritable)?

A: In this case...
scanf("%d", &foo); // Out of range!!!

...foo could indeed be modified, or pretty much anything else can happen. The compiler can't catch this because scanf uses old-fashion c varargs which allows any number of parameters, of any type to be passed, with no checking whatsoever. There is no attempt to ensure that the parameter passed is an address, let alone the address of an int, and certainly not the address of a non-const int.
For safer C++ code, avoid using printf/sscanf family of functions entirely.
Lint or some other source code checker could help here. I haven't tried it with this specific case.

A: You can't protect yourself from such situations directly. If the constant is put inside writable memory, one may always acquire address of this constant and modify it one or another way. Remember though, that standard says, that modifying constant values is considered to have an undefined behavior.
If you want the constant to be unmodifyable, you can make a workaround and use a macro:
#define foo 100

This is a trick, because it will exchange all occurrences of foo in the source into 100, however noone will be able to modify its value in the runtime (by definition, 100 is 100).
However, I would avoid using macros. You may use another workaround instead: define a function:
constexpr int FooValue()
{
    return 100;
}

Noone will be able to modify it either, but this solution allows you to embed such "constant" in class or namespace. If you use compiler, which can handle C++11, using constexpr will allow you to input this function everywhere, where you might have inserted a constant, for example:
int array[FooValue()];

A: C++ is not a safe language. In C++, you can only protect yourself from accidents, not perfidy. If a user wants to change something that they're not supposed to be able to change, it's as simple as this:
void SomeFunc(const Obj &dontChange)
{
  Obj &change = const_cast<Obj &>(dontChange);

  change.X = ...;
}

There is nothing you can do to protect yourself from a user who is determined to violate the contract between your code and theirs. You can only protect yourself from a user who accidentally tried to break the contract. You can't even protect private members of your class, as they can simply cast the type to something else and poke at the memory directly.
Your best bet is this: don't worry about it. If the user does the wrong thing with some variable, then any breakage that happens as a result is their fault.


text:
Q: How to display Unit as Second Display Item for same display Order? I work on SQL server 2012 I face Issue : I can't arrange  Features contain  Unit as second Item display for same Display Order .
for feature family as example
'Family' as [Family], 'FamilyMaxValue' as [FamilyMaxValue], 'FamilyUnit' as [FamilyUnit]

I need it to be as below
'Family' as [Family], 'FamilyUnit' as [FamilyUnit],'FamilyMaxValue' as [FamilyMaxValue]

Feature and Unit and max value get same DisplayOrder for every Feature but my issue
How to get Unit as Second Display for same Display Order .
Meaning change will be Order of items separated by comma to display feature Unit as second display  for same Display Order.
 create table #SplitNumberAndUnitsFinal
(
DKFeatureName  nvarchar(100),
DisplayOrder  int
)
insert into #SplitNumberAndUnitsFinal (DKFeatureName,DisplayOrder)
values
('package',1),
('packageUnit',1),
('Family',2),
('FamilyMaxValue',2),
('FamilyUnit',2),
('parts',3),
('partsMaxValue',3),
('partsUnit',3)
DECLARE @Header nvarchar(max)=( select
substring(
    (
        Select  ', '''+ DKFeatureName +''' as ['+ DKFeatureName +']' AS [text()]
        From #SplitNumberAndUnitsFinal
        GROUP BY DKFeatureName
        ORDER BY MIN(DisplayOrder)
        --order by DisplayOrder

        For XML PATH ('')
    ), 2, 10000) [Columns])
    print @Header

Expected Result arrange feature Unit as second display to be as:
Feature,FeatureUnit,FeatureMaxValue according to same display Order

'package' as [package], 'packageUnit' as [packageUnit],
'Family' as [Family], 'FamilyUnit' as [FamilyUnit],'FamilyMaxValue' as [FamilyMaxValue],
'parts' as [parts], 'partsUnit' as [partsUnit],'partsMaxValue' as [partsMaxValue]

AND I don't Need to Display it  as below :
Feature,FeatureMaxValue,FeatureUnit for same Display Order

'package' as [package], 'packageUnit' as [packageUnit],
 'Family' as [Family], 'FamilyMaxValue' as [FamilyMaxValue], 'FamilyUnit' as [FamilyUnit],
 'parts' as [parts], 'partsMaxValue' as [partsMaxValue], 'partsUnit' as [partsUnit]

A: You need an additional column to control the display order if DisplayOrder alone is not unique. That will allow you to specify both columns in the ORDER BY clause for the desired order:
CREATE TABLE #SplitNumberAndUnitsFinal
(
    DKFeatureName  nvarchar(100),
    DisplayOrder  int,
    SecondaryDisplayOrder  int
);
INSERT INTO #SplitNumberAndUnitsFinal (DKFeatureName,DisplayOrder,SecondaryDisplayOrder)
VALUES
    ('package',1,1),
    ('packageUnit',1,2),
    ('Family',2,1),
    ('FamilyMaxValue',2,3),
    ('FamilyUnit',2,2),
    ('parts',3,1),
    ('partsMaxValue',3,2),
    ('partsUnit',3,3)
DECLARE @Header nvarchar(MAX)=( select
SUBSTRING(
    (
        SELECT  ', '''+ DKFeatureName +''' as ['+ DKFeatureName +']' AS [text()]
        FROM #SplitNumberAndUnitsFinal
        ORDER BY DisplayOrder,SecondaryDisplayOrder
        FOR XML PATH ('')
    ), 2, 10000) [Columns]);
PRINT @Header;


text:
Q: Adding a detailed disclosure indicator to Call out in Annotation.h Can you add a disclosure indicator to the call out when creating your annotations?  Thanks.

A: Found the answer: rightCalloutAccessoryView


text:
Q: How to start internet in emulator of windows? I'm using Windows 8.1 and visual studio 2013 to develop windows phone application.
I'm also using PCL to interact with Web Service
I'm using HTTPClient to call web service method and get response in JSON format
when I try to run application on emulator or physical device , appliction is not working.

A: I would suggest testing the internet connection using IE and if you can browse to internet sites. If you can browse using IE, then you might want to check your application endpoint\URL is correct.
If you have problems connecting to internet from IE, then check the WiFi connection and\or data connection on device to see if it is setup correctly. For Emulator you can follow below steps troubleshoot internet connectivity issues.
https://msdn.microsoft.com/en-us/library/windows/apps/jj681694(v=vs.105).aspx#BKMK_CannotconnecttoInternetdestinations


text:
Q: Fusion charts npm , how to upgrade to licensed version I was using FusionCharts to build some charts.Now that i know how to integrate it using npm I want to upgrade to a commercial license for my client. I didn't see any documentation specific to npm version.
The documentation on official website points to Fusion charts npm installation but there is no mention of how to upgrade to licensed version.

A: Documentation is really lacking in this regard, that's a shame. After reading tons of stuff, that's what I came up, in Angular 7:

*

*Removed the npm package fusioncharts, but kept "angular-fusioncharts": "^3.0.1"

*Created a folder libs in the root of my project, then put inside this folder the content downloaded from the link in the purchase email, renaming to fusioncharts

*Changed my imports from:
    import * as FusionCharts from 'fusioncharts'
    import * as Charts from 'fusioncharts/fusioncharts.charts'
    import * as PowerCharts from 'fusioncharts/fusioncharts.powercharts'
    import * as FusionTheme from 'fusioncharts/themes/fusioncharts.theme.fusion'

to
    import * as FusionCharts from 'libs/fusioncharts/js/fusioncharts'
    import * as Charts from 'libs/fusioncharts/js/fusioncharts.charts'
    import * as PowerCharts from 'libs/fusioncharts/js/fusioncharts.powercharts'
    import FusionTheme from 'libs/fusioncharts/js/themes/fusioncharts.theme.fusion'

*The init code was the same:
FusionChartsModule.fcRoot(FusionCharts, Charts, PowerCharts, FusionTheme)

I don't understand why I was getting an error if I kept the import * as FusionTheme for the theme package, I had to change to import FusionTheme from.
I put "allowSyntheticDefaultImports": true in my tsconfig.json at some point during this process, not sure if this configuration is needed for this last step.
Some (not that) useful links:
https://www.fusioncharts.com/dev/getting-started/angular/angular/configure-your-chart-using-angular
https://www.fusioncharts.com/dev/upgrading/upgrading-from-evaluation-versions


text:
Q: Service wake up randomly, with setExactAndAllowWhileIdle method I need to wake up a service every 60 seconds (for example).
The service configures itself to wake up with the following code:
private void rescheduleService() {

    // setup calendar
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(Calendar.SECOND, 60);

    // setup intent
    Intent serviceGeofence = new Intent(this, ServiceGeofence.class); // this service
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, serviceGeofence, PendingIntent.FLAG_CANCEL_CURRENT);

    // setup alarm
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    if(Build.VERSION.SDK_INT >= 23) {
        alarmManager.setExactAndAllowWhileIdle(
                AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                pendingIntent);
    } else if(Build.VERSION.SDK_INT >= 19){
        alarmManager.setExact(
                AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                pendingIntent);
    } else {
        alarmManager.set(
                AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                pendingIntent);
    }

    Log.i(TAG, "next alarm: " + calendar.toString());
    Log.i(TAG, "alarm configured");

}

The code above works fine while the phone is charging or connected via USB. It executes every 60 seconds as expect. And I able to see it in LogCat.
BUT, when I unplug phone from USB, the service is wake up randomly (3 or 5 minutes,... even 30 minutes later).
I'm using methods like setExactAndAllowWhileIdle, setExact (it depends of Android version) to wake up the device extrictly in the time I configured it. But it only works when device is connected to USB.
TL;DR; With code above:

*

*When device is connected to USB: works fine.

*When device is disconnected from USB: doesnt work as expected.

Any idea of what is happening?

A: "
Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.
"
Basically... If sdk >= 19 you need to use serExact. Dont use setExactAndAllowWhileIdle


text:
Q: iphone sdk, Generating a .pdf file using data from text fields of a registration form I have to  generate a .pdf file using data from text fields of a registration form. I searched all around but didn't get any relevant solution. All answers are to draw a line or image or single string.
Thanks in advance.


text:
Q: How can I avoid multiple nested subscriptions using RxJS operators? I am working on a file encryption and upload class using Angular. Many of these operations are async and therefore the methods I wrote are returning RxJS Observables.
// 1.
private prepareUpload(file): Observable<T>;

// 2.
private encryptData(data, filekey): Observable<T>

// 3.
private uploadEncryptedData(formData, token, range): Observable<T>

// 4.
private completeUpload(updatedFilekey, token): Observable<T>

I want to encapsulate this logic in a public upload(file) method and I ended up using nested subscriptions and it works but I know that it is wrong and an anti-pattern in RxJS for several reasons. Here is a simplified version of the code:
public upload(file) {
    const gen = this.indexGenerator(); // generator function

    this.prepareUpload(file).subscribe(values => {
    const [response, filekey, data] = values;

    this.encryptData(data, filekey).subscribe(encryptedDataContainer => {
      const formData = this.prepareEncDataUpload(encryptedDataContainer.data, file.name)
      const range = this.getRange(file.size, gen.next().value);

      this.uploadEncryptedData(formData, response.token, range).subscribe(() => {
        if (range.isFinalPart) {
            this.completeUpload(encryptedDataContainer.updatedFilekey, response.token).subscribe(console.log);
        }
      });

    });

  });

}

I failed to clean this code using combinations of several RxJS operators. My goal is to avoid nested subscriptions and instead return a single Observable from the public upload() method when the workflow is completed.
Thanks!

A: You want to use pipe before subscribing. Pipe allows you to make changes to values coming down the stream before the stream emits them. Also, use mergeMap to flatten the subscribe chain. Here's an overview. This doesn't provide a full solution - not paying me enough ;) - but is sufficient to point you in the right direction:
this.prepareUpload(file).pipe(
  tap(values => console.log('hello1', values)),
  map(values => [response, filekey, data]),
  tap(values => console.log('hello2', values)),
  mergeMap(() =>
      // essential to catchError else an HTTP error response will disable this effect - if it uses HTTP - catchError essentially prevents the stream from erroring in which case it will never emit again
      this.encryptData(data, filekey).pipe(
        map(res => res), // do something with res here if you want
        catchError(() => {
          return of(null)
        })
      )
    ),
    filter(res => !!res)
    // more mergemap stuff here
  ).subscribe(values => {
    console.log(values)
  })

Hint: use the tap operator to console.log values as they are passing down the stream
PS: Syntax not checked, may be missing a comma or bracket or 2
PPS: the functions in the pipe are all RxJS operators

A: You can use mergeMap and filter operators from RxJs and chain your calls. You will need to create some function level variables to use during the chaining.
import { mergeMap, filter, catchError } from 'rxjs/operators`

public upload(file) {
    const gen = this.indexGenerator(); // generator function
    let range, token;
    this.prepareUpload(file)
      .pipe(
        mergeMap((values) => {
          const [response, filekey, data] = values;
          token = response.token;
          return this.encryptData(data, filekey);
        }),
        mergeMap(encryptedDataContainer => {
          const formData = this.prepareEncDataUpload(encryptedDataContainer.data, file.name)
          range = this.getRange(file.size, gen.next().value);

          return this.uploadEncryptedData(formData, token, range);
        }),
        filter(() => !!range.isFinalPart),
        mergeMap(() => {
          return this.completeUpload(encryptedDataContainer.updatedFilekey, token);
        })
        catchError((error) => {
          console.log(error);
          // handle the error accordingly.
        })
      )
      .subscribe(() => {
        console.log('success');
      });

  }

A: You can merge those observables using mergeMap rxjs operator and get rid of nested subscriptions.
Though there is one catch,
Be aware that because mergeMap maintains multiple active inner subscriptions at once it's possible to create a memory leak through long-lived inner subscriptions.
For reference and example:
https://www.learnrxjs.io/operators/transformation/mergemap.html

A:
I think chaining your observables would do it, you can do it with
  flatMap (alias for mergeMap) maybe - https://stackoverflow.com/a/37777382/9176461 and
  RxJS Promise Composition (passing data)

As in my comment mentoined, something like the following should work (pseudo code):
public upload(file) {
    const gen = this.indexGenerator(); // generator function

    return Rx.Observable.just(file).pipe(
         mergeMap(this.prepareUpload),
         mergeMap(this.encryptData),
         mergeMap(this.prepareEncDataUpload),
         mergeMap(this.prepareEncDataUpload),
         .... )
}


text:
Q: Warnings of "NAs introduced by coercion" in fread function I am trying to use fread() to read in a table of 2 columns (x, y) and ~3 00 million rows (62 GB) and plot the x and y in a scatter plot. I am using "fread" and it works fine if I only use a small portion of the data, like 30000 rows.
But if I run it on the whole data set, I got:
"Warning message:
In setattr(ans, "row.names", .set_row_names(nr)) :
  NAs introduced by coercion to integer range
/var/spool/torque/mom_priv/jobs/11244921.cri16sc001.SC: line 14: 70765 Killed                  Rscript 10_plotZ0Z1.R"
What could be the reason?

A: You could sample your big file as already suggested in the comments. Unfortunately, it seems that fread doesn't have yet such a feature implemented - see this opened issue (upvoting the feature could motivate the developers to work on it). But as mentioned here, if you are on Linux, then try the shuf -n shell command:
library(data.table)

# Generate some random data
dt <- data.table(x = rnorm(10^6), y = rnorm(10^6))
# write to csv file
fwrite(dt, "test-dt.csv")

# Read a random sample of 10^5 rows
dt2 <- fread(cmd = "shuf -n 100000 test-dt.csv")
dt[, plot(x,y)]

Alternatively, you could read blocks of rows from your file with multiple calls to fread as showed here.


text:
Q: Python script to change an attribute value in .tcx file (XML) I have a .tcx (XML) file, with the following schema:
<Activities>
<Activity>
<Lap StartTime="2015-12-24T08:12:18.969Z">
<TotalTimeSeconds>4069.0</TotalTimeSeconds>
<DistanceMeters>30458.794921875</DistanceMeters>
<MaximumSpeed>43.36123275756836</MaximumSpeed>
<Calories>2286</Calories>
<AverageHeartRateBpm><Value>144</Value></AverageHeartRateBpm><MaximumHeartRateBpm><Value>169</Value></MaximumHeartRateBpm>
<Intensity>Active</Intensity>
<Cadence>87</Cadence>
<TriggerMethod>Manual</TriggerMethod>

<Track>
    <Trackpoint>
        <Time>2015-12-24T08:12:19.969Z</Time>
        <Position><LatitudeDegrees>45.4917</LatitudeDegrees><LongitudeDegrees>9.16198</LongitudeDegrees></Position>
        <AltitudeMeters>124.018</AltitudeMeters>
        <DistanceMeters>0.0</DistanceMeters>
        <SensorState>Present</SensorState>
        <Extensions><TPX xmlns="http://www.garmin.com/xmlschemas/ActivityExtension/v2"><Watts>0</Watts></TPX></Extensions></Trackpoint>

...
</Track>
</Lap>
</Activity>
</Activities>

and need to change (double) the Watts attribute.
Would like a simple python script

A: Simply run an XSLT script. No Python loops or expensive XPaths (//) is needed. As information, XSLT is a declarative, special-purpose programming language used specifically to restructure, redesign, or re-format XML documents to various end use needs. Like most general purpose languages such as Java, C#, Perl, PHP, VB, Python comes equipped with an XSLT 1.0 processor in its lxml module.
Below runs an identity transform to copy entire document as is and then multiplies the current value in any Watts node by 2. I declare a namespace doc in XSLT to reference the Watts element.
XSLT (save as .xsl or .xslt)
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
               xmlns:doc="http://www.garmin.com/xmlschemas/ActivityExtension/v2">
<xsl:output version="1.0" encoding="UTF-8" indent="yes" />
<xsl:strip-space elements="*"/>

  <!-- Identity Transform -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="doc:Watts">
    <xsl:copy>
      <xsl:value-of select=". * 2"/>
    </xsl:copy>
  </xsl:template>

</xsl:transform>

Python Script
import lxml.etree as ET

dom = ET.parse('Input.xml')
xslt = ET.parse('XSLTScript.xsl')

transform = ET.XSLT(xslt)
newdom = transform(dom)

tree_out = ET.tostring(newdom, encoding='UTF-8', pretty_print=True,  xml_declaration=True)

xmlfile = open('Output.xml')
xmlfile.write(tree_out)
xmlfile.close()

A: Your last two element tags need to be closing tags, and you have a Watts element not an attribute.  Here is how to do it with your file structure.
Python provides the ElementTree library for this.  The following script will accomplish what you want:
import xml.etree.ElementTree as ET

tree = ET.parse("test.tcx")

tpxns = "http://www.garmin.com/xmlschemas/ActivityExtension/v2"
for watts in tree.iter("{%s}Watts"%tpxns):
    watts.text = str(2*int(watts.text))

tree.write("testnew.tcx")

Here I import the ElementTree library and use a simpler name for it.  The parse function creates an ElementTree object from your file.  I walk through the file to find all Watts elements (as these occur in a namespace, I actually need to look for {http://www.garmin.com/xmlschemas/ActivityExtension/v2}Watts, which I build up using string formatting).
When I find such an element, I set the inner text to be twice what the previous value was (converting to an int first and then back to a string).
Finally, I write the new xml file out.  I could have overwrote the original file here if I wanted to.
Look over the documentation for the ElementTree module if you need to do anything fancier.  It provides very powerful tools for working with XML.  There are even more powerful libraries out there if you need more features (I like lxml for example).


text:
Q: mysql-python connector work with python2.7 and 3.4 at the same time Python 2.7 and 3.4 co-exist in my mac-os. After installing the official mysql connector (downloaded from dev.mysql.com), import mysql.connector can only pass in python 2.7. Is there any way for the connector to work for both python versions?

A: You can install the same connector via easy-install or pip from pypi
easy_install-3.4 mysql-connector-python

A: Relative to Python 3.6:
The official mysql connector only worked in python 2.7 after i installed it on OSX.
As an alternative I used the easy_install-3.6 python module integrated in python 3.6

Go to directory: /Library/Frameworks/Python.framework/Versions/3.6/bin
command: easy_install-3.6 mysql-connector-python


text:
Q: Como fazer exibição dinâmica em HTML+PHP? Estou estudando HTML e PHP, mas tem coisas que não estou conseguindo descobrir como faz. Afinal como obtenho dados de entrada para processá-los? Como no teclado com aqueles campos de texto <input type="text">. E, depois disso, como adapto a interface da página ou a atualizo com a nova interface em função dos dados coletados?
Para facilitar, coloquei um exemplo onde se fornece um tamanho de matriz quadrada e de acordo com o valor fornecido a interface da página disponibiliza células para serem preenchidas. O gif abaixo ilustra de forma bem simples essa ideia, mostrando as mudanças da página a cada modificação da string no campo "ordem".

Já agradeço antecipadamente a quem me esclarecer.

A: Descobri como faz, sem a necessidade de ajax, javascript, table e outros. Vou explicar com o exemplo. Fiz a interface dinâmica de matriz quadrada toda no arquivo "index.php".
Primeiramente, coloco o campo que deve atualizar a interface. Usando <form action="index.php" method="post">, a entrada pelo campo <input name="numeroDeEquações" type="text" /> vai reabrir a página "index.php" com a variável $_POST['numeroDeEquações'] atualizada com o valor que foi passada no campo.
O segundo e último passo é determinar a interface de acordo com o valor do campo. Para isso, primeiramente verifico se $_POST['numeroDeEquações'] foi definido. Depois verifico se o valor é válido. De acordo com as condições, se constrói a interface.
Simples assim. Segue o código e agradeço a todos que tentaram ajudar.

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Matriz Quadrada</title>

        <form action="index.php" method="post">
            Ordem: &nbsp&nbsp <input name="numeroDeEquações" type="text" />

        </form>

        <?php
            $inválido = true ;
            if( isset($_POST['numeroDeEquações']) ){
                $numeroDeEquações = $_POST['numeroDeEquações'] ;
                if( $numeroDeEquações>1 && $numeroDeEquações<10 ){
                    $inválido = false ;
                    for( $índice1=0 ; $índice1<$numeroDeEquações ; $índice1++ ){
                        for( $índice2=0 ; $índice2<$numeroDeEquações ; $índice2++ ){
                            echo( "<input size=1 type='text' />" ) ;
                        }
                        echo( "
" ) ;
                    }
                }
            }
            if( $inválido ) echo( "
Forneça um número de 2 a 9." ) ;
        ?>


text:
Q: Sudo not available in guest login When I login as guest I am unable to execute any command with sudo.
E.g.:
sudo ps

returns:
sudo: unable to change to sudoers gid: Operation not permitted

How can I fix this?

A: It is every easy to do administrative tasks from  a guest session. The su is disabled, but they cannot disable ssh.
All you have to do is ssh into an account in the sudoers list on localhost:
ssh <username>@localhost

where <username> is that of the account.

A: I recommend against all the solutions here, again for security reasons. In the use-case outlined by the op in his response:

A guest user is logged in and I/root come over and want to do something(say, copy a specific file from my profile to the guest's desktop) which requires root and sudo seems to be the most convenient way of doing that.

The most convenient way of doing this is to execute su [your username]. By default root has no password and you can't use that username, so use your regular admin account. You will then be prompted for your password. You can then execute what commands you wish, perhaps prepending them with sudo, typing your password again. When you are finished using your own account's permissions, type exit and they will be returned to their own prompt.

A: Rather than trying to fix it, consider creating a second user with sudo privileges. Hopefully this is straighforward to do via the unity ui, since I only know how to do it by editing /etc/sudoers. That way, "guest" remains unpriviliged like it's supposed to be, and you can make the second user as secure or insecure as you like.

A: This is designed as a security feature, really.  The "guest" user has a locked down set of permissions and are denied access to sudo, su, and other commands.
If you need to access those commands, you can login as your own user on the TTY, through Ctrl+Alt+F1 or any of the other F# keys up to 6, and login through that, however guest user is locked out of the administrative commands and such.

A: The guest user in Ubuntu is a generated user every time you log in with guest. See:
guest-5VczkW@host:~$ grep guest /etc/passwd
guest-5VczkW:x:115:125:Guest,,,:/tmp/guest-5VczkW:/bin/bash

The name guest-5VczkW is changing with every guest session. The script that generates this user is the a script called guest-account:
which guest-account
/usr/sbin/guest-account

Now you can edit this sciript by adding the guest user to a sudo group. So every new generated guest user is added to this group that has the right to gain root-privileges.
But, I can't recommend this intrusion into the system. It's a major security risk. In your situation I would just make a new normal user called "guest" with a password that everyone knows, and add this user to the sudo group. But notice, even with this solution everyone that known the guest login can change the system significantly.


text:
Q: Microsoft Graph access token for single user within Outlook add-in Is there is a way to get Microsoft Graph access token from Azure AD within Outlook add in? Technically user is logged in when Outlook is open, so from outlook add in I can get email ID (internetMessageId https://dev.office.com/reference/add-ins/outlook/1.5/Office.context.mailbox.item?product=outlook&version=v1.5), username, etc.
I want to use email id and token to retrieve single email message https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/message_get
But is it possible to generate Azure AD access token not making the user log in once again like in the example? https://github.com/AzureAD/microsoft-authentication-library-for-js
Cheers

A: You can obtain a token for using with Graph/Outlook REST APIs using the Office.context.mailbox.getCallbackTokenAsync() method introduced in Mailbox 1.5.
There is a walkthrough of this in the docs: Use the Outlook REST APIs from an Outlook add-in.


text:
Q: Delphi, HighCharts and UniGui setData not working on recreated frames Hi Everyone and Thanks in advance.
I have created a web application using delphi xe2 and unigui. In my application, I display charts using Highcharts for delphi(THTMLCharts) with the use of UniGui. In displaying charts, this is the original process:

*

*Organize the fields and values for display.

*Provide the highchart(THTMLCharts) object of the fields and values.

*Recreate the charts. Recreate the series and drilldown values.

*Redraw the charts.

That process is being executed every 10 seconds in a timer to update the charts on display. We notice that it's a bit of a process and not user friendly if the user keeps on seeing the page being refreshed every 10 seconds to update the charts. Increasing the timer's interval is not a very a good thing as the user should at least see the latest updates immediately without clicking any button for refresh. The Web application is like some sort of Dashboard that is always open and should remain on a same page while the charts are being updated.
So I searched online on how to update data of a chart in a highchart object for delphi. Please note that the delphi object for highchart does not have the option to just update values but rather requires redrawing. We found online for highchart site for the 'setData' javascript function and initially, it is working. The javascript is passed through Unisession.AddJS.
Please note in delphi unigui, the term 'frame(s)' are the web pages.
The issue here is, it only works on the initial loading of the charts, but, when the frames are reloaded, say we switch views to a different frame, then go back to the charts (which will then redraw the charts), the setData function is no longer working, both through the source code(delphi) and in the browser's console.
Would anyone have any knowledge as to why this occurs? We cannot fully refresh the page because this will just put everything back to the very first page, which is the login page.
Below is the code I'm using to compose the setData function as well as how it is passed to the display
procedure TGraphPageFrame.SetDataPass(chrt: THTMLFrameChart; nChartIndex : Integer; isDrillDown: Boolean; isNewData: Boolean = False);
var
  oSeriesOtherInfos : TSeriesOtherInfos;

  srsCount : integer;

  srsVal : TSeriesValues;
  drilldownVal : TItemSeriesValues;

  extn_datas: TlkJSONlist;
  extn_data: TlkJSONobject;
  extn_names : TStringList;

  y, z, ndx: Integer;
  nTot : Double;

  sJSCommand,
  sJSCommand_drilldown,
  sChartIndex,
  sChartDatas ,
  sDrillDownName : string;
begin
  sChartIndex := IntToStr(nChartIndex);

  extn_datas := TlkJSONlist.Create;
  extn_names := TStringList.Create;
  extn_names.OwnsObjects := True;

  try
    try
      srsVal := chrt.Series.Items[0].Values;
      srsCount := srsVal.count;

      for y := 0 to srsCount - 1 do
      begin
        ndx := extn_names.IndexOf(srsVal.Items[y].Title);

        sDrillDownName := 'DrillDown_'+ srsval.Items[y].Title;

        if ndx < 0 then
        begin
          extn_data := TlkJSONobject.Create;
          extn_data.Add('name', srsVal.Items[y].Title);

          oSeriesOtherInfos := TSeriesOtherInfos.Create;
          oSeriesOtherInfos.nIndex := extn_names.Count;

          extn_names.AddObject(srsVal.Items[y].Title, oSeriesOtherInfos);
        end
        else
        begin
          oSeriesOtherInfos := TSeriesOtherInfos(extn_names.Objects[ndx]);

          extn_data := TlkJSONobject(extn_datas.Child[oSeriesOtherInfos.nIndex]);
        end;

        nTot := 0;
        if isDrillDown then
        begin
          for z := 0 to srsVal.Items[y].drilldown.Items[0].Values.Count - 1 do
          begin
            drilldownVal := srsval.Items[y].drilldown.Items[0].Values.Items[z];
            nTot := nTot + drilldownVal.Value;
          end;
        end
        else
        begin
          nTot := srsVal.Items[y].Value;
        end;

        if ndx < 0 then
        begin
          extn_data.Add('y', nTot);
          if isDrillDown then
            extn_data.Add('drilldown', sDrillDownName);
          extn_datas.Add(extn_data);
        end
        else
        begin
          extn_data.Field['y'].Value := nTot;
        end;
      end;

      sChartDatas := TlkJSON.GenerateText(extn_datas);
      sChartDatas := StringReplace(sChartDatas, '"name"', 'name', [rfReplaceAll]);
      sChartDatas := StringReplace(sChartDatas, '"y"', 'y', [rfReplaceAll]);
      sChartDatas := StringReplace(sChartDatas, '"drilldown"', 'drilldown', [rfReplaceAll]);

      sJSCommand := 'Highcharts.charts['+ sChartIndex +'].series[0].setData('+sChartDatas+', false, true, true);';

      UniSession.AddJS(sJSCommand);

      if isDrillDown then
      begin
        sleep(500);

        UniSession.AddJS('Highcharts.charts['+ sChartIndex +'].options.drilldown.series.length = 0;');

        Sleep(500);

        srsCount := srsVal.count;

        for y := 0 to srsCount - 1 do
        begin
          sDrillDownName := '"DrillDown_'+ srsval.Items[y].Title +'"';

          sJSCommand_drilldown := 'Highcharts.charts['+ sChartIndex +'].options.drilldown.series.push('+
            '{'+
              'type: "bar",'+
              'name: "'+ srsval.Items[y].Title +'",'+
              'color: "#ef6986",'+
              'id: ' + sDrillDownName + ',' +
              'showInLegend: true,'+
              'dataLabels:{enabled: true, format: "{point.y}"},'+
              'tooltip:{animation: true, enabled: true, hideDelay: 500, pointFormat: "{point.y}"},'+
              'data:[';

          for z := 0 to srsVal.Items[y].drilldown.Items[0].Values.Count - 1 do
          begin
            drilldownVal := srsval.Items[y].drilldown.Items[0].Values.Items[z];

            sJSCommand_drilldown := sJSCommand_drilldown +
              '["'+ drilldownVal.Title +'",'+ FloatToStr(drilldownVal.Value) +'],';
          end;

          sJSCommand_drilldown := Copy(sJSCommand_drilldown, 1, Length(sJSCommand_drilldown) - 1);
          sJSCommand_drilldown := sJSCommand_drilldown +
            ']' + '}' + ');';

          UniSession.AddJS(sJSCommand_drilldown);

          Sleep(100);
        end;
      end;
    except
      on E:Exception do
      begin
        ShowMessage('SetDataPass::Exception = ' + e.Message);
      end;
    end;
  finally
    FreeAndNil(extn_names);
    FreeAndNil(extn_datas);
  end;
end;


text:
Q: Count all from another table I have one table like this:
a. tbl_cdr

b. tbl_wo_notification_contacts

What I want was count all from tbl_wo_notification_contacts and tbl_cdr. Here is my query.
SELECT SUBSTRING(n.last_attempt,1,10) AS DATE,
SUM(IF(n.STATUS=1, 1,0)) AS 'Success',
SUM(IF(n.STATUS=2, 1,0)) AS 'Failed',
COUNT(*) AS 'TotalCalls'
FROM tbl_wo_notification_contacts n
WHERE n.last_attempt >= '2019-05-01' AND n.last_attempt <= '2019-07-01'
GROUP BY SUBSTRING(n.last_attempt,1,10);

The problem is I want to add new column called 'Total Duration' where it counts all from tbl_cdr based on the query condition.

A: Group tbl_cdr by ContactsID to get the counts.
SELECT SUBSTRING(n.last_attempt,1,10) AS DATE,
        SUM(IF(n.STATUS=1, 1,0)) AS 'Success',
        SUM(IF(n.STATUS=2, 1,0)) AS 'Failed',
        COUNT(*) AS 'TotalCalls',
        IFNULL(c.TotalDuration, 0) AS TotalDuration
FROM tbl_wo_notification_contacts n
LEFT JOIN (
    SELECT ContactID, COUNT(*) AS TotalDuration
    FROM tbl_cdr
    GROUP BY ContactID) AS c ON c.ContactID = n.id
WHERE n.last_attempt >= '2019-05-01' AND n.last_attempt <= '2019-07-01'
GROUP BY SUBSTRING(n.last_attempt,1,10);


text:
Q: How to frame JSON array from passing the checked checkbox values using php I am trying to build array from checked checkbox values in views. When form submitting checked checkbox values will form a array. I have a checkbox fields like this. Please anyone help me.
           {{Form::checkbox('additional_rooms[]', 'Prayer Room') }}  Prayer Room
            {{ Form::checkbox('additional_rooms[]', 'Study Room') }}  Study Room
            {{ Form::checkbox('additional_rooms[]', 'Store Room') }}  Store Room
            {{ Form::checkbox('additional_rooms[]', 'Servent Room') }}  Servent Room

A: var values = [];

$('[name="additional_rooms[]"]:checked') // Select checked checkboxes
    .each(function(index, element) {     // Iterate each one
        values.push($(element).val());   // Put its value in an array
    })

console.log(JSON.stringify(values)); // JSON encode the array

A: You cat get all checked checkbox values in a variable after submit form.
Example:
$("#form").submit(function(){
      var values = [];

      $('[name="additional_rooms[]"]:checked') // Select checked checkboxes
         .each(function(index, element) {     // Iterate each one
          values.push($(element).val());   // Put its value in an array
      });
      console.log(JSON.stringify(values)); // JSON encode the array
});


text:
Q: Calculating entropy from co-occurence matrix in Matlab I am trying to extract the entropy from co-occurence matrices with zero entries in Matlab. From the definition of entropy of a co-occurence matrix:

has to be calculated, where cij stands for the (i,j) entry of the co-occurence matrix. Thus it seems to me that if there is a single zero entry, the entropy will be undefined. Do you set some sort of lower limit to log(x) when x = 0, or how do you deal with it?
Link to a pdf with the definition of entropy for the GLCM: http://www.code.ucsd.edu/pcosman/glcm.pdf
EDIT: Thanks for the suggestions on how to deal with log(0), but the equation actually calls for evaluating 0*log(0) which is 0 anyway. It would have been easier to explain if I could use formulas, but maybe my question was more mathematical anyway, and thus on the wrong forum.

A: I always do this if I don't want a -Inf when I log something.
set an epsilon which is very, very little and deal your matrix C like
e = 1e-99;
C = C + e;

then you could run your old code and the answer will not be -Inf.
Thank for @CrisLuengo's useful advice in comment

A: I generally use the following workaround to avoid this issue:
X = C .* log2(C + (C == 0));
entropy = -sum(X(:));

For those entries of C (the co-occurrence matrix) that are 0, the argument of the logarithm function is 1 since the expression (C == 0) is evaluated as 1.


text:
Q: Pass data from activity B to A without B finishing I have a project where the user navigates from activity A to B. Some information from activity B must be send to activity A without B finishing. This should make it possible that A already starts processing the data in the background.
I have following example project:
Activity A:
class MainActivity : AppCompatActivity() {

    private lateinit var goButton: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        goButton = findViewById(R.id.goButton)

        goButton.setOnClickListener{
            startActivityForResult(Intent(this, MainActivity2::class.java), 100)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode == Activity.RESULT_OK){
            if(requestCode == 100){
                Log.e("Picture: ", data!!.getStringExtra("picture")!!)
            }
        }
    }
 }

Activity B:
class MainActivity2 : AppCompatActivity() {

    private lateinit var backButton: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)

        backButton = findViewById(R.id.returnButton)

        backButton.setOnClickListener{
            intent.putExtra("picture", UUID.randomUUID().toString())
            setResult(Activity.RESULT_OK, intent)
            finish()
        }
    }
}

This works but if I remove the "finish()" line this no longer works. But I would like to send the generated UUID each time the button is pressed and not only when B is finished.

A: you can't do this as only one Activity may be working at the same time, all others are paused at least, probably also stopped. thus "backgrounded" Activity can't do anything as Activity is GUI - it isn't visible, so it has nothing to do. if you have to start some logic processing, nothing related with GUI, then all code should start in some background-working component, e.g. new Thread or simply Service and first Activity should read processed data/state of processing when it is resumed (onResume called)


text:
Q: Import of .csv file from linux to windows MYSQl I need a shell script that must import latest ".csv" file into mysql...
My case is--->i need to import the latest ".csv" file from linux to windows mysql i.e my ".csv" files will be stored in a path of linux PC and import need to be done in windows.
I would appreciate the prompt response.

A: shell script
ok:
step 1: sort the csv file by reverse date
        ls --time-style=full-iso -l | grep -E "*.csv" | sort -k5 -k6 -r
step 2: the first file is the latest file
step 3: there should have some tool to import csv file to mysql

windows or linux is not the problem, that's why you can also access window's mysql from linux.
just connect the ip:port address. then do anything you want


text:
Q: Semaphore controlled resources - what is the clean shutdown sequence/pattern If i control a pool of resources with a semaphore, what is the clean shutdown sequence for this resource pool?
  class ResourcePool
  {
  Semaphore resourceSemaphore;
  Stack<ResourceClass> resources;
    public ResourcePool()
    {
        resources ... // Init some Resources in the stack
        resourceSemaphore=  new Semaphore(resources.Count,resources.Count);

    }

    public void ResourceTask()
    {
        resourceSemaphore.WaitOne();
        ResourceClasscurrent = null;
        try
        {
            current = resources.Pop();
            current.Task();
        }
        finally
        {
            if( current != null )
                resources.Push(current);

            resourceSemaphore.Release();
        }

    }
  }

How to implement a clean shutdown sequence for this pool? Maybe the resources use IDisposable, this should eventually come into play.

A: Hope that helps Thread Management In The CLR


text:
Q: MASM, de carácter en registro a número en variable Tengo un código de MASM que, groso modo, se encarga de recoger información de los registros y poner sus valores en una ventana.
Siendo aStr, bStr, cStr y dStr los textos de "presentación" de cada registro y aStrv, bStrv… los valores de éstos, simplemente recoge si haces click derecho o izquierdo (o pulsas una tecla con el focus), para hacer xor y limpiar registros o actualizar los valores mostrados, respectivamente. Por si lo necesitan, tienen todo el código aquí. Si no, tienen más abajo el fragmento concreto donde, a mi parecer, estaría el problema.
.386
.model flat,stdcall
option casemap:none
WinMain proto :DWORD,:DWORD,:DWORD,:DWORD
include \masm32\include\windows.inc
include \masm32\include\user32.inc
include \masm32\include\kernel32.inc
include \masm32\include\gdi32.inc
include \masm32\include\rtutils.inc
includelib \masm32\lib\user32.lib
includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\gdi32.lib
RGB macro red,green,blue
        xor eax,eax
        mov ah,blue
        shl eax,8
        mov ah,green
        mov al,red
endm
.data
ClassName db "Regist",0
AppName  db "Lector de registros generales de CPU",0
aStr  db "Registro eax: ",0
bStr  db "Registro ebx: ",0
cStr  db "Registro ecx: ",0
dStr  db "Registro edx: ",0

aStrv  dd 0b
bStrv  dword 0b
cStrv  dword 0b
dStrv  dword 0b
delayer dword 0
FontName db "Segoe UI",0
MouseClickL db 0
MouseClickR db 0

actul db "Actualizado",0
ers db "Valores borrados",0
.data?
hInstance HINSTANCE ?
CommandLine LPSTR ?
hitpoint POINT <>
.code
 start:
    invoke GetModuleHandle, NULL
    mov    hInstance,eax
    invoke GetCommandLine
    invoke WinMain, hInstance,NULL,CommandLine, SW_SHOWDEFAULT
    invoke ExitProcess,eax

WinMain proc hInst:HINSTANCE,hPrevInst:HINSTANCE,CmdLine:LPSTR,CmdShow:DWORD
    LOCAL wc:WNDCLASSEX
    LOCAL msg:MSG
    LOCAL hwnd:HWND
    mov   wc.cbSize,SIZEOF WNDCLASSEX
    mov   wc.style, CS_HREDRAW or CS_VREDRAW
    mov   wc.lpfnWndProc, OFFSET WndProc
    mov   wc.cbClsExtra,NULL
    mov   wc.cbWndExtra,NULL
    push  hInst
    pop   wc.hInstance
    mov   wc.hbrBackground,COLOR_WINDOW+1
    mov   wc.lpszMenuName,NULL
    mov   wc.lpszClassName,OFFSET ClassName
    invoke LoadIcon,NULL,IDI_APPLICATION
    mov   wc.hIcon,eax
    mov   wc.hIconSm,eax
    invoke LoadCursor,NULL,IDC_ARROW
    mov   wc.hCursor,eax
    invoke RegisterClassEx, addr wc
    invoke CreateWindowEx,NULL,ADDR ClassName,ADDR AppName,\
           WS_OVERLAPPEDWINDOW,0,\
           0,250,180,NULL,NULL,\
           hInst,NULL
    mov   hwnd,eax
    invoke ShowWindow, hwnd,SW_SHOWNORMAL
    invoke UpdateWindow, hwnd
    .WHILE TRUE
                invoke GetMessage, ADDR msg,NULL,0,0
                .BREAK .IF (!eax)
                invoke TranslateMessage, ADDR msg
                invoke DispatchMessage, ADDR msg
    .ENDW
    mov     eax,msg.wParam
    ret
WinMain endp
WndProc proc hWnd:HWND, uMsg:UINT, wParam:WPARAM, lParam:LPARAM
    LOCAL hdc:HDC
    LOCAL ps:PAINTSTRUCT
    LOCAL hfont:HFONT
    .IF uMsg==WM_DESTROY
        invoke PostQuitMessage,NULL
    .ELSEIF uMsg==WM_LBUTTONDOWN
        mov MouseClickL,TRUE
        invoke InvalidateRect,hWnd,NULL,TRUE
    .ELSEIF uMsg==WM_RBUTTONDOWN
        mov MouseClickR,TRUE
        invoke InvalidateRect,hWnd,NULL,TRUE
    .ELSEIF uMsg==WM_CHAR
        mov MouseClickL,TRUE
        invoke InvalidateRect,hWnd,NULL,TRUE
    .ELSEIF uMsg==WM_PAINT
        invoke BeginPaint,hWnd, ADDR ps
        mov    hdc,eax
        invoke SelectObject, hdc, eax
        mov    hfont,eax
        RGB    0, 0, 0
        invoke SetTextColor,hdc,eax
        RGB    255, 255, 255
        invoke SetBkColor,hdc,eax

;--------------------------------------------Fragmento mostrado posteriormente----------------------------------
        update:
        mov aStrv, eax
        mov bStrv, ebx
        mov cStrv, ecx
        mov dStrv, edx
;-------------------------------------------Fin de fragmento----------------------------------------------------

        invoke TextOut,hdc,5,5,ADDR aStr,SIZEOF aStr
        invoke TextOut,hdc,5,30,ADDR bStr,SIZEOF bStr
        invoke TextOut,hdc,5,55,ADDR cStr,SIZEOF cStr
        invoke TextOut,hdc,5,80,ADDR dStr,SIZEOF cStr

        invoke TextOut,hdc,100,5,ADDR aStrv,SIZEOF aStrv
        invoke TextOut,hdc,100,30,ADDR bStrv,SIZEOF bStrv
        invoke TextOut,hdc,100,55,ADDR cStrv,SIZEOF cStrv
        invoke TextOut,hdc,100,80,ADDR dStrv,SIZEOF dStrv
        invoke SelectObject,hdc, hfont

        .IF MouseClickL
            mov MouseClickL, FALSE
            jmp update
        .ENDIF
        .IF MouseClickR
            mov MouseClickR, FALSE
            xor eax, eax
            xor ebx, ebx
            xor ecx, ecx
            xor edx, edx
            jmp update
        .ENDIF
        invoke EndPaint,hWnd, ADDR ps
    .ELSE
        invoke DefWindowProc,hWnd,uMsg,wParam,lParam
        ret
    .ENDIF
    ret
WndProc endp
end start

De éste código creo que sólo es prioritaria la parte de:
mov aStrv, eax
mov bStrv, ebx
mov cStrv, ecx
mov dStrv, edx

Donde me gustaría que aStrv y todas las demás variables no recogieran símbolos como en la imagen:

¿Cómo podría convertir la información del registro a HEX o BIN, y a su vez sacarlo como texto tipo 0x00, para evitar estos caracteres?


text:
Q: Splunk search on computed column I'm trying to search result set computed column based upon a text box token in a dashboard. A simplified version of one of my attempts at the XML definition is below:
 </input>
    <input type="text" token="ID" searchWhenChanged="true">
        BIB ID
    <default>*</default>
 </input>
</fieldset>
<row>

    <title>Customer</title>
    <search>
      <query>sourcetype="source type" | eval "ID"=substr('FullID',21,29) |
        where "ID"="$ID$"
      </query> (...)

I've tried a number of ways of dynamically assigning a value from the text box to filter ID by $ID$ in each of the pipelines, but nothing so far works.


text:
Q: ActiveRecord Fuzzy Search I'm looking to perform a search to find an object similar to this:
Object(id: 1, example: "abc")
by using a search like this:
params[:search] = "abcdef"
Object.where("example LIKE ?", "#{params[:search]%")

but am only able to use the above example if my search has less characters than my object, not more.

A: I think it should be
params[:search] = "abcdef"
Object.where("example LIKE ?", "%#{params[:search]}%")

Also might want to use ilike for case insensitive search (if you're using postgres)

A: Note: the fuzzily gem does not work with Rails 6. This solution has been deprecated.
The fuzzily gem allows you to do fuzzy searching of ActiveRecord models that you've instrumented appropriately.

Fuzzily finds misspelled, prefix, or partial needles in a haystack of strings. It's a fast, trigram-based, database-backed fuzzy string search/match engine for Rails.

Once you've installed the gem, you can instrument your model as follows:
class MyStuff < ActiveRecord::Base
  # assuming my_stuffs has a 'name' attribute
  fuzzily_searchable :name
end

You can then perform fuzzy searches as follows:
MyStuff.find_by_fuzzy_name('Some Name', :limit => 10)
# => records


text:
Q: Current time calculations in ruby I need to determine the current time of day and let the user know it's time to do a particular task. For example if the time is between an amount of hours (eg. Between 6am and 12pm) the user should do a certain task. If the time is after that (between 1pm and 6pm) the user should do another task and if the time is any time outside those times they should do something else.
I don't know enough about ruby to post an example of code I've worked on so far. All I know is how to determine what the current time is with t = Time.now and how to determine if the time is between certain hrs, what I don't know is how to put that in a method to determine if the hrs are between a given time to tell the user to perform the task.
Any help appreciated.

A: First of all, get acquainted with usage of Time class in ruby.
As you get comfortable with it, you'll see that making comparisons like below is simple enough.
2.3.1 :001 > n = Time.now.hour
 => 17
2.3.1 :002 > n.between? 13, 18 #1 pm - 6 pm
 => true
2.3.1 :004 > n.between? 6, 12
 => false

Note: between comes from Comparable module
you can start by playing with below snippet.
2.3.1 :001 > def task_for_night
2.3.1 :002?>   puts "night task started"
2.3.1 :003?>   end
 => :task_for_night
2.3.1 :004 > def task_for_day
2.3.1 :005?>   puts "day time"
2.3.1 :006?>   end
2.3.1 :021 > def assign_task
2.3.1 :022?>   (Time.now.hour.between? 6,12) ? task_for_night : task_for_day
2.3.1 :023?>   end
 => :assign_task
2.3.1 :024 > assign_task
day time
 => nil

A: case with ranges is the perfect syntax for what you want to do :
case Time.now.hour
when (6..12)
  puts "Task A"
when (13..18)
  puts "Task B"
else
  puts "Free time"
end

A: Get current time (only hour: %H) and convert it to integer.
time = Time.now.strftime('%H').to_i
# 15

And check condition of time in nested ternary operator (conditional operator)
(time.between? 6,12) ? "Do morning's task" : (time.between? 13,18) ? "Do afternoon's task" : "Do something else"

# Do afternoon's task

A: Also you can use #case :
def what_should_i_do_now?
  case Time.now.hour
  when 6..12 then 'Do morning task'
  when 13..18 then "Do afternoon's task"
  else "Do something else"
  end
end

and now you can do even more:
def what_should_i_do_at(time)
  case time.hour
  when 6..12 then 'Do morning task'
  when 13..18 then "Do afternoon's task"
  else "Do something else"
  end
end

> what_should_i_do_at(Time.now+60*60) # plus 1 hour
#=> "Do afternoon's task"


text:
Q: MySQL subquery with between date My query is for calculating sales profit. To calculate cost price I need to take average cost for particular date. The below query works well if I have a single date, but for a range of dates (replacing '=2014-12-30 ' with 'BETWEEN '2014-12-30' AND '2015-01-02' at both places) it does not generate required output
SELECT sinvoiceno,sinvoicedate,pureweight,makingcharge,totalamount,rd.avgr ,
    (pureweight*rd.avgr)+makingcharge AS TotalCost ,
    totalamount-((pureweight*rd.avgr)+makingcharge) AS Profit
FROM
    (SELECT DATE_FORMAT(gdate,'%Y-%m-%d') AS grDate,AVG(goldrate24) AS AvgR
     FROM rate_detail r
     GROUP BY grDate
     HAVING grdate = '2014-12-30' ) AS rd,
    sales_master sm
WHERE  sinvoicedate = '2014-12-30'

A: You need a joining condition so that you link rows of the subquery with sales_master on the same date.
SELECT sinvoiceno,sinvoicedate,pureweight,makingcharge,totalamount,rd.avgr ,
    (pureweight*rd.avgr)+makingcharge AS TotalCost ,
    totalamount-((pureweight*rd.avgr)+makingcharge) AS Profit
FROM
    (SELECT DATE(gDate) AS grDate, AVG(goldrate24) AS AvgR
     FROM rate_detail r
     WHERE DATE(gDate) BETWEEN '2014-12-30' AND '2015-01-02'
     GROUP BY grDate ) AS rd
JOIN sales_master sm ON sinvoicedate = grDate
WHERE sinvoicedate BETWEEN '2014-12-30' AND '2015-01-02'

A: Try this:
SELECT sinvoiceno, sinvoicedate, pureweight, makingcharge,
       totalamount, rd.avgr, (pureweight * rd.avgr) + makingcharge AS TotalCost ,
       totalamount -((pureweight * rd.avgr) + makingcharge) AS Profit
FROM (SELECT STR_TO_DATE(gdate,'%Y-%m-%d') AS grDate,AVG(goldrate24) AS AvgR
      FROM rate_detail r
      WHERE STR_TO_DATE(gdate,'%Y-%m-%d') BETWEEN '2014-12-30' AND '2015-01-02'
      GROUP BY grDate
     ) AS rd,
INNER JOIN sales_master sm ON rd.grDate = sinvoicedate
WHERE sinvoicedate BETWEEN '2014-12-30' AND '2015-01-02';

A: You seem to want the rd subquery to return one row, an average over a period of time.  So, remove the group by and put in the appropriate bounds using where:
SELECT sm.sinvoiceno, sm.sinvoicedate, sm.pureweight, sm.makingcharge, sm.totalamount,
       rd.avgr, (sm.pureweight*rd.avgr) + sm.makingcharge AS TotalCost ,
       sm.totalamount-((sm.pureweight*rd.avgr)+sm.makingcharge) AS Profit
FROM sales_master sm CROSS JOIN
     (SELECT AVG(goldrate24) AS AvgR
      FROM rate_detail r
      WHERE grDate = '2014-12-30'
     ) rd
WHERE sm.sinvoicedate = '2014-12-30';

You can then put a range in to expand the time period for the average.  For instance:
SELECT sm.sinvoiceno, sm.sinvoicedate, sm.pureweight, sm.makingcharge, sm.totalamount,
       rd.avgr, (sm.pureweight*rd.avgr) + sm.makingcharge AS TotalCost ,
       sm.totalamount-((sm.pureweight*rd.avgr)+sm.makingcharge) AS Profit
FROM sales_master sm CROSS JOIN
     (SELECT AVG(goldrate24) AS AvgR
      FROM rate_detail r
      WHERE grDate BETWEEN '2014-12-30' AND '2015-01-02'
     ) rd
WHERE s.invoiceDate BETWEEN '2014-12-30' AND '2015-01-02';

EDIT:
It occurs to me that you want the average on a single date, which is the invoice date.  In that case:
SELECT sm.sinvoiceno, sm.sinvoicedate, sm.pureweight, sm.makingcharge, sm.totalamount,
       rd.avgr, (sm.pureweight*rd.avgr) + sm.makingcharge AS TotalCost,
       sm.totalamount-((sm.pureweight*rd.avgr)+sm.makingcharge) AS Profit
FROM sales_master sm JOIN
     (SELECT date(grDate) as grDate, AVG(goldrate24) AS AvgR
      FROM rate_detail r
      WHERE BETWEEN '2014-12-30' AND '2015-01-02'
      GROUP BY date(grDate)
     ) rd
     ON rd.grDate = sm.s.invoicedate
WHERE s.invoiceDate BETWEEN '2014-12-30' AND '2015-01-02';

I am unclear as to whether or not the "date" columns have time components.  If so, then you want to use date() where appropriate.


text:
Q: Radical of the sum of modules Let $R$ be a commutative ring (not necessarily with a unit), $M$ be some $R$-module, and N a submodule of the module M. We define (according to Zariski and Samuel, 1958) the radical $\sqrt N$ of the submodule N as the set $\tau$ of all elements $a \in R$, some $n$-th power each of which satisfies the relation $a^n \dot M \subset N$. $\tau$ is obviously the ideal in $R$.
Is it true that $\sqrt{M_1 + M_2} = \sqrt {\sqrt M_1 + \sqrt M_2}$, where $M_1$ and $M_2$ are submodules of $M$? And if not, what is the counterexample?

A: An easy counterexample is the 2-dimensional vector space M with basis $\{е_1, е_2\}$ and the subspaces $М_1$ and $М_2$ generated by $\{е_1\}$ and $\{е_2\}$, respectively.


text:
Q: Issue in showing File Upload for image in Draft JS I using the draft-js to show editor in web application. But i am facing issue in showing the file upload option in draft editor.
here is a screenshot :

This is how editor is shown on their demo

You can check the demo here https://jpuri.github.io/react-draft-wysiwyg/#/
Please check the code below and suggest the solution :
import React, { Component } from 'react';
import logo from './logo.svg';

import { EditorState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty(),
    };
  }

  onEditorStateChange: Function = (editorState) => {
    this.setState({
      editorState,
    });
  };

  render() {
    const { editorState } = this.state;
    return (

         <Editor
  editorState={editorState}
  toolbarClassName="toolbarClassName"
  wrapperClassName="wrapperClassName"
  editorClassName="editorClassName"
  onEditorStateChange={this.onEditorStateChange}
toolbar={{
    inline: { inDropdown: true },
    list: { inDropdown: true },
    textAlign: { inDropdown: true },
    link: { inDropdown: true },
    history: { inDropdown: true },
    inputAccept: 'application/pdf,text/plain,application/vnd.openxmlformatsofficedocument.wordprocessingml.document,application/msword,application/vnd.ms-excel'
  }}
/>

    );
  }
}

export default App;

A: Solved the issue. I forgot to implement the callback function to upload a file. Here is the working code:
    import React, { Component } from 'react';
    import logo from './logo.svg';

    import { EditorState } from 'draft-js';
    import { Editor } from 'react-draft-wysiwyg';
    import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

    class App extends Component {

      constructor(props) {
        super(props);
        this.state = {
          editorState: EditorState.createEmpty(),
          uploadedImages: []
        };
        this._uploadImageCallBack = this._uploadImageCallBack.bind(this);
      }

      onEditorStateChange: Function = (editorState) => {
        this.setState({
          editorState,
        });
      };

      _uploadImageCallBack(file) {
        // long story short, every time we upload an image, we
        // need to save it to the state so we can get it's data
        // later when we decide what to do with it.

        // Make sure you have a uploadImages: [] as your default state
        let uploadedImages = this.state.uploadedImages;

        const imageObject = {
          file: file,
          localSrc: URL.createObjectURL(file),
        }

        uploadedImages.push(imageObject);

        this.setState({ uploadedImages: uploadedImages })

        // We need to return a promise with the image src
        // the img src we will use here will be what's needed
        // to preview it in the browser. This will be different than what
        // we will see in the index.md file we generate.
        return new Promise(
          (resolve, reject) => {
            resolve({ data: { link: imageObject.localSrc } });
          }
        );
      }
      render() {
        const { editorState } = this.state;
        return (

              <Editor
                editorState={editorState}
                toolbarClassName="toolbarClassName"
                wrapperClassName="wrapperClassName"
                editorClassName="editorClassName"
                onEditorStateChange={this.onEditorStateChange}
                toolbar={{
                  inline: { inDropdown: true },
                  list: { inDropdown: true },
                  textAlign: { inDropdown: true },
                  link: { inDropdown: true },
                  history: { inDropdown: true },
                  image: { uploadCallback: this._uploadImageCallBack },
                  inputAccept: 'application/pdf,text/plain,application/vnd.openxmlformatsofficedocument.wordprocessingml.document,application/msword,application/vnd.ms-excel'
                }}
              />

        );
      }
    }

    export default App;


text:
Q: Stream is disposing before EndOfData is true I am writing a method that connects to an FTP, reads a csv file into a stream then uses a TextFieldParser to process the data.
It's all working except for an issue I'm getting when it gets about halfway through reading the CSV suddenly I get an ObjectDisposedException exception.  I've tried passing both the StreamReader & TextReader to the TextFieldParser but both result in the same problem.
Should I be downloading the CSV to a temporary local directory and then reading that or is there no issue reading a file from an FTP?  I figured there might be some server setting possibly timing out the stream before it reads the entire file.
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("REMOVED.csv");
request.Credentials = new NetworkCredential("xyz", "*******");
using (WebResponse response = request.GetResponse())
{
    using (Stream stream = response.GetResponseStream())
    {
        using (TextReader reader = new StreamReader(stream))
        {
            using (TextFieldParser parser = new TextFieldParser(reader))
            {
                parser.HasFieldsEnclosedInQuotes = true;
                parser.Delimiters = new string[] { "," };
                while (!parser.EndOfData) //exception is thrown here about 1500lines into csv
                {
                    Console.WriteLine(parser.ReadLine().ToString());
                }
            }
        }
    }
}

LAST LINE OF OUTPUT BEFORE EXCEPTION THROWN
190500,Courier Delivery,Freight,Distributor,1,5,15/12/2014 16:44

If I should be downloading the file first, do I just use WebClient.DownloadFile() ?? How can I tell when the file has finished downloading to then read it?
EDIT:
System net tracing output shows the following

System.Net.Sockets Verbose: 0 : [10412] Exiting Socket#24914721::Receive()    -> Int32#95
  System.Net Information: 0 : [10412] FtpControlStream#15315213 - Received response [226-File successfully transferred
  226 5.748 seconds (measured here), 30.91 Kbytes per second]
  System.Net Information: 0 : [10412] FtpWebRequest#16868352::(Releasing FTP connection#15315213.)

FURTHER EDIT
The output from System.Net Tracing shows the last line of the CSV being received, so why is the parser being Disposed before it finishes??  I'm still quite new to programming so I'm not really sure how to proceed

A: So I was unable to figure out how to stop the stream disposing before I read to the end with my TextFieldParser, instead I did the following:

Connect to FTP
Read the file into a stream
Copy the stream to a FileStream and create a temporary file
Read the temporary file
Delete the temporary file

This isn't very elegant but if anyone else comes across the above error know that downloading the file is an alternative.

A:
Use the Peek method instead of EndOfData - havent tested this, but should work...

//...
  using (var response = request.GetResponse())
  {
    using (var stream = response.GetResponseStream())
    {
      using (var reader = new StreamReader(stream))
      {
        while (reader.Peek() != -1) //use Peek instead
        {
          Console.WriteLine(reader.ReadLine());
        }
      }
    }
  }
//...


text:
Q: Audio file progress is not displayed in Chrome/Chromium browsers I have a situation where .mp3 audio files can be played from my site, but in Chrome and Chromium-based browsers (e.g. Edge), the progress bar does not display the location and you are unable to advance forward by clicking in the progress bar. In Firefox and IE it works correctly.
This happens when I embed the file in the page with <audio> tags, but also when I access the file directly in the browser. So it's not an application issue.
I've tested the same file on another server and it works in Chrome, so I suspect there is something going on at the server level that is affecting how it's loading, but have not been able to pinpoint the cause. We're running Centos7.

A: I traced the issue to the Apache mod_pagespeed module. Ironic, as this is a module produced by Google and the issue only affected chromium based browsers. I suspect it has something to do with how that module tries to progressively download content. I decided to just disable the module altogether and the audio files began working as expected.


text:
Q: Replacing unicode character with similar character from standard utf-8 english I was building a database with python/mysql by parsing a data file.
At a point, the file contained the character 'р'. When the mysql query gets that as input, it breaks.
So the problem is the above is not standard English character "p"
if you try json.dumps('р'), you'll find it outputs '\u0440'
Is there a way to detect the encoding and replace with something similar from standard utf-8 English ? I can't manually replace all р with p as there are lots of other Unicode characters as well.
Beating my head right now. Pls throw some light or hint.


text:
Q: Basic Memory Game Java I'm doing this memory Game and I can't seem to figure out the algorithm for matching the cards.
Like if two cards are the same, it gets disabled else hide the cards again.
Every time I click a card, it stays open and when I randomly select another card, for some reason the other ones closes again.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MemGame extends JFrame implements ActionListener
{
GridLayout three = new GridLayout(4,4);

String dolls[]= {"Ugly1.jpg","Ugly1.jpg","Ugly2.jpg","Ugly2.jpg","Ugly3.jpg","Ugly3.jpg","ugly4.jpg","Ugly4.jpg","Ugly5.jpg","Ugly5.jpg","Ugly6.jpg","Ugly6.jpg","Ugly7.jpg","Ugly7.jpg","Ugly8.jpg","Ugly8.jpg"};
JButton button[]= (new JButton[dolls.length]);
int current,shuffle,trans;
int check=0;
int holder[]=new int [2];

String container[]={"",""};

public MemGame()
{
    Container c = getContentPane();
    c.setLayout(three);

        for(current=0;current<dolls.length;current++)
        {

            int shuffle=(int)(Math.random()*dolls.length);
            String hold=dolls[current];
            dolls[current]=dolls[shuffle];
            dolls[shuffle]=hold;

        }

        for(int x=0;x<dolls.length;x++)
        {
            button[x]=new JButton();
            c.add(button[x]);
            button[x].addActionListener(this);
        }

    setVisible(true);
    setSize(500,500);
}
public void actionPerformed(ActionEvent e)
{
        for(int x=0;x<dolls.length;x++)
        {
            if(e.getSource()==button[x])
            {
                button[x].setText("");
                button[x].setIcon(new ImageIcon(dolls[x]));
                button[x].setEnabled(false);

            //This is where my problem starts.... I think

                check++;

                if(check==1)
                {
                    container[0]=dolls[x];
                    holder[0]=x;

                }
                if(check==2)
                {

                    container[1]=dolls[x];
                    holder[1]=x;

                }
                if(check==3)
                {
                    if(container[0].equals(container[1]))
                    {
                        button[holder[0]].setEnabled(false);
                        button[holder[1]].setEnabled(false);
                    }
                    else
                    {
                        button[holder[0]].setEnabled(true);
                        button[holder[0]].setIcon(new ImageIcon());

                        button[holder[1]].setEnabled(true);
                        button[holder[1]].setIcon(new ImageIcon());

                    }
                    check=1;

                }
            }
        }
    }

    public static void main (String args[])
    {
        new MemGame();
    }
}

A: Check for a valid combination on the second click, when check equals 2, and re-enable the buttons if they do not match.
To redraw the screen while handling an event, this logic needs to run in a new thread, because the one responsible for updating the UI is already busy executing the event handler code.
@Override
public void actionPerformed(ActionEvent e) {
    Thread t = new Thread(() -> {
        for (int x = 0; x < dolls.length; x++) {
            if (e.getSource() == button[x]) {
                button[x].setText("");
                button[x].setIcon(new ImageIcon(dolls[x]));
                button[x].setEnabled(false);

                check++;
                if (check == 1) {
                    container[0] = dolls[x];
                    holder[0] = x;
                }
                if (check == 2) {
                    container[1] = dolls[x];
                    holder[1] = x;

                    try {
                        Thread.sleep(500L);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }

                    if (!container[0].equals(container[1])) {
                        button[holder[0]].setEnabled(true);
                        button[holder[0]].setIcon(new ImageIcon());
                        button[holder[1]].setEnabled(true);
                        button[holder[1]].setIcon(new ImageIcon());
                    }
                    check = 0;
                }
            }
        }
    });
    t.start();
}


text:
Q: Facebook share URL with get parameters I'm trying to generate a share URL with get parameters and it's doing some double encoding shenanigans.

produces an error url while

is fine.  Anyone have ideas?

A: Facebook share link needed to be cached on their side.  This has since be resolved on facebooks end.


text:
Q: Django: What's the standard way to use a view just to process a form? A user is viewing another user's profile at profile/userB/, and clicks the Add Friend button.
This submits a POST form containing both users to the create view in the friends app (friends/create/), which processes the data, creates a new Friend object and saves it in the database. A flash message is set as feedback, and the user finds themselves back on at profile/userB/.
The user never sees friend/create/.
This feels really obvious, and I did this regularly with CakePHP, but I'm having trouble picturing this in Django. I'm trying to keep a forms.py separate, with templates surrounding forms separate as well (e.g. the 'Add Friend' template may be included in various locations, including the form and submitting as above). I think that's the right way to do this?
Thanks

A: Sounds like you don't even need a form and there's no need to submit POST. Instead of defining your url as friend/create/, use something like this:
url(r'^create-friendship/(?P<user_id>\d+)/$', 'create_friendship', name='create-friendship'),

Then you define your Add Friend as a link(but you should make it like a button for user experience), roughly like this:
Add friend

Notice that I added a GET parameter from at the end of the link, that's the current url you pass to the view method. Then in your create view:
def create_friendship(user_id):
    # logic to build your friendship relationship between user_id and request.user
    if request.GET.get('from'):
        return HttpResponseRedirect(request.GET.get('from'))
    else:
        # return to some other urls

There's no "built-in" way to do this in django, but once you understand the framework better, it should become obvious.
ps: In order to access request variable in django template, you have to enable a template processor, add following to your TEMPLATE_CONTEXT_PROCESSOR in settings:
TEMPLATE_CONTEXT_PROCESSORS = (
  # ...
  'django.core.context_processors.request',
  # ...
)


text:
Q: Finding last item that matches criteria in Python https://stackoverflow.com/a/9868665/433570 finds the first item.
I can think of doing reverse first before applying the solution above.
But then I would end up with two reverse which might be avoided.
Is there a better solution than using two reverse and next ?

A: The accepted answer in related questions suggested to use an iterator on the list to build a generator containing only matching elements and take first element from that generator:
next(obj for obj in objs if condition)

You can do the same using range in opposite order:
next(objs[i] for i in range(len(objs) -1, -1, -1))

(use xrange in Python2)

A: Instead of reversing the list, which may be a lengthy operation (l.reverse()) because it reverses the whole list, I'd simply use a reversed iterator reversed(l) with whatever matching method you want, since you can stop early at the first match, it may save you time vs reversing the whole list.
Of course there's best case and worst cases for both methods, below may give you an idea, based on where the match is in the list (e.g. towards the end, the beginning, or the middle)
In [1]: l = range(0, 100000)

In [2]: %timeit next((i for i in reversed(l) if i == 1), None)
100 loops, best of 3: 2.94 ms per loop

In [3]: %timeit next((i for i in reversed(l) if i == 50000), None)
1000 loops, best of 3: 1.39 ms per loop

In [4]: %timeit next((i for i in reversed(l) if i == 99000), None)
10000 loops, best of 3: 29.4 µs per loop

Below is an idea of how long it takes to reverse the same list:
In [5]: %timeit l.reverse()
10000 loops, best of 3: 71.5 µs per loop

Note: I ran above on Python 2, so range() is a list not an iterator, so no need to list(range()) it to make the comparison worthwhile.

A: x = range(11)
y = next((i for i in reversed(x) if i % 2 == 1), None)


text:
Q: Como consultar 2 array con Volley Tengo el siguiente problema: Quiero que en un solo onResponse pueda traer dos array que tengo en un archivo PHP que he creado en un server de pruebas.
Pero cuando quiero trabajar el segundo array me dice que esta vació y la App se traba y cierra.
Tengo esto
// Funcion para consultar todas las Brigadas en server remoto
private void descargarBrigadas(){
    String url = "https://www.simcrs.org.sv/OCHOA/apiRestOCHOA";
    jrq = new JsonObjectRequest(Request.Method.GET, url, null, this, this);
    rq.add(jrq);
}

Esa dirección tiene 2 array juntos uno que llamo brigadas, 15 registros y el otro array que llamo turnos que básicamente tiene un registro por cada dia del año, ahorita tiene como 90
Luego tengo esto
@Override
public void onResponse(JSONObject response) {
    // Objeto AdminSQLiteOpenHelper
    AdminSQLite adminsql = new AdminSQLite(getActivity(), "ochoa", null, 1);
    // Abrir Base en modo lectura/escritura
    SQLiteDatabase DBM = adminsql.getWritableDatabase();
    // Borramos todo lo de las tablas Brigadas y Turnos
    DBM.delete("brigada",null,null);
    DBM.delete("turno",null,null);

    //Creamos objeto de la clase Brigadas
    Brigadas brigadas = new Brigadas();

    // brigadas se llama mi array en el server
    JSONArray jsonArrayBrigadas = response.optJSONArray("brigadas");
    JSONObject jsonObjectBrigadas = null;

    // Resgistros del array
    int arrayBrigadasLenght = jsonArrayBrigadas.length();

    for (int i = 0; i < arrayBrigadasLenght; i++){
        try {
            jsonObjectBrigadas = jsonArrayBrigadas.getJSONObject(i);
            brigadas.setBrigada(jsonObjectBrigadas.optInt("brigada"));
            brigadas.setJefe(jsonObjectBrigadas.optString("jefe"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // Variables para mostrar
        int brigada = brigadas.getBrigada();
        String jefe = brigadas.getJefe();

        // Toast.makeText(getActivity(),"Brigada: " + brigada + ", Jefe: " + jefe, Toast.LENGTH_SHORT).show();

        ContentValues registro = new ContentValues();
        registro.put("brigada", brigada);
        registro.put("jefe", jefe);

        DBM.insert("brigada", null, registro);
    }
    DBM.close();
}

Ahí voy al server remoto, traigo el array y lo inserto en mi tabla, hasta ahí todo bien.
El problema inicio cuando quiero hacer lo mismo con el 2do array y me dice que el JSONArray jsonArrayTurnos = response.optJSONArray("turnos"); es null y se crashea la app
@Override
public void onResponse(JSONObject response) {
    // Objeto AdminSQLiteOpenHelper
    AdminSQLite adminsql = new AdminSQLite(getActivity(), "ochoa", null, 1);
    // Abrir Base en modo lectura/escritura
    SQLiteDatabase DBM = adminsql.getWritableDatabase();
    // Borramos todo lo de las tablas Brigadas y Turnos
    DBM.delete("brigada",null,null);
    DBM.delete("turno",null,null);

    //Creamos objeto de la clase Brigadas
    Brigadas brigadas = new Brigadas();

    // brigadas se llama mi array en el server
    JSONArray jsonArrayBrigadas = response.optJSONArray("brigadas");
    JSONObject jsonObjectBrigadas = null;

    // Resgistros del array
    int arrayBrigadasLenght = jsonArrayBrigadas.length();

    for (int i = 0; i < arrayBrigadasLenght; i++){
        try {
            jsonObjectBrigadas = jsonArrayBrigadas.getJSONObject(i);
            brigadas.setBrigada(jsonObjectBrigadas.optInt("brigada"));
            brigadas.setJefe(jsonObjectBrigadas.optString("jefe"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // Variables para mostrar
        int brigada = brigadas.getBrigada();
        String jefe = brigadas.getJefe();

        // Toast.makeText(getActivity(),"Brigada: " + brigada + ", Jefe: " + jefe, Toast.LENGTH_SHORT).show();

        ContentValues registro = new ContentValues();
        registro.put("brigada", brigada);
        registro.put("jefe", jefe);

        DBM.insert("brigada", null, registro);
    }

    // Creamos objeto de la clase Turnos
    Turnos turnos = new Turnos();

    // turnos se llama mi array en el server
    JSONArray jsonArrayTurnos = response.optJSONArray("turnos");
    JSONObject jsonObjectTurnos = null;
    // Resgistros del array
    int arrayTurnosLenght = jsonArrayTurnos.length();

    for (int i = 0; i < arrayTurnosLenght; i++){
        try {
            jsonObjectTurnos = jsonArrayTurnos.getJSONObject(i);
            turnos.setFecha(jsonObjectTurnos.optString("fecha"));
            turnos.setBrigadaTurno(jsonObjectTurnos.optInt("brigada"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // Variables para mostrar
        String fecha = turnos.getFecha();
        int brigadaTurno = turnos.getBrigadaTurno();

         Toast.makeText(getActivity(),"Brigada: " + brigadaTurno + ", Fecha: " + fecha, Toast.LENGTH_SHORT).show();

        //ContentValues registro = new ContentValues();
        //registro.put("fecha", fecha);
        //registro.put("brigada", brigadaTurno);

        //DBM.insert("turno", null, registro);
    }
    DBM.close();
}

Busque info de como hacerlo y me tope con dos únicos sitios
Sitio 1, el cual adapte pero no pude traer ningun dato
Sitio 2, el que tiene casi que mi mismo problema pero no hubo solución. En este sitio le piden que haga un solo array pero no se si se aplica a mi pues yo tengo en un array 15 registros y en el otro muchisimos mas.
Les pido de favor su ayuda de como seria la mejor manera de poder descargar ambos arrays para poder continuar con mi proyecto.
Gracias

A: Ps si el api esta bien en el try catch yo lo uso así solo es acceder el nombre del array q necesites, Por EJEMPLO :
try {
                JSONObject jsonObject=new JSONObject(response);
                JSONArray array1 =jsonObject.getJSONArray("data"); //especificas el array q necesitas acceder
                for (int i=0; i<array.length(); i++ ){
                    JSONObject ob = array.getJSONObject(i);
                    List_Data_Trends listData=new List_Data_Trends(ob.getString(("id"))
                            ,ob.getString("row1")
                            ,ob.getString("row2")
                            ,ob.getString("row3"));

                }
             JSONArray array2 =jsonObject.getJSONArray("data2");
                for (int i=0; i<array.length(); i++ ){
                    JSONObject ob = array.getJSONObject(i);
                    List_Data_Trends listData=new List_Data_Trends(ob.getString(("id"))
                            ,ob.getString("row1")
                            ,ob.getString("row2")
                            ,ob.getString("row3"));

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

}

A: Puedes intentarlo de esta forma:
// Los datos que te recibes del Servidor es en JsonArray
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, URL_TEST, null,
        new Response.Listener<JSONArray>() {

            @Override
            public void onResponse(JSONArray response) {

                try {
                    // Acceder al Indice 0 del JSONObject para Brigadas
                    JSONObject jsonObjectBrigadas = response.getJSONObject(0);
                    // Acceder al JSONArray "brigadas"
                    JSONArray jsonArrayBrigadas = jsonObjectBrigadas.getJSONArray("brigadas");
                    Log.d(TAG,String.valueOf(jsonArrayBrigadas));

                    //Recorrer los datos del arreglo
                    for (int i = 0; i < jsonArrayBrigadas.length(); i++) {

                        JSONObject jsonObjectBrigadas1 = jsonArrayBrigadas.getJSONObject(i);
                        int brigada = (jsonObjectBrigadas1.getInt("brigada"));
                        String jefe = (jsonObjectBrigadas1.getString("jefe"));

                        // Mostrar la Informacion de las Brigadas
                        Toast.makeText(getApplicationContext(), "Brigada: " + brigada + ", Jefe: " + jefe, Toast.LENGTH_SHORT).show();
                    }

                    // Acceder al Indice 1 del JSONObject para los Turnos
                    JSONObject jsonObjectTurnos = response.getJSONObject(1);
                    // Acceder al JSONArray "turnos"
                    JSONArray jsonArrayTurnos = jsonObjectTurnos.getJSONArray("turnos");
                    Log.d(TAG,String.valueOf(jsonArrayTurnos));

                    for (int i = 0; i < jsonArrayTurnos.length(); i++) {

                        JSONObject jsonObjectTurnos_2 = jsonArrayTurnos.getJSONObject(i);
                        String fecha = (jsonObjectTurnos_2.getString("fecha"));
                        int brigadaTurno = (jsonObjectTurnos_2.getInt("brigada"));

                        // Mostrar la Informacion de los Turnos
                        Toast.makeText(getApplicationContext(), "Brigada: " + brigadaTurno + ", Fecha: " + fecha, Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.d(TAG, "Error: " + error.getMessage());
        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
        MY_DEFAULT_TIMEOUT,
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

AppController.getInstance().addToRequestQueue(jsonArrayRequest);

Espero te sirva, saludos.