Q:

Extracting Rare Words From A Corpus

This question might be too general, or opinion-based, but I was looking for advice on how to extract rare words from a very large corpus. The rare words wouldn't necessarily be consistent from document to document, so traditional tf-idf wouldn't be quite right.
Specifically, I'm looking at restaurant reviews, and want to highlight reviews that use very specific language, e.g. "The steak tartare tasted like cotton candy" vs "The food was good". The fact that the sentiment was negative or positive is not as important.
Using a binary tf-idf seems to help, as it doesn't overweight the fact that a word was used multiple times in a single document. Is there any other advice as to how this can be detected?

A:

I can recommend AntConc's
Word List tool. It produces a frequency list of all word tokens in the file(s) that you've got open, and links each item on this list to its own KWIC-concordance––handy if you want to see the context in which the word is used.
One caveat, though: this tool only works with 'single-word' items. Compound nouns  such as cotton candy, for instance, are not detected.
With a view to answering your question: I suppose you could collect the least frequent words into a 'mini-lexicon' and then search your corpus for all sentences containing one or more items on this list.
This approach is rudimentary and probably (it's hard to tell) doesn't answer your question; but I'd recommend trying it if you're still stuck.

A:

You could use concordance software to do this. It will generate a concordance of your text which will show (amongst other things) how often each word occurs. If you use a KWIC (key word in context) concordancer it will also show the immediate context within which each word occurs.
As an example, here's a concordancer for Macintosh OS X computers, CasualConc


Q:

How to save several objects into relationship entity. Xcode

I have data in array. I loaded them into UITableViewController, and when I select a cell, data from cell adds to Array. Then I want to save data from Array in Core Data, but I cannot make it. I can to save only one file. How can I make it?
@IBAction func saveAllData(sender: UIBarButtonItem) {
    var index = tableView.indexPathForSelectedRow()!
    var row = tableView.indexPathForSelectedRow()!.row
    var playlistEntity = NSEntityDescription.insertNewObjectForEntityForName("Playlist", inManagedObjectContext: managedObjectContext) as! NSManagedObject
    var songEntity = NSEntityDescription.insertNewObjectForEntityForName("Song", inManagedObjectContext: managedObjectContext) as! NSManagedObject

    if boolForName == true {
        playlistEntity.setValue(currentSong, forKey: "namePlaylist")
        boolForName = false
    }

    for item in arraySong {
        println(item)
        songEntity.setValue(item, forKey: "dataSong")
    }
    playlistEntity.setValue(NSSet(object: songEntity), forKey: "song")
    managedObjectContext.save(nil)
    println("play list \(playlistEntity)")
    println("song entity \(songEntity)")
    var storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
    var navi = storyboard.instantiateViewControllerWithIdentifier("navi") as! UINavigationController
    presentViewController(navi, animated: true, completion: nil)
}

Updated
I remake this code, but it saves the same.
@IBAction func saveAllData(sender: UIBarButtonItem) {
    var index = tableView.indexPathForSelectedRow()!
    var row = tableView.indexPathForSelectedRow()!.row
    println(index)
    println(currentArray[row])
    var currentFile = currentArray[row]

    var playlistEntity = NSEntityDescription.insertNewObjectForEntityForName("Playlist", inManagedObjectContext: managedObjectContext) as! NSManagedObject
    var songEntity = NSEntityDescription.insertNewObjectForEntityForName("Song", inManagedObjectContext: managedObjectContext) as! NSManagedObject

    if boolForName == true {
        playlistEntity.setValue(currentSong, forKey: "namePlaylist")
        boolForName = false
    }

    for item in arraySong {
        songEntity.setValue(item, forKey: "dataSong")
        playlistEntity.setValue(NSSet(object: songEntity), forKey: "song")
        managedObjectContext.save(nil)
        println(songEntity)
    }
    managedObjectContext.save(nil)
    println("play list \(playlistEntity)")
    println("song entity \(songEntity)")
    var storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
    var navi = storyboard.instantiateViewControllerWithIdentifier("navi") as! UINavigationController
    presentViewController(navi, animated: true, completion: nil)
}

UPDATE
var arraySong = [String]()
// MARK: IBAction func
@IBAction func saveAllData(sender: UIBarButtonItem) {
    var row = tableView.indexPathForSelectedRow()!.row
    var currentFile = currentArray[row]

    var playlistEntity = NSEntityDescription.insertNewObjectForEntityForName("Playlist", inManagedObjectContext: managedObjectContext) as! NSManagedObject
    var songEntity = NSEntityDescription.insertNewObjectForEntityForName("Song", inManagedObjectContext: managedObjectContext) as! NSManagedObject

    if boolForName == true {
        playlistEntity.setValue(currentSong, forKey: "namePlaylist")
        boolForName = false
    }

    for item in arraySong {
        songEntity.setValue(item, forKey: "dataSong")
        playlistEntity.setValue(NSSet(object: songEntity), forKey: "song")
        managedObjectContext.save(nil)
        println("play list \(playlistEntity)")
        println("song entity \(songEntity)")
    }
    managedObjectContext.save(nil)

    var storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
    var navi = storyboard.instantiateViewControllerWithIdentifier("navi") as! UINavigationController
    presentViewController(navi, animated: true, completion: nil)
}

I tried it but the same I save only the last object from the array.
  for var x = 0; x < arraySong.count; x++ {
            var item = arraySong[x]
                println(item)
                songEntity.setValue(item, forKey: "dataSong")
                playlistEntity.setValue(NSSet(object: songEntity), forKey: "song")
                managedObjectContext.save(nil)
                //            println("play list \(playlistEntity)")
                //            println("song entity \(songEntity)")
            println(songEntity)
        }

So I am adding songs from UITableViewController into the array.
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.None)
    var row = tableView.indexPathForSelectedRow()!.row
    var song = currentArray[row]
    arraySong.append(song)
    var cell = tableView.cellForRowAtIndexPath(indexPath)!
    cell.accessoryType = UITableViewCellAccessoryType.Checkmark
}

UPDATE 2
I tried it
for var x = 0; x < arraySong.count; x++ {
        var item = arraySong[x]
            println(item)
            var songEntity = NSEntityDescription.insertNewObjectForEntityForName("Song", inManagedObjectContext: managedObjectContext) as! NSManagedObject
            songEntity.setValue(item, forKey: "dataSong")
            playlistEntity.setValue(NSSet(object: songEntity), forKey: "song")
            managedObjectContext.save(nil)
            //            println("play list \(playlistEntity)")
            //            println("song entity \(songEntity)")
        println(songEntity)
    }

UPDATE 3
Still I tried this method but I save only first object which I selected. Are there any methods for it? How can I save several songs( objects) for specific playlist (another entity)?
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.None)
        var indexPath = tableView.indexPathForSelectedRow()!
        var row = tableView.indexPathForSelectedRow()!.row
        var song = currentArray[row]
//        arraySong.append(song)
        var cell = tableView.cellForRowAtIndexPath(indexPath)!
        cell.accessoryType = UITableViewCellAccessoryType.Checkmark

        var playlistEntity = NSEntityDescription.insertNewObjectForEntityForName("Playlist", inManagedObjectContext: managedObjectContext) as! NSManagedObject
        var songEntity = NSEntityDescription.insertNewObjectForEntityForName("Song", inManagedObjectContext: managedObjectContext) as! NSManagedObject

        if boolForName == true {
            playlistEntity.setValue(currentSong, forKey: "namePlaylist")
            boolForName = false
        }

        songEntity.setValue(song, forKey: "dataSong")
        playlistEntity.setValue(NSSet(object: songEntity), forKey: "song")
        managedObjectContext.save(nil)

        println(songEntity)
    }

Still I tried it.
   override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.None)
    var indexPath = tableView.indexPathForSelectedRow()!
    var row = tableView.indexPathForSelectedRow()!.row
    var song = currentArray[row]
    arraySong.append(song)
    var cell = tableView.cellForRowAtIndexPath(indexPath)!
    cell.accessoryType = UITableViewCellAccessoryType.Checkmark

    let playlistEntity = NSEntityDescription.insertNewObjectForEntityForName("Playlist", inManagedObjectContext: managedObjectContext) as! NSManagedObject
    let songEntity = NSEntityDescription.insertNewObjectForEntityForName("Song", inManagedObjectContext: managedObjectContext) as! NSManagedObject

    if boolForName == true {
        playlistEntity.setValue(currentSong, forKey: "namePlaylist")
        boolForName = false
    }

    for var digit = 0; digit < arraySong.count; digit++ {
        var savedSong = arraySong[digit]
        songEntity.setValue(savedSong, forKey: "dataSong")
        playlistEntity.setValue(Set(arrayLiteral: songEntity), forKey: "song")
        managedObjectContext.save(nil)

    }

Entites
import Foundation
import CoreData

@objc(Playlist)
class Playlist: NSManagedObject {

    @NSManaged var namePlaylist: String
    @NSManaged var song: NSSet
}

import Foundation
import CoreData

@objc(Song)
class Song: NSManagedObject {

    @NSManaged var dataSong: String
    @NSManaged var playlist: Playlist

}

Relationships entities in Core Data

UPDATE 4
I tried like but this method saves several new playlists. I knew it. Can anyone show me programmatically it?
   override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.None)
    //
    let indexP = tableView.indexPathForSelectedRow()!
    let row = tableView.indexPathForSelectedRow()!.row
    var song = currentArray[row]

    var cell = tableView.cellForRowAtIndexPath(indexPath)!
    cell.accessoryType = UITableViewCellAccessoryType.Checkmark

    let playlistEntity = NSEntityDescription.insertNewObjectForEntityForName("Playlist", inManagedObjectContext: managedObjectContext) as! NSManagedObject
    let songEntity = NSEntityDescription.insertNewObjectForEntityForName("Song", inManagedObjectContext: managedObjectContext) as! NSManagedObject

    songEntity.setValue(song, forKey: "dataSong")
    playlistEntity.setValue(Set(arrayLiteral: songEntity), forKey: "song")
    println(songEntity)
    println(playlistEntity)
    managedObjectContext.save(nil)
}

A:

Each time you select a row you are creating one new playlist and one new song.  Create your playlist before selecting songs and only update the relationship when you add a new song.


Q:

When, during authentication, should I ask for an OTP token?

I was working on implementing an OTP strategy in our login process of a web application when I was asking myself: Should I ask for the OTP token before or after asking for the username/password?
What I generally see with services I use is, I have to provide the OTP token after they've verified my username/password.
I was wondering if this was just due to user experience decisions or if there was a security aspect to it.

A:

From a security perspective, it makes sense to ask at the same time -- that way, an attacker doesn't know what they got wrong. With some services (e.g. Google), the OTP has another option to send a text message, so from a UX perspective, putting it after the password cuts back on spurious texts.


Q:

How is the element denoted by *(arr+i)[1] and **(arr+i) being determined?

I can't understand how the following elements are getting determined:

*(arr+1)[1] - 7 is printed.
**(arr+1) - 4 is printed.

#include <stdio.h>
int main()
{
    int arr[3][3]={1,2,3,4,5,6,7,8,9};
    printf("%d %d",*(arr+1)[1],**(arr+1));
    return 0;
}

A:

By definition, a[b] is equivalent to *(a + b).
[] (postfix) has higher precedence than * (prefix), so *a[b] parses as *(a[b]).

*(arr+1)[1] parses as *((arr+1)[1]).
*((arr+1)[1]) is equivalent to *(*(arr+1+1)).
*(*(arr+1+1)) reduces to **(arr+2).
**(arr+2) is equivalent to *(arr[2]).
*(arr[2]) is equivalent to *(arr[2]+0).
*(arr[2]+0) is equivalent to arr[2][0].
**(arr+1) is equivalent to *(arr[1]).
*(arr[1]) is equivalent to *(arr[1]+0).
*(arr[1]+0) is equivalent to arr[1][0].

As for the actual data:
int arr[3][3]={1,2,3,4,5,6,7,8,9};

is a bit hard to read. Better:
int arr[3][3]={
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

In the first case, arr[2][0] gives you the first element (7) of the third subarray (7,8,9) while in the second case, arr[1][0] gives you the first element (4) of the second subarray (4,5,6).


Q:

XSLT counting elements with a given value

I need to count the number of elements in an XML file that have a particular value (to verify uniqueness). The XML file looks like this:
EDIT: I updated the original "simplified" XML with the actual hairy mess someone designed. Unfortunately, this is going to make all the previous Answers really confusing and wrong unless edited.
<root>
  <ac>
   <Properties>
     <Property Name="Alive">
      <Properties>
        <Property Name="ID">
         <Properties>
           <Property Name="Value">
            <long>11007</long>
           </Property>
         </Properties>
        </Property>
      </Properties>
     </Property>
     <Property Name="Dead">
      <Properties>
        <Property Name="ID">
         <Properties>
           <Property Name="Value">
            <long>11008</long>
           </Property>
         </Properties>
        </Property>
      </Properties>
     </Property>
     ...
     <Property Name="MostlyDeadAllDay">
      <Properties>
        <Property Name="ID">
         <Properties>
           <Property Name="Value">
            <long>99001</long>
           </Property>
         </Properties>
        </Property>
      </Properties>
     </Property>
   </Properties>
  </ac>
</root>

I am trying to define a variable to see how many of the properties at the Alive/Dead level have the long value (ID) as defined in a template parameter. Something along these lines (though I suspect this is wrong)...
<xsl:param name="parPropId"/>
<xsl:variable name="countProperties">
   <xsl:value-of select="count(/root/ac/
      Properties/Property/
      Properties/Property[@Name = 'ID']/
      Properites/Property[@Name = 'Value']/long = $parPropId)"/>
</xsl:variable>

There can be multiple Property elements defined at the "ID" level. But I am fairly certain I can count on just one Property element ("Value") under "ID", and only one "long" element under "Value".
[disclaimer] Whoever designed the overall XML file I'm stuck working with REALLY didn't know how to structure XML (e.g., backwards use of attributes versus elements). I fear my XSLT thinking has temporarily been warped :) as a result. [/disclaimer]

A:

This XPath:
count(//Property[long = '11007'])

returns the same value as:
count(//Property/long[text() = '11007'])

...except that the first counts Property nodes that match the criterion and the second counts long child nodes that match the criterion.
As per your comment and reading your question a couple of times, I believe that you want to find uniqueness based on a combination of criteria. Therefore, in actuality, I think you are actually checking multiple conditions. The following would work as well:
count(//Property[@Name = 'Alive'][long = '11007'])

because it means the same thing as:
count(//Property[@Name = 'Alive' and long = '11007'])

Of course, you would substitute the values for parameters in your template. The above code only illustrates the point.
EDIT (after question edit)

You were quite right about the XML being horrible. In fact, this is a downright CodingHorror candidate! I had to keep recounting to keep track of the "Property" node I was on presently. I feel your pain!
Here you go:
count(/root/ac/Properties/Property[Properties/Property/Properties/Property/long = $parPropId])

Note that I have removed all the other checks (for ID and Value). They appear not to be required since you are able to arrive at the relevant node using the hierarchy in the XML. Also, you already mentioned that the check for uniqueness is based only on the contents of the long element.


Q:

How to properly remove error from redux store

I have a react-redux application, and I catch every error response from redux-saga, save it in the redux-store and render it in the component. The main problem is the ability to remove it when the component is updated or when the user has moved to another page. I tried to use the component lifecycle methods (componentWillUpdate), but it didn’t work correctly because I had other store parts connected to the component, and when they are updated, it clears the error before the user sees it.
My question is: is there a proper way to store/view/delete errors using the redux?
I handle errors in this way
export function* errorHandler(err: any): SagaIterator {
   // put an error in the redux-store
}

// it's a wrapper for every saga
export const genericErrorHandler = (saga: (...args: any[]) => SagaIterator, ...args: any[]) =>
    function* handleApp(action: any): any {
        try {
            yield call(saga, action, args);
        } catch (err) {
            yield call(errorHandler, err);
        }
    };

A:

I could probably give a more specific suggestion if we had more details about the design of your app & how you're handling errors. But here are some things that might help:

split up errors by type, with separate actions/reducers/store locations for each. This will help you be specific about what kind of error has occurred and when/how to show each.
fire an action to clear the error state. This ensures you're being specific about what errors are no longer present, and when that change occurs. If possible, don't do this as a side effect of something else happening, be specific about when & why.
if the error state is specific to a UI component, and should be removed from the store when that component goes away, consider firing the error-clearing action in that component's componentWillUnmount method. This is called only when the component is being removed from the DOM.


Q:

What is causing Access Denied when using the aws cli to download from Amazon S3?

I'm really flailing around in AWS trying to figure out what I'm missing here. I'd like to make it so that an IAM user can download files from an S3 bucket - without just making the files totally public - but I'm getting access denied. If anyone can spot what's off I'll be stoked.
What I've done so far:

Created a user called my-user (for sake of example)
Generated access keys for the user and put them in ~/.aws on an EC2 instance
Created a bucket policy that I'd hoped grants access for my-user
Ran the command aws s3 cp --profile my-user s3://my-bucket/thing.zip .

Bucket policy:
{
  "Id": "Policy1384791162970",
  "Statement": [
    {
      "Sid": "Stmt1384791151633",
      "Action": [
        "s3:GetObject"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::my-bucket/*",
      "Principal": {
        "AWS": "arn:aws:iam::111122223333:user/my-user"
      }
    }
  ]
}

The result is A client error (AccessDenied) occurred: Access Denied although I can download using the same command and the default (root account?) access keys.
I've tried adding a user policy as well. While I don't know why it would be necessary I thought it wouldn't hurt, so I attached this to my-user.
{
  "Statement": [
    {
      "Sid": "Stmt1384889624746",
      "Action": "s3:*",
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::my-bucket/*"
    }
  ]
}

Same results.

A:

I was struggling with this, too, but I found an answer over here https://stackoverflow.com/a/17162973/1750869 that helped resolve this issue for me. Reposting answer below.

You don't have to open permissions to everyone. Use the below Bucket policies on source and destination for copying from a bucket in one account to another using an IAM user
Bucket to Copy from – SourceBucket
Bucket to Copy to – DestinationBucket
Source AWS Account ID - XXXX–XXXX-XXXX
Source IAM User - src–iam-user
The below policy means – the IAM user - XXXX–XXXX-XXXX:src–iam-user has s3:ListBucket and s3:GetObject privileges on SourceBucket/*  and s3:ListBucket and s3:PutObject privileges on DestinationBucket/*
On the SourceBucket the policy should be like:
{
"Id": "Policy1357935677554",
"Statement": [
    {
        "Sid": "Stmt1357935647218",
        "Action": [
            "s3:ListBucket"
        ],
        "Effect": "Allow",
        "Resource": "arn:aws:s3:::SourceBucket",
        "Principal": {"AWS": "arn:aws:iam::XXXXXXXXXXXX:user/src–iam-user"}
    },
    {
        "Sid": "Stmt1357935676138",
        "Action": ["s3:GetObject"],
        "Effect": "Allow",
        "Resource": "arn:aws:s3::: SourceBucket/*",
        "Principal": {"AWS": "arn:aws:iam::XXXXXXXXXXXX:user/src–iam-user"}
   }
]
}

On the DestinationBucket the policy should be:
{
"Id": "Policy1357935677554",
"Statement": [
    {
        "Sid": "Stmt1357935647218",
        "Action": [
            "s3:ListBucket"
        ],
        "Effect": "Allow",
        "Resource": "arn:aws:s3::: DestinationBucket",
        "Principal": {"AWS": "arn:aws:iam::XXXXXXXXXXXX:user/src–iam-user"}
    },
    {
        "Sid": "Stmt1357935676138",
        "Action": ["s3:PutObject"],
        "Effect": "Allow",
        "Resource": "arn:aws:s3::: DestinationBucket/*",
        "Principal": {"AWS": "arn:aws:iam::XXXXXXXXXXXX:user/src–iam-user"}
   }
]
}

command to be run is s3cmd cp s3://SourceBucket/File1 s3://DestinationBucket/File1

A:

When I faced the same issue it turned out that AWS required server-side encryption to be enabled. So the following command worked successfully for me:
aws s3 cp test.txt s3://my-s3-bucket --sse AES256

A:

I wouldn't recommend the 'Any authenticated AWS user' option mentioned by James.
Doing so adds a bucket-level ACL that allows any AWS account (not just your IAM users) to list/delete/modify-acls for that bucket.
i.e. public read/write for anyone with an aws account.


Q:

Broadcast receiver android.intent.action.BOOT_COMPLETED not working

I am trying to start service on Boot completion, After doing lot digging I have found nothing.
Very first approach that I have tried was this, I found this approach in most answers, but it doesn't work.
Then I have found that this approach is not working on 3.1+ from here
I have also seen this, https://developer.android.com/about/versions/android-3.1.html#launchcontrols
and used FLAG_INCLUDE_STOPPED_PACKAGES also in my code.I have referred this approach from here.
AndroidMenifest

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.REAL_GET_TASKS"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/security"
    android:label="@string/app_name"
    android:supportsRtl="true">

    <receiver android:name="com.reversebits.projects.app.easyerase.receiver.BootReceiver"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
        android:enabled="true"
        android:exported="true">

        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>

        <intent-filter>
            <action android:name="myReceiver" />
        </intent-filter>

    </receiver>

    <activity
        android:name=".Home"
        android:theme="@style/AppTheme">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    </activity>

    <service
        android:name=".services.BootService"
        android:enabled="true">

        <intent-filter>
            <action android:name="com.reversebits.projects.app.easyerase.services.BootService"/>
        </intent-filter>

    </service>

</application>

BootReciever
public class BootReceiver extends BroadcastReceiver {

    public BootReceiver() {
    }
    @Override
    public void onReceive(Context context, Intent intent) {

        if(intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED))
        {
            context.startService(new Intent(context, BootService.class));
        }
    }
}

BootService
public class BootService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //TODO do something useful Recommended by google instead of onStart()
        return Service.START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        loopThread();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    void loopThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                switch (am.getRingerMode()) {
                    case AudioManager.RINGER_MODE_SILENT:
                        Log.e("MyApp", "Silent mode");
                        break;
                    case AudioManager.RINGER_MODE_VIBRATE:
                        Log.e("MyApp", "Vibrate mode");
                        break;
                    case AudioManager.RINGER_MODE_NORMAL:
                        Log.e("MyApp", "Normal mode");
                        break;

                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                loopThread();
            }
        }).start();
    }
}

Code works perfect and i got all logs when service is starting from activity, but on Boot complete, it is not working
Note:
I have read almost all related answers and on some answers,I have also read comments and I know almost all related things, so please do not provide me other links, as  have seen most of them already, I need the perfect solution. Any help is appreciated.

A:

  <receiver android:name=".BootCompletedIntentReceiver"
        android:enabled="true"
        android:exported="true"
        >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

    <service android:name=".Service"
        android:enabled="true"
        android:exported="true">

    </service>

yo
          public class BootCompletedIntentReceiver extends BroadcastReceiver {
   public void onReceive(Context context, Intent intent) {

    if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
        Intent pushIntent = new Intent(context, Service.class);

        context.startService(pushIntent);}

and dont forget
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

service
public class BootService extends Service {
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStart(Intent intent, int startId) {
    //TODO do something useful Recommended by google instead of onStart()
     new Thread(new Runnable() {
        @Override
        public void run() {
            AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            switch (am.getRingerMode()) {
                case AudioManager.RINGER_MODE_SILENT:
                    Log.e("MyApp", "Silent mode");
                    break;
                case AudioManager.RINGER_MODE_VIBRATE:
                    Log.e("MyApp", "Vibrate mode");
                    break;
                case AudioManager.RINGER_MODE_NORMAL:
                    Log.e("MyApp", "Normal mode");
                    break;

            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }).start();
}

@Override
public void onDestroy() {
    super.onDestroy();
}
  }


Q:

What is the point of JObject's CreateWriter if using the writer just throws ArgumentException?

I have a "legacy" method that takes a JsonWriter and dumps a bunch of json..   Out of this, I want a JObject instance, so I tried the following:
JObject myObj = new JObject();
using (var writer = myObj.CreateWriter())
{
    TheLegacyMethod(writer);
}
// TODO:  Do stuff with the nicely initialized JObject instance

The issue is that the first time "TheLegacyMethod" attempts to actually use the writer to do a:
writer.WriteStartObject();

I get an ArgumentException complaining that a JObject can't be added to a JObject.
I've used a smelly workaround, writing the Json to a StringBuilder first, then doing a JObject.Parse() on the result...  but I would like to avoid this intermediate.
What is the point of JObject.CreateWriter() if you can't use it?   Am I missing something?  (I'm hoping I am).
Thanks,
Tyler

A:

When writing values to an object the property name must be written before the value.


Q:

Find getElementById property in window.document

Summary: I wanted to know if there was a way to open console in chrome, type window, go to document and search for the getElementById method
Reason: I was searching around and found a lot of the CSS styles for an element(see picture 1 below) and was curious if methods like getElementById were displayed as well
What I tried:
1) I tried looking searching for the getElementById by control + f and searched for "get"
2) Tried seeing if I could get info from mdn: https://developer.mozilla.org/en-US/docs/Web/API/Document/Document
3) Tried reading the link pasted on mdn https://dom.spec.whatwg.org/#interface-nonelementparentnode
Still couldn't find it though :/
element css styles
window.document properties

A:

If I understand you right (directly - how to find 'getElementById' property within global Window object) it is possible to do. You should write in the console Window, open document, then __proto__ (should be the last property of the document object), then __proto__ again, and now you can find getElementById method here. The reason is Window object quite difficult, and uses prototypes to keep all inherit properties and methods: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype


Q:

Retrieving table rows with matching values in a SET Field Type

I have a field in tables, with datatype "set" so that it can accept multiple values. But I got stuck at the time, when I am retrieving the results matching values to it.
An Example field
"menuPosition" : set('top','left','right','bottom')

An Example query
SELECT * FROM mytable where menuPosition='top'

This query only returns those rows with only top as their values, the rows having multiple values like top,left are not returned. How to retrieve all those records?
And since my above query only compares one values, how to write a query to match multiple values like where menuPosition='top' && 'bottom'

A:

You caeither use FIND_IN_SET like:
SELECT * FROM mytable WHERE FIND_IN_SET('top', menuPosition)

Or you can use LIKE:
SELECT * FROM mytable WHERE menuPosition LIKE '%top%'

I guess the first one is faster.


Q:

Defer HTML generation via handlebars.js

We have a page that displays enormous amount of data.
Currently, the entire page is generated on the IIS server and then downloaded to the browser.
Due to the amount of code being executed on the server a performance issue is visible to the testing team.
We are planning to use handlebars.js to delegate the task of generating the html from the server to the browser.
So, basically the server code will be refactored to quickly generate some json data which will be sent to the browser and the html will be generated on the browser, hence reducing the amount of data being transmitted from the server to the browser.
The thought that straight away comes to my mind is that there's so much(a lot) of html to be generated that the javascript may cause the browser to hang and very much would not be a pleasing user experience.
Hence, I want to process an amount 'x' of json objects such that the html they generate provide just a little amount of scroll, AND when the user scrolls and the page is about to reach the bottom, I generate the next 'x' amount of json objects, and so on.
As a reference this would be something like the goolge image search where scrolling to the bottom of the screen automatically lists the next set of images.
However, in my case I'll already have the json objects loaded on my page.
We already have handlebars added to the project and would like to keep third party libraries at a minimum.

A:

Only send a limited amount of results when you query the database (for example 10 results).  Then when they get to the end of the results list, they would hit a button that says, for example, "Load More" and that would initiate an AJAX request to your application to query the database and return the next 10 results, and so on.  You shouldn't be sending the entire data-set back at once that is why you are experiencing memory performance issues.
<script src="/path/to/jquery.min.js"></script>
<script src="/path/to/waypoints.min.js"></script>

<script>
$(document).ready(function(){

     // will initiate when the element with id="my_results" first comes into the users view
     $('#my_results').waypoint(function(){
            // do you stuff with the json that you already have loaded on the page (this is the callback function)
       },
       { offset: 'bottom-in-view' }
     );

});
</script>


Q:

SQL fixed-length insert statement formatter

Lets assume I have this long insert statement
insert into table1 (id, name, phone, very_long_col_name, ...)
            values (1, 'very long name indeed...', '555-555-5555', 1, ...)

As you can see above, it gets hard to tell values from their column since their length is uneven
I'm looking for something (e.g. command line util) to format the above (not just SQL format) to this:
insert into table1 (id, name                      , phone         , very_long_col_name, ...)
            values (1 , 'very long name indeed...', '555-555-5555', 1                 , ...)

This way I can see which value goes with which column easily
It can be a plugin to notepad++, a java utility, a plugin to an SQL IDE, what ever does the trick...
Prepared statements, T-SQL parameters, Hibernate, JPA etc is not an option right now

A:

Not suggesting a plugin, but I mostly see this kind of thing formatted this way:
insert into table1
       (
         id,
         name,
         phone,
         very_long_col_name,
         ...
       )
values
       (
         1,
         'very long name indeed...',
         '555-555-5555',
         1,
         ...
       )

I find this more readable than scrolling through a very long line.


Q:

Client Side binding of telerik radgrid not updating after databind

I'm trying to bind a radgrid using the client side api.
I issue a call to javascript function DoUpdate(sbiId)
function DoUpdate(sbiId) {
    var input = '{"SbiId":"' + sbiId+ '"}';
    var dataSource;

    $.ajax({ url: "http://localhost/Meta.WebService/DataService.svc/GetData",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: input,
        dataType: "json",
        success: function(data) {
            updateGrid(data);
        }
    });
}

function updateGrid(result) {
    var mtv = RadGridSprintBackLogItemDetailsInstance().get_masterTableView();
    mtv.set_dataSource(result);
    mtv.dataBind();
}

The ajax call returns seemingly correct JSON data; here is the response content per fiddler:

{"d":[{"_type":"SBIRevision:#Meta.Scrum","AssignedTo":"Roger
  Ng","ChangedBy":"Bob Hung","ChangedDate":"8/8/2011 3:48:31
  PM","Description":"","State":"Not Done","Title":"MARS Unit
  Tests","WorkEstimate":"50","WorkRemaining":"50"},{"_type":"SBIRevision:#Meta.Scrum","AssignedTo":"Roger
  Ng","ChangedBy":"Roger Ng","ChangedDate":"8/8/2011 5:12:46
  PM","Description":"","State":"In Progress","Title":"MARS Unit
  Tests","WorkEstimate":"50","WorkRemaining":"50"},{"_type":"SBIRevision:#Meta.Scrum","AssignedTo":"Roger
  Ng","ChangedBy":"Roger Ng","ChangedDate":"8/8/2011 5:13:39
  PM","Description":"","State":"In Progress","Title":"MARS Unit
  Tests","WorkEstimate":"50","WorkRemaining":"50"},{"_type":"SBIRevision:#Meta.Scrum","AssignedTo":"Roger
  Ng","ChangedBy":"Roger Ng","ChangedDate":"8/8/2011 5:14:25
  PM","Description":"Ran into...pointing to the wrong build
  service","State":"In Progress","Title":"MARS Unit
  Tests","WorkEstimate":"50","WorkRemaining":"50"},{"_type":"SBIRevision:#Meta.Scrum","AssignedTo":"Roger
  Ng","ChangedBy":"Bob Hung","ChangedDate":"8/10/2011 10:59:09
  AM","Description":"Ran into...pointing to the wrong build
  service","State":"In Progress","Title":"MARS Unit
  Tests","WorkEstimate":"50","WorkRemaining":"50"},{"_type":"SBIRevision:#Meta.Scrum","AssignedTo":"Roger
  Ng","ChangedBy":"Roger Ng","ChangedDate":"8/11/2011 12:04:09
  PM","Description":"Ran into...pointing to the wrong build
  service","State":"Done","Title":"MARS Unit
  Tests","WorkEstimate":"50","WorkRemaining":"50"}]}

Here is how I declare my radgrid on the aspx page
<telerik:RadGrid runat="server" ID="RadGridSprintBackLogItemDetails" EnableViewState="false" EnableEmbeddedSkins="false" Skin="Meta">
    <MasterTableView AutoGenerateColumns="false" EnableNoRecordsTemplate="true" ShowHeadersWhenNoRecords="true">
        <ItemStyle Wrap="false"></ItemStyle>
        <NoRecordsTemplate>

                Select a Sprint Backlog Item (SBI) from above to view its Revisions

        </NoRecordsTemplate>
        <Columns>
            <telerik:GridBoundColumn DataField="ChangedDate" HeaderText="Changed Date">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="Title" HeaderText="Title">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="Description" HeaderText="Description">
            <ItemStyle Wrap="false"></ItemStyle>
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="AssignedTo" HeaderText="Assigned To">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="WorkEstimate" HeaderText="Work Estimate">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="WorkRemaining" HeaderText="Work Remaining">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="State" HeaderText="State">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="ChangedBy" HeaderText="Changed By">
            </telerik:GridBoundColumn>
        </Columns>
    </MasterTableView>
</telerik:RadGrid>

Oddly enough, after the data is returned and bound, the no records template appears.

A:

Change your updateGrid function as follows (use result.d for binding):
function updateGrid(result) {
  var mtv = RadGridSprintBackLogItemDetailsInstance().get_masterTableView();
  mtv.set_dataSource(result.d);
  mtv.dataBind();
}

Hope, this helps.

A:

When binding with set_dataSource(), you need to pass the actual array of data objects. The jQuery result you are getting contains the data array in a field named .d. This is why you need to use result.d.
On a side note, did you know that RadGrid can bind to WCF Web Services automatically? Refer to RadGrid's .NET 3.5 Client-Side DataBinding demo for a live example. Service settings are specified right in RadGrid's definition through the markup. RadGrid then automatically connects to the data service, retrieves the result and databinds.


Q:

Compilation Error : "Conversion to Dalvik format failed: Unable to execute dex: Cannot merge new index 74303 into a non-jumbo instruction"

I'm adding these two libraries in project appcompat_v7 & google_play_services but couldn't get the project compiled due to following Dalvik error
[2014-10-03 20:04:57 - Dex Loader] Unable to execute dex: Cannot merge new index 74303 into a non-jumbo instruction!
[2014-10-03 20:04:57 - TestProject] Conversion to Dalvik format failed: Unable to execute dex: Cannot merge new index 74303 into a non-jumbo instruction!

any pointer?

A:

Got it, Add dex.force.jumbo=true to project.properties.
See screenshot


Q:

Drawing a thickened Möbius strip in Mathematica

I would like to have Mathematica plot a "thickened Möbius strip", i.e. a torus with square cross section that is given a one-half twist. Ideally, I would like this thickened Möbius strip to be transparent with a (non-thickened) solid Möbius strip sitting at its center; here is the best approximation I could draw by hand of what I want:

My motivation here is that I want to use the thickened Möbius strip a visual representation of a line bundle over $E$, where $E$ is the Möbius strip; that's why I'd like the Möbius strip at the center to be visible. A line bundle over $E$ can be identified with the bundle $E\oplus E$ over $\mathbb{S}^1$.
I was approaching this by attempting to draw the (two) sides of the thickened Möbius strip as parametric surfaces. Modeling my line bundle as $$E\oplus E=\mathbb{R}^3/\langle (t,x,y)\mapsto(t+2\pi,-x,-y)\rangle,$$
a global frame is given by the vector fields $v,w:\mathbb{S}^1\rightarrow E\oplus E$, where
$$v(t)=\overline{(t,\cos(t),\sin(t))},\hskip0.3in w(t)=\overline{(t,-\sin(t),\cos(t))}.$$
Using these $\{v(t),w(t)\}$ as a basis for the copy of $\mathbb{R}^2$ at each point $t\in\mathbb{S}^1$, it is not hard to describe what the sides of the thickened Möbius strip look like within $E\oplus E$. My difficultly lies in finding the equations that describe the "obvious" immersion $F:E\oplus E\rightarrow\mathbb{R}^3$, the map that e.g. has
$$F\left(\overline{(t,0,0)}\right)=(R\cos(t),R\sin(t),0)$$
where $R$ is the radius of the "actual" square-torus-with-twist, and
$$F\left(\\{\overline{(t,x,y)}\mid x,y\in [-r,r]\\}\right)= {\text{a (rotated) square of side length $2r$ centered at $F(\overline{(t,0,0)})$}\atop\text{and lying in the plane containing $(0,0,1)$ and $F(\overline{(t,0,0)})$}}.$$
Any help would be much appreciated.

A:

The following code produces roughly what you're looking for:
F[x_, y_, t_] := {(3 + x*Cos[t/2] - y*Sin[t/2])*Cos[t],
                  (3 + x*Cos[t/2] - y*Sin[t/2])*Sin[t],
                  x*Sin[t/2] + y*Cos[t/2]}
Show[
    ParametricPlot3D[
      {F[1, u, t], F[u, 1, t], F[u, 0, t]},
      {t, 0, 4 Pi}, {u, -1, 1},
      PlotStyle -> {{Blue, Opacity[0.3]}, {Blue, Opacity[0.3]},
                    {Green, Opacity[0.5]}},
      Mesh -> None, PlotPoints -> {30, 2},
      ImageSize -> 500, ViewPoint -> {0, -3, 3},
      ViewVertical -> {0, 0, 1} , Boxed -> False, Axes -> None],
    ParametricPlot3D[
      {F[1, 1, t], F[-1, 1, t], F[1, 0, t]},
      {t, 0, 4 Pi},
      PlotStyle -> Darker[Blue] , PlotPoints -> 30]
    ]

A:

I have been working on the problem some more, and I think the equations I came up with are equivalent to Jim's. I've combined parts of Jim's answer with mine, made the code a bit more modular, and for the sake of completeness I'll post here the result:

F[R_][t_, x_, y_] := {(R + x) Cos[t], (R + x) Sin[t], y}
Faces[R_, r_, s_,
    t_] := {F[R][t, -r Sin[t/2] + s Cos[t/2], r Cos[t/2] + s Sin[t/2]],
    F[R][t, r Cos[t/2] - s Sin[t/2], r Sin[t/2] + s Cos[t/2]]}
Strip[R_, r_, s_, t_] := F[R][t, s Cos[t/2], s Sin[t/2]]
Edges[R_, r_,
    t_] := {F[R][t, -r Sin[t/2] + r Cos[t/2], r Cos[t/2] + r Sin[t/2]],
    F[R][t, -r Sin[t/2] - r Cos[t/2], r Cos[t/2] - r Sin[t/2]],
    F[R][t, r Cos[t/2], r Sin[t/2]]}
ThickMobius[R_, r_, u_] := Show[
    ParametricPlot3D[Faces[R, r, s, t], {s, -r, r}, {t, 0, 4 Pi},
     PlotStyle -> {{Blue, Opacity -> 0.25}, {Blue, Opacity -> 0.25}},
     PlotPoints -> {2, 50}, Mesh -> None, Boxed -> False, Axes -> None],
    ParametricPlot3D[Strip[R, r, s, t], {s, -r, r}, {t, 0, 2 Pi},
     Mesh -> None, PlotStyle -> Red, PlotPoints -> 50],
    ParametricPlot3D[Edges[R, r, t], {t, 0, 4 Pi},
     PlotStyle -> {Darker[Blue], Thickness[u]}, PlotPoints -> 30]]

Here are some example results:
ThickMobius[6,2,0.001]

ThickMobius[6,1,0.001]

ThickMobius[6,2.5,0.003]

A:

I'm too late the hero here, but I'm posting the general form of a "twisted" surface for completeness, which you can easily adapt to your needs:
$$\begin{pmatrix}\cos\,u&-\sin\,u&0\\\sin\,u&\cos\,u&0\\0&0&1\end{pmatrix}\cdot\left(\begin{pmatrix}a\\0\\0\end{pmatrix}+\begin{pmatrix}
\cos\,bu&0&-\sin\,bu\\0&1&0\\\sin\,bu&0&\cos\,bu\end{pmatrix}\cdot\begin{pmatrix}f(v)\\0\\g(v)\end{pmatrix}\right)$$
or explicitly,
$$\begin{align*}x&=(a+f(v)\cos\,bu-g(v)\sin\,bu)\cos\,u\\y&=(a+f(v)\cos\,bu-g(v)\sin\,bu)\sin\,u\\z&=f(v)\sin\,bu+g(v)\cos\,bu\end{align*}$$
where $(f(v)\quad g(v))^T$ is the plane curve that makes the "cross-section" of your twisted surface, $b$ is a "twist factor" (e.g. $b=\frac12$, a "half-twist", for a Möbius strip), and $a$ is the distance from the origin to the "center" of the cross-section. (The way I have written the matrix-vector expression for the twisted surface should give a hint on how it was derived.) For the case of the Möbius strip, one appropriate cross-section is the line segment given by $(c-v\quad 0)^T$, $c$ a constant.
For the problem at hand of drawing a "thickened" strip, I use the square Lamé curve $(|\cos\,v|\cos\,v\quad |\sin\,v|\sin\,v)^T$ (suitably rotated) as the cross-section. (If needed, it is of course trivial to change the square to a rectangle.)
Thus, the following Mathematica code generates a Möbius strip and its "thickened" version: (adjust parameters and colors/styles to taste):
twist[{f_, g_}, a_, b_, u_] := {Cos[u] (a + f Cos[b u] - g Sin[b u]),
  Sin[u] (a + f Cos[b u] - g Sin[b u]), g Cos[b u] + f Sin[b u]}

With[{a = 3, b = 1/2, f = 1/2},
  ParametricPlot3D[{
     twist[f {Cos[Pi v/f] Abs[Cos[Pi v/f]] - Sin[Pi v/f] Abs[Sin[Pi v/f]],
        Cos[Pi v/f] Abs[Cos[Pi v/f]] + Sin[Pi v/f] Abs[Sin[Pi v/f]]}, a, b, u],
     twist[{f - v, 0}, a, b, u]}, {u, 0, 2 Pi}, {v, 0, 2 f},
     Axes -> None, Boxed -> False,
     Mesh -> None, PlotStyle -> {{Opacity[1/5], Blue}, Green}]]


Q:

How is same dimension alone equivalent to isomorphic?

Theorem: Two finite-dimensional vector spaces over a field $F$ are isomorphic if and only if they have the dimension.

By isomorphic, my text means there exists an invertable linear map from one space to another.
Consider the vector spaces ${\mathbb Q}^3$ and ${\mathbb R}^3$.  They are both vector spaces with the same dimension.  Thus there must a 1-1 map from ${\mathbb Q}^3$ to ${\mathbb R}^3$.  But   ${\mathbb Q}^3$ is countable and ${\mathbb R}^3$ is uncountable.  So how can there exist such a 1-1 map?

A:

Such a map can't exist, but it doesn't violate the theorem. The theorem says two vector spaces over the same field $F$ are isomorphic if and only if they have the same dimension. And while $\mathbb Q^3$ and $\mathbb R^3$ have the same dimension, they are not over the same field.


Q:

Working with strings in python produces strange quotation marks

currently I am working with scrapy, which is a web crawling framework based on python. The data is extracted from html using XPATH . (I am new to python) To wrap the data scrapy uses items, e.g.
item = MyItem()

item['id'] = obj.select('div[@class="id"]').extract()

When the id is printed like print item['id'] I get following output
[u'12346']

My problem is that this output is not always in the same form. Sometimes I get an output like
"[u""someText""]"

This happens only with text, but actually there is nothing speciall with the text compared to other text that is handled corretly just like the ID.
Does anyone know what the quotation marks mean? Like I said the someText was crawled like all other text data, e.g. from
someText

Any ideas?
Edit:
My spider crawls all pages of a blog. Here is the exact output
[u'41039'];[u'title]

[u'40942'];"[u""title""]"]

...

Extracted with
item['title']   = site.select('div[@class="header"]/h2/a/@title').extract()

I noticed that always the same blog posts have this quotation marks. So they dont appear randomly. But there is nothing special to the text. E.g. this title produces quotation marks

    Xtra Pac Telekom web'n'walk Stick Basic für 9,95

So my first thought was that this is because of some special chars but there arent any.
This happeny only when the items are written to csv, when I print them in cmd there are no quotation marks.
Any ideas?

A:

python can use both single ' and double " quotes as quotation marks.  when it prints something out it chooses single quotes normally, but will switch to double quotes if the text it is printing contains single quotes (to avoid having to escape the quote in the string):
so normally, it is printing [u'....'] but sometimes you have text that contains a ' character and then it prints [u"...."].
then there is an extra complication writing to csv.  if a string is written to csv that contains just a ' then it is written as it is.  so [u'....'] is written as [u'....'].
but if it contains double quotes then (1) everything is put inside double quotes and (2) any double quotes are repeated twice.  so u["..."] is written as "[u""...""]".  if you read the csv data back with a csv library then this will be detected and removed, so it will not cause any problems.
so it's a combination of the text containing a single quote (making python use double quotes) and the csv quoting rules (which apply to double quotes, but not single quotes).
if this is a problem the csv library has various options to change the behaviour - http://docs.python.org/library/csv.html
the wikipedia page explains the quoting rules in more detail - the behavuour here is shown by the example with "Super, ""luxurious"" truck"


Q:

Is pincushion or barrel distortion really all that bad in a lens?

Given that software can pretty trivially fix pincushion and barrel distortion patterns if you're shooting in RAW (Lightroom did the right thing just by knowing what lens I used with the given EXIF information), does it really matter if a lens has these types of distortion (so long as the are not so significant that the post processing does not lead to other significant artifacts of course)?
Reasoning for asking this:
I've found the distortion with the D7000's kit lens to be really bad -- but optically it's fine on pretty much every other front. Lightroom makes this go away, but I want to be aware of possible issues this might cause while I'm actually shooting...

A:

No, it's not all that bad. On most shots, you won't be able to tell by eye if the curvilinear distortions have been corrected for or not - you'll need straight lines adjacently parallel to each other or to edge to tell. In nature, you won't have those lines. In portraiture, it will exaggerate some parts and diminish others, but perspective distortion and lighting has much more effect on result.
The reason you've heard so much about them is that you've read many lens reviews, and distortion is rather easy to measure and write about.
Possible downsides of shooting distorted and correcting in post:

you'll spend more time setting up and verifying your workflow;
in your heart, you might want to do as much as possible in camera (many cameras can correct JPEGs for manufacturer's brand lenses);
some contests have quite strict rules against manipulation in digital post-processing;
as Jerry Coffin already commented, slight loss of sharpness;
as you mentioned in your question, it's easy to correct if you're shooting RAW and your software knows the lens. These conditions might not be true for various reasons.

A:

Yes, distortion is the second worst type of aberration. The worst is softness.
That is why when Nikon introduced their 18-200mm lens, instead of making it extremely soft like all others of the same focal-range, they made it sharper but left in a lot more severe  distortion.
Distortion is particularly bad because it is impossible to correct without losing sharpness.
Correcting distortion also affects composition, so some things that were in the frame can end up cropped-out of the frame as the distortion correction involves stretching parts of the image and the results get cropped to keep the frame rectangular.
The reason distortion is better than general softness is that you at least have the option to not correct it and - of course - not make everything soft at the same time. There are plenty of subjects for which distortion is not easily noticeable.
Chromatic aberrations are annoying but generally avoidable and affect only small parts of the image. Correcting them has a very localized effect.
Vignetting is extremely annoying but, unless it is severe (1+ stops), can be correct quite easily without much detriment to image quality. You will get increased noise in the extreme corners but that is usually it. Of course, when it is above +1 stop, it can cause areas to be under-exposed while measurably withing the camera's dynamic-range. Personally, I find that 1/4 EV or less of vignetting is not noticeable on most subjects.

A:

As the post above says, it depends on what you shoot. I do allot of architectural and travel photography: Except where I want to use a distortion for artistic effect, I dislike any pincushion or barrel effects. Five years ago when I mainly shot landscapes it could also be a problem when the horizon was off centre, it would curve up or down. However for nature and close up shots it should be less of an issue and you should look for the lens sharpness, fine detail or speed instead.
Although you say you can easily correct distortion in you computer, it's always best to get it right in the camera first time. You should only resort to the computer when it is impossible or impractical to do better at the time.


Q:

PHP 7 not working on windows 10

I have problem with getting php 7 work on windows 10.
Wierd thing is that it worked.
I have Ampps installed. As I said php 7 worked but I had to switch to php 5.6. After switching back to php 7 apache did not start.
So I downloaded easyPHP to test php 7 (ampps is closed). I have the same thing. Php 5.6 is working but when I switch to php 7 apache is not starting and no info in error log.
What could it be?
EDIT:
I've tried to run PHP7's php.exe from command line and got that error: No VCRUNTIME140.dll
PHP  5.6

PHP 7

No log change

A:

I found solution.
Problem was that I didn't have Visual C++ Redistributable for Visual Studio 2015 installed.
https://www.microsoft.com/en-us/download/details.aspx?id=48145
But I had to use 32bit version - vc_redist.x86.exe file


Q:

Distance between unequal number of locations in R (latitude and longitude are inputs)

How do I calculate the distance between each location in one data frame versus each in another when they have a different number of rows?
For example, say I have dataframe A with 3 rows and dataframe B with 4 rows. These are from the SNAP (United States federal food / beverage assistance for low-income households) Retailer Locator :
A
      Store_Name     Longitude Latitude
1     Food Lion 2213 -80.86581 35.59477
2 THE CORNER GROCERY -81.09917 35.26776
3          FISH WING -80.88245 35.21639

B
         Store_Name     Longitude Latitude
1    SUPERIOR GROCERIES -79.80839 35.73597
2     MORVEN TRUCK STOP -80.01122 34.88312
3       GREENHILL STORE -81.99146 35.34768
4 NORTHSIDE FOOD MARKET -77.94242 34.24158

Here are some failed attempts:
mapdist(as.character(a), as.character(b))

YIELDS: from and to entries that resemble the following and only one distance calculation that is possibly useful: c(35.594765, 35.267761, 35.216393)
distcomp <- mapdist(from = c(lon = as.character(a$Longitude), lat = as.character(a$Latitude)), to = c(lon = as.character(b$Longitude),   lat = as.character(b$Latitude)), mode = "driving")

YIELDS: Error  arguments imply differing number of rows: 6, 8
# row-bind the rows even though this would mean extra work so that I could only have the distances from those in a to those in b:

c <- rbind(a,b)
distcomp <- mapdist(from = c(lon = as.character(c$Longitude), lat = as.character(c$Latitude)),
                     to = c(lon = as.character(c$Longitude),   lat = as.character(c$Latitude)), mode = "driving")

YIELDS: A bunch of NAs in the results. Nothing helpful.

A:

You can merge the tables together so that every row of each table is joined to every row on the other table (often referred to as a full-join), and then calculate the distances between each set of lat/lon coordinates.
In your question it appears you're asking for the driving distance, as given by Google Maps. Here I'm giving both the driving and the haversine distance.

Joining the data
## create a key column to join on
A$key <- 1
B$key <- 1

## Join together
AB <- merge(A, B, by = "key")

Distance Calculation - haversine
## Here I'm using the haversine distance calculation from geosphere
library(geosphere)

AB$distance <- distHaversine(p1 = matrix(c(AB$Longitude.x, AB$Latitude.x), ncol = 2),
                             p2 = matrix(c(AB$Longitude.y, AB$Latitude.y), ncol = 2))

head(AB)
#   key     Store_Name.x Longitude.x Latitude.x        Store_Name.y Longitude.y Latitude.y  distance
# 1   1     FoodLion2213   -80.86581   35.59477   SUPERIORGROCERIES   -79.80839   35.73597  96915.65
# 2   1     FoodLion2213   -80.86581   35.59477     MORVENTRUCKSTOP   -80.01122   34.88312 110963.56
# 3   1     FoodLion2213   -80.86581   35.59477      GREENHILLSTORE   -81.99146   35.34768 105691.88
# 4   1     FoodLion2213   -80.86581   35.59477 NORTHSIDEFOODMARKET   -77.94242   34.24158 306403.99
# 5   1 THECORNERGROCERY   -81.09917   35.26776   SUPERIORGROCERIES   -79.80839   35.73597 128061.51
# 6   1 THECORNERGROCERY   -81.09917   35.26776     MORVENTRUCKSTOP   -80.01122   34.88312 107968.35

Distance calculation - Google Maps driving
To use Google maps distances you can use mapdist from ggmap as you were doing (but for some reason I could only get it to work in an apply function)
library(ggmap)

mdist <- apply(AB, 1, function(x){
    f = as.numeric(c(x[['Longitude.x']], x[['Latitude.x']]))
    t = as.numeric(c(x[['Longitude.y']], x[['Latitude.y']]))
    mapdist(f, t)
})

AB$mapDist <- do.call(rbind, mdist)

head(AB)
# key     Store_Name.x Longitude.x Latitude.x        Store_Name.y Longitude.y Latitude.y  distance
# 1   1     FoodLion2213   -80.86581   35.59477   SUPERIORGROCERIES   -79.80839   35.73597  96915.65
# 2   1     FoodLion2213   -80.86581   35.59477     MORVENTRUCKSTOP   -80.01122   34.88312 110963.56
# 3   1     FoodLion2213   -80.86581   35.59477      GREENHILLSTORE   -81.99146   35.34768 105691.88
# 4   1     FoodLion2213   -80.86581   35.59477 NORTHSIDEFOODMARKET   -77.94242   34.24158 306403.99
# 5   1 THECORNERGROCERY   -81.09917   35.26776   SUPERIORGROCERIES   -79.80839   35.73597 128061.51
# 6   1 THECORNERGROCERY   -81.09917   35.26776     MORVENTRUCKSTOP   -80.01122   34.88312 107968.35
# mapDist.from                                       mapDist.to mapDist.m
# 1 507-543 NC-150, Mooresville, NC 28117, USA 1504N N Fayetteville St, Asheboro, NC 27203, USA    118648
# 2 507-543 NC-150, Mooresville, NC 28117, USA                2876 US-52, Morven, NC 28119, USA    135294
# 3 507-543 NC-150, Mooresville, NC 28117, USA   136 Firethorn Ln, Rutherfordton, NC 28139, USA    149211
# 4 507-543 NC-150, Mooresville, NC 28117, USA      603 Red Cross St, Wilmington, NC 28401, USA    359219
# 5  101 McAdenville Rd, Lowell, NC 28098, USA 1504N N Fayetteville St, Asheboro, NC 27203, USA    160581
# 6  101 McAdenville Rd, Lowell, NC 28098, USA                2876 US-52, Morven, NC 28119, USA    137167
# mapDist.km mapDist.miles mapDist.seconds mapDist.minutes mapDist.hours
# 1    118.648      73.72787            5049        84.15000      1.402500
# 2    135.294      84.07169            5574        92.90000      1.548333
# 3    149.211      92.71972            5812        96.86667      1.614444
# 4    359.219     223.21869           13264       221.06667      3.684444
# 5    160.581      99.78503            5782        96.36667      1.606111
# 6    137.167      85.23557            5639        93.98333      1.566389


Q:

Why is the ul element being below the other ul elements due to difference in children?

I have this footer menu that I've made consisting of ul and li, one of them which, only has two elements (children) within, whereas the other two ul elements have more. Now, here's the issue; as I line them to be display: inline-block; the ul with the least children is below the level of the other two ul elements.
Why is this happening and how can I fix this without a padding or a margin cheat?
Here's an example in a fiddle.
As you can see, the feature menu is obviously below the other ul menus, which leaves me yet again with the question; why is this happening and how can I fix it?
If the code is necessary again to this question, I'd be more than happy to comply.

A:

display: inline-block goes hand in hand with vertical-align, for which the default value is baseline.
You will want to set vertical-align: top on the .menu class here. To be safe, it's good to always specify vertical align whenever you use inline block, because you'll rarely want it to be baseline.


Q:

Problem understanding this differential equation on elasticity. Help!

I read following in my text book: We take an infinitesimal segment of a bar of uniform cross sectional area $A$, length of this segment starts from $x$ to $x+dx$. We apply stress $S$ in the direction of the length $x$ and $u$ is the displacement of the bar under this stress.Now if  $\rho$ is mass density of the bar then from Newton's 2nd law,$$(\rho A dx)\frac{\partial^2u}{\partial t^2}=[S(x+dx)-S(x)]A$$I am having problem understanding r.h.s. of above equation because for that infinitesimal segment stress applied should be $S(x)$ only and not $[S(x+dx)-S(x)]$. Please explain how the r.h.s. in the above equation has such a form.

A:

You are looking at Newton's second law
$$m \vec{a} = \vec{F} $$
Now $a=\frac{\partial^{2}u}{\partial t^2}$, $m = \rho A dx$ meaning that the body under consideration is this infinitesimal volume of the bar of length $dx$. Now what is the net force on this volume? Assuming that the stress field is only along the direction of the bar, there are two forces on this volume: on the surface with area $A$ at $x$, which is $- S(x) A$, and on the surface with area $A$ at $x+dx$, which is $S(x+dx) A$. The change in sign results from the different orientations of the surfaces. The total force on the volume is just the sum of those two forces and thus we arrive at the expression you give in your question.


Q:

Error in Types for the reducers in TypeScript in React-Redux

I am using TypeScript for my React-Redux app. I have followed the TypeScript React Starter, however, the example mentioned there does not have any action methods that has some arguments/payload.
I have a simple requirement -

Show a list of names and when a button is clicked a new name is added. When another button is clicked 2 names are added.

The entry point for the app index.tsx looks like this -
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
import { createStore } from 'redux';
import { StoreState } from './types';
import { listUsers } from './reducers';
import { Provider } from 'react-redux';
import ListUsers from './containers/ListUsers';

const store = createStore<StoreState>(listUsers, {
  'users': [
    {
      'id': 0,
      'firstName': 'Aniyah',
      'lastName': 'Luettgen',
      'phone': '861-332-5113',
      'email': 'Danika.Ryan84@yahoo.com',
      'role': 'admin'
    },
    {
      'id': 1,
      'firstName': 'Alisa',
      'lastName': 'Pacocha',
      'phone': '085-056-3901',
      'email': 'Eusebio68@yahoo.com',
      'role': 'admin'
    }
  ]
});

ReactDOM.render(
  <Provider store={store}>
    <ListUsers/>
  </Provider>,
  document.getElementById('root') as HTMLElement
);
registerServiceWorker();

The constants file (constants/index.tsx) looks like this -
export const LIST_USERS = 'LIST_USERS';
export type LIST_USERS = typeof LIST_USERS;

export const ADD_USER = 'ADD_USER';
export type ADD_USER = typeof ADD_USER;

export const ADD_USERS = 'ADD_USERS';
export type ADD_USERS = typeof ADD_USERS;

The types (types/index.tsx) are -
export interface User {
  id: number;
  firstName: string;
  lastName: string;
  phone: string;
  email: string;
  role: string;
}

export interface StoreState {
  users: Array<User>;
}

export interface Action<T> {
  type: string;
  payload?: T;
}

My Component (components/ListUsers.tsx) looks like this -
import * as React from 'react';
import { DispatchProps, ListUsersProps } from '../containers/ListUsers';
import { User } from '../types';

interface ListState {
  counter: number;
}

class ListUsers extends React.Component<ListUsersProps & DispatchProps, ListState> {

  constructor(props: ListUsersProps & DispatchProps) {
    super(props);

    this.addUser = this.addUser.bind(this);
    this.addMultipleUser = this.addMultipleUser.bind(this);

    this.state = {
      counter: 0
    };
  }

  render() {
    return (

        <button onClick={() => this.addUser()}>Add User</button>
        <button onClick={() => this.addMultipleUser()}>Add User</button>
        {this.props.users.map((user: User) => (

{user.firstName}

        ))}

    );
  }

  private addUser() {
    this.props.addUser({
      id: this.state.counter,
      firstName: 'abcd',
      lastName: 'efgh',
      email: 'abcd@gmail.com',
      phone: '1234567890',
      role: 'admin'
    });
    this.setState({
      ...this.state,
      counter: this.state.counter + 1
    });
  }

  private addMultipleUser() {
    this.props.addUsers([{
      id: this.state.counter,
      firstName: 'abcd',
      lastName: 'efgh',
      email: 'abcd@gmail.com',
      phone: '1234567890',
      role: 'admin'
    }, {
      id: this.state.counter,
      firstName: 'ijkl',
      lastName: 'mnop',
      email: 'ijkl@gmail.com',
      phone: '1234567890',
      role: 'admin'
    }]);
    this.setState({
      ...this.state,
      counter: this.state.counter + 2
    });
  }
}

export default ListUsers;

My container component (containers/ListUsers.tsx) looks like this -
import { connect, Dispatch } from 'react-redux';
import { Action, StoreState, User } from '../types';
import ListUsers from '../components/ListUsers';
import { addUser, addUsers } from '../actions';

export interface ListUsersProps {
  users: Array<User>;
}

export interface DispatchProps {
  addUser(user: User): Action<User>;
  addUsers(users: Array<User>): Action<Array<User>>;
}

export const mapStateToProps = (state: StoreState): ListUsersProps => {
  return {
    users: state.users
  };
};

export const mapDispatchToProps = (dispatch: Dispatch<DispatchProps>) => {
  return {
    addUser: (user: User) => dispatch(addUser(user)),
    addUsers: (users: Array<User>) => dispatch(addUsers(users))
  };
};

export default connect<ListUsersProps, DispatchProps, {}>(mapStateToProps, mapDispatchToProps)(ListUsers);

Now here is the reducer where I am facing issues (reducers/index.tsx) -
import { Action, StoreState, User } from '../types';
import { ADD_USER, ADD_USERS, LIST_USERS } from '../constants';

export const listUsers = (state: StoreState, action: Action<User>): StoreState => {
  switch (action.type) {
    case LIST_USERS:
      return state;
    case ADD_USER:
      return {
        ...state,
        users: action.payload === undefined ? [...state.users] : [...state.users, action.payload]
      };
    case ADD_USERS:
      return {
        ...state,
        users: action.payload === undefined ? [...state.users] : [...state.users, ...action.payload]
      };
    default:
      return state;
  }
};

Here the compiler says that in the reducers/index.tsx in
case ADD_USERS:
  return {
    ...state,
    users: action.payload === undefined ? [...state.users] : [...state.users, ...action.payload]
  };

that action.payload is User and not Array<User> which is right (I have declared the reducer with type (state: StoreState, action: Action<User>)).
How do I work with this? If there isn't an alternative, I will have to write separate reducers for every ACTION that has a different payload which I think is bad.
The way I am using the DispatchProps type also looks very odd to me. I am trying to follow this for the types of mapStateToProps and mapDispatchToProps.
Is there any work around for this?
PS: I am using react, redux and react-redux libraries.

A:

I found a solution for this. I am not sure if it is right way to do this.

Instead of making the Action Type generic like so -
interface Action<T> {
  type: string;
  payload?: T;
}

I created a Separate Action Type for each Action and then the Action Type accepted by the Reducer would be the | of them.

So, the types look like this (types/index.tsx) -
import { ADD_USER, ADD_USERS, LIST_USERS } from '../constants';

export interface User {
  id: number;
  firstName: string;
  lastName: string;
  phone: string;
  email: string;
  role: string;
}

export interface StoreState {
  users: Array<User>;
}

export type ListUsersAction = {type: typeof LIST_USERS};
export type AddUserAction = {type: typeof ADD_USER, payload: User};
export type AddUsersAction = {type: typeof ADD_USERS, payload: Array<User>};

export type Actions = ListUsersAction | AddUserAction | AddUsersAction;

and the Container Component (containers/ListUsers.tsx) looks like this -
import { connect, Dispatch } from 'react-redux';
import { AddUserAction, AddUsersAction, StoreState, User } from '../types';
import ListUsers from '../components/ListUsers';
import { addUser, addUsers } from '../actions';

export interface ListUsersProps {
  users: Array<User>;
}

export interface DispatchProps {
  addUser(user: User): AddUserAction;
  addUsers(users: Array<User>): AddUsersAction;
}

export const mapStateToProps = (state: StoreState): ListUsersProps => {
  return {
    users: state.users
  };
};

export const mapDispatchToProps = (dispatch: Dispatch<DispatchProps>) => {
  return {
    addUser: (user: User) => dispatch(addUser(user)),
    addUsers: (users: Array<User>) => dispatch(addUsers(users))
  };
};

export default connect<ListUsersProps, DispatchProps>(mapStateToProps, mapDispatchToProps)(ListUsers);

There are no compilation errors any more, and payload for both ADD_USER and ADD_USERS is received properly.

There is a recommendation to reduce the Action Type boilerplate here.


Q:

Mysterious error when using django server with grequests

Currently, I am running a vagrant server on Ubuntu 14.04 and I test all my django modules by using the simple python manage.py runserver 0.0.0.0:8000
Since I am connecting to the django webserver using chrome through http://localhost:8000 and the server is running on a VM, I am port forwarding through the usage of the following setting in Vagrantfile
config.vm.network "forwarded_port", guest: 8000, host: 8000
Everything runs normally (all modules/views/tests function as expected), however, ever since I started using grequests I get this weird error
Exception happened during processing of request from ('10.0.2.2', 63520)
Traceback (most recent call last):
  File "/home/vagrant/anaconda3/lib/python3.6/socketserver.py", line 639, in process_request_thread
    self.finish_request(request, client_address)
  File "/home/vagrant/anaconda3/lib/python3.6/socketserver.py", line 361, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/home/vagrant/anaconda3/lib/python3.6/socketserver.py", line 696, in __init__
    self.handle()
  File "/home/vagrant/anaconda3/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 159, in handle
    self.raw_requestline = self.rfile.readline(65537)
  File "/home/vagrant/anaconda3/lib/python3.6/socket.py", line 586, in readinto
    return self._sock.recv_into(b)
  File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/_socket3.py", line 385, in recv_into
    self._wait(self._read_event)
  File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/_socket3.py", line 157, in _wait
    self.hub.wait(watcher)
  File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/hub.py", line 651, in wait
    result = waiter.get()
  File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/hub.py", line 899, in get
    return self.hub.switch()
  File "/home/vagrant/anaconda3/lib/python3.6/site-packages/gevent/hub.py", line 630, in switch
    return RawGreenlet.switch(self)
gevent.hub.LoopExit: ('This operation would block forever', <Hub at 0x7f3b777e8af8 epoll pending=0 ref=0 fileno=34>)

Note that I am not using grequests and that simply importing it seems to cause this error even when it is not being called or anything
Anyone have any ideas?

A:

This is an issue with one of the underlying dependency - gevent, which overrides the default behaviour of python builtin such as time, etc.
You would have to monkeypatch.
Something like:
from gevent import monkey
monkey.patch_all()

Here is the relevant gevent documentation.
I recently ran into this exact issue - so stopped using grequests and implemented my own async requests logic


Q:

How should I handle a lot of questions by a single OP that I feel should be closed?

I recently read this question, I voted to close it as I feel it doesn't meet the standards of SO. The OP commented and gave the impression it had annoyed him, so I replied explaining my reasons.
What caught my eye was how the user had gotten so much rep yet still managed to ask such a poor question, so I looked through his user profile for some past questions. Having looked through them there seem to be a lot that I would naturally vote to close for whatever reason (a lot seem too broad). I voted on a couple but I am now hesitant to cast anymore votes as I don't want to seem like I am targeting that specific user.
Should I just continue to vote on the ones I think should be closed? Regardless of the fact they all have the same OP.
In general there seems to be something more suspicious going on. Some questions have answers with what seems to be a lot of effort put in for such a poor question (this one for example). I am a bit lost as to why this user has been able to create so many questions without any close votes being picked up? Though perhaps this is because Scala is more niche and doesn't have as many 'voting users' viewing them?

A:

In regards to that specific user, I see nothing suspicious at all in anything I have access to here. While you may think many of their questions deserve to be closed, I see many specific programming-related questions that received very good answers. I don't think I'd close many of these, myself. There's nothing at all anomalous about any of the votes they've received.
Close votes are subjective, so what you think is worthy of closure is not necessarily what others would agree on. Again, many of these look like decent question to me.
I might not target a specific user with close votes, because that seems to me like you're starting to prejudge content based on the person who left it. I've seen that be used vindictively, and we have had to warn people about targeting folks like this. If there are a few obviously bad things to act on, OK, but I might not work your way through their history with close votes.
I can't find them right now, but we had a general set of guidelines here about going back through someone's question history and downvoting. I'd apply the same sort of thinking to this as with downvotes like that.


Q:

How can i keep track of String values?

I'm building some kind of game for programming class and I need to have a history of the people who played, you can play multiple times when you run the game, so I'm not trying to store it permanently just when the game is executing.
I was thinking maybe some kind of array or something that can store all the string variables (names), but I don't how to do this indefinitely until the game stops.
Also, I am not allowed use java data structures (ArrayList, LinkedList, etc.)
.
Alternatively, if this is not possible or very complicated, maybe some way to store the names of only the last 10 people that play would work.
Any help is appreciated.

A:

If data structures are not allowed, you could actually just make do of a comma-delimited String because an array in order to initialize you need to specify its size already (but this is something you definitely cannot know yet).  Have a static instance of the String, then append to it a delimiter (comma) and the the player name.
private static String commaDelimitedStr = "";

public void addPlayerName (String playerName) {
commaDelimitedStr = commaDelimitedStr.concat(",").concat(playerName);
}

Then at the end you can split the String to get an array version of it.
String[] names = commaDelimitedStr.split(",");


Q:

Optimizing a "stop light" circuit to run on lower voltage

I am specifically talking about the circuit found here.

I want to make this same circuit but make it run on much lower voltage, preferably a coin cell or two. Longevity is not important.

A:

You could run it from 6 volts - just stick two CR2032 coin cells together. Make sure your 4017 and 555 ICs are the CMOS versions, as they can run on lower voltages (see your data sheets). You also may want to reduce the value of the 470 ohm current-limiting resistors that are before the LEDs, perhaps 330 ohm if you're on 6 volts.
That looks like fun, I'm going to build it myself tonight. Thanks!


Q:

Laravel get relations return wrong data

I have four tables, seller, products, and buyers, downloads, the logic is: seller can make products and buyers can buy products and it store in downloads table. so for example:
Seller:
---------------------
|id | name | phone  |
---------------------
| 1 | mike | 989898 |
---------------------
| 2 | joe  | 989898 |
---------------------

Products:
---------------------
|id | name | user_id|
---------------------
| 1 | benz |    1   |
---------------------
| 2 | bmw  |    1   |
---------------------

Buyers:
----------------------
|id | name   | phone  |
----------------------
| 1 | carlos | 989898 |
----------------------
| 2 | nina   | 989898 |
----------------------

Downloads:
-----------------------------
|id | product_id  | buyer_id |
-----------------------------
| 1 |      1      |     2    |
-----------------------------
| 2 |      2      |     2    |
-----------------------------

So consider an buyer bought a product with id 2, I want to get products (id 2) and seller data (id 1), in other hand, nina bought benz and bmw, these products belongs to mike, so I want to get products data and seller data in buyerController.
class Buyer extends Authenticatable
{
...
    public function downloads(){
        return $this->hasMany('App\Download','buyer_id');
    }

    public function products(){
        return $this->hasManyThrough('App\Product','App\Seller', 'id', 'user_id');
    }
}

In controller:
public function files()
{
    $buyer = Buyer::find($id);
    $files = Buyer::with('downloads', 'products')->get();

    return $files;
}

It works without any error but return wrong data, for example a product that buyer not buy and also it not return seller data, it just return "laravel_through_key": 1. First function work good but second, hasManyThrough not working correctly.
I am new to Laravel, specially relations.
What I have done wrong?

A:

According to your explanation, Buyer has direct relation downloads and indirect relation products, but latter is through downloads, not sellers. Thus, it should be:
class Buyer extends Authenticatable
{
  //...
  public function downloads()
  {
    return $this->hasMany(Download::class);
  }

  public function products()
  {
    return $this->hasManyThrough(Product::class, Download::class,
      'buyer_id', 'id', 'id', 'product_id');
  }
}

Don't forget to write relations for other models:
class Product extends Model
{
    function seller()
    {
      return $this->belongsTo(Seller::class, 'user_id');
    }
    function downloads()
    {
      return $this->hasMany(Download::class);
    }
}

class Download extends Model
{
    function product()
    {
      return $this->belongsTo(Product::class);
    }

    function buyer()
    {
      return $this->belongsTo(Buyer::class);
    }
}

Now you can use its power:
1. Get buyer products:
>>> App\Buyer::find(2)->products
=> Illuminate\Database\Eloquent\Collection {#3018
     all: [
       App\Product {#3022
         id: 1,
         name: "benz",
         user_id: 1,
         laravel_through_key: 2,
       },
       App\Product {#3019
         id: 2,
         name: "bmw",
         user_id: 1,
         laravel_through_key: 2,
       },
     ],
   }

2. The same but with seller info
>>> App\Buyer::find(2)->products()->with('seller')->get()
=> Illuminate\Database\Eloquent\Collection {#3026
     all: [
       App\Product {#3034
         id: 1,
         name: "benz",
         user_id: 1,
         laravel_through_key: 2,
         seller: App\Seller {#3038
           id: 1,
           name: "mike",
           phone: "989898",
         },
       },
       App\Product {#3031
         id: 2,
         name: "bmw",
         user_id: 1,
         laravel_through_key: 2,
         seller: App\Seller {#3038},
       },
     ],
   }


Q:

Typescript error in ngrx/effects: computed property name must refer to a built in symbol

I am working with ngrx to implement an app state in my ionic 3.9.2 app (using this tutorial for guidance: https://gonehybrid.com/a-beginners-guide-to-using-ngrx-in-an-ionic-2-app-part-1/)
I am currently receiving this error when I try to run the app:
typescript: ...foo/bar/node_modules/@ngrx/effects/src/on_run_effects.d.ts, line: 9
A computed property name in a type literal must directly refer to a built-in symbol.

The error is in reference to the following code block:
export declare function isOnRunEffects(sourceInstance: {
    [onRunEffectsKey]?: onRunEffectsFn;
}): sourceInstance is OnRunEffects;

I am using ngrx effects version 6.1.0.
Any and all help is appreciated, as I am admittedly quite stumped by this. Thanks.
EDIT
I am using typescript version 3.0.1

A:

Based on the error message, it looks like you're using a TypeScript version older than 2.7.  Please upgrade to 2.7 or newer, which has new rules.


Q:

Why does Intellij freeze upon maven pom changes only when the project panel is showing?

I know that I should ask this question to the developers of Intelli IDEA and indeed I just did: https://youtrack.jetbrains.com/issue/IDEA-138746
However, since IDEA is such a fine program and so many people are happily using it, I was wondering if maybe this is a known issue that could be avoided or resolved.
I searched a lot and there are a number of spurious reports in this direction, but nothing clear.
So these are the steps that allow me to reproduce the problem even after a clean restart of IDEA:
1) Make IDEA use up all the allocated memory (-Xmx750)
- I use Intellij on OSX Yosemite (MacBook Air) and its allocated memory must be used up entirely before this effect shows.
- Typically I can reach this by opening a couple of projects and changing maven selecting some maven profiles.
- Then the OSX Activity monitor would say the Intellij process uses e.g. 900m real memory.
2) Ensure the project panel is showing and make changes to the pom and then click "import changes".
- Indexing and import will go at normal speed.
- Then Intellij will stop to indicate any ongoing processes and the UI freezes for about 30 seconds with highest CPU (> 100%) usage.
- Also a little wheel is showing in the top right corner of said project panel.
3) If I hide the project panel, the UI does NOT freeze and is immediately responsive.
Thank you.

A:

Because the project panel is updated on EDT, see and vote: https://youtrack.jetbrains.com/issue/IDEA-117446


Q:

Scraper fails on files over ~390KB

Does the Facebook's URL scarper have a size limitation on it? We have several books available on a website. Those that have an HMTL filesize under a certain size (~390KB) get scraped and read properly but the 4 that are larger do not. These larger items get a 200 response code and the canonical URL opens.
All of these pages are built using the same template, the only differences being the size of the content within each book and the number of links each book makes to other pages on the site.

click on canonical URL
Open Firebug In Firefox or developer tools in Chrome to network tab
3, The *.html size at >~390KB for the listed failures & <~390K for the successes
Click on "See exactly what our scraper sees for your URL"
Blank page for failures, HTML present for successes

Failures:

https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Frcg.org%2Fbooks%2Ftapom.html
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Frcg.org%2Fbooks%2Ftbgpu.html
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Frcg.org%2Fbooks%2Fttjc.html
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Frcg.org%2Fbooks%2Ftbdse.html

Successes:

https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Frcg.org%2Fbooks%2Fthogtc.html
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Frcg.org%2Fbooks%2Faabibp.html
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Frcg.org%2Fbooks%2Ftww.html
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Frcg.org%2Fbooks%2Ftsosw.html
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Frcg.org%2Fbooks%2Fsyottc.html
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Frcg.org%2Fbooks%2Fttigtio.html
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Frcg.org%2Fbooks%2Faadac.html
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Frcg.org%2Fbooks%2Fsiud.html
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Frcg.org%2Fbooks%2Ftuyc.html

A:

A solution for your problem might be to check whether a real user or the Facebook bot is visiting your page. If it is the bot, then render only the necessary meta data for it. You can detect the bot via its user agent which according to the Facebook documentation is:"facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)"
The code would look something like this (in PHP):
function userAgentIsFacebookBot() {
    if ($_SERVER['HTTP_USER_AGENT'] == "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)") {
        return true;
    }
    return false;
}


Q:

Compile multiple autoit scripts using batch

I have this autoit script:
Aut2exe.exe /in %cd%\n1.au3 /out %cd%\n1.exe /icon %cd%\icon.ico /x86 /comp 4

I need it to compile all scripts in the dir not just the file specified. I have tried this:
Aut2exe.exe /in %cd%\* /out %cd%\* /icon %cd%\icon.ico /x86 /comp 4

But it gives a error does any one know what I could do. Thanks.

A:

@echo off
    setlocal enableextensions disabledelayedexpansion

    for %%a in ("%cd%\*.au3") do (
        Aut2exe.exe /in "%%~fa" /out "%%~dpna.exe" /icon "%%~dpa\icon.ico" /x86 /comp 4
    )

    endlocal


Q:

Handle Website Pop-Up While Navigating with IE

I have an Excel VBA macro that

opens IE,
navigates to the Medicare website,
logs me in,
compares the claims listed on the website with those already in the workbook
alerts me to any differences

It is during the log-in step that I have a problem, so I've reproduced that portion of my code below.  As soon as the .click line is executed a pop-up window appears asking the user to click the OK button in order to proceed.  Macro execution is suspended until I manually click the OK  button on the pop-up.
The source code behind the http://www.mymedicare.gov web page has information relative to the pop-up, but I haven't been able to figure out how to use it so that I can programmatically click the pop-up OK button.
Several years ago, I posted this question and Tim Williams provided an excellent solution based on interacting with the javascript behind the pop-up window.  Medicare has since changed the code behind the web page and Tim's solution no longer handles the pop-up window.  I've tried a lot of variations on Tim's theme but haven't found the solution.
Any help in terms of figuring out how to programmatically click the pop-up's OK button would be much appreciated.

note: For the purpose of this question, any user id and password can be used (I've out abcde and 12345 in the code below). If you handle the pop-up you'll be passed to a page that says something like incorrect user id / password. That will indicate that you've been successful in handling the pop-up.

Sub Medicare_Claims()'
' Update the status bar
  Application.StatusBar = "Running the Medicare Claims subroutine"

' Open the "MyMedicare web page
    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = True
        .Navigate "https://www.mymedicare.gov/"
    End With

' Loop until the page is fully loaded
    Do Until ie.ReadyState = 4 And Not ie.Busy
        DoEvents
    Loop

' Log-in
    ie.Document.all.Item("ctl00_ContentPlaceHolder1_ctl00_HomePage_SWEUserName").Value = "abcde"
    ie.Document.all.Item("ctl00_ContentPlaceHolder1_ctl00_HomePage_SWEPassword").Value = "12345"
    ie.Document.getElementById("ctl00_ContentPlaceHolder1_ctl00_HomePage_SignIn").Click

' Loop until the page is fully loaded
    Do Until ie.ReadyState = 4 And Not ie.Busy
        DoEvents
    Loop

    Application.Wait (Now + TimeValue("0:00:15"))

' Navigate further to the Search Claims" web page
    ie.Navigate "https://www.mymedicare.gov/searchclaims.aspx"

A:

This worked for me
Sub Medicare_Claims() '
' Update the status bar
  Application.StatusBar = "Running the Medicare Claims subroutine"

' Open the "MyMedicare web page
    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = True
        .Navigate "https://www.mymedicare.gov/"
    End With

' Loop until the page is fully loaded
    Do Until ie.ReadyState = 4 And Not ie.Busy
        DoEvents
    Loop

' Log-in
    Dim doc As Object

    Set doc = ie.Document

    doc.getElementById("ctl00_ContentPlaceHolder1_ctl00_HomePage_SWEUserName").Value = "abcde"
    doc.getElementById("ctl00_ContentPlaceHolder1_ctl00_HomePage_SWEPassword").Value = "12345"
    doc.getElementById("ctl00_ContentPlaceHolder1_ctl00_HomePage_Agree").Value = "True"

    doc.parentWindow.execScript "window.ConfirmationPopup = function(){null;}", "jscript"

    doc.getElementById("ctl00_ContentPlaceHolder1_ctl00_HomePage_SignIn").Click

End Sub


Q:

AppSettings vs project-specific settings in Web.Config

Okay, so this one has got me a bit confused. I have the following:
string csvOfAttributes = CableSolve.Web.Properties.Settings.Default.GenerateBoothReportAttributes;

and in my web.config:
<CableSolve.Web.Properties.Settings>
  <setting name="GenerateBoothReportAttributes" serializeAs="String">
    <value>327, 329, 330, 369, 342</value>
  </setting>
</CableSolve.Web.Properties.Settings>

I have two questions about this:

If I omit my setting from the web.config file I receive compilation errors. How is this possible? Web.config is user-editable; I would only expect run-time errors. If I compile my application, deploy, then the user edits the name of this setting -- wouldn't that break the compiled code?
I could potentially store this setting in the appConfig section of my web.config file. To access the values I would go through ConfigurationManager -- and I would only receive a null object at run-time if the setting is missing. This seems less advantageous as I tend to prefer my errors arising during compilation, but it leaves me wondering: what are the differences between these two options and when should I use them?

A:

I think the answer is mostly contained in the question: the whole difference is the basic key-value pair schema verses more complex schemas.  By extension, the difference relates to weakly-typed versus strongly-typed, and run-time versus compile-time.  In general the latter is better, in the same sense that .NET is "better" than Javascript: you get alerted to errors early, rather than having them bubble into your application in unpredictable and hard-to-trace ways.  Exceptions to the strong-schema preference might include:

Your application requirements are evolving, so you don't want to lock in a schema
You're working with a root-level configuration that different developers or applications will be using
You want to allow "invalid" configurations and handle them at runtime


Q:

How to configure url rewriting in IIS6 to consider url ending with "/" like a page?

I'm working on Windows Server2003 with the following:

IIS6
  .NET Runtime 2.0
  ASP.NET C#

I've got some pages like these:

fr.mywebsite.eu/productA/sub_product1.html
fr.mywebsite.eu/productA/sub_product2.html

fr.mywebsite.eu/productB/sub_product14.html
fr.mywebsite.eu/productC/sub_product26.html

The directories productA, productB, productC don't really exist.
In my global asax, I get the url requested and I do something like this:
HttpContext.Current.RewritePath(
    "product.aspx?p=" + codeProduct + "&sp=" + codeSubProduct);

For now everything is working.
But I'm trying to make the following page list all subproducts:
http://fr.mywebsite.eu/productB/
The problem is that IIS considers productB to be a directory and I get a 404 error.
Is there any directive to make IIS not check if DIRECTORY exist similar to the manner of ISAPI extensions but for a directory?

A:

I just find the issue. I had to insert a wildcard application maps to
\v2.0.50727\aspnet_isapi.dll
don't check if the file exist.


Q:

php: Anonymous function and arguments

I have an array of objects (from DB) and need to foreach this one before send to the viewer:
$data['contracts'] = array();

foreach ($contracts as $c) {
    $data['contracts'][] = array(
         'id' => $c->id,
         'num' => $c->num,
         'delay' => function ($c->date_added) {
              ... blablabla ...
         },
    );
}

This examples returns an error because $c->date_added is uses, as workaround I must define additional variable before foreach loop:
$date_added = $c->date_added;

How can I use properties in anonymous functions without additional variables?

A:

This might be easier:
// more stuff
'delay' => function ($c) {
    $dateAdded = $c->date_added;
    // rest of bla bla bla...
},
// more stuff


Q:

WordPress: 3.5+ Attach Gallery To Post and Use Template Tag

Just wonder if WordPress 3.5+ still attach gallery even if it is not added to the post content area.
Earlier WordPress was adding gallery as an attachment and allowing to populate via template tag even if it is not added to the content area. Now with version 3.5.1 I am trying to create a gallery and it is displaying if I add to the post content but as soon as I remove from the post content than gallery just disappear from the media library as well and there is no attachment found for the post.
Just wonder and trying to understand how they have changed the media library and gallery. I understand the basic that before they were creating a gallery id but now they are adding only image id so there is no more gallery id. Is that correct?
So question how can I add gallery using template tag something like <?php echo do_shortocode('[gallery link="file"]'); ?> or similar?

A:

You have almost answered this question yourself!
Check the codex for the specifics.
I needed to do this with with a custom meta box and the details can be found here. Pre-Select Images when opening WordPress 3.5 media manager.
EDIT:
For the benefit of other readers and for clarification, something like this is required
echo do_shortcode( '[gallery ids="139,138,137,136"]' );

Where the ids is a comma seperated list of attachment id's you want included. This is it in the simplest form - check the codex for more options.


Q:

How should I reject "minor" edits like this?

Now that the "too minor" reason is gone, I was wondering how should I properly reject minor edits like the follows:
https://stackoverflow.com/review/suggested-edits/5805313
Original:

I wonder if someone would be so kind as to tell me why my code is not
  working. I want my random generator to choose between question 1 or
  question 2 and then execute the relevant IF While. As a newbie, I'm
  struggling. The full code is shown:

After change:

... then execute the relevant (IF While)[italicized]. As a newbie, I'm
  struggling. The (full code)[bold-faced] is  ...

I don't think the edit add any value to the OP. Nor is it vandalism, invalid, radical or plagiarism. What's the proper way to prevent this edit from being committed?

A:

Like this:

Also, for questions like this, I recommend dropping out of review and voting to close. Note that there's a suggestion on Meta SE for adding a reason specifically for edits to doomed posts that don't, uh, un-doom them - don't hesitate to upvote that or drop in your own suggestions on that thread.