text:
Q: Can't start ruby from osx yosemite terminal, before and after rbenv, homebrew works though Every time I type ruby and hit Enter at my terminal, it just hangs for seemingly forever. This is happening for the default Yosemite install and after I installed with rbenv, using Homebrew (which works fine), using "Ruby on Rails development setup for Mac OSX".
My current Ruby version is 2.2.2, ruby -v works, and I didn't have this problem when I was using OS X Mavericks.
Has anyone else had this problem and/or found a solution? My google-fu doesn't seem to be strong enough.

A: When you enter ruby at the command-line, it's supposed to "hang forever". It's waiting for you to give it instructions. You can use CTRL+D to get it to stop waiting:
> ruby
puts 1 + 1
2

I then did CTRL+D and returned to the command-line prompt.
Instead though, we don't use Ruby like that. If we want to use it interactively, we use IRb which comes with Ruby. It's the "interactive" Ruby:
> irb
Welcome to IRB. You are using ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin13]. Have fun ;)
>> 1 + 1
2
>> 'foo'.squeeze('o')
"fo"

If we want to run a Ruby script, we use something like:
ruby /path/to/script

and Ruby will load and run it.
I'd recommend reading some Ruby tutorials and learn how the language works before trying to use Rails. Rails uses deep Ruby magic and how Rails works will be unfathomable to you until you do understand better how Ruby is used and how it works and what it can do.
If you're using rbenv to manage your Ruby, then when you enter rbenv versions you should see the Rubies it manages listed:
rbenv versions
  system
  1.9.3-p551
* 2.2.2 (set by /Users/tinman/.rbenv/version)

If you don't, either rbenv isn't in control of Ruby, or you haven't installed any using rbenv. rbenv global system will tell it to use whatever you have installed by default in the system, based on your PATH.
rbenv's documentation and built-in help go over this so if the problems continue then you need to closely examine your install and setup, because 90% of the problems we see using a sandboxed Ruby are due to people not paying attention to the directions, or using the wrong ones, and not completing the installation.


text:
Q: Clicking a button added by JavaScript clicks through it as well I'm working on a script that adds a button that floats on top of a Facebook user's profile photo thumbnail.
Here's a screenshot:

This button, when clicked, returns the Facebook ID of the profile that is being viewed in a prompt. That part works fine (but you'd need to be logged in and looking at a profile besides yours, otherwise there'd be a missing element).
Screenshot:

What's bothering me though, is after clicking the button, and pressing Cancel or Okay in the prompt, the click actually goes through the button and clicks the profile picture thumbnail itself. A single click is clicking both items!
Is there any way we can make it so that the area below the button itself is not clickable? But the rest of the profile picture is?
I've tried searching on this topic but couldn't find much results. Even if I try to search for something like "Add padding below/under button JavaScript", I'm getting padding around the button, and not directly below it
in a z-axis point of view.
Here's the script code, you can copy paste it in the console directly. That is, if you have a Facebook account and are logged in. Also this only works on profiles besides yours (otherwise data-profileid would be missing).
// Create the button
var btn = document.createElement("BUTTON");
var t = document.createTextNode("FBID");    // To replace with icon
btn.appendChild(t);

// Add a listener
btn.addEventListener("click", getFBID);

// Styling (positioning)
btn.style.display="block";
btn.style.position="absolute";
btn.style.top="4px";
btn.style.right="4px";

// Function to get Facebook ID
function getFBID() {
    prompt("Copy it:", document.querySelectorAll("[data-profileid]")[0].getAttribute("data-profileid"));
}

// Append button to profile picture
document.getElementsByClassName("profilePicThumb")[0].appendChild(btn);

Oh yeah, I feel the reason why this is happening is because I am appending to an anchor link. Just in case this info would be useful.
Any help appreciated, thank you!

A: Try this
// Create the button
var btn = document.createElement("BUTTON");
var t = document.createTextNode("FBID");    // To replace with icon
btn.appendChild(t);

// Add a listener
btn.addEventListener("click", getFBID);

// Styling (positioning)
btn.style.display="block";
btn.style.position="absolute";
btn.style.top="4px";
btn.style.right="4px";

// Function to get Facebook ID
function getFBID() {
    prompt("Copy it:", document.querySelectorAll("[data-profileid]")[0].getAttribute("data-profileid"));
    return false;                   // Try returning false here..
}

// Append button to profile picture
document.getElementsByClassName("profilePicThumb")[0].appendChild(btn);

getFBID in this case is a callback for the event that is raised on the click of the button. returning false will make sure that the event is not propagated to its parent and hence will not raise the parent's event or call the eventhandler.

A: Try to prevent the default actions for the click like this:
btn.addEventListener("click", function(event){
  event.preventDefault();
  event.stopPropagation();
  getFBID();
  return false;
});

EDIT: use event.stopPropagation();
(compare to this thread How to stop event bubbling on checkbox click)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ansible synchronize (rsync) fails ansible.posix.synchronize, a wrapper for rsync, is failing with message
"msg": "Warning: Permanently added <host> (ECDSA) to the list of known hosts.\r\n=========================================================================\nUse of this computer system is for authorized and management approved use\nonly. All usage is subject to monitoring. Unauthorized use is strictly\nprohibited and subject to prosecution and/or corrective action up to and\nincluding termination of employment.\n=========================================================================\nrsync error: received SIGINT, SIGTERM, or SIGHUP (code 20) at rsync.c(644) [sender=3.1.3]\n"

My playbook
---
- name: Test rsync
  hosts: all
  become: yes
  become_user: postgres

  tasks:
    - name: Populate scripts/common using copy
      copy:
        src: common/
        dest: /home/postgres/scripts/common

    - name: Populate scripts/common using rsync
      ansible.posix.synchronize:
        src: common/
        dest: /home/postgres/scripts/common

Populate scripts/common using copy executes with no problem.
Full error output
fatal: [<host>]: FAILED! => {
    "changed": false,
    "cmd": "sshpass -d3 /usr/bin/rsync --delay-updates -F --compress --archive --rsh='/usr/bin/ssh -S none -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' --rsync-path='sudo -u postgres rsync' --out-format='<<CHANGED>>%i %n%L' /opt/common/ pg_deployment@<host>t:/home/postgres/scripts/common",
    "invocation": {
        "module_args": {
            "_local_rsync_password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
            "_local_rsync_path": "rsync",
            "_substitute_controller": false,
            "archive": true,
            "checksum": false,
            "compress": true,
            "copy_links": false,
            "delay_updates": true,
            "delete": false,
            "dest": "pg_deployment@<host>:/home/postgres/scripts/common",
            "dest_port": null,
            "dirs": false,
            "existing_only": false,
            "group": null,
            "link_dest": null,
            "links": null,
            "mode": "push",
            "owner": null,
            "partial": false,
            "perms": null,
            "private_key": null,
            "recursive": null,
            "rsync_opts": [],
            "rsync_path": "sudo -u postgres rsync",
            "rsync_timeout": 0,
            "set_remote_user": true,
            "src": "/opt/common/",
            "ssh_args": null,
            "ssh_connection_multiplexing": false,
            "times": null,
            "verify_host": false
        }
    },
    "msg": "Warning: Permanently added '<host>' (ECDSA) to the list of known hosts.\r\n=========================================================================\nUse of this computer system is for authorized and management approved use\nonly. All usage is subject to monitoring. Unauthorized use is strictly\nprohibited and subject to prosecution and/or corrective action up to and\nincluding termination of employment.\n=========================================================================\nrsync error: received SIGINT, SIGTERM, or SIGHUP (code 20) at rsync.c(644) [sender=3.1.3]\n",
    "rc": 5
}

Notes:
User pg_deployment has passwordless sudo to postgres. This ansible playbook is being run inside a docker container.
After messing with it a bit more, I found that I can directly run the rsync command (not using ansible)
SSHPASS=<my_ssh_pass> sshpass -e /usr/bin/rsync --delay-updates -F --compress --archive --rsh='/usr/bin/ssh -S none -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' --rsync-path='sudo -u postgres rsync' --out-format='<<CHANGED>>%i %n%L' common pg_deployment@<host>:/home/postgres/

The only difference I can see is I used sshpass -e while ansible defaulted to sshpass -d#. Could the credentials ansible was trying to pass in be incorrect? If they are incorrect for ansible.posix.synchronize then why aren't they incorrect for other ansible tasks?
EDIT
Confirmed that if I run
sshpass -d10 /usr/bin/rsync --delay-updates -F --compress --archive --rsh='/usr/bin/ssh -S none -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' --rsync-path='sudo -u postgres rsync' --out-format='<<CHANGED>>%i %n%L' common pg_deployment@<host>:/home/postgres

(I chose random number for the file descriptor d10) I get the same error as above
"msg": "Warning: Permanently added <host> (ECDSA) to the list of known hosts.\r\n=========================================================================\nUse of this computer system is for authorized and management approved use\nonly. All usage is subject to monitoring. Unauthorized use is strictly\nprohibited and subject to prosecution and/or corrective action up to and\nincluding termination of employment.\n=========================================================================\nrsync error: received SIGINT, SIGTERM, or SIGHUP (code 20) at rsync.c(644) [sender=3.1.3]\n"

Suggesting that the problem is whatever ansible is using as the file descriptor? It isn't a huge problem since I can just pass in the sshpass as an env variable in my docker container since it's ephemeral, but I still would like to know what is going on with ansible here.
SOLUTION (using command)
---
- name: Create Postgres Cluster
  hosts: all
  become: yes
  become_user: postgres

  tasks:
    - name: Create Scripts Directory
      file:
        path: /home/postgres/scripts
        state: directory

    - name: Populate scripts/common
      command: sshpass -e /usr/bin/rsync --delay-updates -F --compress --archive --rsh='/usr/bin/ssh -S none -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' --rsync-path='sudo -u postgres rsync' --out-format='<<CHANGED>>%i %n%L' common pg_deployment@<host>:/home/postgres/scripts
      delegate_to: 127.0.0.1
      become: no


text:
Q: SQL all rows with a minimum interval between I have a table with only two fields (in SQLite3, but I can use PostgreSQL or SQLServer), that have a datetime and a int value (temperature of a room), like below:
+-----------------------------------+
| Table: Temperature                |
+---------------------+-------------+
| Date                | Temperature |
+---------------------+-------------+
| 2017-03-03 15:10:00 |          25 |
| 2017-03-03 15:11:00 |          25 |
| 2017-03-03 15:12:00 |          25 |
| 2017-03-03 15:13:00 |          25 |
| 2017-03-03 15:14:00 |          26 |
| 2017-03-03 15:15:00 |          26 |
| 2017-03-03 15:16:00 |          26 |
| 2017-03-03 15:17:00 |          26 |
| 2017-03-03 15:18:00 |          26 |
| 2017-03-03 15:19:00 |          27 |
| 2017-03-03 15:20:00 |          27 |
+---------------------+-------------+

Like in the example, I have a temperature at every minute.
This is used to monitor the temperature for other systems, but I like to show this in a web page too, using python (flask), but in the web page it's not important to show the temperature at every minute, but at every 10 minutes or at every hour is better.
How to make a select to show only temperatures at every 10 minutes (or another interval)? So my results must be:
+-----------------------------------+
| Table: Temperature                |
+---------------------+-------------+
| Date                | Temperature |
+---------------------+-------------+
| 2017-03-03 15:10:00 |          25 |
| 2017-03-03 15:20:00 |          27 |
+---------------------+-------------+

A: For sql-server you could do something like this:
select *
from temperature
where datepart(minute,[date])%10 = 0

for postgres you could use something like this:
select *
from temperature
where cast(date_part('minute',date) as int) % 10 = 0;

both return:
+---------------------+-------------+
|        date         | temperature |
+---------------------+-------------+
| 2017-03-03 15:10:00 |          25 |
| 2017-03-03 15:20:00 |          27 |
+---------------------+-------------+

sql server rextester demo: http://rextester.com/DXMCK81428
postgres rextester demo: http://rextester.com/NAXX57760

A: SELECT * FROM table LIMIT -1 OFFSET 10

From this post

A: select * from temperature where substr(date,16,1)='0' order by date

An improvement could be to return the average temperature in each ten minute period. This would also make it more robust against missing meassurements:
select
  'From '||min(date)||' to '||max(date)  period,
  sum(1)                                 meassurements,
  avg(temp)                              avg_temp
from temperature
group by substr(date,1,15)
order by 1

Replace 15 with 14 to show for hour periods instead.
The next step could be to also show periods that miss meassurements altogether. This is also possible to do with just one query. I don't show that here.


text:
Q: Daemon Apps and Scopes So, I am trying to do see if I can support a scenario where a C# daemon app can access a custom Web API protected with MSAL.NET and OAuth2 scopes. As of now, I see no way of doing this.
The versions of the libraries and toolsets are:
.NET Core 2.2
Microsoft.Identity.Client 4.1.0
The client is
var app = ConfidentialClientApplicationBuilder.Create("<client app id>")
                .WithClientSecret("<client_secret>")
                .WithAuthority("https://login.microsoftonline.com/<tenant_id_that_hosts_the_web_api>")
                .Build();

and then to acquire token
await app.AcquireTokenForClient(new string[] { "api://<app_id_of_the_web_api>/.default" });

At this point, I do get the token back with which I call my custom Web API end point protected using MSAL and an Azure App with the above mentioned App ID. This doesn't work since I have a policy based authorization on the end point, expecting a specific custom scope defined in the Azure AD app.
The question is, how do I configure the client and Azure AD so I will get the specific scopes passed in as claims for the Web API?

A: You need to register two applications, one for daemon app(client app), one for web api(backend app).

Click the web api app->Expose an API.

Click the daemon app->API permissions->Add a permission->My APIs->choose web api app->select the permissions.

Then the client
var app = ConfidentialClientApplicationBuilder.Create("<client app id>")
                .WithClientSecret("<client app client_secret>")
                .WithAuthority("https://login.microsoftonline.com/<tenant_id>")
                .Build();

The scope:
await app.AcquireTokenForClient(new string[] { "api://<app_id_of_the_web_api>/read" });

Refer to this sample. You can think of your web api as Microsoft Graph API.

A: First of all thanks much, Caiyi, for the pointers. That got me thinking the right way about the approach. Unfortunately, I am forced to use the api:///.default to get an access token. No amount of cajoling seems to work when using a "regular" scope. I configured the apps as was suggested above, but instead of:
await app.AcquireTokenForClient(new string[] { "api://<app_id_of_the_web_api>/read" });

I had to use:
await app.AcquireTokenForClient(new string[] { "api://<app_id_of_the_web_api>/.default" });

In the configuration for the API app, I had to define an "appRole" in the manifest that identifies the role that I was going to assign the Daemon app and then in the Web API, I changed my policy code to check for the scopes OR the app role - which worked.


text:
Q: Data passing error from javascript to controller I'm working on ASP.NET MVC project , I want to get location dropdown  selected value and according to that i need to  load values to City  dropdown  , i implemented following code and location dropdown onselect event call the javascript function  and javascript function call the controller method  but when executing controller  method locationId is  null ,and i debug javascript and locationID is there till the this  line  data: JSON.stringify({ locationId: +locationId }), after that javascript  returns error.but  controller method get hit but locationId null
code for dropddowns

        @Localizer["Locations"]
        <select id="locationDropDown"  class="selectpicker form-control" asp-for="selectedLocation" onchange="getCityList()">
            <option value="0"><None></option>
            @foreach (var item in Model.LocationList)
            {
                <option value="@item.Id">@item.Name</option>
            }
        </select>

        @Localizer["KioskGroup"]
        <select id="cityDropDown" class="selectpicker form-control">
            <option>---Select City---</option>
        </select>

Javascript code
function getCityList()
        {
        debugger;
            var locationId = $("#locationDropDown").val();
            console.log(locationId)
        $.ajax({
            url: '/Kiosk/GetZoneListBYlocationID',
            type: 'POST',
            datatype: 'application/json',
            contentType: 'application/json',
            data: JSON.stringify({ locationId: +locationId }),
            success: function (result) {
                $("#cityDropDown").html("");
                $("#cityDropDown").append
                ($('<option></option>').val(null).html("---Select City---"));
                $.each($.parseJSON(result), function (i, zone)
                { $("#cityDropDown").append($('<option></option>').val(zone.Id).html(zone.Name)) })

            },
            error: function(){alert("Whooaaa! Something went wrong..")},
        });

controller method
  public ActionResult GetZoneListBYlocationID(string locationID)
        {
            List<Zone> lstZone = new List<Zone>();
            long locationId = long.Parse(locationID);

            var zones = _zoneRepository.GetZonesByLocationId(locationId);

            return Json(JsonConvert.SerializeObject(zones));
        }

A: Why you are stringify  the data.Below one should work without stringify
data: { locationId: +locationId },

A: Your current code is sending the json string {"locationId":101} in the request body because you specified the contentType as application/json. This is useful when you want to send an object with multiple properties and your action method parameter is a DTO/POCO class type. Model binder will be reading from the request body and map it to the parameter.
In your case, all you are sending is a single value. So do not send the JSON string. simply create a js object and use that as the data attribute value. Also remove the contentType: application/json as we are not sending a complex js object as json string.
Also application/json is not a valid option for the dataType property. You may use json. But jQuery is smart enough to guess the value needed here from the response headers coming back from server. So you may remove it.
function getCityList() {

    var locationId = $("#locationDropDown").val();
    $.ajax({
        url: '/Kiosk/GetZoneListBYlocationID',
        type: 'POST',
        data: { locationID: locationId },
        success: function (result) {
           console.log(result);
           // populate dropdown
        },
        error: function () { alert("Whooaaa! Something went wrong..") },
    });

}

Now this data will be send in Form Data as locationID=101 with Content-Type header value as application/x-www-form-urlencoded and will be properly mapped to your action method parameter.
You should use the correct types. In your action method, you are using string as your parameter and later trying to convert it to long. Why not use long as the parameter type ?  Also if zones variable is a list of Zone object, you can pass that directly to the Json method. No need to create a string version in between.
 public ActionResult GetZoneListBYlocationID(long locationId)
 {
    var zones = _zoneRepository.GetZonesByLocationId(locationId);
    return Json(zones);
 }

A: I was facing the same problem. and after that, I have tried below solution.
Hope it will help you.
ajax call is as follows:
          $.ajax({
                type: 'POST',
                url: "/Account/GetCities",
                dataType: 'json',
                data: { id: $("#StateID").val() },
                success: function (states) {
                    $.each(states, function (i, state) {
                       $("#CityID").append('<option value="' + state.Value + '">' + state.Text + '</option>');
                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve cities.' + ex);
                }
            });

The controller code is as follows:
public List<CityModel> GetCities(int id)
{
        //your code
}

You can do in your application like this:
function getCityList()
        {

            var locationId = $("#locationDropDown").val();
            console.log(locationId)
        $.ajax({
            url: '/Kiosk/GetZoneListBYlocationID',
            type: 'POST',
            dataType: 'json',
            data: { locationId: locationId },
            success: function (result) {
                $("#cityDropDown").html("");
                $("#cityDropDown").append
                ($('<option></option>').val(null).html("---Select City---"));
                $.each($.parseJSON(result), function (i, zone)
                { $("#cityDropDown").append($('<option></option>').val(zone.Id).html(zone.Name)) })

            },
            error: function(){alert("Whooaaa! Something went wrong..")},
        });
}

And your controller will be same as you have done.


text:
Q: How do I view GTFS data in QGIS? I would like to use QGIS to create my map. One data feed is the gtfs regarding to bus routes. I can view it on Google Earth (although laggy), but when I tried to import the .kml into QGIS, it just ran out of RAM (for 30 min) and crashed my map. If I import 10 in the 18xx layers, the route is duplicated 10 times (Google Earth could show all the routes, although laggy).
My procedure
I am trying a new method, so...
What I did was download the .txt on TfNSW website (Google tfnsw data and login), then use a .py script called Transitfeed by bdferris to convert the .txt into .kml. Finally import the .kml as vector layers, but I did viewed in Google Earth prior that so I though it will be okay.
I am intended to convert the shape.txt into route shapes.
Problem
I was thinking of the possibilities and solutions, for example:

*

*Faulty .kml

*Faulty .txt in the gtfs

*Faulty conversion from .txt to .kml

I was thinking if either first two possibilities are valid, then what is the suitable validation (of my .kml) solution? Otherwise I would like a cost-less (i.e. monetary) solution for viewing gtfs .txt file into QGIS.

A: From http://code.google.com/p/googletransitdatafeed/wiki/PublicFeeds, I took the data from TriMet Portland and had no problem adding the geometry data (stops.txt and shapes.txt) to QGIS with the MMQGIS plugin.
Once installed, use MMQGIS -> Import/Export -> Geometry Import from CSV file
Geometry Type Point for the stops and Polylinefor the shapes.
If you experience the same laggy effect as with Google Earth, you might save the result to a spatialite database. Or store the data in a postgis database, as explained here:
http://opendesignarch.blogspot.de/2014/03/loading-gtfs-data-into-postgresql.html
https://github.com/pgRouting/pgrouting/wiki/MMPTR-Tutorial

A: I have used the Points2One plugin and I found it pretty straight forward.
https://youtu.be/cxAkTg_01vg
1 - Import GTFS file named 'shapes.txt' using 'Add limited Text Layer'
2 - Click on the Points2One plugin and create Lines by "shape_id"

A: I found this really nice tutorial by google search:
http://www.stevencanplan.com/2016/02/converting-a-transit-agencys-gtfs-to-shapefile-and-geojson-with-qgis/
I got my data here:
http://apps2.saskatoon.ca/app/data/google_transit.zip
In order to make the points into a path, it looks like the Points to Path plugin does not ship with qgis 3, but it also looks like qgis 3 comes bundled with a points to path tool thanks to another post I found here.


text:
Q: Django - Database design in orders ecommerce I have a scenario what will be best design for this .
I have a Articles table (like pizza , drink etc)
class Articles(models.Model):
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE , blank=True, null=True)
    articlename = models.CharField(max_length=50, null=False, blank=False)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    category = models.ForeignKey(Categories, on_delete=models.CASCADE)
    ingredient = models.ManyToManyField(Ingredient)     #done
    articleoptionnames = models.ForeignKey(ArticlesOptionsName , on_delete=models.CASCADE)

2nd table is Article options (Like topping (1 time, 2times or 3 times), extra sauce ,  etc)
class ArticlesOptions(models.Model):
    articleoptionrestaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE , blank=True, null=True)
    optionname = models.ForeignKey(ArticlesOptionsName, on_delete=models.CASCADE, related_name="optionnames")
    min = models.IntegerField()
    max = models.IntegerField()
    choice_price = models.DecimalField(max_digits=10, decimal_places=2)
    choice = models.CharField(max_length=255)
    def __str__(self):
        return str(self.optionname)

And 3rd Order table
class orders(models.Model):
      restaurant=models.ForeignKey(Restaurant, on_delete=models.CASCADE , blank=True, null=True)
      articles=models.ForeignKey(Articles, on_delete=models.CASCADE , blank=True, null=True)
      articleoptions=models.ManyToManyField(ArticlesOptions)
      totalamount=models.DecimalField(max_digits=10, decimal_places=2)

      def __str__(self):
          return str(self.articles)

Customer will be able to purchase many articles at a time and then every article have multipul article options (for example 4 types of topping and 4 type of sauce user can select many type of topping and many type of sauce ).  SO how to make  order table in best way ?

A: Your order table should be split down further to be able to accommodate more than one article and article option. Your article options should be related to the article added to the order and not to the order itself. So, in my opinion, I think your order should look like this,
class Orders(models.Model):
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, blank=True, null=True)
    total_amount = models.DecimalField(max_digits=10, decimal_places=2)

And add an order Article model which has the articles specific to that order each with their own option and each option has a quantity.
class OrderArticle(models.Model):
    order = models.ForeignKey(Orders, on_delete=models.CASCADE)
    article = models.ForeignKey(Articles, on_delete=models.CASCADE)

class OrderArticleOption(models.Model):
    article_option = models.ForeignKey(ArticlesOptions, on_delete=models.CASCADE)
    order_article = models.ForeignKey(OrderArticle, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)

Hope this helps!


text:
Q: PHP, search and delete files from directory - performance I want to delete cache files in a directory, the directory can contain up to 50.000 files. I currently I use this function.
// Deletes all files in $type directory that start with $start

    function clearCache($type,$start)
        {
        $open = opendir($GLOBALS['DOC_ROOT']."/cache/".$type."/");
        while( ($file = readdir($open)) !== false )
            {
            if ( strpos($file, $start)!==false )
                {
                unlink($GLOBALS['DOC_ROOT']."/cache/".$type."/".$file);
                }
            }
        closedir($open);
        }

This works fine and it is fast, but is there any faster way to do this? (scan_dir seems to be slow). I can move the cache to memory obviously.
Thanks,
hamlet

A: You may want to take a look into the glob function, as it may be even faster... it depends on the C library's glob command to do its work.
I haven't tested this, but I think this would work::
foreach (glob($GLOBALS['DOC_ROOT']."/cache/".$type."/".$start) as $file) {
    unlink($GLOBALS['DOC_ROOT']."/cache/".$type."/".$file);
}

Edit: I'm not sure if $file would be just the filename or the entire path.  glob's documentation implies just the filename.

A: Either glob as suggested before or, if you can be certain there won't be malicious input, by issueing directly to the system via exec(sprintf('rm %s/sess*', realpath($path)));, which should be fastest.


text:
Q: Add category selection to custom post type I wanna be able to post my WooCommerce products into my  "posts" categories. Based based off this cod below, it's possible. Here's the code I'm using in my functions.php. The categories are clickable when I make a new product in Woo however, it's not posting to the category itself. Appreciate any insight on this matter.
Add category selection to custom post type
function reg_cat() {
     register_taxonomy_for_object_type('category','CUSTOM_POST_TYPE');
}
add_action('init', 'reg_cat');

A: Please try This Code for register new texonomy
function custom_taxonomy() {
    register_taxonomy(
        'custom_categories',  //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
        'post_type',        //post type name
        array(
            'hierarchical' => true,
            'label' => 'Themes store',  //Display name
            'query_var' => true,
            'rewrite' => array(
                'slug' => 'themes', // This controls the base slug that will display before each term
                'with_front' => false // Don't display the category base before
            )
        )
    );
}
add_action( 'init', 'custom_taxonomy');

Note: Please add this code in theme function.php or your plugin
=======================================================================
function reg_cat() {
         register_taxonomy_for_object_type('category','CUSTOM_POST_TYPE');
    }
add_action('init', 'reg_cat');

This code working post category display in custom post type texonomy section Please refer

A: For register custom taxonomy you can try below code, for more https://codex.wordpress.org/Function_Reference/register_taxonomy
<?php
add_action( 'init', 'create_book_tax' );

function create_book_tax() {
    register_taxonomy(
        'genre',
        'book',
        array(
            'label' => __( 'Genre' ),
            'rewrite' => array( 'slug' => 'genre' ),
            'hierarchical' => true,
        )
    );
}
?>


text:
Q: Change Tab Programmatically with SlidingTabLayout I'm using the SlidingTabLayout example provided by Google.  I'm trying to programmatically switch back to the first tab inside a dialogView that is inside a fragment.
I see a scrollToTab(int tabIndex, int positionOffset).  How can I call this to return to the first tab?

A: You can use:
viewPager.setCurrentItem(itemIndex);

viewPager being your view pager for the tabs that you specified in the layout as
android.support.v4.view.ViewPager


text:
Q: auto login for skydrive api php I want to make just offline authentication in SkyDrive api PHP,just want to provide client_id,client_secret_key and access or refresh token which may be preferable and than authenticate me on that basis.After successful offline login create one folder in SkyDrive (OneDrive) and upload files inside that created folder.
And how to refresh access token automatically without login.
Please help me out if anyone have idea regarding that.

A: Finally i got it,
Please use the Following source it's work for me
https://github.com/lovattj/php-skydrive
Within that Below File is so useful
https://github.com/lovattj/php-skydrive/blob/master/src/functions.inc.php
i changed in curl function and it's work for me
For e.g
i replaced curl_get function by below and it work for me
protected function curl_get($uri, $json_decode_output="true", $expected_status_code="HTTP/1.1 200 OK") {
                try{
                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, $uri);
                        //curl_setopt($ch, CURLOPT_HEADER, true);    // we want headers
                        //curl_setopt($ch, CURLOPT_NOBODY, true);
                        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch, CURLOPT_FAILONERROR, false);
                        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                        $result = curl_exec($ch);
                        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                        curl_close($ch);
                }  catch (Exception $e){}
                if ($httpcode == "201" || $httpcode == "200") {
        return json_decode($result, true);
                } else {
                        return array('error' => 'HTTP status code not expected - got ', 'description' => $httpcode);
                }
                var_dump(json_decode($result));
}


text:
Q: child process error: Error: channel closed - node + atom I am relatively new to Node. I am using Atom and the following error message keeps popping up over and over again:
child process error: Error: channel closed

Additionally, there have been a couple of times my page has become non-responsive (not sure they are related but believe there is a high likelihood).
What are the steps one would take to track down the cause of this error in order to resolve it?
Hoping the SO community can help!
Thanks in advance.

A: Check to see if you have the 'atom-ternjs' package installed. I have it installed on Atom 1.8.0 on OS X 10.11.5 and am seeing this error quite often recently. Disable this plugin if you have it installed and see if the error goes away.

A: Not really a permanent solution, but I found if you "restart" the ternjs server the errors go away (at least for a little while)


text:
Q: Unable to extract the text content from pdf file using tika I am using a Postscript printer which generates a '.ps' file,and I am converting this .ps file into .pdf using 'ps2pdf' command in my linux machine.The file which is generated here, it's content is not selectable and copyable .Also when I try to extract the content from same pdf file using apache Tika it return an empty string (means not able to extract).I thought it might be problem with some fonts,so I installed some new fonts also but still it didn't work for me.
I am not able to find out what the problem is.Whether it is problem with printer driver or ghostscript (which is being used to convert '.ps' into '.pdf') or it is problem with fonts or something-else.
while retrieving content using tika it is printing some warning (not errors) as below.
WARN  No Unicode mapping for CID+1 (1) in font WKQJKU+ArialNarrow-Identity-H
WARN  No Unicode mapping for CID+2 (2) in font WKQJKU+ArialNarrow-Identity-H
WARN  No Unicode mapping for CID+3 (3) in font WKQJKU+ArialNarrow-Identity-H
WARN  No Unicode mapping for CID+4 (4) in font WKQJKU+ArialNarrow-Identity-H
WARN  No Unicode mapping for CID+5 (5) in font WKQJKU+ArialNarrow-Identity-H

....
Any help is appreciated .Thanks in advance.

A: Without seeing the original PostScript file and the PDF its not really possible to tell what the problem is, or if it can be fixed. You need to post the files somewhere public.
You also don't say exactly what the 'ps2pdf' command is, there are several different utilities that use the same name. If its using Ghostscript then it will say so when running. If so you would do better to run Ghostscript directly to avoid confusion. You should also quote the version of Ghostscript you are using.
Now PostScript programs are normally intended to be sent to printers for printing. As such it does not matter what character codes are used to represent a glyph, provided that the font Encoding and the character code combine to produce the expected character shape on output. So there is absolutely no guarantee that an 'A' in your original application, which gets printed as an 'A' on paper is actually represented by character code 0x41 for example. Its not uncommon for an application to create a subset font, which only contains the glyphs actually printed, and which is arranged so that the first character to be printed is given the code 1, the second is given the code 2 etc. Thus 'Hello' would be 0x01 0x02 0x03 0x03 0x04
The Windows PostScript printer driver adds a non-standard G2U table, which maps glyph names to Unicode code points, and using this it is possible to construct a ToUnicode CMap and embed that in the PDF file. This allows complex Encodings to be converted into Unicode values, which means that search and copy/paste will work.
But You haven't said which system you are using to create the PostScript program, and since you haven't supplied an example, we simply don't know how your PostScript is being generated.
It does appear that your PDF file is using a CIDFont, and does not contain a ToUnicode CMap. Its fairly unlikely that this will yield a PDF file where you can copy/paste stuff. Of course, that wasn't the original goal of PDF anyway, which is why its not guaranteed to be possible.
It may well be that there simply is no way to turn the PostScript file into an editable PDF file, but you haven't supplied enough information to tell.
[later]
The PostScript is produced by Cairo, possibly from a PDF file, but that's not totally clear, it may simply be the way that Cairo works. In any event.... The PostScript contains an embedded subset CIDFont with CIDFontType 2 (TrueType outlines). Because PostScript doesn't have a defined mechanism for supplying Unicode information there is none supplied. As described above, the 'encoding' is created as the characters are encountered, so the first glyph is encoded as 0x01 etc.
The result of this is that there is no simple way to extract meaningful text from this PostScript file, other than printing it and using OCR of course.
Its just conceivable that the sfnts of the CIDFont contains a 3,0 CMAP subtable which would map the glyph IDs to Unicode values, but it would take me some time to check.
However, even if that is the case, Ghostscript's pdfwrite code doesn't currently attempt that feat (nor does Acrobat Distiller, nor any other PostScript to PDF creator that I'm aware of).
So, fundamentally, you can't do what you're trying to do. Why not have Cairo produce a PDF file instead of a PostScript file ? Its more likely to work that way I would have thought. Of course that would probably mean you'll have to look at how your virtual printer works, if you are using CUPS it should be possible I would have thought, since PDF is the itnernal format used by modern versions of CUPS.


text:
Q: For $I$ a bounded real interval, do we have that $L^1(I) \subsetneq L^2(I)$? Let $I$ be a bounded real interval. Then we have that $L^1(I) \subset L^2(I)$ due to the following:

But is there an example of an $f \in L^2(I)$ that is not also in $L^1(I)$? That is, do we have that
$$
L^1(I) \subsetneq L^2(I)?
$$
And if so, why?

A: The graph of the exponential is convex, meaning that
$$
           e^{rx+(1-r)y} \le re^{x}+(1-r)e^{y},\;\; 0 \le r \le 1.
$$
(Draw a picture and you're see it.) It follows that
$$
                 X^{r} Y^{1-r} \le rX+(1-r)Y, \;\; X,Y \ge 0,\;\; 0 \le r \le 1.
$$
Setting $Y=1$ gives
$$
                 X^{r} \le rX+(1-r)1, \;\;\; 0 \le r \le 1.
$$
So, if $X$ is absolutely integrable on a finite interval, then so is $X^r$ for every $0 < r < 1$. So, for example, $L^2 \subseteq L^p$ for all $1 \le p \le 2$. However $L^1 \not\subseteq L^2$ because $1/\sqrt{x}\in L^1$ and $1/\sqrt{x}\notin L^2$.


text:
Q: Apply Linq Func key selector at single element level Sorry if the title is misleading, wasn't sure how to describe this one.
My end goal is to have an extension method of IQueryable<T> and some form (see below for example) of expression that will allow me to have to return an IQueryable<EntityIndex<T>> (or similar) which contains the original T in the Entity field, and an array/ienumerable containing the elements as describe by the some form of expression.
I know that doesn't really make sense, hopefully it will after an example...
This is what I have so far:
class EntityIndex<T, TKey>
{
    T Entity { get; set; }
    // Doesn't have to be IEnumerable, whatever is easier
    IEnuermable<TKey> Index { get; set; }
}
static class Elsewhere
{
    [Extension()]
    public IQueryable<EntityIndex<T, TKey>> IndexBy<T, TKey>(this IQueryable<T> source, Expression<Func<T, TKey[]>> indexSelector)
    {
        return source.Select(n => new EntityIndex<T, TKey> {
            Entity = n,
            Index = new T[] { n }.Select(indexSelector)
        });
    }
}

Note: The above does not compile, it's simply there to try and show what I'm trying to achieve.
I've used the standard selector, but sub-optimally, had to arbitrarily create an array of T on the assignment to the 'Index' property to be able to apply the selector.  I'm hoping a better choice of parameter may resolve this, but possibly not.  The main issue is this doesn't compile so if there is a minor tweak that will allow it to work that's fine by me, if you can understand my gibberish and understand what I'm trying to do, and happen to know a better way to go about it I'd be greatly appreciative.
Ideally, I need the solution to be understood by the L2S engine, which I'm not convinced the above is thanks to the introduction of the EntityIndex class, but I'm holding out hope that it'll treat it as an anonymous class.
EDIT:
Good point Damien, the bigger picture is probably much easier to describe...
I want an extension method that accepts an expression, the expression should describe which fields on the entity to index, which will be used after this particular expression to allow a criterion (where clause) to be applied to the selected fields.
Long story short, in a number of places in code we have a wildcard string search.  If I have an EntityA with Property1, Property2, Property3, etc, it is not uncommon to see code such as:
Handwritten, please excuse minor typos
public string[] WildcardSearch(string prefixText, int count)
{
    string searchTerm = prefixText.Replace(wildcard, string.Empty);
    if (prefixText.StartsWith(wildcard) && prefixText.EndsWith(wildcard)) {
        return entitySet.Where(n => n.Property1.Contains(searchTerm) || n.Property2.Contains(searchTerm)).Select(n => n.Property3).ToArray();
    } else if (prefixText.StartsWith(wildcard)) {
        return entitySet.Where(n => n.Property1.EndsWith(searchTerm) || n.Property2.EndsWith(searchTerm)).Select(n => n.Property3).ToArray();
        // you get the picture, same with EndsWith, no wildcards defaults to contains...
    }
}

EDIT:
Further clarification - using the above WildcardEarch as an example, what I was hoping for was to be able to have a selector as follows or similar:
Func<EntityA, IEnumerable<string>> indexSelector = n => new string[] {
    n.Property1,
    n.Property2
};

// Alternatively, a ParamArray of keySelector might work?
Func<EntityA, string>[] keySelectors = new Func<EntityA, string>[] {
    n => n.Property1,
    n => n.Property2
};

Given an adequate expression describing which fields on the entity to search, returning the IQueryable<EntitySearch<T>> as shown above, I hoped to be able to apply a single criterion, similar to:
Func<EntitySearch<T>, bool> criterion = n => false;
if (wildcardIsContains) {
    criterion = n => n.Values.Any(x => x.Contains(searchTerm));
} else if (wildCardIsStartsWith) {
    criterion = n => n.Values.Any(x => x.Contains(searchTerm));
    //etc
}

Given the extension at the very top that I can't get to work, and this criterion logic, I should be able to take an IQueryable<T>, select some fields, and apply an appropriate wildcard search on the fields, finally returning IQueryable<T> again having added the filtering.
Thanks¬!
Please comment if you need more information/clarification...
EDIT:
Fair one @subkamren and thanks for the interest. Some non-generic examples may be of use.  I'll draft something up and add them shortly.  For the time being, some clarification based on your comment...
Given an IQueryable<Animal> I want an extension allowing me to select fields on Animal which I intend to search/index by.  For example, Animal.Description, Animal.Species.Name etc.  This extension should return something like an IIndexedQueryable<Animal>.  That is the issue I'm trying to deal with in the question above.  The wider picture mentioned, which I'd be exceptionally pleased if you're willing to help with, is as follows:
The IIndexedQueryable<T> interface in turn I would like an extension for which could take a string search term. The extension should resolve the wildcards within the search term, extend the original IQueryable with the necessary criterion to perform a search on the indexed fields, and return an IQueryable<T> again.
I appreciate this could be done in a single step, but I hoped to do it this way so that later on I can look into adding a third extension method applicable to IIndexedQueryable<T> allowing me to perform a freetext search with SQL Server... ^^  Make any sense?
That's the bigger picture at least, this question deals primarily with being able to specify the fields I aim to index in such a way I can use them thereafter as mentioned here.

A: So something like:
public static IEnumerable<EntityIndex<T, Y>> IndexBy<T, Y>(this IEnumerable<T> entities, Func<T, Y> indexSelector) {
    return entities.Select(e => new EntityIndex<T, Y> { Entity = e, IndexValue = indexSelector(e) });
}

Noting that generically defining EntityIndex with the TIndexType (called Y here) is important because you don't know ahead of time what the index is.  The use of a generic allows Y to be an enumeration, thus the following would work as an index selector:
// Assuming Animal has attributes "Kingdom", "Phylum", "Family", "Genus", "Species"
// this returns an enumeration of EntityIndex<Animal, String[]>
var animalsClassified = someAnimals.IndexBy(a => new String[] { a.Kingdom, a.Phylum, a.Family, a.Genus, a.Species });

EDIT (Adding further detail):
Using the above, you can group the results by unique index value:
var animalClassifications = animalsClassified
                                .SelectMany(ac => ac.IndexValue.Select(iv => new { IndexValue = iv, Entity = ac.Entity }))
                                .GroupBy(kvp => kvp.IndexValue)

What I've described here, by the way, is (a very simplified form of) the MapReduce algorithm as popularized by Google. A distributed form of the same is commonly used for keyword identification in text search, where you want to build an index of (search term)->(list of containing documents).


text:
Q: How to find if a pixel is entirely within another pixel when comparing for example two GeoTIFF raster maps? Using GDAL and/or Python
Red: GeoTIFF raster Map layer 1
Blue: GeoTIFF raster Map layer 2

A: Assuming no rotation, if you have the coordinates of the center of your pixel, you can check that both the absolute difference between the X or Y coordinates of your "blue" pixel" and the "red" pixel is smaller than the difference between the half-width of the "red pixel" and the "blue" pixel (in the X and Y direction).
gdalinfo will give you the necessary information.


text:
Q: Multiplication Explicit Casting not working C long long int calculateUnits(int tokenVal, int billVal, int numOfTokens, int numOfBills)
{
    long long int units;

    // tokenUnits = billVal * numOfTokens;
    // billUnits = tokenVal * numOfBills;
    units = (long long int)(billVal * numOfTokens) + (long long int)(tokenVal * numOfBills);

    // return number of units
    return units;
}

For small numbers this works fine. But as soon as the multiplication outcome gets big enough, I start getting negative numbers. I thought the explicit casting would solve the issue.
Am I using it wrong, or is there something else I am missing?

A: Multiplying ints returns an int. If the result is too large for an int, it overflows and you get implementation-dependent behavior.
You should cast one of the parameters to long long, then the result will be long long. Casting the result doesn't work, because that does the conversion after the overflow has already occurred.
units = ((long long int)billVal * numOfTokens) + ((long long int)tokenVal * numOfBills);

A: (long long int)(billVal * numOfTokens)

This doesn't mean "treat both these as if they were long long int", it means do the multiplication using their actual types, then upgrade the result to long long int. The multiplication, and therefore any overflow, is done first.
What you need to do is force one of the variables to be the wider type (the other will be implicitly upgraded) so that the multiplication uses the wider type:
(long long int)billVal * numOfTokens

However, a better solution, since you want to work with the wider type, may be to use that wider type in the function signature:
long long int calculateUnits(long long int tokenVal, long long int billVal,
    long long int numOfTokens, long long int numOfBills)
{
    return billVal * numOfTokens + tokenVal * numOfBills;
}

That way, you don't need to worry about casting, the variables will implicitly be upgraded to the wider type as part of the function call, and your code becomes more succinct.


text:
Q: How can I use EF5 in the nest website when EF6 in the root website I have published web app A in the root directory and web app B in the /B.
A and B are not dependence.
A use EF6 while B use EF5
I got a series of error messages start at duplicate 'entityFramework'. How can I use 2 EF version in 2 URL ?
Thank you.


text:
Q: ListView with images extremely slow I have a ListView which displays an ImageView to show the user the album art and two TextViews for album and artist.
However, when I scroll up and down it is always terribly slow.
public class DSongListAdapter extends ArrayAdapter<Song> {

    Context mContext;
    List<Song> mObjects;

    public DSongListAdapter(Context context, List<Song> songList ) {
        super(context, R.layout.list_item_song, songList );
        this.mContext = context;
        this.mObjects = songList;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;
        if( convertView == null ){
            holder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item_song, parent, false);
            holder.titleLabel = (TextView) convertView.findViewById(R.id.titleLabel);
            holder.artistLabel = (TextView) convertView.findViewById(R.id.artistLabel);
            holder.cover = (ImageView) convertView.findViewById(R.id.list_image);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }
        holder.titleLabel.setText( mObjects.get(position).getTitle() );
        holder.artistLabel.setText( mObjects.get(position).getArtist() );
        Bitmap bm = SongManager.loadBitmap(mContext, mObjects.get(position).getAlbumId() );

        if( bm == null )
            holder.cover.setImageDrawable( mContext.getResources().getDrawable(R.drawable.untitled) );
        else
            holder.cover.setImageBitmap(bm);

        return convertView;
    }

    class ViewHolder {
        TextView titleLabel;
        TextView artistLabel;
        ImageView cover;
    }

}

That's the list adapter I created. The SongManager.loadBitmap() method returns either a bitmap or null. If it is null I will use a default bitmap from my resources.
What can I do to increase the speed? The amazon music player for example is way faster and smoother than mine! Also I have noticed my app takes 42 MB of Ram. Is that too much?
Edit:
public static Bitmap loadBitmap( Context c, int album_id ){
    Bitmap bm = null;
    try {
        final Uri sArtworkUri = Uri
                .parse("content://media/external/audio/albumart");

        Uri uri = ContentUris.withAppendedId(sArtworkUri,
                album_id);

        ParcelFileDescriptor pfd = c.getContentResolver()
                .openFileDescriptor(uri, "r");

        if (pfd != null) {
            FileDescriptor fd = pfd.getFileDescriptor();
            bm = BitmapFactory.decodeFileDescriptor(fd);
        }
    } catch (Exception e) {

    }

    return bm;
}

A: You are performing IPC, and indirect disk I/O, on every getView() call. Had you used Traceview, you would have determined that this is the source of your difficulty.
Please consider using a library like Picasso to load those images asynchronously and cache them. There are many other such libraries -- see the "Image Loaders" and "Image Views" categories in the Android Arsenal.

A: You should never do I/O-Operations on the ui thread. Instead of this, you should load your images aynchronously. Luckyly, there are a tone of good libraries for doing this. Just check out this one, it is simple to use and customize: https://github.com/nostra13/Android-Universal-Image-Loader


text:
Q: Is there any option to make my curves more smooth? I used Scilab to get this output. Is there any option in Xcos simulation parameters to make my curves more smooth?
[1]: https://i.stack.imgur.com/r32Ke.png  [Scilab's figure][1]

A: This may not be of much help, but it, as a whole, depends on the time interval you are choosing. Is there a way to change the time scale? Maybe put 1E-5 instead of 0E0. I suspect that writing 0 is making the program choose a default time scale.


text:
Q: How to make a piece of Javascript work only when the user is on a different tab? I have the following javascript to make the webpage title change again and again after every five seconds.
<script>
        var titleArray = ["TITLE-1","TITLE-2","TITLE-3","TITLE-4"];
        var N = titleArray.length;
        var i = 0;
        setInterval(func,5000);
        function func(){
            if (i == 4) {
                i = 0;
            }
            document.title = titleArray[i];
            i++;
        }

</script>

I want it to work only when the user has opened a different tab in order to "attract" him/her back to my site.While he/she is on my site I want this javascript to stop working so the title of the webpage is what I simply write in the title tags.
here is a summary of what I want.
<script>
if (the user is not on this tab but has opened and is using a different tab)
{the javascript I have mentioned above};
elce {nothing so the title tags work};
</script>

P.S:  Is this a good idea? Got any other suggestions? I just really like thinking out of the box.

A: Please try with below script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
    var isActive;

    window.onfocus = function () {
      isActive = true;
    };

    window.onblur = function () {
      isActive = false;
    };

    // test
    var titleArray = ["TITLE-1","TITLE-2","TITLE-3","TITLE-4"];
    var N = titleArray.length;
    var i = 0;
    function changeTitle(){
        if (i == 4) {
            i = 0;
        }
        document.title = titleArray[i];
        i++;
    }

    setInterval(function () {
      if(window.isActive !== true){
        changeTitle();
      }
    }, 1000);
</script>


text:
Q: Can I just move SSD from 13inch MBP to 15 inch? Mid 2010 13 inch MBP is under 10.11.6 while the 15 inch is a 2012 non-retina model that is under macOS Sierra. I've been told that this is possible earlier but would like to hear form more people. Some are saying Macs are hardware independent, some say they are, so I need a consistent answer. The 15 inch currently has a HDD which is not going to cut it for me.
What do you suggest I do to move my 13 inch's SSD + data into the 15 inch safely. I have a bunch of environments setup which would take so much time to set up again, so I'm trying to make the switch safely.

A: Yes you can make that move. Whether or not your environments will transfer I cannot say: it depends whether they are hardware-independent like MacOS. You should have at least one (possibly two, if you're very concerned) backups of your data. These can take the forms of: clone the drive (using Carbon Copy Cloner or similar), time machine backups, or a disk image of the entire SSD. This way if there is a problem during or after the move, everything will be recoverable. After making sure your data is secure, follow a repair guide (I have found that generally iFixit and Other World Computing make good tutorials/video guides) to remove the SSD from the first computer and put it into the second computer.
A few people recommend doing NVRAM and SMC resets before booting the new combination. Try doing these and then booting. Test your apps and environments to make sure everything is working okay. I'd suggest keeping a backup on hand until you know that everything worked. If things didn't work, you can try wiping the SSD and restoring to the new computer from backup, or if you want to revert back to the old setup you knew worked, you could do that as well.
Good luck! Make sure that you understand everything before you do it. Feel free to ask questions or challenge my answer if you have heard otherwise.


text:
Q: Most effecient way to export data from mongodb We are using mongo (self hosted, not a managed service) as our data store, but our data volume is far too big for mongo to handle. We are going to transition to Google's big table service, but now we have a problem: we have to do a one time export of 65 million records (~200GB) from a single mongo collection. We also want to do it in a couple hours to reduce the amount of data that will have been updated in that time.
I'm not very concerned with writing to big table as it has seemed pretty fast, is easy to parallelize, and is actually designed to handle this much data. The hard part is reading from mongo.
What we have tried:
Run a query in node (no sorts/filters), run the output through a transform, then upload to big table. As it turns out, this approach was extremely naive. We blew out the CPU on the box with no obvious bottlenecks, however even if we skip the whole writing part, the reading part is still really slow.
The next options all revolved around the general idea of 'do a full database dump, split it into even-sized chunks, process it in parallel.'
Use mongoexport. This is still really slow, but substantially better then the db query.
Use mongodump. This was faster than mongoexport, but still on the slow side. Also, I don't know how easy it is to parse the files.
I have been having difficulty identifying what the bottlenecks are. CPU is generally high, but not maxed out (except for the naive approach mentioned above). As expected, disk I/O is also generally very high. I also don't think I can control that because it is on the cloud (GCP).
I'm mostly trying to get other ideas/approaches here, although I am fully aware that this may simply not be possible, but I would like a second opinion before making that conclusion.


text:
Q: Algorithm to check if two numbers can become the same Hello I have to answer this question as a task. I have done the code yet I don't get full marks because apparently I am missing some conditions
Given two integers AA and BB, determine if it is possible to do the same by applying any number of the operations shown below:

*

*Multiply the number AA by 2.

*Multiply the BB number by 2.
If true print "felizmil", else output "tristemil"
Code
def ___gcd(a,b):
    if (a == 0 or b == 0):
        return 0
    if (a == b):
        return a
    if (a > b):
        return ___gcd(a-b, b)
    return ___gcd(a, b-a)

def lcmOfArray(arr,n):
    ans = arr[0]
    for i in range(1,n):
        ans = (arr[i]*ans)/___gcd(arr[i], ans)
    return ans
def checkArray(arr, num, n, m):
    lcm = lcmOfArray(arr, n)
    for i in range(n):
        val = lcm/arr[i]
        for j in range(m and val!=1):
            while (val % num[j] == 0):
                val = val/num[j]
        if (val != 1):
            return 0
    return 1
arr=list(map(int,raw_input().split()))
num = [2]
n = len(arr)
m = len(num)
if 0 in arr:
    print("tristemil")
else:
    if(checkArray(arr, num, n, m)):
        print("felizmil")
    else:
        print("tristemil")

examples-->
3 5 output: tristemil
14 7 output: felizmil
I don't know which cases/conditions I am missing i would really appreciate your help. Thanks very much :D

A: Simply we can do:
def are_equal(a, b):
    if a > b:
        a, b = b, a

    if a == 0:
        return b == 0

    while a < b:
        a *= 2

    return a == b

if are_equal(2, 4):
    print('felizmil')
else:
    print('tristemil')

if are_equal(2, 3):
    print('felizmil')
else:
    print('tristemil')

assert are_equal(0, 0) == True
assert are_equal(0, 1) == False
assert are_equal(1, 0) == False
assert are_equal(1, 2) == True
assert are_equal(2, 1) == True
assert are_equal(2, 2) == True

A: My friend A. Mercado solved this problem with the following code:
a, b = raw_input().split()
a = int(a)
b = int(b)
if a == b:
    print("felizmil")
else:
    if a % 2 != 0 and b % 2 != 0:
        print("tristemil")
    elif a % 2 == 0 and b % 2 == 0:
        if a > b:
            if a % b == 0:
                print("felizmil")
            else:
                print("tristemil")
        else:
            if b % a == 0:
                print("felizmil")
            else:
                print("tristemil")
    else:
        if a > b:
            if (a*2) % b == 0:
                print("felizmil")
            else:
                print("tristemil")
        else:
            if (b*2) % a == 0:
                print("felizmil")
            else:
                print("tristemil")


text:
Q: CSS variables in media queries on Chrome? Does Chrome not support CSS variables within media queries?
I have the following CSS:
:root {
 --threshold-lg: 1200px;
 --threshold-md: 992px;
 --threshold-sm: 768px;
 --sidebar-margins: 10px;
}

@media(min-width: var(--threshold-sm)) {
  .sidebar {
    top: var(--sidebar-margins);
    bottom: var(--sidebar-margins);
  }
}

In both Chrome 50 and Chrome Canary (52), I see no margin adjustment. In Safari 9.1, it works as expected.

A: Sadly CSS variables cannot be used in @media queries.  For more details see the top answer to the question here.  (I would flag these two questions as duplicates if I knew how and had access!)

A:

:root {
 --threshold-lg: 1200px;
 --threshold-md: 992px;
 --threshold-sm: 768px;
 --sidebar-margins: 10px;
}

body {
  background-color: pink;
}
@media(min-width: 300px) {
  .sidebar {
    position: absolute;
    top: var(--sidebar-margins);
    bottom: var(--sidebar-margins);
    background-color: tan;
  }
}

sidebar

Based on this test it seems it is only the media query conditional that has the issue.


text:
Q: Why does Combustion Man keep blowing himself up? According to the Avatar Wikia, Combustion Man was unable to control his power early on and accidentally blew up his arm and leg.
In Avatar: The Last Air Bender, two times he is seen using his power after clearly suffering a head blow and being disoriented:

*

*The first time is when Toph protects herself from Combustion Man's attack and a pebble "coincidentally" hits his third eye. He becomes disoriented and tries to use his power but it backfires on him and and he hurts himself even more. (Why didn't he just run after them...)

*After Sokka hits him in the head with his boomerang, he is heavily disoriented and tries to his power, killing himself in the process.
Why does he keep blowing himself up? Also, how did he survive so long? He's an assassin so clearly he would have had to fight others a lot and I'm sure at some point he would have been hit in his third eye and then the person would have been able to kill Combustion Man while he's disoriented.

A: To preface this, through his interactions with Zuko, It seems that Combustion man has a lot of pride related to his work, given that he refuses to call off a mission, despite his employer (Zuko) calling off the attack. I think this interaction serves as the primary example of his moral code/compass. With that in mind, lets explore some potential answers to your question:

*

*Combustion man is willing to fight through the pain and complete his task no matter the opposition. This could be pride of professionalism, it's really up for you to observe/decide. As this is likely the answer to your question, please keep in mind that he was also fighting children. You could imagine that a professional hit-man would refuse to be bested by a few 12/13 year-olds.

*Reactionary combat. Through disorientation and combat instincts, Combustion man's critical thinking skills are severely impaired, resulting in the aforementioned results of his attacks.


text:
Q: Where to find backend print outs on staging/production? Usually when I have backend print outs, I just look in the console that's running npm run dev. That's for local development, but where do I look for console.log() after pushing to staging or production website?
I'm using react-redux with express and specifically don't know where to look when I console.log() something in a routes file.
Any help is appreciated; thanks in advance :)

A: Just found out that I had to go to heroku. There's a "more" button on the top right that has an option to "view logs" which is where the backend prints out are.


text:
Q: destroying a class instance doesn't kill instances it owns in vala I have a subclass of Gtk.Box that contains a GLib.Timer that fires a notification after a given interval. I have method in this class that calls this.destroy() on the Gtk.Box. The timer continues to run and fires the notification even after its parent instance has been destroyed. All instances of this class that have been destroyed exhibit this behaviour and continue to use CPU and memory untill the process is killed.
How do I fix this? How can I kill instances effectively and how do I manually free memory instead of relying on vala's garbage collection.
edit: here's an (embarrassing) mvce
// mvce_deletable
// nine
// 2017.01.11
// valac --pkg gtk+-3.0 --pkg glib-2.0 deletablebox.vala

using Gtk;
using GLib;

class RemovableBox : Gtk.Box {
    private Gtk.Button delete_button;
    private GLib.Timer timer;
    private Gtk.Label label;

    public RemovableBox () {
        delete_button = new Gtk.Button.with_label ("DESTROY");
        delete_button.clicked.connect (()=>{this.destroy();});
        this.add (delete_button);
        label = new Gtk.Label ("0000000");
        this.add (label);
        timer = new GLib.Timer ();
        timer.start ();
        Timeout.add (50, update);
        this.show_all ();
    }

    private bool update () {
        if (timer.elapsed () > 10.0f) {
            stdout.printf("and yet it breathes\n");
        }
        label.set_text ("%f".printf(timer.elapsed()));
        return true;
    }
}

int main ( string [] args ) {
    Gtk.init(ref args);
    var window = new Gtk.Window ();
    window.destroy.connect (Gtk.main_quit);
    var delete_me = new RemovableBox ();
    window.add ( delete_me );
    window.show_all();
    Gtk.main();
    return 0;
}

I added a timer_id the the RemovableBox class but it still doesn't work as desired.
class RemovableBox : Gtk.Box {
    private Gtk.Button delete_button;
    private uint timeout_id;
    private GLib.Timer timer;
    private Gtk.Label label;

    public RemovableBox () {
        delete_button = new Gtk.Button.with_label ("DESTROY");
        delete_button.clicked.connect (()=>{this.destroy();});
        this.add (delete_button);
        label = new Gtk.Label ("0000000");
        this.add (label);
        timer = new GLib.Timer ();
        timer.start ();
        timeout_id = Timeout.add (40, update);
        this.show_all ();
    }

    ~ RemovableBox () {
        Source.remove (timeout_id);
    }

    private bool update () {
        if (timer.elapsed () > 10.0f) {
            stdout.printf("and yet it breathes\n");
        }
        label.set_text ("%f".printf(timer.elapsed()));
        return true;
    }
}

A: GLib.Timer is a stopwatch that returns the elapsed time. It doesn't generate events, but GLib.Timeout does.
GLib makes use of an event loop. This is the same for GTK+, which uses the same underlying GLib event loop. GLib.Timeout is used to create one kind of event source - a timer that fires after a given interval. When your program creates the event source you are given an identifier for the source. For example:
timer_id = Timeout.add_seconds (1, my_callback_function);
What your program needs to do is store that timer identifier in the object and then when the button click handler is called you can remove the timer as a source of events:
Source.remove (timer_id);
Strictly speaking Vala doesn't have a garbage collection cycle. Other languages will collect references that are no longer used and then remove the resources allocated to them during a clean up cycle. Vala uses reference counting, but it is deterministic. So when an object is no longer used, usually when it goes out of scope, the resources allocated to the object are removed immediately. For normal objects in Vala, rather than compact classes, a destructor is also called when the object is freed. This allows for the resource allocation is initialization (RAII) pattern to be used effectively in Vala.
In general you should not be manually freeing objects, Vala's reference counting is very good. I think it is important to understand GLib's event loop and sources of events to understand what is going on. For a detailed description see GLib's documentation on its main event loop.
Now you have provided a MCVE we can look in detail at how Vala manages memory. If you want to dig deep into what is going on behind the scenes you can use the --ccode switch with valac.
The first line of interest in your program is:
Timeout.add (50, update);
Looking at the C code from valac this line uses the g-timeout-add-full () function:
g_timeout_add_full (G_PRIORITY_DEFAULT, (guint) 50, _removable_box_update_gsource_func, g_object_ref (self), g_object_unref);
The crucial part here is g_object_ref (self). This increases the reference count for the object by one and passes a pointer to the object. This makes a lot of sense, because the update () callback passed in the Vala code makes use of the instance data from the object. Vala is doing the right thing and making sure that the instance data is kept alive while the timer is around. The 'g_object_unref' is called when the source is removed. Here's a modified version of your program putting this understanding in to practise:
// mvce_deletable
// nine
// 2017.01.11
// valac --pkg gtk+-3.0 deletablebox.vala

using Gtk;

class RemovableBox : Gtk.Box {
    private Gtk.Button delete_button;
    private uint timeout_id;
    private GLib.Timer timer;
    private Gtk.Label label;

    public RemovableBox () {
        delete_button = new Gtk.Button.with_label ("DESTROY");
        delete_button.clicked.connect (()=>{this.tidy_up_and_destroy ();});
        this.add (delete_button);
        label = new Gtk.Label ("0000000");
        this.add (label);
        timer = new GLib.Timer ();
        timer.start ();
        timeout_id = Timeout.add (40, update);
        this.show_all ();
    }

    ~ RemovableBox () {
        print ("RemovableBox destructor called\n");
    }

    private bool update () {
        if (timer.elapsed () > 10.0f) {
            stdout.printf("and yet it breathes\n");
        }
        label.set_text ("%f".printf(timer.elapsed()));
        return true;
    }

    private void tidy_up_and_destroy () {
        print ("RemovableBox.tidy_up_and_destroy called\n");
        Source.remove (timeout_id);
        this.destroy ();
    }
}

void main ( string [] args ) {
    Gtk.init(ref args);
    var window = new Gtk.Window ();
    window.window_position = WindowPosition.CENTER;
    window.resize (250,50);
    window.destroy.connect (Gtk.main_quit);
    window.add (new RemovableBox ());
    window.show_all();
    Gtk.main();
}

Previously the program still kept a reference to the RemovableBox object and so was never completely removed. By removing the event source first then calling this.destroy (); it means there are no more references and the object is removed.
There is one other important point here. The lines:
var delete_me = new RemovableBox ();
window.add ( delete_me );

in main () have been changed to:
window.add (new RemovableBox ());

Vala objects exist for the scope of the block they were created in. By assigning the object to delete_me you are keeping a reference to the object for the rest of the main () block. By changing that to be an argument of a method call it is just for the call and so is freed when the button is clicked.
By the way, GLib is automatically included when using valac so there is no need for using GLib; or compiling with --pkg glib-2.0.

A: You are confusing automatic reference couting with full garbage collection.
There is no garbage collector in GLib, but classes have a reference count instead that is increased when a GObject is used in multiple places and decreased when it is no longer used in those places, until it reaches zero. The object is then freed.
In fact in C code the reference counting is manual:
// Reference count is set to 1 on gobject_new
gpointer obj = gobject_new (G_SOME_OBJECT, NULL);
// It can be manually increased when the object is stored in multiple places
// Let's increase the ref count to 2 here
gobject_ref (obj);
// Let's decrease it until it reaches 0
gobject_unref (obj);
gobject_unref (obj);
// Here the object is destroyed (but the pointer is still pointing to the previous memory location, e.g. it is a dangling pointer)
// gobject_clear (obj) can be used in situation where the variable is reused
// It still only unrefs the object by 1 though! In addition it will set obj to NULL

Vala adds the auto to reference counting, which makes it "automatic reference counting" (ARC). That is you don't have to worry about the reference count in Vala, it will add the appropriate ref and unref operations for you.
In full garbage collection (like in C#, Java, ...) memory deallocation is not deterministic, the object can be kept alive even if it isn't used anymore. This is done using something called a "managed heap" and a garbage collector is run in the background (i.e. as a GC thread).
Now that we have the background stuff covered to your actual problem:
You have to remove the Gtk.Box from it's parent container and also set any references you might still have in your Vala code to null in order to get the reference count to 0. It will then be unrefed.
There are of course other options, like disabling the timer, etc. You should really add an MVCE to your question for us to be able to give you some design advice on your code.
PS: Reference counting is often considered as a simple method of garbage collection. That's why I write full garbage collection (also called tracing garbage collection) in order to not confuse the two terms. See the Wikipedia article on garbage collection.


text:
Q: Javascript / jQuery Find & Replace I would like to find:
<input type="button" class=" btn btn-lg btn-info" value="Continue" onclick="loadFinal();">
and replace it with:
<input type="button" class=" btn btn-lg btn-info" value="Continue" onclick="loadFinal(); applyCode();">.
In short, insert applyCode(); to onclick.

A: There are 2 things you can do. Approach 1 would remove all click events from the button and add events, approach 2 would add additional events in addition to the existing event.
Approach 1
$('input:button').unbind('click'); // remove all click events associated
$('input:button').on("click",function() // add new click events
{
  loadFinal();
applyCode();
});

Approach 2
$('input:button').on("click",function() // add additional click events
    {
    applyCode();
    });

UPDATE :
In order to apply or append the applycode() event to the same element that has loadfinal(), you can use $._data to extract the events and check if a certain event exists or not.
$("input:button").click(function() {
    var events = $._data(document.getElementById('btn1'), "events");
    $.each(events,function(i,o)
    {
        alert(i);// give the event type like 'click'
        alert(o); // give the event object - you can extract the event name from the object and do the compare with the existint event.
    });
});

Alternately, you can directly target the click event.
var events = $._data(document.getElementById('btn1'), "events").click;
        $.each(events,function(i,o)
        {
            alert(i);// give the index
            alert(o); // give the event object - you can extract the event name from the object and do the compare with the existint event.
        });
    });

Implementation : http://jsfiddle.net/qk5qj33u/15/

A: I don't think find & replace is what you'd be best using. Instead you can use Javascript to attach events for you. As you've tagged the question with jQuery, try this:
<input type="button" class=" btn btn-lg btn-info" value="Continue">

$(function() {
    $('input[type=button]').click(function() {
        loadFinal();
        applyCode();
    });
});

Note that the above selector is purely for demonstration purposes, you'd be better setting an id attribute, or single specific class on the element and selecting it by that instead. You could even hook to the submit event of the form, assuming this button is used for that purpose.


text:
Q: Magento 2 How to open custom login popup when click of 'Proceed to Checkout' How to add custom login popup when click on 'Proceed to Checkout' button in minicart as well as in checkout/cart.
Thanks in advance.

A: Go to Stores->Configuration->Sales->Checkout
Under the checkout options set "Allow Guest Checkout" to "No".
Clear the cache and check if everything works as you need.
Also you can override the pop up in your theme as per your need.

A: You have to create Mixin on minicart.js and called Magento_Customer/js/model/authentication-popup's showModal method on MiniCart Proceed to checkout button.
MIXIN: https://devdocs.magento.com/guides/v2.4/javascript-dev-guide/javascript/js_mixins.html
Create app/code/{VendorName}/{ModuleName}/view/frontend/requirejs-config.js and add below code:
var config = {
    'config': {
        'mixins': {
            'Magento_Checkout/js/view/minicart': {
                '{VendorName}_{ModuleName}/js/checkout/view/minicart': true
            }
        }
    }
};

Create Mixin Js app/code/{VendorName}/{ModuleName}/view/frontend/web/js/checkout/view/minicart.js
And below code:
define([
    'jquery',
    'Magento_Customer/js/model/authentication-popup',
    'Magento_Customer/js/customer-data'
], function ($, authenticationPopup, customerData
) {
    'use strict';

    return function (Component) {
        return Component.extend({

            /**
             * @override
             */
            getCartParam: function (name) {
                var self = this;

                if(name === 'possible_onepage_checkout'){
                    $('#top-cart-btn-checkout').click(function (event) {
                        var customer = customerData.get('customer');
                        if (!customer().firstname) {
                            event.preventDefault();
                            authenticationPopup.showModal();
                            return false;
                        }
                    });

                }
                return this._super(name);
            },
        });
    }
});


text:
Q: Javascript - Fork async generator Say I have an async generator, like this:
// This could be records from an expensive db call, for example...
// Too big to buffer in memory
const events = (async function* () {
    await new Promise(r => setTimeout(r, 0));
    yield {type:'bar', ts:'2021-01-01 00:00:00', data:{bar:"bob"}};
    yield {type:'foo', ts:'2021-01-02 00:00:00', data:{num:2}};
    yield {type:'foo', ts:'2021-01-03 00:00:00', data:{num:3}};
})();

How can I copy it to acheive something like:
function process(events) {

    async function* filterEventsByName(events, name) {
        for await (const event of events) {
            if (event.type === name) continue;
            yield event;
        }
    }

    async function* processFooEvent(events) {
        for await (const event of events) {
            yield event.data.num;
        }
    }

    // How to implement this fork function?
    const [copy1, copy2] = fork(events);

    const foos = processFooEvent(filterEventsByName(copy1, 'foo'));
    const bars = filterEventsByName(copy2, 'bar');

    return {foos, bars};
}

const {foos, bars} = process(events);

for await (const event of foos) console.log(event);
// 2
// 3

for await (const event of bars) console.log(event);
// {type:'bar', ts:'2021-01-01 00:00:00', data:{bar:"bob"}};

A: I have a solution using Highland as an intermediary.
Note that (from the docs):

A stream forked to multiple consumers will pull values, one at a time, from its source as only fast as the slowest consumer can handle them.

import _ from 'lodash'
import H from 'highland'

export function fork<T>(generator: AsyncGenerator<T>): [
    AsyncGenerator<T>,
    AsyncGenerator<T>
] {
    const source = asyncGeneratorToHighlandStream(generator).map(x => _.cloneDeep(x));
    return [
        highlandStreamToAsyncGenerator<T>(source.fork()),
        highlandStreamToAsyncGenerator<T>(source.fork()),
    ];
}

async function* highlandStreamToAsyncGenerator<T>(
    stream: Highland.Stream<T>
): AsyncGenerator<T> {
    for await (const row of stream.toNodeStream({ objectMode: true })) {
        yield row as unknown as T;
    }
}

function asyncGeneratorToHighlandStream<T>(
    generator: AsyncGenerator<T>
): Highland.Stream<T> {
    return H(async (push, next) => {
        try {
            const result = await generator.next();
            if (result.done) return push(null, H.nil);
            push(null, result.value);
            next();
        } catch (error) {
            return push(error);
        }
    });
}

Would love to see alternative solutions without a library, or with another library.


text:
Q: How do I store an array into an element of ArrayList? Robentry [] Rb = new Robentry[robNum];

How can I store Rb into an ArrayList<E> Rt, so that Rt.get(0) == Rb is true. I do not know how to define E in the ArrayList<E>.
Edit:
If I use :
Robentry [] Rb = new Robentry[robNum];
List<Robentry []> Rt = new  ArrayList<Robentry []>();
// initialize Rb
//...
//
Rt.add(Rb);

If I change Rb[0], Rt.get(0)[0] is also changed. So how can I store the content of Rb into Rt so that Rt is independent of Rb?

A: ArrayList<Robentry[]> arrList sounds like what you want.
This means arrList is a List (or ArrayList) of Robentry[].

A: you can use Type Robentry[] to a List. like -
List<Robentry []> list = new ArrayList<Robentry []>();

A: You can declare and use the List of type Robentry[] as below:
    //Declare a list of type Robentry[]
    List<Robentry[]> list = new ArrayList<Robentry []>();
    //add the rb to the list
    list.add(Rb);

    //compare the list element with Rb
    System.out.println(list.get(0)==Rb);//should print true

Please note: == is fine in above example since list element is same as Rb, otherwise equals method is recommended.

A:  ArrayList<Robentry> Rt=(ArrayList<Robentry>) Arrays.asList(Rb);

or in your ways,
ArrayList<Robentry[]> Rt=new ArrayList<Robentry[]>();
rt.add(Rb);

This is called Generics,was made to ensure that the variable should contain only specific types.See this for official docs.

A: Based on your modified question, you probably want
Rt.add(Rb.clone());

or
Rt.add(Arrays.copyOf(Rb, Rb.length));

Array references are passed around by value, so you have to do an explicit copy if you want the arrays to be independent of one another.


text:
Q: Secured annotaion I've got a servlet that handles POST and GET requests. GET requests are available for everyone, but POST requests are for ROLE_ADMIN only. If I annotate my method with @Secured("ROLE_ADMIN"), regular user will catch

405 Request method 'POST' not supported

How can I make my servlet throw 403 instead?


text:
Q: how to display recently viewed products in cms block and call it in details page? I wanted to display the recently viewed products in the cms/block and call it in product details page.
This is the line I gave in cms/block:
<p>{{block type="reports/product_viewed"template="reports/product_viewed.phtml"}}</p>
And in view.phtml I included this part:
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('product_details_tab')->toHtml() ?>

But nothing is getting displayed. Where have I went wrong?

A: call this in your phtml instead
<?php echo $this->getLayout()->createBlock('reports/product_viewed')->setTemplate('reports/product_viewed.phtml')->toHtml(); ?>

A: Your code looks ok
  1. Do Re-Indexing from Admin > System > Index Management.
 2. Refresh Statics from Admin > Report > Products > Most Viewed.
 3. Check Recently Viewed/Compared Products count from
System -> Configuration -> Catalog -> Recently Viewed/Compared Products
 4. Refresh Cache
Now try.


text:
Q: All minimal Levenshtein Distance solutions in C I'm supposed to compute the Levenshtein distance of two strings in C.
I have successfully created the matrix and returned the correct Levenshtein Distance, however, now I also need to print all different possible solutions for the minimal Levenshtein Distance
I am trying to do this recursively but I fail everytime.

Here's the code for what I most recently tried:
void printLevenshteinSolutions(int const matrix[], int rows, int cols, int r, int c, char* solution){

    if((r==0) && (c==0)){
        printf("Solution found:\t|%s|\n", solution);
        solutionCount++;
    }
    else{
        int currentIndex = convertMatrixIndex(r, c, cols);
        int leftIndex = convertMatrixIndex(r-1, c, cols);
        int topIndex = convertMatrixIndex(r, c-1, cols);
        int diagonalIndex = convertMatrixIndex(r-1, c-1, cols);
        char oldSolution[MAX];
        strcpy(oldSolution, solution);

        if(matrix[currentIndex] >= matrix[leftIndex]){
            if((matrix[leftIndex]<=matrix[topIndex]) && (matrix[leftIndex]<=matrix[diagonalIndex])){
                strcat(solution, "d");
                if((r-1>=0))
                    printLevenshteinSolutions(matrix, rows, cols, r-1, c, solution);
                strcpy(solution, oldSolution);
            }
        }
        if(matrix[currentIndex] >= matrix[topIndex]){
            if((matrix[topIndex]<=matrix[leftIndex]) && (matrix[topIndex]<=matrix[diagonalIndex])){
                strcat(solution, "i");
                if((c-1>=0))
                    printLevenshteinSolutions(matrix, rows, cols, r, c-1, solution);
                strcpy(solution, oldSolution);

            }
        }
        if(matrix[currentIndex] >= matrix[diagonalIndex]){
            if((matrix[diagonalIndex]<=matrix[topIndex]) && (matrix[diagonalIndex]<=matrix[leftIndex])){
                if(matrix[currentIndex] > matrix[diagonalIndex]){
                    strcat(solution, "c");
                }
                else{
                    strcat(solution, " ");
                }
                if((c-1>=0)&&(r-1>=0))
                    printLevenshteinSolutions(matrix, rows, cols, r-1, c-1, solution);
                strcpy(solution, oldSolution);
            }
        }

    }
}

This will now output the solution the wrong way around, which I can fix, however the bigger problem is the solutions simply not being correct.
UPDATE::
I am trying to compute possible paths from the bottom right to the top left of the matrix.
I don't just want any paths!
Any connection from one cell to another MUST be going left, top or the top left
Furthermore it also must only go to the minimal values of those three neighboring cells.
e.g:
012
134
234
Here the bottom 4 has to connect with the 3 on its left for one possible solution.
It also has to connect to the 3 diagonally to the left of it for another possible solution.
It must not include the path from the bottom 4 to the top 4 since 4 > 3


text:
Q: Dynamic route/ Param doesn't work in coreui-free-react-admin-template Dynamic route doesn't work in coreui-free-react-admin-template
const routes = [

{ path: '/users/details/:id', exact: true, name: 'Users Details', component: UsersDetails },

]

A: You will also need to add the following import:
import { matchPath } from 'react-router-dom'

Then add on the page AppBreadcrumb.js
  const getRouteName = (pathname, routes) => {
    for (var i = 0; i < routes.length; i++) {
      var routePath = routes[i]
      if (matchPath(pathname, { path: routePath.path, exact: true, strict: false })) {
        return routePath.name
      }
    }
    return null
  }

  const getBreadcrumbs = (location) => {
    const breadcrumbs = []
    location.split('/').reduce((prev, curr, index, array) => {
      const currentPathname = `${prev}/${curr}`
      const routeName = getRouteName(currentPathname, routes)
      if (routeName) {
        breadcrumbs.push({
          pathname: currentPathname,
          name: routeName,
          active: index + 1 === array.length ? true : false,
        })
      }
      return currentPathname
    });
    return breadcrumbs
  }


text:
Q: Ruby on Rails + PostgreSQL app fails to start on AWS EC2. Error is: "cannot load such file -- pg_ext (LoadError)" I began by installing all these dependencies:
sudo yum install ruby19 ruby19-devel gem rubygems19-devel make gcc postgresql9 postgresql9-devel postgresql9-server

Then I switch to the root user and I run
bundle install

and I get the green success message:
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.

However, when I cd to the dir and run
rails s -p80

it I get all this and it fails to start (I'm still root because bind won't work to port 80 if I'm not root):
/usr/local/share/gems/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `require': cannot load such file -- pg_ext (LoadError)
    from /usr/local/share/gems/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `block in require'
    from /usr/local/share/gems/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:236:in `load_dependency'
    from /usr/local/share/gems/gems/activesupport-3.2.8/lib/active_support/dependencies.rb:251:in `require'
    from /usr/local/share/gems/gems/pg-0.14.0/lib/pg.rb:4:in `<top (required)>'
    from /usr/local/share/gems/gems/bundler-1.2.0/lib/bundler/runtime.rb:68:in `require'
    from /usr/local/share/gems/gems/bundler-1.2.0/lib/bundler/runtime.rb:68:in `block (2 levels) in require'
    from /usr/local/share/gems/gems/bundler-1.2.0/lib/bundler/runtime.rb:66:in `each'
    from /usr/local/share/gems/gems/bundler-1.2.0/lib/bundler/runtime.rb:66:in `block in require'
    from /usr/local/share/gems/gems/bundler-1.2.0/lib/bundler/runtime.rb:55:in `each'
    from /usr/local/share/gems/gems/bundler-1.2.0/lib/bundler/runtime.rb:55:in `require'
    from /usr/local/share/gems/gems/bundler-1.2.0/lib/bundler.rb:128:in `require'
    from /home/user/TransForm/config/application.rb:7:in `<top (required)>'
    from /usr/local/share/gems/gems/railties-3.2.8/lib/rails/commands.rb:53:in `require'
    from /usr/local/share/gems/gems/railties-3.2.8/lib/rails/commands.rb:53:in `block in <top (required)>'
    from /usr/local/share/gems/gems/railties-3.2.8/lib/rails/commands.rb:50:in `tap'
    from /usr/local/share/gems/gems/railties-3.2.8/lib/rails/commands.rb:50:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

Perhaps there is an easy way to just deploy it correctly from the begining instead of messing around with error craps?  I need PostgreSQL.  This app works everywhere except this AWS EC2 instance, so I know my Gemfile is correct.  Any clues would help.

A: open irb & type require "pg" does it work? if not, then check that pg_ext exists in /usr/local/share/gems/gems/pg-0.14.0/lib/ directory.   you can install manually postgresql gem manually, using
gem install pg

If this still doesn't work, ensure that you are using latest version of ruby & latest version of rubygems using gem environment command.if its the older version, you can install latest ones using rvm

A:         use gem pg
            than
             bundle install
             bundle update
               please not use any version of pg
       I face this error and solved by this


text:
Q: Stop VC++ debugger stepping into operator new It's really annoying when stepping through code and everytime a new object is created, the debugger doesn't go straight to the constructor but through the CRT new operator in new.cpp:
void *__CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc)
        {       // try to allocate size bytes
        void *p;
        while ((p = malloc(size)) == 0)
                if (_callnewh(size) == 0)
                {       // report no memory
                static const std::bad_alloc nomem;
                _RAISE(nomem);
                }

        return (p);
        }

Is there a way to selectively stop specific functions/classes getting stepped into, or some other way I can avoid this?

A: Andy Pennell's blog entry "How to Not Step Into Functions using the Visual C++ Debugger"  provides most of the answer.  I was trying to figure this out as well and through perseverance (or perversity I guess) I tried each letter of the alphabet until I got a hit with o.*=nostepinto.
From that, noticing in the Modules window it said msvcr100d.dll!operator new, led me to try "operator new.*" as the regular expression.
It worked!  The magic to put in for Andy's how to is "operator new.*=nostepinto"
n.b.  I was using VS 2010, but the same should work on VS 2008

A: Visual studio has a feature where you can choose which function to step into.
So if you have code like this:
foo* p = new foo( new baz ( new flip() ) );
You right click to bring up the pop-up menu. From there select 'Step into', and it will give you a list of functions you can step into. So here you can avoid all the new calls, and have your choice of which constructor you step into.