text:
Q: FB.ui() ignoring the "to" property Has anyone experienced the situation where the "to" property of FB.ui gets ignored - even if it's set - and the post only goes to the wall of the currently logged in user?
When working with a completely stripped down test page that uses the FB sample code (and hard-coded parameter values) it posts to my wall as expected. But when I add "to" property to this FB code, it still only posts to my wall.
Any ideas would be greatly appreciated, as I have trawled these archives and the FB dev site in what I believe to be a thorough way.
The SDK loads properly and the iframe pops up (though it scrolls to the top of the page).
Here's the stripped down code used in my test page:
$("#well").click(function(e) {
  FB.ui(
  {
   method: 'feed',
   to: '***', /* <=== this person is a confirmed friend with appropriate privacy settings */
   name: 'The Facebook SDK for Javascript',
   caption: 'Bringing Facebook to the desktop and mobile web',
   description: (
      'A small JavaScript library that allows you to harness ' +
      'the power of Facebook, bringing the user\'s identity, ' +
      'social graph and distribution power to your site.'
   ),
   link: 'https://developers.facebook.com/docs/reference/javascript/',
   picture: 'http://www.fbrell.com/public/f8.jpg'
  },
  function(response) {
    if (response && response.post_id) {
      alert('Post was published.');
    } else {
      alert('Post was not published.');
    }
  }
);

Thanks in advance.
# # UPDATE # #
Thanks to Sahil Mittal's contributions I worked out this fairly reasonable solution:
`
var jqxhr = $.get( "http://graph.facebook.com/"+$("#fbto").val()+"?fields=id", function( data ) {
 // could do something useful here...
})

.done(function(  data ) {
  // do something else useful useful, in this case finish posting stuff to the wall
})

.fail(function(  data ) {
 // thrown if the user doesn't exist
})

.always(function(  data ) {
  // etc...
})

`
Now, this is a jQuery 1.8.* solution, and I should also add that in a high-traffic scenario I'm not sure how kindly FB would take to hammering on their URL to convert submitted usernames to ids. But that's a bridge I'll happily cross if we get there!
Thanks again to Sahil.

A: You cannot use username in the to parameter. You have to use id instead.
If you dont have the id, you can get that from the username itself. Make the call /{username}?fields=id and you'll get the id in response.
For eg: http://graph.facebook.com/sahilmittal?fields=id.
The response is:
{
  id: "595273610"
}

Just get this id and use it in the to parameter.


text:
Q: changing the color of a link I want to change the accordion based on clicking a link .It is working fine.The demo is shown in the following link http://jsfiddle.net/kufi/qp5Mg/
Now,I want to change the color of link that clicked(here from red to green).If I click a link it is changing from red to green .If i Click second link the first link remains in green only,It should be changed to red.
Thanks in advance

A: $(".accordion-opener").click(function(e) {
    $(".accordion-opener").removeClass('green');
    $(this).addClass('green');
    e.preventDefault();
});

Make use of the addClass and removeClass, Demo:
http://jsfiddle.net/qp5Mg/2/

A: You should add:
<style>
  .clicked{
    color: green;
  }
</style>

And, in js:
$(".accordion-opener").click(function(){
  ...
  $(this).addClass("clicked");
});

EDIT: I've updated your fiddle with this code and is working OK: http://jsfiddle.net/qp5Mg/6/
Hope this helps. Cheers

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert csv to Json to send to watson-personality insight API with Python I am trying to convert a csv which contains some reviews that I've extracted. I need to convert to a Json as input to IBM watson personality insights.
The csv (WordFinal.csv) with the reviews is like this:
ID,Review,advice,con,date,employeeType,overallStar,position,pro,reviewLink,reviewNo,summary
3,ive been with amazon for 3 years before i finally resigned i started directly out of college as an area manager and promoted once a year to operation manager and was starting to get tapped for senior operations manager the progression at this company is unbelievable and growth potential is nearly limitless you get to work with a highly dedicated team that strives to raise the bar dont get me wrong you may come across individuals who also do the minimum and cut corners to get results but that is the case anywhere i was able to lead teams of up to 700 associates and indirectly oversee 1500 associates during the holiday season all at the age of 25 i was able to influence shift wide department wide building wide and even region wide procedures processes decisions for the company . my only con was the work life balance i was put on nights my entire time with amazon in order to continue to help the lower performing shifts and this would lead to having a daily schedule of wake up go straight to work usually forget to eat leave after 14 hours go to the gym eat maybe sleep wake up after 4 5 hours do it again based on location your leadership team s culture may vary drastically in california i had an extremely supportive senior and general manager team once i came to new jersey the senior team was pretty blind to their own operation super focused on creating reports continuous innovation projects in excel sheets versus just letting us go out there and do the actual improvements there was an extremely slow uptake on just do it recommendations and it was highly evident that this mentality was built into the department as well so again take it with a grain of salt ,"Cali - keep it up, you have culture nailedJersey - This is amazon, you can't raise the bar at amazon without actually being innovating and taking big steps to change things up.",my only con was the work life balance i was put on nights my entire time with amazon in order to continue to help the lower performing shifts and this would lead to having a daily schedule of wake up go straight to work usually forget to eat leave after 14 hours go to the gym eat maybe sleep wake up after 4 5 hours do it again based on location your leadership team s culture may vary drastically in california i had an extremely supportive senior and general manager team once i came to new jersey the senior team was pretty blind to their own operation super focused on creating reports continuous innovation projects in excel sheets versus just letting us go out there and do the actual improvements there was an extremely slow uptake on just do it recommendations and it was highly evident that this mentality was built into the department as well so again take it with a grain of salt ," Nov 9, 2017",Former Employee - Operations Manager,3,I worked at Amazon full-time (More than 3 years),ive been with amazon for 3 years before i finally resigned i started directly out of college as an area manager and promoted once a year to operation manager and was starting to get tapped for senior operations manager the progression at this company is unbelievable and growth potential is nearly limitless you get to work with a highly dedicated team that strives to raise the bar dont get me wrong you may come across individuals who also do the minimum and cut corners to get results but that is the case anywhere i was able to lead teams of up to 700 associates and indirectly oversee 1500 associates during the holiday season all at the age of 25 i was able to influence shift wide department wide building wide and even region wide procedures processes decisions for the company ,https://www.glassdoor.com/Reviews/Amazon-Reviews-E6036.htm/Reviews/Employee-Review-Amazon-RVW17818923.htm,empReview_17818923,Take it with a grain of salt
19, company is on an unstoppable growth trajectory amazons business model is incredible is riding a number of secular trends ecommerce cloud ai and the stock is a winner employees are making more money than expected leadership principles drive a high performance culture that focuses on customers it feels great to work on products that customers love you get to work on very difficult problems with smart people once you establish yourself as a high performer you have a high level of job security and internal mobility teams are constantly hiring and building really innovative things and you are encouraged to move around and explore teams tend to be lean and you will be asked to learn a lot quickly ownership is highly valued office environment is really desirable located in a great downtown seattle neighborhood many people walk to work bring dogs to the office and restaurants and bars are very accessible amazon veterans tend to be incredibly talented individuals and other companies realize it being successful at amazon is well respected in the industry .  work life balance can be a challenge work demands are high and teams are often too lean you have to set your own boundaries even with kind managers overachievers will feel under water frugality as a core value goes overboard if amazon doesn t have to give it you it won t no perks no free food or drinks bad coffee unsubsidized cafeterias mediocre hardware for non technical people there doesn t seem to be a morale budget and you will have few official team outings compensation policies are not employee friendly 401k matching is subpar once your signing cash bonus is fully vested your entire compensation will be base salary and stock base salary is capped at 160k across the company stock vests twice a year if you re below a director so your compensation is very lumpy stock price appreciation is taken into consideration in your total compensation targets ie if the value of previously offered shares increases the company will count that as a raise and might not grant you additional stock bonuses despite strong performance ,None, work life balance can be a challenge work demands are high and teams are often too lean you have to set your own boundaries even with kind managers overachievers will feel under water frugality as a core value goes overboard if amazon doesn t have to give it you it won t no perks no free food or drinks bad coffee unsubsidized cafeterias mediocre hardware for non technical people there doesn t seem to be a morale budget and you will have few official team outings compensation policies are not employee friendly 401k matching is subpar once your signing cash bonus is fully vested your entire compensation will be base salary and stock base salary is capped at 160k across the company stock vests twice a year if you re below a director so your compensation is very lumpy stock price appreciation is taken into consideration in your total compensation targets ie if the value of previously offered shares increases the company will count that as a raise and might not grant you additional stock bonuses despite strong performance ," Oct 29, 2016",Current Employee - Product Manager,4,I have been working at Amazon full-time (More than 3 years), company is on an unstoppable growth trajectory amazons business model is incredible is riding a number of secular trends ecommerce cloud ai and the stock is a winner employees are making more money than expected leadership principles drive a high performance culture that focuses on customers it feels great to work on products that customers love you get to work on very difficult problems with smart people once you establish yourself as a high performer you have a high level of job security and internal mobility teams are constantly hiring and building really innovative things and you are encouraged to move around and explore teams tend to be lean and you will be asked to learn a lot quickly ownership is highly valued office environment is really desirable located in a great downtown seattle neighborhood many people walk to work bring dogs to the office and restaurants and bars are very accessible amazon veterans tend to be incredibly talented individuals and other companies realize it being successful at amazon is well respected in the industry ,https://www.glassdoor.com/Reviews/Amazon-Reviews-E6036.htm/Reviews/Employee-Review-Amazon-RVW12494284.htm,empReview_12494284,Incredible growth opportunity with downsides

The format accepted by IBM-Watson is as follows:
    {
   "contentItems": [
      {
         "content": "Wow, I liked @TheRock before, now I really SEE how special he is. The daughter story was IT for me. So great! #MasterClass",
         "contenttype": "text/plain",
         "created": 1447639154000,
         "id": "666073008692314113",
         "language": "en"
      },
      {
         "content": ".@TheRock how did you Know to listen to your gut and Not go back to football? #Masterclass",
         "contenttype": "text/plain",
         "created": 1447638226000,
         "id": "666069114889179136",
         "language": "en"
      },
      {
         "content": ".@TheRock moving back in with your parents so humbling. \" on the other side of your pain is something good if you can hold on\" #masterclass",
         "contenttype": "text/plain",
         "created": 1447638067000,
         "id": "666068446325665792",
         "language": "en"
      }
   ]
}

I'm trying to generate the output as IBM-watson accept it, but I can't figure out how can i achieve such task. The code below:
import json, csv

csvfile = 'C:\\WordFinal.csv'
jsonfile = 'C:\\OutputJ.json'

fieldnames=['ID','summary']
data= {}
with open(csvfile) as cs:
    #reader = csv.DictReader(cs)
    reader = csv.DictReader(cs, fieldnames)
    for row in reader:
    csvid = row["ID"]
    data[csvid] = row

with open(jsonfile, "w",encoding='utf8') as js:
    js.write(json.dumps(data,indent=2))

And the output (I only need ID and summary columns from my csv - first and last column):
   {
  "ID": {
    "ID": "ID",
    "summary": "Review",
    "null": [
      "advice",
      "con",
      "date",
      "employeeType",
      "overallStar",
      "position",
      "pro",
      "reviewLink",
      "reviewNo",
      "summary"
    ]
  },
  "3": {
    "ID": "3",
    "summary": "ive been with amazon for 3 years before i finally resigned i started directly out of college as an area manager and promoted once a year to operation manager and was starting to get tapped for senior operations manager the progression at this company is unbelievable and growth potential is nearly limitless you get to work with a highly dedicated team that strives to raise the bar dont get me wrong you may come across individuals who also do the minimum and cut corners to get results but that is the case anywhere i was able to lead teams of up to 700 associates and indirectly oversee 1500 associates during the holiday season all at the age of 25 i was able to influence shift wide department wide building wide and even region wide procedures processes decisions for the company . my only con was the work life balance i was put on nights my entire time with amazon in order to continue to help the lower performing shifts and this would lead to having a daily schedule of wake up go straight to work usually forget to eat leave after 14 hours go to the gym eat maybe sleep wake up after 4 5 hours do it again based on location your leadership team s culture may vary drastically in california i had an extremely supportive senior and general manager team once i came to new jersey the senior team was pretty blind to their own operation super focused on creating reports continuous innovation projects in excel sheets versus just letting us go out there and do the actual improvements there was an extremely slow uptake on just do it recommendations and it was highly evident that this mentality was built into the department as well so again take it with a grain of salt ",
    "null": [
      "Cali - keep it up, you have culture nailedJersey - This is amazon, you can't raise the bar at amazon without actually being innovating and taking big steps to change things up.",
      "my only con was the work life balance i was put on nights my entire time with amazon in order to continue to help the lower performing shifts and this would lead to having a daily schedule of wake up go straight to work usually forget to eat leave after 14 hours go to the gym eat maybe sleep wake up after 4 5 hours do it again based on location your leadership team s culture may vary drastically in california i had an extremely supportive senior and general manager team once i came to new jersey the senior team was pretty blind to their own operation super focused on creating reports continuous innovation projects in excel sheets versus just letting us go out there and do the actual improvements there was an extremely slow uptake on just do it recommendations and it was highly evident that this mentality was built into the department as well so again take it with a grain of salt ",
      " Nov 9, 2017",
      "Former Employee - Operations Manager",
      "3",
      "I worked at Amazon full-time\u00c2\u00a0(More than 3 years)",
      "ive been with amazon for 3 years before i finally resigned i started directly out of college as an area manager and promoted once a year to operation manager and was starting to get tapped for senior operations manager the progression at this company is unbelievable and growth potential is nearly limitless you get to work with a highly dedicated team that strives to raise the bar dont get me wrong you may come across individuals who also do the minimum and cut corners to get results but that is the case anywhere i was able to lead teams of up to 700 associates and indirectly oversee 1500 associates during the holiday season all at the age of 25 i was able to influence shift wide department wide building wide and even region wide procedures processes decisions for the company ",
      "https://www.glassdoor.com/Reviews/Amazon-Reviews-E6036.htm/Reviews/Employee-Review-Amazon-RVW17818923.htm",
      "empReview_17818923",
      "Take it with a grain of salt"
    ]
  },
  "19": {
    "ID": "19",
    "summary": " company is on an unstoppable growth trajectory amazons business model is incredible is riding a number of secular trends ecommerce cloud ai and the stock is a winner employees are making more money than expected leadership principles drive a high performance culture that focuses on customers it feels great to work on products that customers love you get to work on very difficult problems with smart people once you establish yourself as a high performer you have a high level of job security and internal mobility teams are constantly hiring and building really innovative things and you are encouraged to move around and explore teams tend to be lean and you will be asked to learn a lot quickly ownership is highly valued office environment is really desirable located in a great downtown seattle neighborhood many people walk to work bring dogs to the office and restaurants and bars are very accessible amazon veterans tend to be incredibly talented individuals and other companies realize it being successful at amazon is well respected in the industry .  work life balance can be a challenge work demands are high and teams are often too lean you have to set your own boundaries even with kind managers overachievers will feel under water frugality as a core value goes overboard if amazon doesn t have to give it you it won t no perks no free food or drinks bad coffee unsubsidized cafeterias mediocre hardware for non technical people there doesn t seem to be a morale budget and you will have few official team outings compensation policies are not employee friendly 401k matching is subpar once your signing cash bonus is fully vested your entire compensation will be base salary and stock base salary is capped at 160k across the company stock vests twice a year if you re below a director so your compensation is very lumpy stock price appreciation is taken into consideration in your total compensation targets ie if the value of previously offered shares increases the company will count that as a raise and might not grant you additional stock bonuses despite strong performance ",
    "null": [
      "None",
      " work life balance can be a challenge work demands are high and teams are often too lean you have to set your own boundaries even with kind managers overachievers will feel under water frugality as a core value goes overboard if amazon doesn t have to give it you it won t no perks no free food or drinks bad coffee unsubsidized cafeterias mediocre hardware for non technical people there doesn t seem to be a morale budget and you will have few official team outings compensation policies are not employee friendly 401k matching is subpar once your signing cash bonus is fully vested your entire compensation will be base salary and stock base salary is capped at 160k across the company stock vests twice a year if you re below a director so your compensation is very lumpy stock price appreciation is taken into consideration in your total compensation targets ie if the value of previously offered shares increases the company will count that as a raise and might not grant you additional stock bonuses despite strong performance ",
      " Oct 29, 2016",
      "Current Employee - Product Manager",
      "4",
      "I have been working at Amazon full-time\u00c2\u00a0(More than 3 years)",
      " company is on an unstoppable growth trajectory amazons business model is incredible is riding a number of secular trends ecommerce cloud ai and the stock is a winner employees are making more money than expected leadership principles drive a high performance culture that focuses on customers it feels great to work on products that customers love you get to work on very difficult problems with smart people once you establish yourself as a high performer you have a high level of job security and internal mobility teams are constantly hiring and building really innovative things and you are encouraged to move around and explore teams tend to be lean and you will be asked to learn a lot quickly ownership is highly valued office environment is really desirable located in a great downtown seattle neighborhood many people walk to work bring dogs to the office and restaurants and bars are very accessible amazon veterans tend to be incredibly talented individuals and other companies realize it being successful at amazon is well respected in the industry ",
      "https://www.glassdoor.com/Reviews/Amazon-Reviews-E6036.htm/Reviews/Employee-Review-Amazon-RVW12494284.htm",
      "empReview_12494284",
      "Incredible growth opportunity with downsides"
    ]
  }
}

Any idea how can I get the right format?

A: So I find pandas much easier to work with.
First start with creating a dataframe that has your csv information (assumption your file is in a good format).
import pandas as pd
df = pd.read_csv('WordFinal.csv')

Then you can iterate the dataframe.
records = []
for index, row in df.iterrows():
    rec = {
        row['ID']: {
            'ID': row['ID'],
            'summary': row['summary']
            # ... etc
        }
    }

    records.append(rec)

Your records object will contain the JSON code you can save.

A: If you dont need anything other than summary, just store only summary in data
with open(csvfile) as cs:
    reader = csv.DictReader(cs, fieldnames)
    first_row = next(reader)             # skip reading the header line
    for row in reader[:
        csvid = row["ID"]
        data[csvid] = row['summary']     # just store the summary

A: Don't specify the field names. Pull out the ones you want from the full records:
with open(csvfile, "r", encoding="utf-8") as infile:
    reader = csv.DictReader(infile)

    with open(jsonfile, "w", encoding="utf-8") as outfile:
        outfile.write(json.dumps([{"ID": row["ID"], "summary": row["summary"]} for row in reader], indent=2))

Gives:
[
  {
    "ID": "3",
    "summary": "Take it with a grain of salt"
  },
  {
    "ID": "19",
    "summary": "Incredible growth opportunity with downsides"
  }
]


text:
Q: Displaying labels created using LabelLayer only at certain scales in ArcGIS API for JavaScript I am using ESRI Javascript 3.7 framework to develop a map application, in it I am trying to display labels created using LabelLayer at certain scales only, say from 1:1 to 1:500 scale only.
How can I achieve this?
I played a little with ScaleDependentRenderer but it results in 2 firebug exceptions. Not sure if the ScaleDependentRenderer is the right answer or not.
var occupancyLabelLayer = new esri.layers.LabelLayer({ id: "labels" });
// add the label layer to the map
map.addLayer(occupancyLabelLayer);

var labelField = "FLOOR";
// create a text symbol to define the style of labels

var spaceLabelColor = new dojo.Color("red");
var spaceOccupancyLabel = new esri.symbol.TextSymbol().setColor(spaceLabelColor);
//spaceOccupancyLabel.font.setSize("14pt");
spaceOccupancyLabel.font.setFamily("arial");
var spaceOccupancyLabelRenderer = new esri.renderer.SimpleRenderer(spaceOccupancyLabel);

var spaceLabelScaleDependentRenderer = new ScaleDependentRenderer({
    rendererInfos: [{
        renderer: spaceOccupancyLabelRenderer,
        minScale: 500,
        maxScale: 1
    }]
});

occupancyLabelLayer.addFeatureLayer(featureLayer, spaceLabelScaleDependentRenderer, "${" + labelField + "}");

Firebug Exceptions:
1)exception in animation handler for: onEnd
http://js.arcgis.com/3.7/ (line 45)
2)TypeError: b is undefined
http://js.arcgis.com/3.7/js/esri/layers/LabelLayer.js    Line 21

A: All layers in the API support minScale and maxScale (and all tiled layers have minZoom and maxZoom) constructor options. The label layer API ref should document this, I'll make sure we get that updated.
Instead of using a scale dependent renderer, use minScale and maxScale to specify your scales (note that since we're talking scales, max scale is the smaller number as that represents a large scale where more area is visible). Here's an example (zoom in to see labels, if you're on a small screen you might need to zoom in twice):  http://jsbin.com/aCicEhe
Relevant code:
var labels = new LabelLayer({
  id: "labels",
  minScale: 10000000,
  maxScale: 0
});


text:
Q: Cost for a Trucking Company Imagine you are the manager of a trucking company. One employee is to drive a truck down a $400$ mile road that has a minimum speed limit of $40$ mph and a maximum speed limit of $70$ mph. You have to pay him $\$6$ per hour, and the cost of operating the truck (in cents, not including the wages) is $12+\dfrac{x}{6}$, where $x$ is the speed of the truck in mph. What driving speed costs the least for this road?
The equations I have are $C_1(x)=12+\dfrac{x}{6}$ and $C_2(x)=600\times\dfrac{400}{x}$. These equations have different units, so how can I combine them to optimize?

A: I realize this is over three years late, but hopefully someone else will stumble across this answer and find it helpful!

The equations do in fact have the same units! They look something like this (dividing everything by $100$ to work with dollars instead of cents):
\begin{align}
C_1(x)&=\frac{1}{100}(\text{cents}+\text{cents}) \\[0.2ex]
&=\text{dollars}+\text{dollars} \\
&=\text{dollars} \\
C_2(x)&=\frac{1}{100}\left(\frac{\text{cents}}{\text{hour}}\times\frac{\text{miles}}{\frac{\text{miles}}{\text{hour}}}\right) \\[0.3ex]
&=\frac{1}{100}\left(\frac{\text{cents}}{\text{hour}}\times\text{hours}\right) \\
&=\frac{1}{100}(\text{cents}) \\[0.5ex]
&=\text{dollars}
\end{align}
Armed with this information, we can now add the two cost functions to find the total cost function:
\begin{align}
C(x)&=\frac{1}{100}\Big(C_1(x)+C_2(x)\Big) \\[0.4ex]
&=\frac{1}{100}\left(12+\frac{x}{6}+\frac{240000}{x}\right) \\[0.3ex]
&\bbox[5px,border:1px solid red]{=\frac{2400}{x}+\frac{x}{600}+\frac{3}{25}}
\end{align}
As always in single-variable optimization problems, we can now set $C'(x)$ equal to $0$ and find the points at which cost is minimized:
\begin{align}
-\frac{2400}{x^2}+\frac{1}{600}&=0 \\[0.2ex]
\frac{2400}{x^2}&=\frac{1}{600} \\
x^2&=1440000 \\
x&=1200
\end{align}
Wait, what? Weren't we supposed to get an answer in miles per hour that was between $40$ and $70$?
Not necessarily. All this answer means is that cost would be minimized if the truck were to drive at $1200$ mph, but that's a little difficult to achieve for a number of reasons. The best we can do in this case is to pick the value in our range of allowed values that's closest to $1200$, so we can conclude that you should have the truck driver drive at $70$ mph.


text:
Q: Different results output exec command in Laravel Code tested out of Laravel and work
$process = 'nginx';
$pids  = exec('ps aux|grep "'.$process.'" |grep -v grep');
var_dump($pids)

Exit->  string(86) "www-data  1197  0.0  0.0 125800  3552 ?        S    13:01   0:00 nginx: worker process"

This code is on one command of laravel. If execute my command, when
On localhost on MacosX with Valet (php 7.1) work fine. $pids is a string with content if proccess is running catch this code, result is fine. Get a string with ps lines.
On server with PHP 7.0 alltimes, return empty string ""


text:
Q: Populating child object from dapper stored procedure async How do I get Dapper to populate a 1:1 child object from a async stored procedure call?
I have a Premises object containing an Address object
public class Premises
{
    public int PremisesId { get; set; }
    public int EmployerId { get; set; }
    public Address Address { get; set; }

}

public class Address
{
    public int AddressId { get; set; }
    public string AddressLine1  { get; set; }
    public string AddressLine2 { get; set; }
    public string AddressLine3 { get; set; }
    public string AddressLine4 { get; set; }
    public string AddressLine5 { get; set; }
    public string Postcode { get; set; }
}

I have a stored procedure with the following sql
SELECT
    p.premisesId, p.employerId,
    a.addressId, a.addressLine1, a.addressLine2,
    a.addressLine3, a.addressLine4, a.addressLine5
FROM
    Premises p
INNER JOIN
    Address a ON p.addressId = a.addressId
WHERE
    p.premisesId = @premisesId

Calling the stored procedure with the following code:
Premises premises = await Connection.QuerySingleOrDefaultAsync<Premises>("premisesGetById", new { premisesId }, Transaction, commandType: CommandType.StoredProcedure);

The premisesId and employerId map as expected but the address object is null.

A: Manged to sort it.
My issue stemmed from the fact there isn't an overloaded method of QuerySingleOrDefaultAsync that has the map parameter.
The solution was to use the QueryAsync method then call SingleOrDefault() on the returned IEnumerable
This can be wrapped into a single line
var premises = (await Connection.QueryAsync<Premises, Address, Premises>(
     sql:"premisesGetById",
     param: new { premisesId },
     map: (prem, address) => { prem.Address = address; return prem; },
     splitOn: "AddressId",
     transaction:Transaction,
     commandType: CommandType.StoredProcedure
   )).SingleOrDefault();

Thanks for the pointers. Hope this helps someone in the future.


text:
Q: How to add the product filter in the sidebar? I just want to add the default filter in my sidebar. When looking at the official Magento demo, you can see this on the left sidebar (Shopping Options.) I assume this is available out of the box to enable since the Magento demo shouldn't be using community modules (I think.)

A: It sounds like this is probably layered navigation that you refer to. You can enable this on a per category basis by setting Is Anchor to Yes on the Display Settings tab as explained here.

A: Goto Admin panel
Catalog->Manage Categories

Click on your category then goto Display Setting Tab

Set Is Anchor -> yes

now you'll set filter options in left side bar.
If you not get the filter,
in admin panel category edit check Custom design Tab
set page layout as 2columns-left.phmtl or 3columns.phtml
or check your catalog.xml file in that make sure the category view page template is 2columns-left.phmtl or 3columns.phtml


text:
Q: ActiveRecord::Migration[5.2] stops RubyMine from auto-completing I used RubyMine CTRL+ALT+G to generate a Model called User
class CreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
      t.timestamps
    end
  end
end

I try to use autocomplete and it doesnt work.
I remove [5.2]. It works.
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.timestamps
    end
  end
end

I am using Rails 5.2 and Ruby 2.5.1p57 inside of a RVM installation on RubyMine 2018.2
I have tried invalidating caches.
How do I get autocomplete to work?


text:
Q: Align text with graphic Help, I need to align the text with the graphic, like in the image

\usepackage[utf8]{inputenc}
\usepackage[spanish]{babel}
\usepackage{parskip}
\usepackage{amsmath}
\usepackage{geometry}
\geometry{top=2cm, bottom=2cm, left=4.4cm, right=4.4cm}
\usepackage{setspace}
\usepackage{enumitem}
\usepackage{siunitx}
\sisetup{detect-family,per-mode = symbol}
\spanishdecimal{.}
\usepackage{tikz,pgfplots}
\pgfplotsset{compat=1.18}
\usetikzlibrary{arrows.meta}

\title{E7}
\author{Ing. Luque }
\date{\today}

\begin{document}

\maketitle

\section{Enunciado}

\LARGE
La gráfica corresponde al movimiento uniformemente acelerado que realiza un cuerpo. En el intervalo desde $x=0$ hasta $x=\SI{4}{\metre}$, podemos afirmar\\

\begin{figure}[h!]
\LARGE
    \centering
    \begin{tikzpicture}

    \begin{axis}[x=1cm, xtick distance = 1, y=1cm, ytick distance = 1,xmin=0,xmax=4.8,ymin=0,ymax=4.8,axis x line =center, axis y line =center,xlabel=$X(\si{\metre})$,ylabel=$V^{2}(\si{\metre\squared\per\second\squared})$, x label style={at={(ticklabel* cs:1.2)}},y label style={at={(ticklabel* cs:1.1)}},
    axis line style={-{Stealth[scale=1.2]}}]
    \addplot[very thick, samples=200, domain=0:4]{4-x};

    \end{axis}

    \end{tikzpicture}

\end{figure}

\begin{enumerate}[label=\Alph*),align=parleft,leftmargin=*]
    \item nula.
    \item \SI{4}{\second}.
    \item No se puede
    \item \SI{8}{\metre\per\second}.
    \item \SI{2}{\metre\per\second\squared}.

\end{enumerate}

\end{document}

A: You could use two minipages side by side, adjusting their widths to fit your content.
If you want to align on top use
\begin{minipage}[t][][b]{<width>}
for the left and right side (second figure)

\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[spanish]{babel}
\usepackage{parskip}
\usepackage{amsmath}
\usepackage{geometry}
\geometry{top=2cm, bottom=2cm, left=4.4cm, right=4.4cm, showframe}% changed to show the margins<<<
\usepackage{setspace}
\usepackage{enumitem}
\usepackage{siunitx}
\sisetup{detect-family,per-mode = symbol}
\spanishdecimal{.}
\usepackage{tikz,pgfplots}
\pgfplotsset{compat=1.18}
\usetikzlibrary{arrows.meta}

\title{E7}
\author{Ing. Luque }
\date{\today}

\begin{document}

    \maketitle

    \section{Enunciado}

    \LARGE
    La gráfica corresponde al movimiento uniformemente acelerado que realiza un cuerpo. En el intervalo desde $x=0$ hasta $x=\SI{4}{\metre}$, podemos afirmar \bigskip

    \begin{minipage}{0.45\linewidth}
        \begin{enumerate}[label=\Alph*),align=parleft,leftmargin=*]
            \item nula.
            \item \SI{4}{\second}.
            \item No se puede
            \item \SI{8}{\metre\per\second}.
            \item \SI{2}{\metre\per\second\squared}.
        \end{enumerate}
    \end{minipage}\hfill
    \begin{minipage}{0.55\linewidth}
        \begin{tikzpicture}
            \begin{axis}[x=1cm, xtick distance = 1, y=1cm, ytick distance = 1,xmin=0,xmax=4.8,ymin=0,ymax=4.8,axis x line =center, axis y line =center,xlabel=$X(\si{\metre})$,ylabel=$V^{2}(\si{\metre\squared\per\second\squared})$, x label style={at={(ticklabel* cs:1.2)}},y label style={at={(ticklabel* cs:1.1)}},
                axis line style={-{Stealth[scale=1.2]}}]
                \addplot[very thick, samples=200, domain=0:4]{4-x};
            \end{axis}
        \end{tikzpicture}
    \end{minipage}

    \newpage

    \begin{minipage}[t][][b]{0.45\linewidth}
    \begin{enumerate}[label=\Alph*),align=parleft,leftmargin=*]
        \item nula.
        \item \SI{4}{\second}.
        \item No se puede
        \item \SI{8}{\metre\per\second}.
        \item \SI{2}{\metre\per\second\squared}.
    \end{enumerate}
    \end{minipage}\hfill
    \begin{minipage}[t][][b]{0.55\linewidth}
        \begin{tikzpicture}
            \begin{axis}[x=1cm, xtick distance = 1, y=1cm, ytick distance = 1,xmin=0,xmax=4.8,ymin=0,ymax=4.8,axis x line =center, axis y line =center,xlabel=$X(\si{\metre})$,ylabel=$V^{2}(\si{\metre\squared\per\second\squared})$, x label style={at={(ticklabel* cs:1.2)}},y label style={at={(ticklabel* cs:1.1)}},
                axis line style={-{Stealth[scale=1.2]}}]
                \addplot[very thick, samples=200, domain=0:4]{4-x};
            \end{axis}
        \end{tikzpicture}
        \end{minipage}

\end{document}


text:
Q: mapquest map not following user location I'm developing a android navigation app with mapquest. The marker representing my location on the map, gets out of the map eventually as I move. Is there a way to make the map follow my location as I move??
I tried "map.getController().animateTo(myLocationOverlay.getMyLocation())" inside onLocationChanged(). But the map is starting to twitch every instant
Thanks
Gokul

A: If you tell the map to animate every time you get a location update, it often starts new animations while the old ones are still playing. This is probably the cause of the twitchy behavior you see. Instead of animating, you could move directly to the new location. The downside is that the map will not smoothly scroll to the new location, it will just be there instantly. You can accomplish this with
// replace LAT and LNG with the lat and lng values from your current location
map.getController().setCenter(new GeoPoint(LAT, LNG));

A: The MyLocationOverlay has an api call for this:
mMyLocationOverlay.setFollowing(true);


text:
Q: If $A$ is a subset of $B$, then $\sup A\le\sup B$ Proof by contradiction:
By def of $\sup(A)=x$, $x$ is the upper bound of $A$ which means $x$ is an element of $A$. If $\sup A>\sup B$ then $x$ may not be an element of $B$. Hence contradiction as all the elements of $A$ need to be in $B$, as $A$ is a subset of $B$.

A: A reminder of definitions: For a subset $S$ of a partially ordered set $P,$ an upper-bound is an element $u\in P$ such that for all $x\in S,$ $x\le u.$ An upper-bound $u$ is called a supremum when for all upper-bounds $v$ of $S,$ $v\ge u,$ and is denoted $\sup(S).$
To prove $\sup(A)\le \sup(B),$ it is enough to show, by definition, that $\sup(B)$ is an upper-bound of $A.$ That is, for all $x\in A,$ $x\le \sup(B).$ This is obvious, since $A$ is a subset of $B,$ so in particular, $x\in B,$ and the inequality is true by definition.


text:
Q: Struts tag inside display tag I am getting error when i refer display tag reference from struts tag.
<display:table name="lstEntities" uid="prty">
        <display:column property="propertyType.propertyTypeName"
            titleKey="common.propertytype" />
        <display:column property="propertyName" titleKey="common.property" />
        <display:column titleKey="common.concern" >
        <s:select list="${prty.propertyConcern}" listKey="prtyCrnId" listValue="concern.concernText"></s:select>
        </display:column>
    </display:table>

Error:
Custom tag attribute list cannot be runtime expression. value: "[${prty.propertyConcern}]"

Please help me. how to resolve this.

A: Such expressions were allowed in earlier releases of Struts2, but were turned off after struts 2.0.10 to resolve a security issue.
You should be able to access the "prty" object in struts tags using this alternative syntax:
<s:select list="#attr.prty.propertyConcern" listKey="prtyCrnId" listValue="concern.concernText"></s:select>

A: Modifying fieldValue="#attr.resultTable1.id" to fieldValue="%{#attr.resultTable1.id}" resolved my problem.
i.e.:
<display:table name="libraryList" requestURI="showCopyTravelType.action" sort="external"
defaultsort="1" pagesize="10" uid="resultTable1" partialList="true" size="totalRecordCount">
<display:column title="Select">
<s:checkbox id="copiedFlag" name="copiedFlag" fieldValue="%{#attr.resultTable1.id}" />
</display:column>
<display:column property="code"/>
<display:column property="name"  />
<display:column property="description"  />
<display:footer>
<s:submit action="copyTravelType" />
<s:submit action="searchTravelType"/>
</display:footer>
</display:table>

A: <s:select list="#attr.prty.propertyConcern" listKey="prtyCrnId" listValue="concern.concernText"></s:select>

If we want a list then the parameter should passed like:
list="%{#attr.prty.propertyConcern}"


text:
Q: Express-session cookie not saving in browser I've been researching this for hours now. What could be the reason why the cookies are not being saved in the browser? I'm using express-session. Below are the pieces of code I'm using.
const app = express();

// CORS config
app.use(cors({
  origin: process.env.API_URL,
  credentials: true,
  optionsSuccessStatus: 200
}));

app.use(cookieParser());

// Where the sessions are stored
const MongoDBStore = new MongoDBSession({
  uri: process.env.MEDIRECORDS_URI,
  collection: "sessions"
})

app.set("trust proxy", 1);

const oneDay = 1000 * 60 * 60 * 24;

app.use(session({
  name: "irmp_session",
  secret: process.env.AWS_SESSION_KEY,
  resave: false,
  saveUninitialized: false,
  maxAge: 7200000, // 2 hrs validity
  store: MongoDBStore,
   cookie: {
    path: '/',
    sameSite: false,
    secure: false,
    maxAge: oneDay
  }
}))

When I try to login using the frontend, the login is successful, the session is stored in the database. However, when I check the cookie storage, it is empty.

A: After spending hours of researching, I learned that this is due to Chrome's cookie updates. Here is what the update is all about.
As the link states, for a cookie to be saved in Chrome and if it is really needed to set the sameSite to none, developers should set the secure option to be true. Default value of sameSite if not set is lax.
Hope this helps anyone who might encounter the problem.

A: If anyone here uses heroku or render.com for free, I added all the answers above but it is still not working. I have tried another solution here which is add app.set("trust proxy", 1); before app.use(session(sessionSettings)) and it now saves cookie to different browsers.

A: Thank you so much for sharing it. I was stack on this for 2 days now, in localhost things worked perfectly, but after deploy my MERN app in differents servers,  cookie  stoped working...
using express-session:
app.use(session({
   .......
   .......
    cookie:{
    maxAge: 24*60*60*1000, //please change it based on your needs
    secure: app.get('env') === 'production'?true:false,
    sameSite: 'none'
}}));

this will solve the problem!!


text:
Q: How to pass JPanel instance to another class? I'm struggling to display the JPanel instances I've created in another class.
I can draw from another class, but I want to have JButtons which are on a JPanel in my BorderLayout.NORTH; I only wanted to draw to my mainGame which is BorderLayout.CENTER.
I'm unsure how to achieve this though.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.image.*;

public class RPGClicker {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                mainGameScene();
            }
        });
    }

    private static void mainGameScene() {
        JFrame window;
        mainGamePanel mainGameInstance;
        statusPanel statusInstance;
        playerInfoPanel playerInfoInstance;
        navBarDisplayPanel navBarDisplayInstance;

        window = new JFrame("RPGClicker: An Unknown Quest!");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setLayout(new BorderLayout());

        mainGameInstance = new mainGamePanel();
        statusInstance = new statusPanel();
        playerInfoInstance = new playerInfoPanel();
        navBarDisplayInstance = new navBarDisplayPanel();

        window.add(mainGameInstance, BorderLayout.CENTER);
        window.add(statusInstance, BorderLayout.SOUTH);
        window.add(playerInfoInstance, BorderLayout.EAST);
        window.add(navBarDisplayInstance, BorderLayout.NORTH);

        window.pack();
        window.setLocationRelativeTo(null);
        window.setVisible(true);
    }
}

I'm able to draw mainGamePanel, but now I can only draw to my other panels; I wanted them to contain textfields and JButtons though.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.image.*;

class navBarDisplayPanel extends JPanel {

    JButton yourStory;

    public Dimension getPreferredSize() {
        return new Dimension(1280, 256);
    }

    private void navBarDisplayPanel() {
        yourStory = new JButton("Your Story");
        add(yourStory);
    }
}

The code compiles, but nothing appears when it's run. The north bar is completely empty. Can anyone gives any ideas?

A: I am assuming this:
private void navBarDisplayPanel()

is what you think the constructor of your class navBarDisplayPanel really is.
As a constructor, you should not let this be private if you want to make objects with it from external classes, you should remove the void mark as this is not a regular method, and (optional but not optional) you should name all your classes (and their constructors) with the first letter as capital.
In order to make your code work, I guess you just need to rename this:
private void navBarDisplayPanel(){
    yourStory = new JButton("Your Story");
    add(yourStory);
}

to this:
public navBarDisplayPanel(){
    yourStory = new JButton("Your Story");
    add(yourStory);
}

But as I pointed it, try to follow the Java Naming Conventions (and others conventions too) to avoid future mistakes.


text:
Q: Generate keywords for contents through Solr I'm integrating Solr for my new PHP application.
As I'm newbie in solr section, I want to know that is it possible to generate some useful tags for every content pages through solr? something like auto-tagging mechanism.
Thanks in Advance...
P.S My contents available in both Persian and English languages.

A:
something like auto-tagging mechanism.

Yes, you can build something like that.
There are 2 different ways to realize that:

*

*Use the Clustering Component from Solr to build groups of docs and label those docs by solr. The labels are something like the taggs your are looking for.

*Realize a tagging by using the MLT feature.

I started an auto-tagging project with the 1.) method with medium success. Finding labels for a cluster of documents is an hard process.
But fortunately, I had some already taggegd documents. If you also have some documents with valid tags, than you can use the 2.) method to use those document as an base to start learning:
Take a document without tags and perform a MLT search against docs with tags. Take the tags from the docs you fond and count them. Depending on the count, apply one or more tags to the untaggegd document. In my case, that works very well. Method 2.) is an cheep implementation of machine based learning, but you will get 95% success with only 5% Work-input.

A: As it's a PHP application, if it's OK for you to generate tags in php and then inserting/updating to Solr, Here are few options -

*

*If using a web service is OK, check Yahoo's Term Extractor

*If you can/want to host a term extraction service yourself to (may be in local server), check FiveFilters

*Here is a php function for extracting valuable words from text block. Surely not as efficient as Yahoo Term Extractor, but it may work for you.


text:
Q: Why did Happybase's connection to Hbase Thrift just stop working? I had code working and reading from Hbase yesterday, streaming large quantities of data. I have not touched the code and yet, somehow, when I came back to it today it doesn't want to print out the data. The only thing I did on the server was set up a REST framework for writing to the database. Here's part of the code that works (so it seems like it's getting a connection)-
import happybase

connection = happybase.Connection('<ip-address>', '9090')

table = connection.table('rawdataingestion')

Then, when it gets to this part, it just stops working.
n = 0
li = []
for key, data in table.scan(row_start=None):
    data = json.loads(data['cf:rawmsg'])
    li.append(data)
    n += 1
    if n == 1000:
        break

Like I said, the only thing that changed on the server is that I set up the REST port (8000). Is that the problem? All I need is to pull data from the database.

A: Correct me if I'm wrong but it appears that REST and THRIFT do not work on the same server simultaneously. So it appears that I can either pull data from Hbase using THRIFT or push data to Hbase using REST. If one program works at pulling data, the other program that pushes data will fail and vice versa.
I solved the problem by typing in jps (you can also use ps -a) to find the number corresponding to the THRIFT process. I then killed the process with kill 12345. After that I restarted THRIFT in the background by typing ./hbase-daemon.sh start thrift. After I did that my program could successfully pull data from the database, but my other program that inserts data stopped working.
There's nothing wrong with the code, the problem is that REST and THRIFT do not work on the same server simultaneously.


text:
Q: Displaying images in sequence with a loop I got an NSArray with 5 pictures. I want to display them one after the other in a loop.
My code :
 NSArray *tabImage = [[NSArray alloc] init];

tabImage = [[NSArray arrayWithObjects:
               [UIImage imageNamed:@"picto_1.png"],
               [UIImage imageNamed:@"picto_2.png"],
               [UIImage imageNamed:@"picto_3.png"],
               [UIImage imageNamed:@"picto_4.png"],
               [UIImage imageNamed:@"picto_5.png"],
               nil] retain];

int var = 0;
var = indexPath.row;

for (int var = 0; var < 20; var++) {
    pictoImage.image = [tabImage objectAtIndex:(var % 5)];
}

I got the same picture all the time.
Thanks for help.

A: I'm guessing pictoImage is an UIImageView. In that case look at the class reference, specifically the animationImages properties.
 pictoImage.animationImages = [NSArray arrayWithObjects:
                                   [UIImage imageNamed:@"picto_1.png"],
                                   [UIImage imageNamed:@"picto_2.png"],
                                   [UIImage imageNamed:@"picto_3.png"],
                                   [UIImage imageNamed:@"picto_4.png"],
                                   [UIImage imageNamed:@"picto_5.png"],
                                   nil];

 // How many seconds it should take to go through all images one time.
 pictoImage.animationDuration = 5.0;

 // How many times to repeat the animation (0 for indefinitely).
 pictoImage.animationRepeatCount = 4;

 [pictoImage startAnimating];

A: You are not giving the framework time to actually render the images to the window.
All your updates are being coalesced into one "setNeedsDisplay" call. On the next iteration of the run loop, the image view will be rendered using the last image that you set in the loop.

A: If pictoImage is an UIImageView, @Hagelin's answer is the best way to go. Now, if pictoImage is not an UIImageView object then you will have to take a different approach and that definitely is not a loop.
Set an NSTimer with a desired time interval and invoke a method that updates pictoImage iterating over the tabImages. It should be something like this :-
- (void)setup {
    ...

    [NSTimer scheduledTimerWithTimeInterval:2.0
                                     target:self
                                   selector:@selector(updatePictoImage:)
                                   userInfo:nil
                                    repeats:YES];

    ...
}

- (void)updatePictoImage:(NSTimer*)theTimer {
    static int i = 0;
    if ( i > 20 ) {
        pictoImage.image = [tabImages objectAtIndex:(i % 5)];
    } else {
       [theTimer invalidate];
    }
}

This should update the pictoImage every 2 seconds with images in tabImages.

A: You don't print anything.
You are overriding the contents of your pictoImage 20 times in a row, leaving it with the last assignment when var is 19, so it should be picto_4.png.
Also, the whole var declaration doesn't make much sense at all... first you set it to 0, then you set it to indexPath.row, and in the loop it is completely redefined....


text:
Q: How to hide an specific field from result in strongloop I'm trying to create an project using strongloop, in which I'm creating an web service for user login, My code runs well & gets desired output except the fact that it does not hide password
I'm getting result as
{
    "result": [{
        "_id": 2,
        "address": "abc",
        "created_by": 1,
        "created_date": "2016-03-04T00:00:00.000Z",
        "firstname": "Anup",
        "isdeleted": 0,
        "lastname": "Deshpande",
        "mobile_number": "9700128907",
        "oldpassword": "string",
        "profile_picturename": "anup.jpeg",
        "role_id": 1,
        "user_email_id": "anupd@ideaentity.com",
        "user_password": "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
        "user_status": 1
    }]
}

Where I want to hide or delete "user_password": "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8", field.
can anyone tell me how can i do that in strongloop's remote method
My renote method code is like follows
db.collection('users').find({
                user_email_id : par,
                user_password : sha256(par2)
            }).toArray(function(err, result) {

                // var passwordHash = hashPassword(user_password);
                // console.log(passwordHash);
                if (err) {
                    throw err;
                }
                if (result.length > 0) {
                    self.callback(null, result);
                    // db.disconnect();
                } else {
                    self.callback(null, response);
                    // db.disconnect();
                }
            });

Here "result will give all details" I want to hide password from result
Thanks in advance

A: Try this.
{ fields: {propertyName: <true|false>, propertyName: <true|false>, ... } }

propertyName is the name of the property (field) to include or
  exclude.  signifies either true or false Boolean literal.
  Use true to include the property or false to exclude it from results.
  You can also use 1 for true and 0 for false. By default, queries
  return all model properties in results.  However, if you specify at
  least one fields filter with a value of true, then by default the
  query will include only those you specifically include with filters.

refer this link
https://docs.strongloop.com/display/public/LB/Fields+filter
Example:
var query = { fields: {password: false} }
Model.find(query, function()
{
});

Otherwise you can manually remove in afterremotemethod(), in
  ctx.result.
  refer this link https://docs.strongloop.com/display/public/LB/Remote+hooks

A:
Add hidden field in you model.json  that is  "hidden": ["password",
  "verificationToken"],

Example:
{
  "name": "User",
  "properties": {
    "realm": {
      "type": "string"
    },
    "username": {
      "type": "string"
    },
    "password": {
      "type": "string",
      "required": true
    },
    "credentials": {
      "type": "object",
      "deprecated": true
    },
    "challenges": {
      "type": "object",
      "deprecated": true
    },
    "email": {
      "type": "string",
      "required": true
    },
    "emailVerified": "boolean",
    "verificationToken": "string",
    "status": "string",
    "created": "date",
    "lastUpdated": "date"
  },
  "options": {
    "caseSensitiveEmail": true
  },
  "hidden": ["password", "verificationToken"],
  "acls": [

  ],
  "relations": {

  }
}

A: for me
// {user_password:0} - to hide password
db.collection('users').find({
                user_email_id : par,
                user_password : sha256(par2)
            },{user_password:0}).toArray(function(err, result) {

this worked fine
for mare details you can check here


text:
Q: SQL query to remove duplicates based on the modified date I have a database table with the following columns regularization_dt, modified_dt and account_id. For a particular whenever an account is updated an entry is added in to the table with new modified_dt for the regularization_dt and account_id.
I want an SQL query to remove duplicates of regularization. Only one entry for the regularization should be selected based on the recent modified_dt.
For example the entries in the table are as follows:
regularization_dt | account_id | modified_dt
----------------- | ---------- | ----------
03-28-2013        |  123       |05-26-2014
03-28-2013        |  123       |01-14-2014
05-26-2014        |  123       |05-25-2014

The resulting query should yield:
regularization_dt | account_id | modified_dt
----------------- | ---------- | ----------
03-28-2013        |  123       |05-26-2014
05-26-2014        |  123       |05-25-2014

How should I remove duplicates of a column based on a different column?
select * from history where account_id = 123;

A: Sounds like you want to use an aggregate function and a  GROUP BY :
SELECT   regularization_dt,
         account_id,
         MAX(modified_dt) as modified_dt
FROM     yourtable
GROUP BY regularization_dt,
         account_id;

This should return deduplicated rows with only the latest modified_dt for rows with identical regularization_dt and account_id column values.


text:
Q: What is the order of records in a table with a composite primary key In PostgreSQL, when a combination of multiple columns is specified as the PRIMARY KEY, how are the records ordered?
This is with the assumption that PostgreSQL orders the records in the order of the primary key. Does it?
Also, is the primary key automatically indexed in case of PostgreSQL?

A: This question makes the misguided assumption that the primary key imposes a table order at all. It doesn't. PostgreSQL tables have no defined order, with or without a primary key; they're a "heap" of rows arranged in page blocks. Ordering is imposed using the ORDER BY clause of queries when desired.
You might be thinking that PostgreSQL tables are stored as index-oriented tables that're stored on disk in primary key order, but that isn't how Pg works. I think InnoDB stores tables organized by the primary key (but haven't checked), and it's optional in some other vendors' databases using a feature often called "clustered indexes" or "index-organized tables". This feature isn't currently supported by PostgreSQL (as of 9.3 at least).
That said, the PRIMARY KEY is implemented using a UNIQUE index, and there is an ordering to that index. It is sorted in ascending order from the left column of the index (and therefore the primary key) onward, as if it were ORDER BY col1 ASC, col2 ASC, col3 ASC;. The same is true of any other b-tree (as distinct from GiST or GIN) index in PostgreSQL, as they're implemented using b+trees.
So in the table:
CREATE TABLE demo (
   a integer,
   b text,
   PRIMARY KEY(a,b)
);

the system will automatically create the equivalent of:
CREATE UNIQUE INDEX demo_pkey ON demo(a ASC, b ASC);

This is reported to you when you create a table, eg:
regress=>     CREATE TABLE demo (
regress(>        a integer,
regress(>        b text,
regress(>        PRIMARY KEY(a,b)
regress(>     );
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "demo_pkey" for table "demo"
CREATE TABLE

You can see this index when examining the table:
regress=> \d demo
     Table "public.demo"
 Column |  Type   | Modifiers
--------+---------+-----------
 a      | integer | not null
 b      | text    | not null
Indexes:
    "demo_pkey" PRIMARY KEY, btree (a, b)

You can CLUSTER on this index to re-order the table according to the primary key, but it's a one-time operation. The system won't maintain that ordering - though if there's space free in the pages due to a non-default FILLFACTOR I think it will try to.
One consequence of the inherent ordering of the index (but not the heap) is that it is much faster to search for:
SELECT * FROM demo ORDER BY a, b;
SELECT * FROM demo ORDER BY a;

than:
SELECT * FROM demo ORDER BY a DESC, b;

and neither of these can use the primary key index at all, they'll do a seqscan unless you have an index on b:
SELECT * FROM demo ORDER BY b, a;
SELECT * FROM demo ORDER BY b;

This is becaues PostgreSQL can use an index on (a,b) almost as fast as an index on (a) alone. It cannot use an index on (a,b) as if it were an index on (b) alone - not even slowly, it just can't.
As for the DESC entry, for that one Pg must do a reverse index scan, which is slower than an ordinary forward index scan. If you're seeing lots of reverse index scans in EXPLAIN ANALYZE and you can afford the performance cost of the extra index you can create an index on the field in DESC order.
This is true for WHERE clauses, not just ORDER BY. You can use an index on (a,b) to search for WHERE a = 4 or WHERE a = 4 AND b = 3 but not to search for WHERE b = 3 alone.


text:
Q: Invalid login credentials while Google Play reviews Flutter app I have uploaded my Flutter app to the Google Play store and requested a review so the app can be published.
App content is hidden behind google sign-in. I have provided demo account for the reviewers, but app keeps getting rejected because of "Issue: Invalid or incomplete login credentials".
When I run my app locally, with provided demo account details, everything works fine. Both on the emulator and also when I download signed app bundle from the Google Play store. I have tried with multiple different mobile devices and on all of them google sign-in is working with demo account details.
Demo account details (username, password) are provided inside "App content" -> "App access" and are correct ones that I use when testing.
I added SHA-1 and also SHA-256 to the firebase project from both App signing key certificate and Upload key certificate section.
Any ideas, suggestions? Thanks.

A: After some time I was able to resolve my issue.
Everything is ok from the technical app side. We are using Google login service to authenticate users, but not every user with gmail account can login, but only users that are inside are auth DB.
So we created Google Test account for Google support so they can review with it (test account doesn't have any 2FA, just password). Unfortunately they have some strange policies, they aren't able to login because every time Google account tries to "Verify this is really you..." they don't verify it for some strange reason or whatever, thus resulting in login failure.
What was the fix for this...we recorded a video which demonstrates app functionalities behind the login wall. We recored every in-app screen for at least two seconds. Recored video was hosted and we sent the video link to Google support. They accepted our appeal and the app was accepted and published.


text:
Q: Идентификация сетевого трафика телеграмм Необходимо выявлять трафик мессенджера телеграмм.
Волнует не с точки зрения статистического анализа, а конкретных пробелов в мимикрировании под tls 1.2.
Вот самая актуальная статья по этой теме. Пробовал руками сравнить нормальный трафик и тг, отличия были очень сильные. Явно не по этим полям теперь начинать сравнивать.
В каком направлении рыть? Изучать всю документацию по работе протокола будет слишком долго...


text:
Q: Unable to recieve id and consume it using useParams. Page showing blank in react I have two pages one with a list of products which are rendering fine but when i click any of them it is taking me to route with id but with blank page. My product Details page is not able to consume the id and render the items. There is something wrong but I am not able to find it. How do i solve this?
App.js
<Routes>
 <Route path="/" element={<Products />}></Route>
 <Route path="/:id" element={<ProductDetails />}></Route>
</Routes>

Products Page
{items && items.map(({ id, name,price, desc, small, large }) => (
                <Grid item xs={6} xs={12} sm={6} md={3} >
                  <Link to={`/${id}`}>
                  <Card key={id}>

{name}

Rs {price}

                  </Card>
                  </Link>
                </Grid>
              ))}

Product Details Page
function ProductDetail() {
    const [singleProduct, setSingleProduct] = useState({})
    const { id } = useParams()
    const findProduct = () => {
      setSingleProduct(data.find((product) => product.id === id))
    }

    useEffect(() => {
        findProduct()
    }, [id])

    return (

          {singleProduct.name}

)}

A: Since the routes look correct and I see no reason why the id param wouldn't defined I believe this is a type-mismatch issue where the route param is a string type and the product.id is not a string type.
Use a type-safe comparison when searching the data by converting the product.id to a string.
Example:
const { id } = useParams();

const findProduct = () => {
  setSingleProduct(data.find((product) => String(product.id) === id))
}

And as I pointed out in a comment, there's no need to use any local state, just find the data and render directly.
Example:
function ProductDetail() {
  const { id } = useParams();
  const singleProduct = data.find((product) => String(product.id) === id)) || {};

  return (

{singleProduct.name}

  );
}


text:
Q: Need some suggestions for developing a desktop application that uses offline database I have a web application that needs to be implemented as a desktop application. With my brief research about it, I came to know about Electron. Though it is an amazing tool to convert web applications to desktop ones, my application needs a database to run and it needs to be run offline. I also did read about using SQLite. I need to get more insight and suggestions as to how I should proceed with it.

A: Well if you are going to use SQLite don't to forget to encrypt the database.
To learn more about it check this


text:
Q: Hover property applies to child Good day everyone, i have been trying to apply box-shadow property to a webpage but if i apply the effect to the normal state, everything works fine but on the hover state, if i hover on the child, it applies to both the parent and the child.
Normal state: everything works fine

hover state: property applies to each element in the div

I have tried using Jquery to toggle the state but it does not work.
HTML

A title

shortDiscription

CSS
.result {
  background-color: #fff0f0;
  padding: 5px;
  margin: 1%;
  width: 600px;
  box-shadow: 2px 2px 5px grey;
  transition: all 0.5s ease;
}

.myClmass :hover {
  display: block;
  box-shadow: 2px 2px 5px grey;
  transition: all 0.5s ease;
}

.singleHover {
  all: revert;
}

.results {
  float: left;
}

.vid {
  float: right;
  margin: 1%;
}

.vidHeader {
  background-color: #d69797;
  padding-top: 10px;
  padding-bottom: 10px;
  padding-right: 400px;
  padding-left: 5%;
  text-align: center;
}

This is my java servlet code:
 out.println("
");
                for(Element post : results){
                    String link = post.childNode(0).childNode(0).absUrl("href");
                    String title = post.getElementsByTag("a").text();
                    String shortDiscription = post.getElementsByClass("b_caption").get(0).child(1).toString();
                    out.println("
");
                    out.println("
");
                    out.println("
"+title+"
");
                    out.println("
"+shortDiscription+"
");
                    out.println("

");
                }
                out.println("
");

A: The selector .myClmass :hover means that the rule is applied to all descendant elements of the element with the class myClmass where the mouse is actually over. So your rule is applied to all elements that are within the element with the class myClmass
If you want to apply the box shadow to the element with the class myClmass then the selector has to be .myClmass:hover without the space between .myClmass and :hover

A: Try pointer-events:none; on your child element in your css


text:
Q: Problem to find the optimal number of clusters with scaled and non-scaled data I'm trying to do clustering in my data and I'm having some problems to identify the optimal number of clusters.
My data (https://www.dropbox.com/s/6i6wyy0eohtlrrt/wellA.xlsx?dl=0) is an oil exploration well with information of depth, rock_types (label) and rock properties (features). I have the labels information, but I'd like to see how KMeans would work on this.
The problem is that the elbow method and silhouette score show a clear trend when the data isn't scaled, but a bad clustering. On the other hand, scaled data shows better clusters, but its graphs have "weird" shapes... the first one doesn't has an "elbow" and the other has silhouette scores way smaller than the non-scaled data. Why do I see worse graphs for scaled data?

I would like to know if I'm doing something wrong. The features are highly variables and I think they should be scaled for KMeans purposes. Maybe I should scale the data just after find the optimal number of clusters?
P.S.: I'm sorry for the long question and code (most of it are plots). I tried to edit all of this in a simpler example, but I wasn't able to represent this heterogeneity.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import silhouette_score

data = pd.read_excel(r'C:\...\wellA.xlsx')
data = data.replace(-999.25, np.nan)
data.dropna(axis=0, inplace=True)

# FEATURES SELECTION FOR TRAINING
well = data.drop(['DEPTH','ROCK_TYPE'], axis=1)

# NORMALIZATION
scaled_well = pd.DataFrame(MinMaxScaler().fit_transform(well))

# ELBOW METHOD AND SILHOUETTE SCORE
def optimal_k(data, title):
    inertia =[]
    sil =[]

    for k in range(2,14):
        kmeans_rand = KMeans(n_clusters=k, init='k-means++', random_state=0)
        kmeans_rand.fit(data.values)
        y_pred = kmeans_rand.predict(data.values)

        inertia.append(kmeans_rand.inertia_)
        sil.append((k, silhouette_score(data.values, y_pred)))

    fig, ax = plt.subplots(1, 2, figsize=(12,4))
    ax[0].plot(range(2,14), inertia)
    ax[0].set_title('Elbow Method')
    ax[0].set_xlabel('Number of clusters')
    ax[0].set_ylabel('Inertia')

    x_sil = [x[0] for x in sil]
    y_sil = [x[1] for x in sil]
    ax[1].plot(x_sil, y_sil)
    ax[1].set_xlabel('Number of Clusters')
    ax[1].set_ylabel('Silhouetter Score')
    ax[1].set_title('Silhouetter Score Curve')

    fig.suptitle(title)

optimal_k(well, 'Not scaled')
optimal_k(scaled_well, 'Scaled')

# MODEL
def kmeans(data, k):
    model = KMeans(n_clusters=k, random_state=0, init='k-means++')
    model.fit(data.values)
    labels = model.labels_
    data['KMEANS'] = labels+1

kmeans(well,3)
kmeans(scaled_well,3)

# CONVERT NAME TO VALUE
facies = {'Claystone':1, 'Coal':2, 'Limestone':3, 'Marl':4, 'Sandstone':5}
data['LABEL'] = data['ROCK_TYPE'].map(facies)

# PLOT
cluster_real = np.repeat(np.expand_dims(data['LABEL'], 1), 1, 1)
cluster_kmeans = np.repeat(np.expand_dims(well['KMEANS'], 1), 1, 1)
cluster_kmeans_scaled = np.repeat(np.expand_dims(scaled_well['KMEANS'], 1), 1, 1)

f, ax = plt.subplots(nrows=1, ncols=3, figsize=(2,12))
ax[0].imshow(cluster_real,
   interpolation='none',
   aspect='auto',
   vmin=1, vmax=5,
   extent=[0, 1, data['DEPTH'].max(), data['DEPTH'].min()])

ax[1].imshow(cluster_kmeans,
   interpolation='none',
   aspect='auto',
   vmin=1, vmax=3,
   extent=[0, 1, data['DEPTH'].max(), data['DEPTH'].min()])

ax[2].imshow(cluster_kmeans_scaled,
   interpolation='none',
   aspect='auto',
   vmin=1, vmax=3,
   extent=[0, 1, data['DEPTH'].max(), data['DEPTH'].min()])

ax[0].set_ylabel('Depth (m)')
ax[0].set_xticks([],[])
ax[0].set_xlabel('REAL ROCKS')

ax[1].set_xticks([],[])
ax[1].set_xlabel('KMEANS')

ax[2].set_xticks([],[])
ax[2].set_xlabel('KMEANS SCALED')

A: Some clustering methodologies will automatically find the optimal number of clusters for you.  Affinity Propagation and Mean Shift are two that come to mind.  There are probably a couple others out there that will do the same.
from sklearn.cluster import AffinityPropagation
from sklearn import metrics
from sklearn.datasets import make_blobs

# #############################################################################
# Generate sample data
centers = [[1, 1], [-1, -1], [1, -1]]
X, labels_true = make_blobs(n_samples=300, centers=centers, cluster_std=0.5,
                            random_state=0)

# #############################################################################
# Compute Affinity Propagation
af = AffinityPropagation(preference=-50).fit(X)
cluster_centers_indices = af.cluster_centers_indices_
labels = af.labels_

n_clusters_ = len(cluster_centers_indices)

print('Estimated number of clusters: %d' % n_clusters_)
print("Homogeneity: %0.3f" % metrics.homogeneity_score(labels_true, labels))
print("Completeness: %0.3f" % metrics.completeness_score(labels_true, labels))
print("V-measure: %0.3f" % metrics.v_measure_score(labels_true, labels))
print("Adjusted Rand Index: %0.3f"
      % metrics.adjusted_rand_score(labels_true, labels))
print("Adjusted Mutual Information: %0.3f"
      % metrics.adjusted_mutual_info_score(labels_true, labels))
print("Silhouette Coefficient: %0.3f"
      % metrics.silhouette_score(X, labels, metric='sqeuclidean'))

# #############################################################################
# Plot result
import matplotlib.pyplot as plt
from itertools import cycle

plt.close('all')
plt.figure(1)
plt.clf()

colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk')
for k, col in zip(range(n_clusters_), colors):
    class_members = labels == k
    cluster_center = X[cluster_centers_indices[k]]
    plt.plot(X[class_members, 0], X[class_members, 1], col + '.')
    plt.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,
             markeredgecolor='k', markersize=14)
    for x in X[class_members]:
        plt.plot([cluster_center[0], x[0]], [cluster_center[1], x[1]], col)

plt.title('Estimated number of clusters: %d' % n_clusters_)
plt.show()


text:
Q: Multidimensional array of Objects in Kotlin I'm new in Kotlin, and I want to create a multi dimensional array of a custom class, with null permitted. Something like that
private var array_map = arrayOf<Array<Obstacle?>>()

...

array_map[1][2] = Obstacle()

How can I do it? Thank you!

A: You can use private var arrayMap: Array<Array<Obstacle?>> = arrayOf(). Just wrap with as much Array<> as you need.

A: Not sure if this is what you want, but imagine that Obstacle is a custom class with a field num as below
data class Obstacle(var num: Int){}

A 2D array of the Obstacle object would be as below:
val array: Array<Obstacle?> = arrayOf(Obstacle(123), Obstacle(234))
val arrayOfArray: Array<Array<Obstacle?>> = arrayOf(array)
println(arrayOfArray[0][0]) // would print Obstacle(num=123)
println(arrayOfArray[0][1]) // would print Obstacle(num=234)

So you should be declaring your 2D array as below
val arrayOfArray: Array<Array<Obstacle?>> = arrayOf()

A: In case you need the index of each element in the constructor of the elements of the array:
Declaration:
var matrix: Array<Array<Obstacle?>>

Instantiation and initialization:
matrix = Array(numRows) { row ->
            Array(numCols) { col ->
                Obstacle(row, col)
            }
         }

A: Your code will compile as is. The problem is just that array size can't be changed and arrayOf<Array<Obstacle?>>() creates an empty array, so array_map[1][2] = Obstacle() fails at runtime. (Unless you do array_map = ... somewhere between them. Note that you should prefer val arrayMap, which can't be reassigned, unless you have a specific reason to use var.)
If you want your array to start with nulls, there is arrayOfNulls in the standard library, but it only creates a single-dimensional array, and what you really need is an array of arrays of nulls. You can write a helper function:
inline fun <reified T> matrixOfNulls(n: Int, m: Int) = Array(n) { arrayOfNulls<T>(m) }

private val arrayMap = matrixOfNulls<Obstacle>(5, 5) // example arguments

A: The approach I always use for this case is:
arr2D = Array(sizeA) { Array(sizeB) { content } }

Note I replaced the sizes by fields names to illustrate that each number/field represents the width and height length of each dimension of the 2D array.
Also, content should be replaced by the main content you want to fill in each coordinate, in your case seems you aims to setup with Obstacle() instances. If you want fill this content in other moment put null or a quick Any() reference.
In this last case, after creating that you can simply perform to set the itens:
arr2D[1][2] = Obstacle()


text:
Q: Laplacian Problem I'm going through past exams for study and I've come across a question I can never seem to solve.
Question: Given r = (x,y,z) and $r = \sqrt{x^2 + y^2 +z^2}$. Find $\nabla^2{\cosh(r)}$
I gave it a go and attempted to solve it directly, but the method was very tedious, and in an exam format would take too long. I know there is a way to solve using vector identities (nabla identities), but I'm not sure where to start.
Any help would be appreciated.
Thanks

A: $r = \sqrt{\mathbf{r} \cdot \mathbf{r}}$, so by the chain rule,
$$ \nabla \cosh{r} = (\nabla r) \frac{\partial}{\partial r} \cosh{r} = (\nabla r) \sinh{r}, $$
and then
$$ \nabla^2 \cosh{r} = \nabla \cdot \left( (\nabla r) \sinh{r} \right) = \lvert \nabla r \rvert^2 \cosh{r} + (\nabla^2 r)\sinh{r}. $$
Now,
$$ \nabla r = \nabla \sqrt{\mathbf{r} \cdot \mathbf{r}} = \frac{\mathbf{r}}{(\mathbf{r} \cdot \mathbf{r})^{3/2}} $$
and then
$$ \nabla \cdot \frac{\mathbf{r}}{(\mathbf{r} \cdot \mathbf{r})^{3/2}} = \frac{3}{r^{3/2}} - \frac{3 \mathbf{r} \cdot \mathbf{r} }{r^{5/2}}=0, $$
so we find
$$ \nabla \cosh{r} = \frac{1}{r^2}\cosh{r}. $$
(Of course, the easiest way to do this is to use the Laplacian in spherical coordinates, $ \nabla^2 f = r^{-2}\partial_r r^2\partial_r f + \dotsb $.)

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\mbox{If a function}\ \mrm{f}\ \mbox{depends solely on}\ r = \verts{\vec{r}},\quad
\nabla\mrm{f}\pars{r} = \mrm{f}'\pars{r}\,{\vec{r} \over r} =
{\mrm{f}'\pars{r} \over r}\,\vec{r}
\\[5mm]
&\mbox{Note that}\ \partiald{\mrm{f}\pars{r}}{x} =
\totald{\mrm{f}\pars{r}}{r}\,\partiald{r}{x} =
\totald{\mrm{f}\pars{r}}{r}\,{1 \over 2r}\,\,\partiald{r^{2}}{x} =
\totald{\mrm{f}\pars{r}}{r}\,{x \over r}\quad
\pars{\substack{\mbox{Similarly for}\\[1mm] \ds{y}\ \mbox{and}\ z}}
\\[1cm]
&\mbox{In order to evaluate}\ \nabla^{2}\mrm{f}\pars{r} \stackrel{\mbox{def.}}{=} \nabla\cdot\bracks{\nabla\mrm{f}\pars{r}} =
\nabla\cdot\bracks{{\mrm{f}'\pars{r} \over r}\,\vec{r}}\
\mbox{I'll use the identity}
\\ & \nabla\cdot\pars{\varphi\vec{A}} =
\pars{\nabla\varphi}\cdot\vec{A} + \varphi\nabla\cdot\vec{A}.
\end{align}

\begin{align}
\nabla^{2}\mrm{f}\pars{r} & =
\braces{\nabla\bracks{\mrm{f}'\pars{r} \over r}}\cdot\vec{r} + {\mrm{f}'\pars{r} \over r}\,\ \overbrace{\nabla\cdot\vec{r}}^{\ds{=\ 3}} =
{\vec{r} \over r}\,\totald{}{r}\bracks{\mrm{f}'\pars{r} \over r}\cdot\vec{r} +
{3\,\mrm{f}'\pars{r} \over r}
\\[5mm] & =
r\,{\mrm{f}''\pars{r}r - \mrm{f}'\pars{r} \over r^{2}} +
{3\,\mrm{f}'\pars{r} \over r} =
\bbx{\mrm{f}''\pars{r} + {2\,\mrm{f}'\pars{r} \over r}}
\end{align}

With $\ds{\mrm{f}\pars{r} \equiv \cosh\pars{r}}$:

$$
\nabla^{2}\cosh\pars{r} = \bbx{\cosh\pars{r} + {2\sinh\pars{r} \over r}}
$$


text:
Q: Centre of Mass, Moment of Inertia and Lagrangian of a triangular laminate A triangular laminate has vertices $O = (0, 0), A = (0, a)$ and $B = (a, 0)$ and
constant density $ρ_0$.
(i) Calculate the position of the centre of mass and show that the moment of inertia about the axis perpendicular to the plane of the laminate and passing through O is given by $\frac 13M a^2$, where $M$ is the mass of the laminate.
(ii) A pendulum consists of the triangular laminate which swings freely in a vertical
plane about a horizontal axis through O .
Show that the Lagrangian is given by
$$L =\frac16Ma^2θ^2 +\frac M3\sqrt 2ga \cos θ$$
where M is the mass of the laminate and θ is an angle which should be defined.
(iii) Calculate the period of small oscillations about the downward vertical.
Can i merely state the centre of mass is given by $X=\frac a3 \ Y=\frac a3$? Would I need a double integral to find the moment of inertia?

A: You are right: the center of mass of a triangular lamina lies at the triangle centroid, i.e. it is the common point of its medians.
To see why, consider a thin stripe of the lamina, parallel to a side of the triangle: its center of mass is obviously at its midpoint, and it thus lies on the median corresponding to that side. The lamina can be seen as the sum of such thin stripes, whose centers of mass all lie on the same median: the center of mass of the whole lamina must therefore lie on that median too.
The same reasoning can be repeated for the other two medians, hence the center of mass of the lamina must be at the centroid of the triangle.
As for the moment of inertia, you can avoid the double integral by noticing that the moment of inertia at point $(a/2,a/2)$ is half that of a square at its center, and using then Steiner's theorem.
EDIT.
If you insist on computing the moment of inertia around $O$ with an integral, here it is:
$$
I=\int_0^a\int_0^{a-x}\rho(x^2+y^2)\,dy\,dx,
$$
where $\rho$ is the surface density and $M={1\over2}\rho a^2$.


text:
Q: I keep getting [object][Object] as my request from a form with a POST request method while using node.js I have been trying to get the value of my text input in a form with a POST request, but on the server side, the req.body is returning a [objecet][Object] request, when indeed I put in a value. Here's my code
const express = require('express');
const path = require('path');
let app = express();
const bodyParser = require('body-parser');

//Middleware for
app.use(bodyParser.urlencoded({extended: true}))

//using a middleware to map the /assets link in the url
app.use(express.static(path.join(__dirname, '/public')));

//Setting the view engine
app.set('view engine', 'ejs');

app.get('/', (req, res)=>{
  res.sendFile(__dirname + '/index.html');
})

//Contact page
app.get('/contact', (req, res)=>{
  res.sendFile(__dirname + '/contact.html');
  // res.sendFile(__dirname + '/assets/appUI.js');
})
app.get('/contact-us', (req, res)=>{
  res.sendFile(__dirname + '/contact.html');
})

//Handling  POST request
app.post('/', (req, res )=>{
  console.log('The task is '+ req.body)
})

app.listen(3000, ()=>{
  console.log('The server is up and listening at port 3000!!!')
})

My index.html code is as below
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css" type="image/x-icon">
  <title>To do app</title>
  <link rel="stylesheet" href="styles.css">
  <link rel="stylesheet" href="animate.css">
</script>

CONTACT US

Please add a task

Details added to register!

Todo App

    <form class="form" action="/" method="POST">
          <input type="text"  id="task" name = "task" value="Invents">

          <input type="submit" value="Add task" class="btn" name="addTask">
          <input type="button" value="Clear All" class="btn clear-all"  name="clearTask">
    </form>

And my client side javascript code is as below
function appui(){
//Grabing input
const task = document.querySelector('#task');
const submit = document.querySelector('.btn');
const main = document.querySelector('.main-box');
const form =  document.querySelector('.form');
const taskList = document.querySelector('.task-list');
const clearTask = document.querySelector('.clear-all')
const errorMessage = document.querySelector('#error-message');
const registeredMessage = document.querySelector('#registered-message');
//Load event listener
// loadEventlisntener()
console.log(main)
//adding submit event
submit.addEventListener('click', addTask);

//Funtion Error Display
function errorDisplay(){
  errorMessage.style.setProperty('display', 'none');
}
//Funtion regsitered Display
function registeredDisplay(){
  registeredMessage.style.setProperty('display', 'none');
}

//addtask
//Function addTask
function addTask(e){
  if(task.value !== '') {

    //create Element li
    let list = document.createElement('li');
    //Add a class name
    list.className = 'task-value';

    //create div
    let div = document.createElement('div');
    //Add a class name
    div.className = 'main-box task animated heartBeat';

    //task
    let taskInput = document.createTextNode(`${task.value}`);

    //append text node
    div.appendChild(taskInput);
    //Anchor tag
    let anch = document.createElement('a');
    //Add a class name
    anch.className = 'deleteIcon';

    //Delete mark 'X'
    anch.innerHTML = `<b class="delete-icon">Delete</b>`
    //Append Anchor tag to div
    div.appendChild(anch);

    // main.appendChild(div);
    // form.parentNode.insertBefore(div, form.nextSibling);
    console.log(div)

    // Inserting Element after
    // main.parentNode.insertBefore(div, main.nextSibling);
    document.querySelector('.task-list').appendChild(div);

    registeredMessage.style.setProperty('display', 'block');
    setTimeout(registeredDisplay, 3000);
    task.value ='';

    } else{
      errorMessage.style.setProperty('display', 'block');
      setTimeout(errorDisplay, 3000);
  }
// e.preventDefault();
}

  //Deleting task
  taskList.addEventListener('click', removeTask);

  // Remove Task
  function removeTask(e) {
  if(e.target.parentElement.classList.contains('deleteIcon')) {
  e.target.parentElement.parentElement.remove();
  }
}

//Clear all tasks
clearTask.addEventListener('click', ()=>{
  if(taskList.innerHTML === ''){
    errorMessage.style.setProperty('display', 'block');
      setTimeout(errorDisplay, 3000);
  }else if(confirm('Are you sure ?')){
    taskList.innerHTML = '';
    task.value ='';
  }
})
}

I'm already so frustrated, I hope you all can help out.
Thanks!

A: The automatic string conversion in Javascript for an object is just [Object][object] so when you do this:
console.log('The task is '+ req.body)

that's what is happening.  req.body undergoes an automatic string conversion to [Object][object] and that's appended to your string.
To fix, change your code to this:
console.log('The task is ', req.body);

so that console.log() can output the whole req.body object.


text:
Q: docker-compose not recognizing env_file file/location, and still tries to use the default .env Here's my compose file dev.yml
version: '2'

volumes:
  rethinkdb_data_dev: {}

services:
  rethinkdb:
    image: rethinkdb:latest
    volumes:
      - rethinkdb_data_dev:/home/rethinkdb_data

  rabbitmq:
    image: rabbitmq:latest

  fumio:
    build:
      context: .
      dockerfile: ./compose/fumio_dev/Dockerfile
    depends_on:
      - rethinkdb
      - rabbitmq
    links:
      - rethinkdb
      - rabbitmq
    env_file: ./compose/fumio_dev/dev.env
    environment:
      - GIRLFRIEND_FUMIO_CONFIG=development
      - GIRLFRIEND_FUMIO_NOSQLDATABASE_HOST=rethinkdb
    ports:
      - "${GIRLFRIEND_FUMIO_PORT}:8001"

The environment inside the dev.yml file is intentional, so I can override them inside with dev.env if needed.
My dev.env file, located inside compose/fumio_dev/ folder, relative to the dev.yml file.
GIRLFRIEND_FUMIO_PORT=8000

Here's what happens when I run docker-compose -f dev.yml build

If I provide .env file in the root folder, it runs fine, docker-compose ignores the env_file's value and try to use the default .env instead. So docker-compose env_file is somehow not working as intended or I'm missing something?
My docker-compose version is 1.8.0, I downgraded it to 1.7.1 but still no luck (installed using pip).

A: The .env file in the project root, and the env_file: field in the Compose file are two different concepts.
The .env is for settings a default environment for Compose. Values set in this file can be used within the Compose file.
The env_file: field is for setting the default environment for a container. Values set in this can be used in the container, but not in the Compose file.
See https://docs.docker.com/compose/env-file/ for more information.

A: As @dnephin has explained,

The env_file: field is for setting the default environment for a container. Values set in this can be used in the container, but not in the Compose file.

And one more thing I'd like to notice is that the --env-file flag that you can specify when executing the command, e.g. docker-compose --env-file ./somefile, and the env_file option in the compose file are absolutely different, too.
The --env-file flag enables you to determine a custom environment file that can be used in your Compose file.
So in your case, I think this command will do the trick:
docker-compose --env-file ./compose/fumio_dev/dev.env -f dev.yml build


text:
Q: Views being searched for in the wrong location I'm trying to understand what I've broken in my MVC project. I decided that I wanted to have hyphens supported implicitely in URLs, and so I wrote a RouteHandler to do this:
public class HyphenatedRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        requestContext.RouteData.Values["controller"] = ConvertDashToCamelCase(requestContext.RouteData.Values["controller"].ToString());
        requestContext.RouteData.Values["action"] = ConvertDashToCamelCase(requestContext.RouteData.Values["action"].ToString());
        return base.GetHttpHandler(requestContext);
    }
}

ConvertDashToCamelCase simply does as the name implies and converts a string like "my-controller" into "MyController" (not strictly camelcase I know, but it's not important to this question).
In addition to this, I am using Areas, and I have them set up similar to this:

*

*MyController

*

*Areas

*

*Modals

*

*MyController

*Json

*

*MyController

To clarify, I do have controllers with matching names across my different Areas, as indicated in the above example. And here are the route configurations:
// RouteConfig.cs
var dataTokens = new RouteValueDictionary();
dataTokens["Namespaces"] = new[] {"MyCompany.MyProject.Controllers"};
dataTokens["UseNamespaceFallback"] = false;

var constraints = new RouteValueDictionary();
var routeHandler = new HyphenatedRouteHandler();

var searchRoute = new Route("search",
    new RouteValueDictionary(new { controller = "search", action = "index" }),
    constraints,
    dataTokens,
    routeHandler
);

routes.Add("Search", searchRoute);

routes.Add(
    new Route("{controller}/{action}/{id}",
        new RouteValueDictionary(new { controller = "dashboard", action = "index", id = UrlParameter.Optional }),
        constraints,
        dataTokens,
        routeHandler
    )
);

For clarity, the following are the standard area registration classes generated by Visual Studio, and both inherit from AreaRegistration.
// ModalsAreaRegistration.cs
var dataTokens = new RouteValueDictionary();
dataTokens["Namespaces"] = new[] { "MyCompany.MyProject.Areas.Modals.Controllers" };
dataTokens["UseNamespaceFallback"] = false;

var constraints = new RouteValueDictionary();
var routeHandler = new HyphenatedRouteHandler();

context.Routes.Add("Modals_default",
    new Route("modals/{controller}/{action}/{id}",
        new RouteValueDictionary(new { action = "index", id = UrlParameter.Optional }),
        constraints,
        dataTokens,
        routeHandler
    )
);

.
// JsonAreaRegistration.cs
var dataTokens = new RouteValueDictionary();
dataTokens["Namespaces"] = new[] { "MyCompany.MyProject.Areas.Json.Controllers" };
dataTokens["UseNamespaceFallback"] = false;

var constraints = new RouteValueDictionary();
var routeHandler = new HyphenatedRouteHandler();

context.Routes.Add("Json_default",
    new Route("json/{controller}/{action}/{id}",
        new RouteValueDictionary(new { action = "index", id = UrlParameter.Optional }),
        constraints,
        dataTokens,
        routeHandler
    )
);

When I access any of these URLs:

*

*~/my-controller

*~/modals/my-controller

*~/json/my-controller

The request is routed to the expected controller without any issues.  However, when it comes time for MVC to locate the view, it always searches in the root ~/Views directory instead of the Area relevant to the controller.
I've been unable to discern why this is the case - I imagined that if MVC is able to route to the correct Area, from that point forward it should also be able to search the correct Views directory.
In summary
When I access the controller actions for controllers inside of my Json or Modals areas, MVC is searching for the associated Views inside of the root ~/Views directory instead of the appropriate Area's directory. Why is this happening, and can I fix it?

A: I found an answer for this, using some clues found in an answer to a different but similar question: https://stackoverflow.com/a/6656959/1704985.
I think the issue lies in the fact that I'm manually creating the route using new Route() rather than the usual system of adding the route via the MapRoute method.  I suspect the MapRoute method adds an appropriate DataToken to the route to reflect the current area.
In my case, because I was manually newing up the Route, it didn't contain that all important data token.  I updated my area registration classes to the following:
// ModalsAreaRegistration.cs
var dataTokens = new RouteValueDictionary();
dataTokens["Namespaces"] = new[] { "MyCompany.MyProject.Areas.Modals.Controllers" };
dataTokens["UseNamespaceFallback"] = false;
dataTokens["Area"] = "Modals";

var constraints = new RouteValueDictionary(); var routeHandler = new HyphenatedRouteHandler();

context.Routes.Add("Modals_default",
    new Route("modals/{controller}/{action}/{id}",
        new RouteValueDictionary(new { action = "index", id = UrlParameter.Optional }),
        constraints,
        dataTokens,
        routeHandler
    ) );

// JsonAreaRegistration.cs
var dataTokens = new RouteValueDictionary();
dataTokens["Namespaces"] = new[] { "MyCompany.MyProject.Areas.Json.Controllers" };
dataTokens["UseNamespaceFallback"] = false;
dataTokens["Area"] = "Json";

var constraints = new RouteValueDictionary(); var routeHandler = new HyphenatedRouteHandler();

context.Routes.Add("Json_default",
    new Route("json/{controller}/{action}/{id}",
        new RouteValueDictionary(new { action = "index", id = UrlParameter.Optional }),
        constraints,
        dataTokens,
        routeHandler
    ) );

Hey presto, problem solved!


text:
Q: Drop method of jquery droppable is not triggered for rows dragged out of table zone I've come across a very strange behaviour of my table with draggable rows. Everything seems to work fine with the only exception when I try to drag a row far below my table area and drop. It is actually dropped on the right place as the last row of the table, but drop method does not fire for some reason !
Any ideas how to solve this ?
http://jsfiddle.net/4fdohs4r/
$("tbody").sortable({
    items: "> tr",
    appendTo: "parent",
    helper: "clone"
}).disableSelection();

$(".table tr").droppable({
    hoverClass: "drophover",
    tolerance: "pointer",
    drop: function(e, ui) {
        $(this).append($(ui.draggable));
        alert('I work only if I am dropped gently within table area')
    }
});

A: You can limit your drop area with the
containment: '#somecontainer',

option. See also here: containment