Working with GPS Location

Question: Upon activity launch, the GPS is enabled and grabs the user latitude, longitude and report it to parse as a Geopoint. The issue is that the GPS continuously runs in the background and continuously report to Parse location. I would only want the GPS to grab the location information once and then stops immediately, as by myself I have notice that I have reached around 20k request with Parse on a day and I think its because it runs continuously in the background.
Below is the activity code:
public class MoodActivity extends Activity {

    private FeedbackDialog feedBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mood);
        feedBack = new FeedbackDialog(this, "");
         LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
           LocationListener mlocListener = new MyLocationListener();

           mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);

        final TextView teating = (TextView) this.findViewById(R.id.tdinning);
        teating.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class));
            }
        });

        final ImageView ieating = (ImageView) this.findViewById(R.id.idinning);
        ieating.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class));
            }
        });

        final TextView tdrinks = (TextView) this.findViewById(R.id.tcasual);
        tdrinks.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class));
            }
        });

        final ImageView idrinks = (ImageView) this.findViewById(R.id.icasual);
        idrinks.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class));
            }
        });

        final TextView tshows = (TextView) this.findViewById(R.id.tshows);
        tshows.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, EntertainmentEventsActivity.class));
            }
        });

        final ImageView ishows = (ImageView) this.findViewById(R.id.ishows);
        ishows.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, EntertainmentEventsActivity.class));
            }
        });

        final TextView tarts = (TextView) this.findViewById(R.id.tculture);
        tarts.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, CultureEventsActivity.class));
            }
        });

        final ImageView iarts = (ImageView) this.findViewById(R.id.iculture);
        iarts.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, CultureEventsActivity.class));
            }
        });

        final Button viewall = (Button) this.findViewById(R.id.brandom);
        viewall.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class));
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_activity_actions, menu);
        getActionBar().setDisplayShowTitleEnabled(false);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.pageExperience:
                openPageExperience();
                return true;
            case R.id.pageMessaging:
                openPageMessage();
                return true;

            case R.id.pageEventsBooking:
                openPageBook();
                return true;

            case R.id.pageProfile:
                openPageProfile();
                return true;

            case R.id.pageReport:
                openPageReport();
                return true;

            case R.id.pageAbout:
                openPageAbout();
                return true;

            case R.id.pageLogout:
                openPageLogout();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void openPageLogout() {
        // TODO Auto-generated method stub
        //Now call logout
        ParseUser.logOut();
        Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
        startActivity(intent);
    }

    private void openPageAbout() {
        // TODO Auto-generated method stub

    }

    private void openPageReport() {
        // TODO Auto-generated method stub
        FeedbackSettings feedbackSettings = new FeedbackSettings();

        //SUBMIT-CANCEL BUTTONS
        feedbackSettings.setCancelButtonText("No");
        feedbackSettings.setSendButtonText("Send");

        //DIALOG TEXT
        feedbackSettings.setText("Hey, would you like to give us some feedback so that we can improve your experience?");
        feedbackSettings.setYourComments("Type your question here...");
        feedbackSettings.setTitle("Feedback Dialog Title");

        //TOAST MESSAGE
        feedbackSettings.setToast("Thank you so much!");
        feedbackSettings.setToastDuration(Toast.LENGTH_SHORT);  // Default
        feedbackSettings.setToastDuration(Toast.LENGTH_LONG);

        //RADIO BUTTONS
        feedbackSettings.setRadioButtons(false); // Disables radio buttons
        feedbackSettings.setBugLabel("Bug");
        feedbackSettings.setIdeaLabel("Idea");
        feedbackSettings.setQuestionLabel("Question");

        //RADIO BUTTONS ORIENTATION AND GRAVITY
        feedbackSettings.setOrientation(LinearLayout.HORIZONTAL); // Default
        feedbackSettings.setOrientation(LinearLayout.VERTICAL);
        feedbackSettings.setGravity(Gravity.RIGHT); // Default
        feedbackSettings.setGravity(Gravity.LEFT);
        feedbackSettings.setGravity(Gravity.CENTER);

        //SET DIALOG MODAL
        feedbackSettings.setModal(true); //Default is false

        //DEVELOPER REPLIES
        feedbackSettings.setReplyTitle("Message from the Developer");
        feedbackSettings.setReplyCloseButtonText("Close");
        feedbackSettings.setReplyRateButtonText("RATE!");

        //DEVELOPER CUSTOM MESSAGE (NOT SEEN BY THE END USER)
        feedbackSettings.setDeveloperMessage("This is a custom message that will only be seen by the developer!");
        feedBack.show();
    }

    private void openPageProfile() {
        // TODO Auto-generated method stub
        Intent intent = new Intent(this, profileDetailsActivity.class);
        startActivity(intent);

    }

    private void openPageBook() {
        // TODO Auto-generated method stub

    }

    private void openPageMessage() {
        // TODO Auto-generated method stub

    }

    private void openPageExperience() {
        // TODO Auto-generated method stub
        Intent intent = new Intent(this, MoodActivity.class);
        startActivity(intent);
    }

    public class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location loc) {
            // TODO Auto-generated method stub
            double lati = loc.getLatitude();
            double longi = loc.getLongitude();

            ParseUser currentUser = ParseUser.getCurrentUser();
            currentUser.saveInBackground();

            ParseGeoPoint point = new ParseGeoPoint(lati, longi);
            currentUser.put("location", point);

            currentUser.saveInBackground(new SaveCallback() {
                @Override
                public void done(ParseException e) {
                    setProgressBarIndeterminateVisibility(false);

                    if (e == null) {
                        // Success!

                    } else {

                    }
                }
            });

        }

           @Override
           public void onProviderDisabled(String provider) {
               // TODO Auto-generated method stub
               Toast.makeText(getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show();

           }

           @Override
           public void onProviderEnabled(String provider) {
               // TODO Auto-generated method stub
               Toast.makeText(getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();

           }

           @Override
           public void onStatusChanged(String provider, int status, Bundle extras) {
               // TODO Auto-generated method stub

           }
          }
}

If you need any clarification, let me know.
Thanks in advance.
Update
 I've tried working with Single update instead, but it does not seem to be working.
Under onCreate
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
           LocationListener mlocListener = new MyLocationListener();

           mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mlocListener, Looper.myLooper());

and
    public class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location loc) {
            // TODO Auto-generated method stub
            double lati = loc.getLatitude();
            double longi = loc.getLongitude();

            ParseUser currentUser = ParseUser.getCurrentUser();
            currentUser.saveInBackground();

            ParseGeoPoint point = new ParseGeoPoint(lati, longi);
            currentUser.put("location", point);

            currentUser.saveInBackground(new SaveCallback() {
                @Override
                public void done(ParseException e) {
                    setProgressBarIndeterminateVisibility(false);

                    if (e == null) {
                        // Success!

                    } else {

                    }
                }
            });

        }

           @Override
           public void onProviderDisabled(String provider) {
               // TODO Auto-generated method stub
               Toast.makeText(getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show();

           }

           @Override
           public void onProviderEnabled(String provider) {
               // TODO Auto-generated method stub
               Toast.makeText(getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();

           }

           @Override
           public void onStatusChanged(String provider, int status, Bundle extras) {
               // TODO Auto-generated method stub

           }
          }
}

Answer: you have to find a way to removeupdates like
mlocManager.removeUpdates(mlocListener);

after you send your parse information
Comment: no, what i would do is have my activity implement LocationListener and make the LocationManager public at class level then just do the work in the same class and put removeupdates in the onLocationChanged right after your parse work
Comment: Thanks for your response. I can work around that code. Would I add it under  mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
under onCreate?
Comment: Hi, the one issue I notice with removeUpdates is that it only grabs the location once, which is somehow how I wanted it. I meant more that every time someone launches the application it would record its new location once, and lets say update the location once every 30 minute (because lets say the person never close the application and is on a road trip) as oppose to continuously.
Answer: When you call LocationManager.requestLocationUpdates(), the system will continuously provide location updates through the LocationListener given in that call.
If you are interested in getting only one location update, you have two choices:

Use LocationManager.requestSingleUpdate()
Use LocationManager.requestLocationUpdates() but cancel the updates after receiving the first update.

I will go ahead with 2 since you already have some code.You need to first declare your variable mLocManager to be a class field rather than declare it locally in onCreate(). You then need to add the following code in your LocationListener.
    public class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location loc) {

            double lati = loc.getLatitude();
            double longi = loc.getLongitude();

            mlocManager.remoteUpdates(this); // ADD THIS STATEMENT

            // The rest of your code goes here ...

        }

   }

Comment: @user3907211: It's hard to say what the problem may be with requestSingleUpdate(). Is requestLocationUpdates() working for you? Are you sure you have GPS/WiFi connectivity?
Comment: @user3907211: You can get the geocoordinate from two providers at the same time (GPS and network). See this question: http://stackoverflow.com/questions/4595522/use-gps-and-network-provider-at-the-same-time-in-android
Comment: @user3907211: To get the location once every 30 minutes, there are two ways. (1) In the call to requestLocationUpdates(), you can set the `minTime` parameter. Note that it is in milliseconds. (2) You can use a separate OS timer call to schedule requestLocationUpdate 30 minutes from now. When the geocoordinate is found, you can cancel the requestLocationUpdate and then set another timer. See: http://stackoverflow.com/questions/3072173/how-to-call-a-method-after-a-delay-in-android
Comment: @user3907211: From my understanding, network provider requires that there is Internet connectivity. This provider obtains cell tower and wi-fi base station signals, sends it to Google, and then gets back the geolocation. See: http://blog.shinetech.com/2011/10/14/a-good-look-at-android-location-data/
Comment: @user3907211: If the user does have wi-fi enabled (which is different from having network connectivity), I usually display a Toast message saying "To improve location placement, please enable WiFi". Also see: http://stackoverflow.com/questions/3145089/what-is-the-simplest-and-most-robust-way-to-get-the-users-current-location-in-a
Comment: @user3907211: More good answers: http://stackoverflow.com/questions/21734907/why-does-having-wifi-on-but-not-connected-help-network-location-when-using-loca
Comment: Thank you for your prompt response and clarification. Out of curiosity, how would the first option work?
Comment: I've tried working with Single update instead, but it does not seem to be working. I have included what I have done under the update section of my initial post
Comment: Yes it has managed to work.  I have two issues 1)It uses GPS abd U have quickly realized that its not the best solution since most devices GPS takes a while to load, and hence I am thinking of how I could grab the latitude and longitude information based on wi-fi or mobile data as oppose to GPS.On top of not having the application continuously search for the user location and report it to parse, I would want it to update the location once every 30 minute (because lets say the person never close the application and is on a road trip) as oppose to continuously
Comment: Thanks for your prompt responses, and for the link, and clarification: 1) Does your phone require mobile data to be able to use Network_Provider, or would the device wi-fi also works since it does not run on emulator with wi-fi enabled. mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
In the event that the person does not have wi-fi or mobile data, could I display a popup message instead of the unexpected error that is shown indicating that no network is found.
Answer: Besides what @JRowan said, You can also use:
String provider = LocationManager.getBestProvider(new Criteria(), true);
Location myLocation = LocationManager.getLastKnowLocation(provider);

If your location timing doesn't have to be exact, that is, if you can afford the location data to be somewhat old.
Method link
Comment: Thanks for your prompt response. Along with adding the suggested line Would I need to remove any lines?
Comment: to use this code you don't really need to change anything. Instead of obtaining location in `onLocationReceived` you just use `myLocation` instead. For @JRowan's answer, you need to call `removeUpdates` after you are done receiving information and everything is stored safely.
Comment: Hi, the one issue I notice with removeUpdates is that it only grabs the location once, which is somehow how I wanted it. I meant more that every time someone launches the application it would record its new location once, and lets say update the location once every 30 minute (because lets say the person never close the application and is on a road trip) as oppose to continuously.

Working with GPS Location


Get the AUTO_INCREMENT value after inserting a new row

Question: How can I get the id that was just inserted for the current user if it is controlled by AUTO_INCREMENT?
(I need the Id for another use)
Note: some row can be deleted so MAX(id) is not an option.
Ex:
inserted row 2
inserted row 3
deleted row 3
inserted row 4 but MAX(id) returns 3..
Thank you very much!
Comment: You have tagged this question [tag:php]: which API are you using?
Answer: With PDO:
$db->lastInsertId(); // $db is the PDO object

With MySQLi OOP:
$db->insert_id; // $db is the MySQLi object

With MySQLi procedural:
mysqli_insert_id($db); // $db is the connection variable

If you're using the old MySQL API, switch.
Comment: I dont understand how to use it.. mysql_insert_id returns int and its just goes into a variable. but mysqli_insert_id returns mixed and I have no idea how to use it..
Comment: Are you using the new MySQLi API, or the old MySQL one? You're probably using the latter, since `mysql_insert_id` returns an integer (which is what its supposed to).
Comment: You should know that the old `mysql_*` API is deprecated since PHP 5.5, and is less secure. You should really upgrade to MySQLi.
Comment: yup I use `mysql_insert_id` and it works. Can you help me upgrade my code to mysqli?
Comment: lets do that in chat if you'd like @Marcel
Comment: You should learn the API and change YOUR code YOURSELF. I don't do this for free. Here's something to get you started off: http://codular.com/php-mysqli/, and of course: http://php.net/manual/en/book.mysqli.php.
Answer: try
select @@identity
This should return the last value in the identity column
Answer: Since your answer is tagged with PHP, I'll answer in that context. If you're using the PDO API, you can use PDO::lastInsertId. If you're using the mysql function API, the equivalent would be mysqli_insert_id or mysql_insert_id.
Edit: Ninja'd :P
Answer: Use mysql_insert_id() or mysqli_insert_id()
Comment: I dont understand how to use it.. mysql_insert_id returns int and its just goes into a variable. but mysqli_insert_id returns mixed and I have no idea how to use it..
Comment: For mysqli_insert_id you are required to pass connection variable to the function. Like mysqli_insert_id($con); You can also use LAST_INSERT_ID() for the same.
Answer: you can use mysql_insert_id
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>

EDIT:
mysql_insert_id is deprecated. now its mysqli_insert_id
Comment: `mysql_*` is deprecated. Don't use it.
Comment: I dont understand how to use it.. `mysql_insert_id` returns int and its just goes into a variable. but `mysqli_insert_id` returns `mixed` and I have no idea how to use it..


R Chi-Squared Table Format

Question: So I have some data that is formatted like so:
header1    header2
"nocandy"  "nocandy"
"nocandy"  "nocandy"
"nocandy"  "nocandy"
"nocandy"    "candy"
"nocandy"    "candy"
"candy"    "candy"
etc...

I imported it with candytext <- read.table("candytest.txt", header=TRUE)
And I want to do a chi-squared test to see if there is a difference between the two groups.
When I use the function table(candytest) I get something like this:
         header2
header1   candy nocandy
  candy     112      39
  nocandy     4      82

But if I run summary(candytest) I get something like this:
    header1       header2
 candy  :151   candy  :116
 nocandy: 86   nocandy:121

As you can see the two tables are formatted differently. However, I can run a chisquared test on the first table but not the second. However the summary table is more like the table I would need to use to do a chisq.test() on. The second table looks like it's assuming that the data is paired, but the data is not paired. If it was paired it would be fine and I could use McNemars test on the output of table(candytest), but it's not paired. So how do I create a 2 by 2 matrix that looks like the summary table, without typing it out by hand. I realise I could copy the summary table into a matrix, however I want to know how to convert it in R with functions properly.
Thank you!
Comment: `summary` is not designed to do crosstabulatons or chi-squared statistics. It does not return a table a object. It returns a text output on a column-by-column basis. Please read the help pages.
Comment: You can do `summary(table(df))` and get a chi-squared test result.  But you'll probably need to rearrange the data into groups
Comment: @RichardScriven - beware these are not the same: `summary(table(df))` is equivalent to `chisq.test(tab, correct=FALSE)`, where `correct=TRUE` is the default.
Comment: I suppose I should have written that `summary.data.frame` is not so designed.
Comment: Type `methods(summary)` to see a few other function names.
Comment: I wish I could have given all of you a checkmark. You were all very helpful in answering my novice questions. Thank you!
Answer: Here, I am trying to get summary on each column of df1 using lapply assuming that the column classes are factors.  From the post, I guess that is the case.  Using do.call(data.frame on the list output, converts it to data.frame.
  do.call(data.frame,lapply(df1, summary)) #in case a matrix output is needed, just replace `data.frame` with `cbind`
  #          header1 header2
  #candy         1       3
  #nocandy       5       3

  summary(df1)
  #   header1     header2
  #candy  :1   candy  :3
  #nocandy:5   nocandy:3

If you need only selected columns from many columns in a dataset,
  nm1 <- paste0("header",1:2) #names of columns to do the summary
   do.call(`cbind`, lapply(df1[nm1], summary))
   #        header1 header2
   #candy         1       3
   #nocandy       5       3

You could also do summary with data.table
  library(data.table)
  DT <- setDT(df1)[, lapply(.SD, summary)]   #or

 #DT <- setDT(df1)[, lapply(.SD, table)]
  DT
   #    header1 header2
   #1:       1       3
   #2:       5       3

 chisq.test(DT)

 #    Pearson's Chi-squared test with Yates' continuity correction

  #data:  DT
  #X-squared = 0.375, df = 1, p-value = 0.5403

  #Warning message:
  #In chisq.test(DT) : Chi-squared approximation may be incorrect

data
df1 <- structure(list(header1 = structure(c(2L, 2L, 2L, 2L, 2L, 1L), .Label = c("candy",
"nocandy"), class = "factor"), header2 = structure(c(2L, 2L,
2L, 1L, 1L, 1L), .Label = c("candy", "nocandy"), class = "factor")), .Names = c("header1",
"header2"), row.names = c(NA, -6L), class = "data.frame")

Comment: Beautiful! Now can you explain what this is doing? It looks like voodoo to me, I'm relatively new to R. Is there a better way I could have imported it, or just a better way I could do the test?
Comment: @jelijelidjango I added some explanation.
Answer: It sounds like you want to treat your columns as independent samples. If so, this might not be the best data structure. But you could do
#sample data
candytext<-read.table(text='header1    header2
 "nocandy"  "nocandy"
 "nocandy"  "nocandy"
 "nocandy"  "nocandy"
 "nocandy"    "candy"
 "nocandy"    "candy"
 "candy"    "candy"', header=T)

#summarize
do.call(cbind, lapply(candytext, table))
#         header1 header2
# candy         1       3
# nocandy       5       3

Comment: Yes, I was thinking it wasn't the best data structure. But I'm just getting familiar with R. What would you recommend to use? How should I have started out?
Comment: Two columns: one for the observation (ie "candy","nocandy") and one for the group ("group1" vs "group2")
Answer: Try:
> dd = data.frame(sapply(candytext, summary))
> dd
        header1 header2
candy         1       3
nocandy       5       3

> chisq.test(dd)
        Pearson's Chi-squared test with Yates' continuity correction

data:  dd
X-squared = 0.375, df = 1, p-value = 0.5403

Warning message:
In chisq.test(dd) : Chi-squared approximation may be incorrect
>

If you want to select 2 columns from a multicolumn data frame:
> cc = cbind(summary(candytext$header1), summary(candytext$header2))

> cc
        [,1] [,2]
candy      1    3
nocandy    5    3

> chisq.test(cc)

        Pearson's Chi-squared test with Yates' continuity correction

data:  cc
X-squared = 0.375, df = 1, p-value = 0.5403

Warning message:
In chisq.test(cc) : Chi-squared approximation may be incorrect

In following form, table and summary are same:
> cbind(table(candytext$header1), table(candytext$header2))
        [,1] [,2]
candy      1    3
nocandy    5    3
>
> cbind(summary(candytext$header1), summary(candytext$header2))
        [,1] [,2]
candy      1    3
nocandy    5    3

R Chi-Squared Table Format


variables table in D8?

Question: What database table in Drupal 8 replaces variables table in Drupal 7?
Where are the values of Configuration stored?
example : $config->set('message', 'Hi')->save();
Where can I find value of message variable in database?
Answer: In Drupal 8, you can find the equivalent in the config table.
mysql> desc config;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| collection | varchar(255) | NO   | PRI |         |       |
| name       | varchar(255) | NO   | PRI |         |       |
| data       | longblob     | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> select * from config where name = 'system.theme';
+------------+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| collection | name         | data                                                                                |
+------------+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
|            | system.theme | a:3:{s:5:"admin";s:5:"seven";s:7:"default";s:6:"bartik";s:5:"_core";a:1:{s:19:"default_config_hash";s:43:"gOjer9hADYYnbCJVZMFZIIM1azTFWyg84ZkFDHfAbTz";}} |
+------------+--------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql>

By default, the "active" configuration is stored in the database
  ("config" table). This is for performance and security reasons. This
  is the complete configuration for the entire site at that moment.
  Configuration can be exported and imported as YAML files, either in
  it's entirety, or a single piece of configuration, using Drush config
  commands or the Configuration Manager.

More info: https://www.drupal.org/docs/8/configuration-management/managing-your-sites-configuration
Comment: I think that's only half of the story - there's now the state API, which is used for instance-specific config. The last time cron ran would be in state rather than config, for example, whereas it was all lumped into Variables in D7
Comment: @Clive, can you please add more explanation to this as another answer? or else pls provide a link for reference.. Thanks :)

variables table in D8?


How to specify radio buttons in baseFieldDefinitions?

Question: In the baseFieldDefinitions method of my custom entity, I see I can provide a checkbox list with code like...
$fields['my_field'] = BaseFieldDefinition::create("list_string")
      ->setSetting('allowed_values', $$my_options)
      ->setLabel('My Field')
      ->setRequired(FALSE)
      ->setCardinality(-1)
      ->setDisplayOptions('form', array(
        'type' => 'options_buttons',
        'weight' => 5
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

But how would I specify radio buttons so the user can make only one selection from the list?
Answer: The radios/checkboxes are displayed based on the field's cardinality:

If the field can store more than one (e.g., unlimited: ->setCardinality(-1), or 2,3,etc. ->setCardinality(2), ->setCardinality(3), etc.), it will be displayed as checkboxes.
If the field can store only one (i.e. ->setCardinality(1)), it will be displayed as radio buttons.


Why does deleted row appear after insertion instead of the new row?

Question: I have a custom cell with Text Field. I do row deletion in a standard manner:
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        dataArray.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let myCell = tableView.dequeueReusableCellWithIdentifier("cellId", forIndexPath: indexPath) as! MyCell

        myCell.textField.placeholder = dataArray[indexPath.row]

        return myCell
    }

Also I use my own class for the cell.
class MyCell: UITableViewCell {

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

let textField: UITextField = {
    var field = UITextField()
    field.placeholder = "Placeholder Text"
    field.translatesAutoresizingMaskIntoConstraints = false
    return field
}()

func setupViews() {
    addSubview(textField)

    //Constraints stuff
}

The problem is if Text Field contains a text and I delete that row, after insertion of a new row I get the old one with the text.
How can I avoid it? I need clean row.
BTW, animation doesn't work properly as well.
Thank you for your help!
Comment: Please show your cell for index path function.
Comment: you should call `tableView.beginUpdates()` before you delete the rows and call `tableView.endUpdates()` afterwards. It is also possible that in your `cellForRowAtIndexPath` you are reusing a cell, which has been deleted.
Comment: @dasblinkenlight I've added cellForRowAtIndexPath code and my custom cell class code.
Comment: @kcpac Thank you. Will try and let you know whether it works or not.
Comment: @kcpac ...
        if editingStyle == .Delete {
            **tableView.beginUpdates()**
            timers.removeAtIndex(indexPath.row)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Left)
            **tableView.endUpdates()**
        }
    }
Unfortunately it doesn't work. I am new in iOS and hope that I've added those lines in a correct place.
Comment: Problem solved! Thank to all of you, guys!
Answer: Use UITableViewCell's prepareForReuse() method.
func prepareForReuse() {
    textField.text = nil
}

More info here.
Answer: Your cellForRowAtIndexPath is responsible for setting the correct values on any cell.  It is probably reusing the cell you just delete. Make sure that cellForRowAtIndexPath is resetting the values in your cell based on the indexPath whenever it is called (particularly after you deletion)
Comment: Thank you @Owen! After implementing @Mark's code I see that your answer is great too.


Why is mutate not working within a for loop in R?

Question: I have some variables that should be coded 0-3 or NA but have been coded 1-4 with "." for NA. I want to recode them using mutate() and case_when() in a for loop but after running the loop my data don't change. No errors appear.
Before the transformation the data look like this:
tabyl(df$epds_1)

# df$epds_1  n
# .          6
# 1        472
# 2         93
# 3         45
# 4         23
# <NA>      10

I try to mutate ten variables using the following:
    for (v in c("epds_1", "epds_2", "epds_3", "epds_4", "epds_5", "epds_6",
                "epds_7", "epds_8", "epds_9","epds_10")) {
      df <- df %>% mutate(`v` = case_when(`v` == "." ~ NA_real_,
                                          `v` == "1" ~ 0,
                                          `v` == "2" ~ 1,
                                          `v` == "3" ~ 2,
                                          `v` == "4" ~ 3))
      }

Hoping for the following table to result (the count of 16 combining the top and bottom rows of the original table):
tabyl(df$epds_1)
# df$epds_1  n
# 0        472
# 1         93
# 2         45
# 3         23
# <NA>      16

Comment: It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. To mutate multiple columns, you'll want to use `across()` instead of a loop.
Comment: @NicChr has given you a working solution.  As to the "why" your code does not work, you are a victim of non-standard evaluation [NSE](https://dplyr.tidyverse.org/articles/programming.html): the tidyverse (generally) expects you to provide the unquoted name of a data frame column, not a character variable containing the name of the column.
Answer: You can use across() to apply a function to several variables.
vars <- c("epds_1", "epds_2", "epds_3", "epds_4", "epds_5", "epds_6",
          "epds_7", "epds_8", "epds_9","epds_10")
df %>% mutate(across(all_of(vars), ~ case_when(.x == "." ~ NA_real_,
                              .x == "1" ~ 0,
                              .x == "2" ~ 1,
                              .x == "3" ~ 2,
                              .x == "4" ~ 3)))

As for why the loop isn't working.. to get it to work you would change your code to something like this.
for (v in c("epds_1", "epds_2", "epds_3", "epds_4", "epds_5", "epds_6",
            "epds_7", "epds_8", "epds_9","epds_10")) {
  df <- df %>% mutate(!!v := case_when(.data[[v]] == "." ~ NA_real_,
                                      .data[[v]] == "1" ~ 0,
                                      .data[[v]] == "2" ~ 1,
                                      .data[[v]] == "3" ~ 2,
                                      .data[[v]] == "4" ~ 3))
}

I would advise against this though and utilise dplyr's across as shown in my first example.


systemd starting service even if service in requires wont start

Question: I have a test systemd service that I am testing. I have test.service which looks like this
<code>[Unit]
Description=Dovid Demo Service
After=mariadb.service
Requires=mariadb.service

[Service]
ExecStart=/home/dovid/test.sh
User=dovid
Group=dovid

[Install]
WantedBy=default.target
</code>
If I do
<code>systemctl start test
</code>
It will first start MariaDB and then start my script. However if I have MariaDB masked (I did systemctl mask mariadb) then MariaDB wont start yet systemd will start up test.sh. Shouldn't it fail because start a required process which in this case is MariaDB?
Answer: This is a bug in systemd. I have filed a bug report and done analysis of what is wrong here: https://github.com/systemd/systemd/issues/11338
That issue manifests here as the target gains a Wants= on the unit that Requires= a masked unit. The transaction is built and systemd has already added a job for the anchor unit, its Wants= dependency, and does not remove it when it gets -ERFKILL in your case, and propagating this up to the function called for UNIT_WANTS ignores it (as it isn't a fatal error), so you end up having the unit started even when required unit is masked.
This happens with many other cases, like RequiresMountsFor= for non-existent paths, etc. Same for BindsTo= as well.
Doing traversal from the bottom up is something I played around with, but that results in another issue: if some unit Requires=existing.service non-existent.service, it will still queue a spurious job, so this adding of jobs needs to be atomic at some level. Moreover, it may not enqueue a spurious job, depending on the order you specify things in.
Anyway, consider bumping that GitHub issue, and explain how you're hitting it.
Comment: @johathan Could you explain what a "masked" unit is?  Is there a way to work around the bug.  (After two years the bug is still open.)


what's the biggest and most frequented forum/board for iphone development?

Question: I've just enrolled into the program and it's pending. I know there is an top-secret apple forum for enrolled iphone developers, but I wonder if there are any others which are good?
I feel that my problems are too complex and need more discussion that can't be done just in comments.
Answer: You found it. Welcome to the biggest and most responsive iPhone programming forum.
Answer: If you can avoid it, I wouldnt use the apple iphone forum. Its REALLY slow. I've had better luck this morning finding answers on SO then over 3 days on the iphone boards
Answer: I recommend the iPhoneSDK group on Google. It is frequented by experts.
Apple's members-only forums do have useful stuff especially if you want to find out about Beta products that developers are hesitant to discuss elsewhere.
Answer: http://www.iphonedevsdk.com/forum/ seems to be pretty popular.
Answer: A top-secret apple forum .. I'm an iPhone developer, and I've never heard of it, perhaps I'm just not that good :(
Anyway, the apple support discussion forums are adequate (nothing compares to Stackoverflow); http://discussions.apple.com/forum.jspa?forumID=727&start=0
I'd like to see what other forums people read. I usually end up on some blog when I type in a question in Google.
Comment: you mean that they're less frequented regarding iphone than SO?
Comment: Isn't your comment meant for Alex? ;-)


custom cursor in adobe edge

Question: i am trying to make an custom cursor in adobe edge, without much sucess so i hope someone could help me.
these are the codes that i have tried;
var myCursor = new ball();// as linkage to be done in the library
Mouse.hide();
stage.addEventListener(MouseEvent.MOUSE_MOVE,follow);

function follow(evt:MouseEvent){ addChild(myCursor);
myCursor.x = mouseX;
myCursor.y = mouseY;
}

stage.addEventListener(Event.MOUSE_LEAVE,vanish);
function vanish(event:Event){ removeChild(myCursor);
}

AND
.next:hover { cursor:url(img/right-pointer.png); }

AND
stage.addEventListener(MouseEvent.MOUSE_MOVE, redrawCursor);
stage.addEventListener(Event.MOUSE_LEAVE, hideCursor);
Mouse.hide();

function redrawCursor (event:MouseEvent):void {
sikte.visible = true;
sikte.x = event.stageX;
sikte.y = event.stageY;
}
function hideCursor (event:Event):void { sikte.visible = false; }

Answer: I will try to give you completely new example:

Start a new Adobe Edge project.
Drag and drop on the stage image for cursor.
Name that image (div) e.g. "cursor".
Add event listener to your stage in order to get move events and set callback function. You can also make correction for position if your stage div is nested inside other div and/or it's position in window is not (0,0) - offset.
document.getElementById('Stage').addEventListener('mousemove', mouseMove, false);

function mouseMove(e) {
    var offsetX = document.getElementById('Stage').offsetLeft;
    var offsetY = document.getElementById('Stage').offsetTop;

    var newX = e.pageX - offsetX;
    var newY = e.pageY - offsetY;
    sym.$("cursor").css({
        "left" : newX,
        "top" : newY
    });
}

Set simple css for stage to make default cursor disappear. (cursor: none)

This is the minimum.

custom cursor in adobe edge


Run GitLab and Tomcat on the same website URL

Question: For the longest time I ran GitLab on HTTP and my Tomcat on HTTPS, but now I would like to run both of them on HTTPS.
I own a website url, lets say its called https://www.example.com. I would like to let my tomcat instance handle everything that is not https://www.example.com/gitlab. Is this possible? Both services are running on different ports and my problem is, that if I open tomcat first, it will handle all HTTPS requests and if I open GitLab then it will handle all HTTPS requests
Answer: Just add Apache or nginx as a reverse proxy before the two services and let them forward the requests.
Comment: Do you mean Tomcat when you say Apache or are you talking about Apache HTTPD?
Comment: The classic web server, httpd


Criando gráficos com JSON e Highcharts

Question: Estou tentando utilizar um simples exemplo fornecido pelo Highcharts para a criação de um gráfico, porém não estou obtendo sucesso.
HTML
<!DOCTYPE HTML>

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

data.json
[
[1,12],
[2,5],
[3,18],
[4,13],
[5,7],
[6,4],
[7,9],
[8,10],
[9,15],
[10,22]
]

Minha dúvida é: por que o gráfico não é criado? Se eu quisesse alterar o formato para [{"a","b"}] como eu deveria alterar a passagem dos dados para o gráfico?
Comment: O objeto `options` é bem complexo, onde está ele? senão vai dar erro na consola se tentar usar `options.series[0].data = data;`. Dê uma olhada aqui e complete a sua pergunta: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-basic/
Comment: Não entendi muito bem a segunda pergunta, poderia esclarecer?
Answer: Testei o seu HTML e o que parecia ser o problema que não criava o gráfico é que a biblioteca do Highcharts parece ter uma dependência do jQuery, e o jQuery está sendo declarado só depois do Highcharts. Tente mudar para a seguinte ordem:

Criando gráficos com JSON e Highcharts


Forest Plot: Proportions on x axis

Question: In most descriptions of Forest Plots the x-axis is an Odds Ratio or a Difference of means etc.
But I'm now reading a paper where the x-axis is labeled "Proportion" with the scale going from 0 to 0.8. How does one interpret this?
The scale is linear, and not log. OR scales are typically log?
The authors report they've used MedCalc  for the analysis & the plot looks like something a canned, out-of-the-box routine in the software produced.
https://www.medcalc.org/
Edit: They call the plots "Forest plots of proportions of disease response rates".  My guess is that their x-axis quantity is something like the proportion of subjects that showed "improvement" or response to the intervention.
But I'd love any comments.
Answer: You are used to looking at meta-analyses of comparative primary studies but this is a meta-analysis of non-comparative studies so the authors are meta-analysing the proportion of some quantity. Note that the proportions have confidence intervals which are not symmetrical on the scale shown. Whether the software (or the authors) transformed the proportions is not something we can tell from what you give us but it would be usual to do so. There are many possible transformations: log, logit, arcsine square root, Freeman-Tukey, ...
Comment: Thanks! Do you know of any good articles / sites that describe the interpretation and details of a Forest Plot of non-comparative studies?  All the tutorials etc. I came across seem to not explain this type.
Comment: Re. the transformation of the proportions: The paper itself is mum on it but digging deeper into the statistical package's manual reveals that: "MedCalc uses a Freeman-Tukey transformation (arcsine square root transformation; Freeman and Tukey, 1950) to calculate the weighted summary Proportion under the fixed and random effects model (DerSimonian & Laird, 1986)."
Comment: You could look at http://www.metafor-project.org/doku.php/analyses#meta-analysis_of_proportions which has a couple of references, one of which you already have.

Forest Plot: Proportions on x axis


CentOS 9 Stream - errors doing yum update

Question: I'm coming in from using Ubuntu.
Just installed CentOS on my DEV server and right away having issues just doing an update or installing new packages.
Here is the error:
sudo yum update

Last metadata expiration check: 0:41:22 ago on Tue 15 Feb 2022 10:38:21 AM.
Error:

 Problem 1: problem with installed package libidn2-2.3.0-7.el9.x86_64
  - cannot install the best update candidate for package libidn2-2.3.0-7.el9.x86_64
  - nothing provides libunistring.so.0()(64bit) needed by libidn2-2.3.2-1.el7.x86_64

 Problem 2: cannot install the best update candidate for package python3-tracer-0.7.5-4.el9.noarch
  - problem with installed package python3-tracer-0.7.5-4.el9.noarch
  - package python3-tracer-0.7.5-4.el9.noarch requires tracer-common = 0.7.5-4.el9, but none of the providers can be installed
  - cannot install the best update candidate for package tracer-common-0.7.5-4.el9.noarch
  - cannot install both tracer-common-0.7.8-1.el7.noarch and tracer-common-0.7.5-4.el9.noarch

Here are the enabled repos:
yum repolist enabled
repo id       repo name
appstream     CentOS Stream 9 - AppStream
baseos        CentOS Stream 9 - BaseOS
epel          Extra Packages for Enterprise Linux 7 - x86_64
extras-common CentOS Stream 9 - Extras packages
remi-safe     Safe Remi's RPM repository for Enterprise Linux 7 - x86_6

I have tried to:
sudo yum update --best --allowerasing

But its still complaining:
Problem 1: problem with installed package libidn2-2.3.0-7.el9.x86_64
  - cannot install the best update candidate for package libidn2-2.3.0-7.el9.x86_64
  - nothing provides libunistring.so.0()(64bit) needed by libidn2-2.3.2-1.el7.x86_64
 Problem 2: cannot install the best update candidate for package python3-tracer-0.7.5-4.el9.noarch
  - problem with installed package python3-tracer-0.7.5-4.el9.noarch
  - package python3-tracer-0.7.5-4.el9.noarch requires tracer-common = 0.7.5-4.el9, but none of the providers can be installed
  - cannot install the best update candidate for package tracer-common-0.7.5-4.el9.noarch
  - cannot install both tracer-common-0.7.8-1.el7.noarch and tracer-common-0.7.5-4.el9.noarch
(try to add '--skip-broken' to skip uninstallable packages)

Any ideas how to fix this?
UPDATE:
Tried
yum clean all
yum check
yum check-update
yum update

yum update --nobest

Same result:
Last metadata expiration check: 0:49:35 ago on Tue 15 Feb 2022 11:30:57 AM.
Dependencies resolved.

 Problem 1: cannot install the best update candidate for package libidn2-2.3.0-7.el9.x86_64
  - nothing provides libunistring.so.0()(64bit) needed by libidn2-2.3.2-1.el7.x86_64
 Problem 2: package python3-tracer-0.7.5-4.el9.noarch requires tracer-common = 0.7.5-4.el9, but none of the providers can be installed
  - cannot install both tracer-common-0.7.8-1.el7.noarch and tracer-common-0.7.5-4.el9.noarch
  - cannot install the best update candidate for package tracer-common-0.7.5-4.el9.noarch
  - cannot install the best update candidate for package python3-tracer-0.7.5-4.el9.noarch
==================================================================================================================================================
 Package                                Architecture                    Version                               Repository                     Size
==================================================================================================================================================
Skipping packages with conflicts:
(add '--best --allowerasing' to command line to force their upgrade):
 tracer-common                          noarch                          0.7.8-1.el7                           epel                           31 k
Skipping packages with broken dependencies:
 libidn2                                x86_64                          2.3.2-1.el7                           epel                          148 k

Answer:
baseos        CentOS Stream 9 - BaseOS
epel          Extra Packages for Enterprise Linux 7 - x86_64
extras-common CentOS Stream 9 - Extras packages

You are using old EPEL (and "remi") for EL-7 while you are running EL-9
You need to remove epel-release and remi-release and install the proper versions.
Comment: Not fun, as quite common ;)  but always "strange" and "sad" to see people asking in random places instead of dedicated ones (forum, github issues, irc, discord...)
Comment: Is it fun seeing people use your repo in the wild? :D
Answer: Try:
yum clean all
yum check
yum check-update
yum update

If there is still a problem, try:
yum update --nobest
Comment: I have tried this and its still throwing the same error - added output to my original post.
Comment: It almost feels like there are two repos with same package that are conflicting with each other.
Comment: I think its coming from epel repo. When doing sudo yum --disablerepo=epel updates, the errors do not show up. The problem is that I cant install htop without it.
Comment: @KalvinKlien you're most likely correct. Epel and remi-safe might be conflicting.
Comment: Are you sure this is a clean install? You shouldn't be having these problems if that was the case. Just need to enable to epel repo and you're set.
Comment: Yes, just installed CentOS 9 Stream yesterday. Its has Desktop version with GUI.
Answer: Figured it out, I copy pasted and added epel from CentOS 7 so it was conflicting with existing one on the CentOS 9.
Used this to remove the older repo:
sudo yum remove epel-release-latest-7.noarch.rpm

FYI: there is apparently epel-next:
https://www.linuxcapable.com/how-to-install-enable-epel-epel-next-repository-on-centos-9-stream/
UPDATE:
As others mentioned there is an updated official guide to repos on CentOS9:
https://docs.fedoraproject.org/en-US/epel/#_centos_stream_9
Comment: That guide is outdated and inaccurate.  You're better off following the official instructions.

https://docs.fedoraproject.org/en-US/epel/#_centos_stream_9


How do/did composers deal with very many contrapuntal voices?

Question: A work that I've admired as long as I've known about it is Antonio Caldara's Crucifixus for 16 voices. YouTube video here.
It does make me wonder how a composer like Caldara (or Thomas Tallis for that matter) went about composing for that many voices.
More specifically, I would like to know the following:

Did composers elaborate basic harmonic outlines which they had prepared beforehand, or did they make up the harmonies on-the-fly as the melodies came to mind?
How did they evaluate their voice-leading? I mean, in a composition for 16 (real) voices, there are 120 distinct voice pairs to evaluate. Would Caldara in a likely scenario evaluate all of them conscientiously, or did they trust on their intuition that they wrote correctly?
Which kinds of contrapuntal licenses are allowed in this type of composition? I already know that the rules regarding fifths and octaves by similar motion are considerably relaxed in a moderate number of voices (four or five, say), and that voice crossing is freely employed, even if it makes some melodies rather "leapy". But what about outright parallels between inner voices, or wrongly prepared dissonances?
Comment: I don't know enough to answer, but do you know Purcell's [Hear my prayer, O Lord]https://www.youtube.com/watch?v=FyieyUw3GXk)? I suspect that it was written by contrapuntally working an interesting chromatic melody (it e. g. contains both minor and major 3rd), throwing all caution to the wind, which results in lots of dissonances (that I personally love). (Curious to think that those "jazzy" chords were written in 1570!) So there could be wildly different approaches by different composers...
Comment: Yes, I know the work; another miracle of intricate voice-leading. I'd place the work closer to 1680, by the way. Thanks for your contribution anyway!
Comment: Oh, you're definitely correct.
Answer: There are two books which I would recommend for dealing with this voice-leading. It is best to approach the subject in order of the texts.
The first is a book which describes the actual methods and instruction of composers of the era, from a historical and theoretical point of view. There is much in the book for instructing oneself to write in the style. It is called "The Art of Partimento" by Sanguinetti, a contemporary theorist.
The second book, which can treat larger fugal forms, is called "The Study of Fugue" by Mann. It is a theoretical study and a classic book on counterpoint. It contains less practical instruction, and more classification, as compared with the first book.
Regarding your questions, I will try to answer.

Composers of the era utilized the partimento method of composing / notation. These partimentos were the equivalent of shorthand lead-sheets of today's musicians. They contained bass, melody, and a rough outline of the harmony, using numbers instead of assigning registers to the notes. The musicians of the time were well versed in the ways to ornament the music presented in the partimenti, and were able to improvise within the harmonies.
The voice leading can be looked at from the viewpoint of species counterpoint. Without explaining the different species, I'll give a brief overview of one way to build a 16 voice counterpoint.

Start with a partimento
For the harmonies outlined, designate some voices to sing long notes (whole, double whole, or half notes)
At this point, there should be at least 4 voices: bass, melody, and two harmonies.
Moving on, find opportunities for another two voices of quicker rhythm, to move between the harmonies without violating the basic rules. There are many tools to help with this: ornamentation (embellishments), stopping and starting at different places, increasing or decreasing the rhythm values.
Now, there should be at least 6 voices
If there is more rhythmic space available, continue with the above method up to 8 voices

Using the suggestions above can help to add detail to a counterpoint. There are other techniques detailed in "The Study of Fugue" which can quickly and accurately create counterpoint lines, when constructed within the constraints. These techniques are shown in the text as "Inversion at the Octave/10th/12th". These are shorthand methods for generating notes that follow the rules of counterpoint.

In the style of music of Caldara, as given in the example, the licenses may be limited to voice crossing and leaps, as well as stopping and starting lines when convenient. Ensemble register changes are also helpful.


Certificate problems with Apache LDAPS access


Undetermined Coefficients: $y''-2y'-3y=-3te^{-t}$

Question: I am trying to solve the following DFQ: $y''-2y'-3y=-3te^{-t}$.
I solved the homogeneous  equation to find that the general solution is $y(t)=c_1e^{3t}+c_2e^{-t}$, and therefore a good guess for the particular equation would be $Y_p(t)=Ate^{-t}$b because it is not proportional to $e^{3t}$ or $e^{-t}$. So, we get $Y_p'(t)=A e^{-t}-A e^{-t} t$ and $Y_p''(t)=A e^{-t} t-2 A e^{-t}$. But, when we plug $Y_p$ into $y''-2y'-3y=3te^{-t}$ we get:
\begin{align*}
Ate^{-t} -2Ae^{-t} +2Ate^{-t} -2Ae^{-t} -3Ate^{-t} &= -3te^{-t}\\
-4Ae^{-t} &= -3te^{-t}
\end{align*}
So, $Y_p$ turns out to be a bad guess.  Why is it that $Y_p$ turns out to be a bad guess? I thought that it met all of the criteria, unless I am missing something.
Comment: Try adding a $t^2 e^{-t}$ term in.
Answer: I think the general rule (if you look up Stewart or some other "standard" book) is you need a higher order term than what appears on the right hand side. So in your case we should try $$At^{2}e^{-t}+Bte^{-t}$$I hope this helps as I do not have time to do the computation.
Comment: @user32240 Thanks! I will do the computation here shortly. I was only concerned with the criteria anyways.
Comment: @user32240: You are welcome. Regards
Comment: @Amzoti You suggestion was wrong.
Comment: @Artem: $A = \frac{3}{8}, B = \frac{3}{16}$.
Comment: @Amzoti Ups, apologies.
Comment: No problem, you had me worried for a sec there!


Ubuntu - Nginx client cert authentication: is a public CA a security risk?

Question: I am struggling with a Nginx setup as reverse proxy with client certificate authentication. The client is only accepting publicly signed certificates to be imported as client certificates for authentication.
On the Nginx side I can setup the public available CA which was used to sign the client certificate (e.g. Let's encrypt) certificate with following settings (as suggested by many solutions):
<code>ssl_client_certificate  /etc/nginx/ssl/ca.cer;
ssl_verify_client on;
</code>
I am now questioning the security of this setup and wanted to know if:

Any client using a valid client certificate signed by the public CA can now connect to the Nginx server and authenticate?

If the above answer is yes, how can I only allow my client certificate to be successfully authenticated and forbid the others?
Do I need to specify my own CA (which will render this setup useless since the client side only allows public CA signed client certificates to be imported).

Thank you for your help.
Comment: No this is not a secure design. It also isn't the way most organizations handle certificate authentication. It's straightforward and expected that an organization would either have their own PKI and/or exercise the granularity to designate the root authorities that they trust, and remove authorities that they do not trust. The "publicly trusted" part of the requirements is unusual and probably naive. Also no organizations have only one factor of authentication, and it is a certificate not issued by them and not trusted by them for the purposes.
Comment: Letsencrypt doesn't even offer certificates for client authentication.
Answer: For client certificates you should use a private ca, but Amazon AWS also offers private CA's.
https://aws.amazon.com/private-ca/
For nginx to use client certificates authentication you need to use these directives
<code>    server {
        listen 443 ssl;
        server_name your_domain.com;

        ssl_certificate /path/to/server.crt;
        ssl_certificate_key /path/to/server.key;
        ssl_client_certificate /path/to/ca.crt;
        ssl_protocols TLSv1.2 TLSv1.3;
       ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305;  ssl_prefer_server_ciphers off;
    ssl_verify_client on;
    }
</code>
And you need to create a private ca and issue client certificates. In your Nginx configuration file, specify the paths to the server certificate, private key, and CA certificate (public part of your private CA). I also added some options to secure it


Kendo MVC not Displaying Sprites.PNG 404 Error

Question: Vs'12 Internet Application Template + KendoUI - MVC4 , EF Code First

Followed KendoDocumentation
Adjusted using kahanu's Awesome post
Everything worked great, so i turn <compilation debug="false" targetFramework="4.5"> from true to false
Kendo UI stopped finding Spites.png ( by Kendo )
Went looking and found this ( didn't resolve my issue ): stackOverflow1
Checked and Rechecked Steps 1-2, went looking for Sprites.png on the server, It exists.. but in some subolder of Kendo not in the directory below? /

Where do I re-write the code and have it look for the sprite in the actual location rather than this one?: GET http://cls-og.com/bundles/css/Default/sprite.png 404 (Not Found)
Comment: Please share your `bundles.Add(new StyleBundle("...").Include(...));` and `@Styles.Render("...")` codes to find out what is your problem.
Comment: Check out my answer for that post: [try this solution](http://stackoverflow.com/a/40156673/7018932)
Comment: Check out my answer for that post: [try this solution](http://stackoverflow.com/a/40156673/7018932)
Answer: I think your problem is in bundles, that's why it works great on debug (without bundles therefore) but not on release mode.
My advice is to put kendo styles folder on Content and create the bundle at the same place.
For example:
BundleTable.Bundles.Add(new StyleBundle("~/Content/kendo/kendo").Include(
            "~/Content/kendo/kendo.common.min.css",
            "~/Content/kendo/kendo.dataviz.min.css",
            "~/Content/kendo/kendo.default.min.css",
            "~/Content/kendo/kendo.dataviz.default.min.css"
        ));

Another tip: to avoid bundle problems in the future insert this in RegisterBundles method:
        BundleTable.EnableOptimizations = true;

That forces bundeling also in debug mode!
Hope this helps!
Have a nice day,
Alberto
Comment: Excellent, the key here is the "extra" "kendo" in the Bundle config : StyleBundle("~/Content/kendo/kendo")
Comment: btw.... I struggled for ages with this as I had just StyleBundle("~/Content/kendo") which conflicted somehow and caused a "403 Forbidden" rather than a 404, finally I spotted the extra "kendo" in this answer and voila! it works.  Thanks Alberto!
Comment: The EnableOptimizations is great - it helps with debugging. Thx!
Answer: I had the similar issue with sprite.png  and following is what did to resolve the issue.
This is how my bundling code looked like before I faced the issue.
bundles.Add(new StyleBundle("~/Kendo/css").Include(
                "~/Content/kendo/2016.2.504/kendo.common.min.css",
                "~/Content/kendo/2016.2.504/kendo.rtl.min.css",
                "~/Content/kendo/2016.2.504/kendo.default.min.css",
                "~/Content/kendo/2016.2.504/kendo.dataviz.min.css",
                "~/Content/kendo/2016.2.504/kendo.dataviz.default.min.css",
                "~/Content/jquery-ui.css"));

@Styles.Render("~/Kendo/css")

I referred to kahanu's blog and made following changes and it worked perfectly for me.
bundles.Add(new StyleBundle("~/Content/kendo/2016.2.504/kendostyles").Include(
                "~/Content/kendo/2016.2.504/kendo.common.min.css",
                "~/Content/kendo/2016.2.504/kendo.rtl.min.css",
                "~/Content/kendo/2016.2.504/kendo.default.min.css",
                "~/Content/kendo/2016.2.504/kendo.dataviz.min.css",
                "~/Content/kendo/2016.2.504/kendo.dataviz.default.min.css",
                "~/Content/jquery-ui.css"));

@Styles.Render("~/Content/kendo/2016.2.504/kendostyles")

Hope this will help others.


Why is this homomorphism an isomorphism?

Question: Let $R$ be a commutative ring with identity. Suppose $R=(r_1,\ldots,r_k)$. Take an homomorphism of $R$-modules: $f:M\rightarrow N$. Suppose that the function $\frac{f}{1}:M_{r_i}\rightarrow N_{r_i}$ is an isomorphism for every $i=1,\ldots,k$; how can I prove that then $f$ is an isomorphism?
$M_{r_i}$ denotes the localization of $M$ at the multiplicatively closed set $\{r_i^n:n\geq0\}$.
Comment: I take it that $(r_1,\dots,r_k)=R$ means they generate $R$ as a ring?
Comment: @AlexM I don't understand your notation for the ring $R$.....What do you mean by $R = (r_1, \ldots, r_k)$?
Comment: @AlexM Please explain your notation for $R$.
Comment: @AlexM  It is hard for people to help you if you don't explain the notation.
Comment: It means they generate $R$ as an ideal
Answer: First, a lemma.

Let $L$ be an $R$ module. $L = 0$ $\Leftrightarrow$ $L_{r_i} = 0$ for each $i$.

$\Rightarrow$. Clear.
$\Leftarrow$. Let $x \in L$. $x$ goes to zero in $L_{r_i}$ if and only if $r_i^{n_i}x = 0$ for some $n_i$. Now, if $(r_1, \ldots, r_k) = R$ then one can write $(r_1, \ldots, r_k)^N = R$ for any $N$. Do you see how to finish this off?
Now, $f\colon M \to N$ is injective if and only if $\ker f = 0$. In any case, we have an exact sequence
\[
0 \to \ker f \to M \to N
\]
and localization is flat. Now show that $(\ker f)_{r_i} \approx \ker f_{r_i}$. You can also write down an exact sequence that expresses surjectivity and make the same argument.
Comment: This is really close to being the proof that "being an (epi/mono/iso)morphism is local at the primes". You'll see $\{r_1, \ldots, r_k)$ called a "partition of unity", and for good reason!
Comment: Hi, I have a question. What do you mean by $(r_1, \ldots, r_k)^N$? So far I could only come up with "all N-fold products of elements in $(r_1, \ldots, r_k)$, but my interpretation doesn't make sense here.
Comment: @rschwieb Oh, sorry, just the $N$-th [ideal product](http://en.wikipedia.org/wiki/Ideal_(ring_theory)#Ideal_operations). I only wanted to say why the $\{r_i^{n_i}\}$ will still generate the unit ideal.
Comment: I've been having some trouble with what was meant: is it safe to say the OP meant that those $k$ elements generate $R$ as an ideal, and not as a ring? (I should do some problems of the OP's type... I have very poor intuition on the topic.)
Comment: @rschwieb I've only ever seen $(a, b, \ldots)$ to mean "the ideal generated by $a$, $b$, ...". If it is as a ring, then I don't have any ideas.
Comment: If this setup looks familiar to you, then that's probably what was meant. It just looks a little weird to me. For example you could put $(1,x)=R$ for any $x$ at all in $R$, and this would still be true? If so it amazes me a little :)
Comment: @rschwieb True, but this is a surprisingly practical condition: in the Zariski topology on $\operatorname{Spec} R$ this is the condition for the "distinguished opens" $R_{r_i}$ to cover the whole space, and these are a basis for the topology so there's usually no loss in assuming that your cover is of this form. This also shows that spectra are quasi-compact. So I think there's real content to the statement.
Comment: @DylanMoreland: that was exactly my idea too, but the problem that I had (and still have) is how can I deduce in the lemma that $x=0$ from the fact that $r_i^{n_i}x=0$ and $R=(r_1,\ldots,r_k)^N$ for any N. Could you explain it to me?
Comment: @AlexM By the bi/multinomial theorem or whatever you like, as well as the definition of an ideal, you'll show that $(r_1^{n_1}, \ldots, r_k^{n_k}) = R$. In particular, $1$ is a linear combination of these elements. An element is zero in $L$ if and only if it is annihilated by $1$.
Comment: @DylanMoreland: I'm sorry Dylan but I really cannot understand why $R=(r_1^{n_1},\ldots,r_k^{n_k})$. Can you write a little proof, please?
Comment: Let $N$ be the sum of all the $n_i$. If you have an expression for $1$ as a linear combination $\sum a_ir_i$ of the $r_i$, then raise that to the $N$-th power. Argue that in each term of the resulting sum,  some $r_i$ occurs to a power $\geq n_i$. This is sort of like proving that the nilpotent elements form an ideal.


Finding random point of specified order using MAGMA

Question: I would like to use MAGMA to construct a random point of specified order on an elliptic curve over a finite field. I have created the elliptic curve E0, but I'm not sure how to get the subgroup of points of a fixed order. There is a solution to this problem for general groups here in the answer by verret, but trying to follow that produces an error:
> p := 2^216 * 3^137 - 1;
> Fp2 := GF(p^2);
> E0 := EllipticCurveWithjInvariant(Fp2 ! 1728);
> AbE0 := TorsionSubgroup(E0);
> PremE0 := CosetAction(AbE0, sub<AbE0|>);
>> PremE0 := CosetAction(AbE0, sub<AbE0|>);
                        ^
Runtime error in 'CosetAction': Coset table not finite

I tried this code with a small "toy" example of an abelian group and it worked fine, so I'm wondering if the issue is that the size of AbE0 is just too large? AbE0 is finite, but (very) large.
Finally, is there a better way of doing this for elliptic curves? Even if I am able to turn the group of points on E0 into a permutation group and use the suggestions in the link to get the subgroup of order I'm interested in, then pick a random element, I will eventually want to use that element as a point on the curve, so I would need to translate back again. It seems there should be a better path...
Comment: Also, thank you so, so much for your help! I'm just starting to learn magma for research and there's no expert on it in my department, so this is really invaluable to me :)
Comment: Added the code for constructing `E0`!
Comment: How about `[P : P in AbE0 | Order(P) eq 12]`? (Or whatever order you want the point to have.) Or if you want the subgroup generated, `sub< AbE0 | S >` where `S` is the above sequence.
Comment: This is super helpful! I think in my case the group is just too large: I'm looking for the A-torsion subgroup where A = 2^216, so there should be 2^532 points. What I really need though is generators for the A-torsion subgroup. Is there a way I can get those without constructing the entire set of points of order A?
Comment: Can you include the actual definition of `E0` in your post? It's hard to give suggestions when I can't actually try them with your curve.
Answer: I don't think there's a built-in command to do this automatically in Magma, but it can be done using a few facts about elliptic curves and cyclic groups. Let $k = \mathbb{F}_{p^2}$. First, $E(k)$ is the direct sum of at most $2$ cyclic groups. (See here, for example.) For your curve, running
> [Factorization(Order(el)) : el in Generators(AbE0)];
[
[ <2, 216>, <3, 137> ],
[ <2, 216>, <3, 137> ]
]

we see that $\newcommand{\Z}{\mathbb{Z}} E(k) \cong \frac{\Z}{2^{216} 3^{137} \Z} \oplus \frac{\Z}{2^{216} 3^{137} \Z}$. Calling these generators $P_1$ and $P_2$, then $Q_1 := 3^{137} P_1$ and $Q_2 := 3^{137} P_2$ generate the subgroups of order $2^{216}$ in their respective factors. Thus, any point of order $2^{216}$ in $E(k)$ can be written as $m_1 Q_1 + m_2 Q_2$ where $\gcd(2, m_1, m_2) = 1$. So to generate a random point of order $2^{216}$, it suffices to pick random $m_1$ and $m_2$ with these properties.
Comment: This works, thanks again!


String.TrimStart does not trim spurious spaces

Question: Well, the title says it all. Reply, in this case, is outputting " This is a".
Is there a known bug with Trim?  My only thought here is that it is something to do with the fact that I am implementing fnms as a method, although I don't see a problem with that?
string nStr = " This is a test"

string fnms(string nStr)
{
    nStr.TrimStart(' ');  //doesn't trim the whitespace...
    nStr.TrimEnd(' ');
    string[] tokens = (nStr ?? "").Split(' ');
    string delim = "";
    string reply = null;
    for (int t = 0; t < tokens.Length - 1; t++)
    {
        reply += delim + tokens[t];
        delim = " ";
    }
    //reply.TrimStart(' ');        //It doesn't work here either, I tried.
    //reply.TrimEnd(' ');
    return reply;
}

Comment: You have to do nStr = nStr.TrimStart(), strings are immutable
Comment: Unrelated, but your `(nStr ?? "")` does not make sense. If `nStr == null`, `nStr.TrimStart(' ')` will throw a `NullReferenceException`,  so if you get to line three, you already know that `nStr` cannot be `null`.
Comment: @hvd Yes, you are correct. The only reason that it is formulated as such is because I have only just realised a need to implement it. However, prior to that I had the array creation as the first task in the method.
Comment: You can use `nStr = nStr.Trim();` to trim leading and trailing spaces at once.
Comment: @Sinatr I thought this would remove all whitespace altogether?
Comment: possible duplicate of [TrimEnd() not working](http://stackoverflow.com/questions/3521300/trimend-not-working)
Comment: @Wolfish, all **leading** and **trailing** [white-spaces](http://msdn.microsoft.com/en-us/library/system.char.iswhitespace.aspx). Won't delete anything in between, aka you will received `"This is a test"`.
Answer: TrimStart and TrimEnd, as well as every other method which acts to change a string return the changed string. They can never change the string in place due to string being immutable.
nStr = nStr.TrimStart(' ').TrimEnd(' ');

You can simplify this by just calling Trim which trims the start and end of the string
nStr = nStr.Trim();

Answer: You need to update nStr to the returned sting from TrimStart, and then do the same for TrimEnd.
        nStr = nStr.TrimStart(' ');
        nStr = nStr.TrimEnd(' ');
        var tokens = (nStr ?? "").Split(' ');
        var delim = "";
        string reply = null;
        for (int t = 0; t < tokens.Length - 1; t++)
        {
            reply += delim + tokens[t];
            delim = " ";
        }
        //reply.TrimStart(' ');        //It doesn't work here either, I tried.
        //reply.TrimEnd(' ');
        return reply;


Fields with an overlap between logic and algebra?

Question: I was curious if there is any field of study that uses both logic and algebra. To clarify, logic and analysis overlap in areas like descriptive set theory, and there are a lot of logic ideas in areas like topology. But I can't seem to think of any analogous relationships between logic and algebra. I'd appreciate any insight. Thanks
Comment: Universal Algebra is certainly such an overlap
Comment: Model theory of fields is a 'large' active area of research in model theory.
Comment: Its not necessarily what you are asking; but Boolean Algebra follows the syntax of both.
Comment: If you want to get a little more specific you can check out o-minimality theory https://en.wikipedia.org/wiki/O-minimal_theory
Comment: Generalizing from Boolean Algebra are [Lindenbaum algebras](https://en.wikipedia.org/wiki/Lindenbaum%E2%80%93Tarski_algebra).  You can also indirectly use the relationships between topology and algebra to establish relationships between logic and algebra. At a much more advanced level, there's topos theory which links topology and algebraic geometry with logic and set theory as covered in [Sheaves in Geometry and Logic](http://www.springer.com/us/book/9780387977102) and many other places.
Answer: One such a field is the theory of automata and regular languages.
I just state here a few results, with links to wikipedia for the definitions, to convince you that algebra and logic really help proving deep theorems in automata theory. There are many more, but unfortunately, most of these research level results are not treated in basic books on automata theory.
Algebra.
Thm 1 (consequence of Kleene 1956). A language is regular if and only if its syntactic monoid is finite.
Thm 2 (Schützenberger 1965). A language is star-free if and only if its syntactic monoid is finite and aperiodic.
Logic
Thm 3 (Büchi 1960). A language is regular if and only if its definable in monadic second order.
Thm 4 (McNaughton 1971). A language is star-free if and only if it is first order definable.
Thm 5 (Kamp 1968). A language is star-free if and only if it is definable in linear temporal logic.
I would also recommend to read the French entries on Wikipedia for
Langage rationnel,
Monoïde syntaxique,
Langage sans étoile,
Logique monadique du second ordre,
that are, for some reason, for detailed than their respective English versions.


What kind of information does PCA preserve?

Question: I was reading up on Non-linear dimensionality reduction. On the Wikipedia article it says that PCA does not preserve the intrinsic geometry of the data. What kind of information is it preserving?
It is interesting, because we are currently working on a problem dealing with supervised learning on images. We don't know what model best suits it, yet. If applying PCA doesn't take into consideration the intrinsic geometry, then is it worthwhile to apply PCA to the data before passing it to a classifier? For instance, the images contain overlapping objects that might be crucial to the classifier. But an argument could be made that we can use PCA to find a basis that has lower noise (in the sense that we may believe that noise correlates with large patches of pixels).
Answer: PCA forms linear combinations of the variables that preserve as much of the variance as possible, subject to orthogonality.
That is, the first PC preserves as much of the variance as possible.  The second preserves as much as possible, given that it is orthogonal (uncorrelated) with the first.  The third has to be orthogonal to both of the first two. And so on.
Comment: I think knew about the variance part. It is said in the link, that NLDR can represent intrinsic variables like "scale" and "rotation" (for their example with the letter A). I guess my question is that how exactly I can think of the variables I get? Can it still be stuff like "rotation" and "scale" as long as they are linearly varying? Are "rotation" and "scale" linear? How can I find out what kind of variables PCA or NLDR is capturing?
Comment: Eg., in the case I provided in my question, can "overlap" be a variable being captured?
Comment: The variables that you get out of PCA are linear combinations of the variables that went into it.  So, it would be something like "scale * 0.4 + rotation *0.3" and so on.
Comment: Ahh, thanks!, I guess my final question would be to ask if we can somehow determine if the variables vary non-linearly or linearly.
Comment: That doesn't make sense.  "Linear" is an adjective that applies to relationships, not variables.
Comment: I'm sorry for phrasing it poorly. I meant how can we determine a variable in in a non-linear relation.


Why is this vanilla 64-bit Ubuntu Server 10.10 eating 446200k of memory?

Question: Just installed 64-bit Ubuntu Server 10.10 inside as guest in a virtual machine. I'm using VMware Player. The host is 64-bit Windows 7.
The minimum requirements for the Ubuntu server is said to be 128MB RAM. https://help.ubuntu.com/community/Installation/SystemRequirements
So right after the install, I ran top command and to my surprise it said:
Tasks: 63 total, 1 running, 62 sleeping, 0 stopped, 0 zombie
Mem: 504088k total, 446192k used, 57896k free, 30548k buffers

From what I've read, modern Linux systems buffer memory for performance reasons. But here, only ~30.5MB is used for buffers.
I sorted based on %MEM and there's nothing that stands out (biggest hogger is at 1.3%). Is it because of the virtualization that the memory is some how pre-allocated and thus shown in the used field?
EDIT:
free -m
          total      used      free     shared     buffers     cached
Mem:        492       435        56          0          29        338
-/+ buffers/cache:     67       424
Swap:       563         0       563

Comment: What does free -m say?
Answer: From your free output, you're only using 67MB.  The rest is used for buffers (29M) and filesystem cache (338MB).
Answer: Check out this page - it'll give you a better understanding of what's most likely going on:
Linux Ate My RAM!
Comment: Very concise link.. exactly to the point. I gave you an upvote, but will accept Cakemox's answer. Thanks!


Stirling numbers of the second kind: a recurrence relation.

Question: This is Exercise 1.9.15 of Howie's "Fundamentals of Semigroup Theory".

Let $X$ be a finite set with $n$ elements and let $S(n, r)$ (for $0\le r\le n$) be the number of equivalences $\rho$ on $X$ such that $\lvert X/\rho\rvert=r$. Show that
  $$S(n, 1)=S(n, n)=1\tag{1}$$ and
  $$S(n, r)=S(n-1, r-1)+rS(n-1, r)\tag{2}$$ for $(2\le r\le n-1)$.

My Attempt:
Let $\mathcal{E}_X$ be the set of equivalences on $X$.
For $(1)$, we have that
$$\begin{align}
S(n, 1)&=\lvert\{\rho\in \mathcal{E}_X : \lvert X/\rho\rvert=1\}\rvert \\
&\stackrel{(?)}{=}\lvert\{X\times X\}\rvert \\
&=1
\end{align}$$ and
$$\begin{align}
S(n, n)&=\lvert\{\rho\in \mathcal{E}_X : \lvert X/\rho\rvert=n\}\rvert \\
&\stackrel{(?)}{=}\lvert\{\operatorname{id}_X\}\rvert \\
&=1.
\end{align}$$

I'm stuck showing $(2)$.
Thoughts:
I suppose showing $(2)$ is a matter of induction on $n$ but I don't know where to start.
Please help :)
Comment: It maybe helpful to think of an equivalence on $ X $ as a partition of $ X $. You can make a partition of $ X $ into $ r $ subsets as follows: Fix an element $ x $ of $ X $. Then either partition the other $ n- 1 $ into $ r-1 $ subsets and put $ x $ into his own subset, or, partition the other $ n-1 $ into $ r $ subsets and put $ x $ into one of those $ r $ subsets. These are the two terms in the recursion relation.
Comment: @user81327 That should be an answer.
Comment: @user81327 I can see how that's a comment if you'll give an answer with more detail.
Answer: From the comments:

It maybe helpful to think of an equivalence on $ X $ as a partition of $ X $. You can make a partition of $ X $ into $ r $ subsets as follows: Fix an element $ x $ of $ X $. Then either partition the other $ n- 1 $ into $ r-1 $ subsets and put $ x $ into his own subset, or, partition the other $ n-1 $ into $ r $ subsets and put $ x $ into one of those $ r $ subsets. These are the two terms in the recursion relation.
Comment: Thank you :) I left it as a comment because I didn't want to give a full answer; I figured you'd fill in the details with the hint.
Comment: @user81327 Here :)


Can I sort a view by a custom date field without the date module?

Question: I would like to organize products in my site by year of production.
And sort them in a view. With the date(year) as exposed filter, in this format:
<code>Products :
From  year :…
to year:….
</code>
Can I do this only by creating a CCK text field with a list of years?
Or should I use the date module instead?
If I have to use this module , How can I change the format in which the date is input. By default, it shows years ,months and days. I want it to show only years.
Answer: Using date field gives you more flexibility, but year made with text field would work also.
But in my opinion after your site grow larger you will probably say to yourself: "Gosh, now I wish to order with moths and days..." and you'll regret not using date field at the beginning.
Comment: Thank you, any idea how to change the format in date module input , to show only years?
Can I do this, just by using (Y) as Custom input format?
Comment: What views version?
Comment: Views version: 6.x-2.16
Comment: Yes, EXACTLY what I'm looking for.
Answer: With D6 and views 2.16 (the integer text way approach) is as follows:
Your content type need to have Integer CCK field (year_int).
In your Views create node view, place some field (i.e. title) and add Filter>Content>year_int exposed grater or equal. After add another time Filter>Content>year_int exposed less or equal. Configure the rest as You need and its done.
Notice: you must type years into the filter, there is no select widget available, when field type is text.
Warning! If your type where year is stored is just text (not decimal), filter in views doesn't have less or greater option.
Answer: With D6 and views 2.16 and date 2.8 (the suggested date way approach) is as follows:
You have to have date field in your content with granularity year (field_date). You can choose list to provide year list when updating/creating product with some range.
In your Views create node view, place some field (i.e. title) and add Filter>Content>field_date exposed grater or equal. After add another time Filter>Content>field_date exposed less or equal. Configure the rest as You need and its done.
Date approach is more flexible and scalable in my opinion and gives more widgets when adding, editing and exposing in views filter. It's just smarter.


Machine Learning text comparison model

Question: I am creating a machine learning model that essentially returns the correctness of one text to another.
For example; "the cat and a dog", "a dog and the cat". The model needs to be able to identify that some words ("cat"/"dog") are more important/significant than others ("a"/"the"). I am not interested in conjunction words etc. I would like to be able to tell the model which words are the most "significant" and have it determine how correct text 1 is to text 2, with the "significant" words bearing more weight than others.
It also needs to be able to recognise that phrases don't necessarily have to be in the same order. The two above sentences should be an extremely high match.
What is the basic algorithm I should use to go about this? Is there an alternative to just creating a dataset with thousands of example texts and a score of correctness?
I am only after a broad overview/flowchart/process/algorithm.
Answer: I think TF-IDF might be a good fit to your problem, because:

Emphasis on words occurring in many documents (say, 90% of your sentences/documents contain the conjuction word 'and') is much smaller, essentially giving more weight to the more document specific phrasing (this is the IDF part).
Ordering in Term Frequency (TF) does not matter, as opposed to methods using sliding windows etc.
It is very lightweight when compared to representation oriented methods like the one mentioned above.

Big drawback: Your data, depending on the size of corpus, may have too many dimensions (the same number of dimensions as unique words), you could use stemming/lemmatization in order to mitigate this problem to some degree.
You may calculate similiarity between two TF-IDF vector using cosine similiarity for example.
EDIT: Woops, this question is 8 months old, sorry for the bump, maybe it will be of use to someone else though.
Comment: No problem! I eventually realised that text comparison was insufficient for my task. Thanks for the comprehensive answer tho

Machine Learning text comparison model


Show algebraically that every pair of distinct points of $\Bbb H$ lies on a unique $\Bbb H$-line.

Question: Let $\Bbb H$ = {$z=x+iy \in \Bbb C | y>0$}. Define $\Bbb H$ lines to be of two kinds, or $L_1$={$x+iy \in \Bbb H |x=c$} or $L_2$= {$x+iy \in \Bbb H | (x-a)^2+y^2=c^2$} with the centre $(a,0)$  on the real axis {$y=0$}.
Show algebraiclly that every pair of distinct points of $\Bbb H$ lies on a unique $\Bbb H$-line.
I can see why this is true, but I'm stuck at proving this algebraically.
Comment: Hint. If the two points have different real parts you can find a point on the real axis equidistant from each. (Just do the algebra.)
Comment: @EthanBolker: That only proves the existence of such a line. The subtler point of the problem is to prove its uniqueness.
Comment: @AlexM.The uniqueness is easier than the existence, suggesting an easier construction: the perpendicular bisector of the line joining the points has a unique intersection with the real axis.
Answer: Suppose that $(x_1,y_1)$ and $(x_2,y_2)$ are two points. If $x_1=x_2$ then there is a unique line of $L_1$ through these points, otherwise there are no lines of type $L_1$.
If a line $(x-a)^2+y^2=c^2$ passes through our points, then for $a$ and $c$ we get the equations
$$(x_1-a)^2+y_1^2=c^2,$$ $$(x_2-a)^2+y_2^2=c^2.$$ It means that $$(x_1-a)^2+y_1^2=(x_2-a)^2+y_2^2,$$ $$x_1^2-2ax_1+a^2+y_1^2=x_2^2-2ax_2+a^2+y_2^2,$$ $$2a(x_2-x_1)=x_2^2-x_1^2+y_2^2-y_1^2.$$ If $x_1=x_2$, then we get $y_2=y_1$, which contradicts that our points are different. Thus in this case we get no lines of type $L_2$ and the line of type $L_1$ through these points is unique.
Otherwise this equation has a unique solution for $a$: $$a=\frac{x_2+x_1}{2}+\frac{y_2^2-y_1^2}{2(x_2-x_1)}.$$ And substituting this $a$ we get the unique $c^2$ - thus, by $c>0$, the unique $c$ - from any of our equations. This means that there is a unique line from $L_2$ (and as we seen, no lines from $L_1$) through our points in this case.


iOS : How to observe the result of "respondToRequest:withResult" in CoreBluetooth

Question: I have been using CoreBlueTooth framework to communicate between BTLE iOS devices.On the Peripheral side, I received a writing request from Central:
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests{
            ...
}

According to Apple's doc on CoreBluetooth, I answered with:
[self.peripheralManager respondToRequest:request  withResult:CBATTErrorSuccess];

However, this method does not have a return value or delegate methods to indicate the result.
Am I missing something?
Answer: respondToRequest:withResult: method is assumed to always successful. You must observe it on Central side at HCI level (probably using hcidump command or btmon if you use linux).
Comment: It is definitely possible that the response is lost due to buffer cap in the Core Bluetooth stack or similar. A recent SO question revealed this issue. When it happens, it causes the connection to be automatically broken in 30 seconds. An indicator for such event is when the `updateValue:ForCharacteristic` returns false.
Comment: @allprog and if it lost, what what happen next?
Comment: @gaussblurinc I'm not sure I get your question. I think I described the "when lost" case in my comment. Can you elaborate a little?
Comment: @allprog sure, you said: "response is lost due to buffer cap in CB stack or similar." and "updateValue:ForCharacteristic returns false".it returns false only if peripheral update its value, not central write to peripheral. could this case causes ( sometimes ) nil CBAttrRequest in didReceive methods?
Comment: @gaussblurinc I haven't seen this but if you can reliably reproduce this event, then probably this is what happens. Unfortunately, I can't confirm or disprove. If you think it's a bug, you should file a RDAR and it would be great if you shared it on the bluetooth-dev mailing list too.
Answer: Please have a look on the documentation provided by Apple about Bluetooth feature
Apple's Bluetooth DOC


Python CSV, Combining multiple columns into one column using CSV

Question: I've been trying to figure out a way to combine all the columns in a csv I have into one columns.
import csv
with open('test.csv') as f:
    reader = csv.reader(f)
    with open('output.csv', 'w') as g:
        writer = csv.writer(g)
        for row in reader:
            new_row = [' '.join([row[0], row[1]])] + row[2:]
            writer.writerow(new_row)

This worked to combine the first two columns, but I've been having trouble trying to loop it and get the rest of the columns into just one.
Answer: You should just pass row to .join because it's an array.
import csv
with open('test.csv') as f:
    reader = csv.reader(f)
    with open('output.csv', 'w') as g:
        writer = csv.writer(g)
        for row in reader:
            new_row = [' '.join(row)] # <---- CHANGED HERE
            writer.writerow(new_row)


Writing streamed files into zip stream in java

Question: I want to write multiple CSVs generated from different tables to a zip file without having a read/write operation required to store the generated CSV files or the generated zip files to a memory.
This zip I need to send as an output stream to a response. Is this possible to do in Java? If yes, then how? I am using OpenCSV library to generate CSVs.
Comment: is your application a servlet?
Comment: Please post some code of your application ([mcve])
Answer:
create a GZIPOutputStream
loop over your csv data units:

open an InputStream for the csv data unit
read it, write it to GZIPOutputStream
close InputStream

close GZIPOutputStream

If you are working with a servlet, you can wrap ServletOutputStream with GZIPOutputStream. If you like, I can give you more information on that.
Comment: Is this approach possible if the csv file is also generated on the fly? I am not reading the file from memory. Do you think that its possible? Because I think your solution assumes the CSV files to be read from memory.
Comment: yes I'mvery sure it's possible. By now, I'm not very familar with JAX-RS (but I have to learn it in a few days:-) ). I think it's possible to obtain an `OutputStream` (something derived) and combine it with `GZIPOutputStream`
Comment: I was struggling to generate `OutputStream` from `OpenCSV` api. If you know how to go about with that part, it would be helpful.


Número "aleatório" sendo gerado junto com hash do md5

Question: Estou desenvolvendo uma aplicação em laravel e em determinado momento eu preciso gerar um valor em MD5 para atribuir a um campo no banco de dados.
O problema, é que ao gerar esse hash de MD5, está surgindo um "número aleatório" e está entrando na variável, ao invés de entrar na variável o hash criado. Veja:
 if($this->emptyField === 0)
 {

     //Criando um id do lote
     $fileId = md5(time() . rand(0, 9999) . time());
     print_r($fileId);
 }

Veja o que é gerado:

Se repararem ali, são gerados 4 números (9634) junto com o hash MD5. Quando entra no banco de dados, só entra esses 4 números na coluna.
As vezes acontece de só gerar o hash MD5 mesmo.
O campo no banco é do tipo varchar(100). E o banco é MySQL.
Poderiam me ajudar ?
Segue o link do código completo, caso queiram consultar.
https://paste.laravel.io/2d6d0c04-82db-476b-b1e6-b37b5f792e68
Comment: Como a conversa se estendeu foi [movida para o chat](https://chat.stackexchange.com/rooms/116917/discussion-on-question-by-gato-de-schrodinger-numero-aleatorio-sendo-gerado-ju) e pode prosseguir por lá, quem tiver interesse em ler e/ou participar, pode clicar no link. Sobre o fechamento, como o que foi apresentado se trata de comportamento esperado, nada a ser feito no escopo do site. Nestes casos, precisa fornecer um [mcve] de um problema real, e que não dependa de links externos. Na ausência destas possibilidades, a pergunta não deve ser feita neste site.
Answer: Prezado,
O hash gerado pelo md5 contêm 32 caracteres,
sua saída no pewview está correta, não há nada de errado.
para conferir, verifique o rand em uma variável separada, depois junte-a com os time() em uma string separada, imprima ambas antes de gerar o md5, gere o md5 e então gere novamente com as saídas anteriores em um site que forneça md5 para fins de conferência, e verás que está tudo correto. Dessa forma:
//Criando um id do lote
       $father = rand(0, 9999);
       print_r($father);
       echo "
";
       $pre_print = (time() . $father . time());
       print_r($pre_print);
       echo "
";
       $fileId = md5($pre_print);
       print_r($fileId);

Podes contar os caracteres em: https://www.quantasletras.com/
E gerar o md5 em: https://www.md5hashgenerator.com/
Comment: Segui a dica do hkotsubo e parei pra analisar o código  usando  a premissa desse seu código ai. Realmente aqueles números fazem parte do hash. Eu dei mole mesmo. Obrigado!
Comment: "Esse problema não pode ser reproduzido, ou é um erro de digitação. Mesmo dentro do escopo do site, sua solução dificilmente seria útil a outros usuários no futuro." Esse é o argumento que deram pra fechar a pergunta. Beleza. Mas dois usuário conseguiram reproduzir o código que postei e tiveram resultados (não importando se positivos ou negativos). E outra coisa, o que garante que uma pessoa não pode estar passando pelo mesmo problema que eu ? Na verdade essa pergunta foi boa, pois, em todo o site, não tem uma outra demonstrando um problema similar (o que é difícil de acontecer).
Comment: ... Uma pessoa, que estiver passando por um problema como o meu pode olhar a resposta do Hkotsubo e essa resposta aqui, e talvez ter a solução para a sua possível dúvida. A pergunta foi "positivada" duas vezes e marcada como "favorita" por uma pessoa. Quer dizer que pra alguém ela pode ter sido útil.