text:
Q: creating preg_match using xpath in php I am trying to get the contents using XPATH in php.

Hi

I am using below php code to get the output.
 $dom = new DOMDocument;
 libxml_use_internal_errors(true);
 $dom->loadHTML($html);
 $xpath = new DOMXPath($dom);
 $xpath->registerPhpFunctions('preg_match');
 $regex = 'post-(content|[a-z]+)';
 $items = $xpath->query("div[ php:functionString('preg_match', '$regex', @class) > 0]");
 dd($items);

It returns output as below
DOMNodeList {#580
+length: 0
}

A: Here is a working version with the different advices you get in comments:
libxml_use_internal_errors(true);

$dom = new DOMDocument;
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
// you need to register the namespace "php" to make it available in the query
$xpath->registerNamespace("php", "http://php.net/xpath");
$xpath->registerPhpFunctions('preg_match');

// add delimiters to your pattern
$regex = '~post-(content|[a-z]+)~';

// search your node anywhere in the DOM tree with "//"
$items = $xpath->query("//div[php:functionString('preg_match', '$regex', @class)>0]");

var_dump($items);

Obviously, this kind of pattern is useless since you can get the same result with available XPATH string functions like contains.

A: For a simple task like this - getting the div nodes with class attribute starting with post- and containing content, you should be using regular simple XPath queries:
$xp->query('//div[starts-with(@class,"post-") and contains(@class, "content")]');

Here,
 - //div - get all divs that...
 - starts-with(@class,"post-") - have "class" attribute  starting with "post-"
 - and - and...
 - contains(@class, "content") - contain "content" substring in the class attribute value.
To use the php:functionString you need to register the php namespace (with $xpath->registerNamespace("php", "http://php.net/xpath");) and the PHP functions (to register them all use $xp->registerPHPFunctions();).
For complex scenrios, when you need to analyze the values even deeper, you may want to create and register your own functions:
function example($attr) {
    return preg_match('/post-(content|[a-z]+)/i', $attr) > 0;
}

and then inside XPath:
$divs = $xp->query("//div[php:functionString('example', @class)]");

Here, functionString passes the string contents of @class attribute to the example function, not the object (as would be the case with php:function).
See IDEONE demo:
function example($attr) {
    return preg_match('/post-(content|[a-z]+)/i', $attr) > 0;
}
$html = <<<HTML

Hi

HTML;
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);

$xp = new DOMXPath($dom);
$xp->registerNamespace("php", "http://php.net/xpath");
$xp->registerPHPFunctions('example');
$divs = $xp->query("//div[php:functionString('example', @class)]");
foreach ($divs as $div) {
    echo $div->nodeValue;
}

See also a nice article about the using of PhpFunctions inside XPath in Using PHP Functions in XPath Expressions.


text:
Q: Python peewee, filtering query based on elapsed time This is my "Request" class/Table:
class Request(BaseModel):
    TIME_STAMP = DateTimeField(default=datetime.datetime.now)
    MESSAGE_ID = IntegerField()

With peewee, I want to select from the table, all of the "requests" that have occurred over the past 10 minutes. Something like this:
rs = Request.select().where(Request.TIME_STAMP-datetime.datetime.now<(10 minutes))

But well, I'm not entirely sure how to get the difference between the TIME_STAMP and the current time in minutes.
EDIT:
I've tried Gerrat's suggestion, but Peewee seems to cry:
/usr/local/lib/python2.7/dist-packages/peewee.py:2356: Warning: Truncated incorrect DOUBLE value: '2014-07-19 15:51:24'
  cursor.execute(sql, params or ())
/usr/local/lib/python2.7/dist-packages/peewee.py:2356: Warning: Truncated incorrect DOUBLE value: '0 0:10:0'
  cursor.execute(sql, params or ())

A: I've never used peewee, but if you're just subtracting two timestamps, then you'll get back a datetime.timedelta object.  You should be able to just compare it to another timedelta object then.  Something like:
rs = Request.select().where(Request.TIME_STAMP-datetime.datetime.now()
                            <(datetime.timedelta(seconds=10*60)))

EDIT
...Looking a little closer at peewee, above may not work.  If it doesn't then something like the following should:
ten_min_ago = datetime.datetime.now() - datetime.timedelta(seconds=10 * 60)
rs = Request.select().where(Request.TIME_STAMP > ten_min_ago)

It seems slightly odd that your timestamp in your database would be greater than the current time (what your select assumes)...so you may want to add the time delta and subtract the values the other way around (eg if you want to select records in the last 10 minutes).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is 3 the only public exponent accepted for Android platform.key? I am building an android system.
I have an existing key pair, with a public exponent F4 (65537).
I try to use it as platform.key (I have the pk8 and the x509).
During the build process, DumpPublicKey is called on my key pair.
At this point, the key is rejected because the public exponent is not 3. (I checked in the code of DumpPublicKey, it is exactly what it does: compare with 3 and reject otherwise)
Here is the stacktrace for this :
java.lang.Exception: Public exponent should be 3 but is 65537.
    at com.android.dumpkey.DumpPublicKey.check(DumpPublicKey.java:75)
    at com.android.dumpkey.DumpPublicKey.main(DumpPublicKey.java:151)

Does this means I have to generate a new key pair using
openssl genrsa -3 ...

or is there any way I can still use my key?
Also, why is it so important that the public exponent is 3 and not F4?
Thanks in advance

A: Looks like a bug in com.android.dumpkey.DumpPublicKey to me.
Restricting the the public exponent of an RSA key to 3 is just plain silly.
Doing so just makes it more likely that implementation errors have desastrous effects,
if the underlying library is not implemented correctly.
As far as I know Android uses Bouncycastle, which is a crypto library that is
not carefully implemented.
Using the standard exponent 2^16+1 as you do, is very reasonable and avoids many potential
problems with small exponents.


text:
Q: I want to redirect and rewrite my urls I have a url like
http://www.mywebsite.com/shop-single-full.php?img=35

I want to rewrite and redirect this url like
http://www.mywebsite.com/Pure-Copper-Embossed-Jug-amp-4-Steel-Copper-Glass-Set-35.html

where text is the product name.
I also want when someone want to access
http://www.mywebsite.com/shop-single-full.php?img=35

it will automatically redirect it to
http://www.mywebsite.com/Pure-Copper-Embossed-Jug-amp-4-Steel-Copper-Glass-Set-35.html

Whatever I have tried is
RewriteRule ^shop-single-full/?$ ([A-Za-z0-9_\-]+)\-([0-9]+).html?%1 [R,L]
RewriteRule ^([A-Za-z0-9_\-]+)\-([0-9]+).html?$ /shop-single-full.php?img=$2&name=$1

but there is some problem in redirection.Thanks

A: Use header() in shop-single-full.php
header("Location: http://www.mywebsite.com/Pure-Copper-Embossed-Jug-amp-4-Steel-Copper-Glass-Set-35.html");

Read more about header() here


text:
Q: Compare the progression in multiple groups with different starting points I am working on a project where 8 municipalities have participated in a program, in which they received consultancy on how to restructure the social sector. As a part of the program the municipalities have been able to follow their development through seven different parameters. My job is to analyze the progression of each municipality but also make a comparison between the progression of the municipalities. However, the municipalities did not start in the program at the same time, and they did not have the same starting point (some municipalities had already been working on the restructuring, before they participated in the program).
My question is therefore: How do I compare the progression between the municipalities and also take their difference in starting points in to consideration? My own thoughts are that I need to establish a baseline of some sort, but how do I do this correctly?

A: If you have repeated measurements you can fit some form of mixed effects model for each of your seven variables separately. To do this you need for each observation: which municipality, which time, and whether before and after the introduction of the restructuring. I would suggest making time zero the timepoint when the restructuring took place so you line them all up with negative times before and positive after. The fit the model with time and before/after and a random effect for municipality. You can then add an interaction between time and before/after to see if the rates of change vary.
One thing to think about here is when you expect the intervention to take effect and how. Will it be immediate or come in gradually over time? Will it be a sudden shift or will it continue to take effect over time?


text:
Q: How to plot seaborn heatmap for target vs independent features I have df3 dataframe, my target column is "Per_of_WgtL" and I have other 12 independent columns. Here I want to see the correlation between target & independent columns in descending order and plot the heatmap for it
corr_matrix = df3.corr()
print(corr_matrix["Percent_of_WgtL"].sort_values(ascending=False))

Output:
Percent_of_WgtL    1.000000
BsND_Bloat         0.190860
BsGluc             0.144318
BsND_Full          0.139811
rs6923761          0.091101
BsND_Agg           0.052269
PrePYYt15          0.043543
Bs_Total_PctFat   -0.003681
MeanPrePYY        -0.012922
Sex               -0.029330
PrePYYt45         -0.040316
rs7903146         -0.043709
BsND_Nausea       -0.044458
PrePYYt90         -0.056125
BsND_Pain         -0.071712
Age               -0.073869
Bs_Trunk_PctFat   -0.100634
BsHgt_M           -0.133866
PrePYYbs          -0.194847
BsWgt_Kg          -0.201106
wk16Wgt_Kg        -0.386535
BsBuff_Kcal       -0.389229

Can anyone help with the heatmap plot which shows above result in visulization


text:
Q: Why is my hamburger navigation not loading when its in desktop mode? I am coding a website for my high school, and I am using a hamburger navigation for the website. When the website is shrunk to mobile mode, the hamburger loads and everything works. But if I close the hamburger and bring the website back to Desktop mode, the navigation is gone, because the
 tag is changed to display="none"; and I can't find a way to fix it.

$(document).ready(function() {
  $(".hamburger").click(function() {
    $("nav > ul").slideToggle(800);
  })
});
nav {
  width: 100%;
  min-height: 50px;
  float: left;
  font-family: "TT Pines Bold Italic DEMO";
  font-size: 18px;
  background: #444;
  text-align: center;
  display: block;
  top: 0;
  position: fixed;
  z-index: 10;
}

nav>ul {
  padding: 0;
  list-style: none;
  overflow: hidden;
  margin: 0;
}

nav>ul>li {
  display: inline;
  line-height: 50px;
}

nav>ul>li>a {
  text-decoration: none;
  color: #fff;
  padding: 25px 17px;
  text-transform: uppercase;
  font-size: 20px;
  letter-spacing: 2px;
  font-family: 'Open Sans Condensed', sans-serif;
}

a:hover {
  text-decoration: none;
  color: #efb60b;
}

@media only screen and (max-width: 320px) {
  nav {
    width: 100%;
    float: left;
    text-align: center;
  }
  nav>ul {
    margin-top: 50px;
    padding: 0;
    display: block;
    list-style: none;
  }
  nav>ul>li,
  nav>ul>li>a {
    line-height: 50px;
    display: list-item;
    margin-left: 0;
  }
  .hamburger {
    padding: 20px;
    display: block;
    float: left;
    text-align: center;
    color: #fff;
    font-size: 24px;
    cursor: pointer;
  }
}

@media only screen and (min-width: 320px) and (max-width: 768px) {
  nav {
    width: 100%;
    float: left;
    text-align: center;
  }
  nav>ul {
    margin-top: 50px;
    padding: 0;
    display: block;
    list-style: none;
  }
  nav>ul>li,
  nav>ul>li>a {
    line-height: 50px;
    display: list-item;
    margin-left: 0;
  }
  .hamburger {
    padding: 20px;
    display: block;
    float: left;
    text-align: center;
    color: #fff;
    font-size: 24px;
    cursor: pointer;
  }
}
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

Home

About

Students

Parents

Athletics

Contact

A: First of all, the hamburguer icon does show up on wide screens. However, its styling is only applied on small screens, and therefore on wide ones it's centered and black, not easily visible on the dark grey background.
Second, the use case you present (opening the site on a small screen, hiding the menu, and then widening the screen) is not very common outside of test situations, so it is not a very big problem. However, you can solve it with a new media query:
@media only screen and (min-width: 768px) {
  nav>ul {
    display: block!important; /* This forces the browser to apply this rule and show the menu, even if the inline css says to hide it */
  }
  nav>.hamburguer {
    display: none; /* This hides the hamburguer icon */
  }
}

A: So I'd like to state that your css is hidden unless the specified dimensions are met. And since "full-screen" mode isn't under those dimensions the css does not apply.
@media only screen and (max-width: 768px) and (min-width: 320px)
js:94
.hamburger {
padding: 20px;
display: block;
float: left;
text-align: center;
color: #fff;
font-size: 24px;
cursor: pointer;
}

This is what's being applied when in your "mobile" mode, have another media parameter for everything above (max-width: 768px, min-width: 320px).
PS: You're doing great, keep at it.


text:
Q: filter Json array multi key I am looking for a solution to let me filter my json with key status = 'p'  exist in lease array.  I tried to use this function it didn't work for me:
myActiveContractItems.filter(( myActiveContractItem ) => myActiveContractItem.leases.map( lease => lease.status === LeaseStatus.Primary))

The following is my JSON:
{
  "results": [
    {
      "contract": {
        "id": 445134,
        "reference": "L|2190197",
        "label": "APREMIS",
        "status": null,
        "payment_mode": null,
        "address": {
          "street": "1 RUE DES ALPILLES",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80000",
          "city": "AMIENS"
        },
        "billing_address": {
          "street": "1 RUE DES ALPILLES",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80090",
          "city": "AMIENS"
        },
        "primary_bank_account": {
          "bank": "",
          "iban": "",
          "bic": "",
          "name_of_account_holder": "",
          "rib": "   ",
          "rum": "",
          "blz": null,
          "account_number": null
        },
        "dedicated_bank_account": {
          "bank": "",
          "iban": "",
          "bic": ""
        },
        "number": "2190197",
        "day_of_collection": 0,
        "direct_debit_start_date": "-0001-11-30",
        "validate": false,
        "balance": -629.64,
        "signed": true,
        "company": null,
        "contacts": [],
        "rent_components": []
      },
      "leases": [
        {
          "reference": null,
          "metering_service_data": null,
          "start_date": "2019-03-05",
          "end_date": "-0001-11-30",
          "presumed_end_date": "-0001-11-30",
          "signing_date": "2019-02-20",
          "expected_rent_deposit": 0,
          "actual_rent_deposit": 0,
          "rent_amount": 217.83,
          "vat": 0,
          "charge_amount": 96.99,
          "flat_category": "Logement",
          "flat_category_id": 291,
          "flat_type": "COLLECTIF TYPE 1BIS",
          "flat_type_id": 618,
          "cost_contribution": 0,
          "tenant_rank": 9,
          "status": "P",
          "end_inspection": null,
          "number_of_occupants": null,
          "move_in_date": null,
          "handover_date": null,
          "move_out_date": null,
          "id": 837057,
          "leaving_reason": null,
          "notice_period": null,
          "flat": {
            "id": 332705,
            "reference": "OP80|SUDE|41|70|AL01|A|2|MISLCAL108",
            "reference_label": "MISLCAL108",
            "label": "MISLCAL108",
            "flat_contact": [],
            "valid": {
              "from": "1975-12-01",
              "to": "-0001-11-30"
            },
            "address": {
              "street": "1 RUE DES ALPILLES",
              "label": null,
              "kind": "main",
              "country": "",
              "federal_state": "",
              "postal_code": "80090",
              "city": "AMIENS"
            },
            "unique_credit_identifier": null,
            "parent_reference": "OP80|SUDE|41|70|AL01|A|2",
            "legal_model_space": "",
            "useful_space": 0,
            "corrected_space": 0,
            "new_rent_amount": null,
            "rental_charge": null,
            "condition": "",
            "location": "108",
            "immovable_property_valuation": 0,
            "valuation_year": 0,
            "comment": null,
            "category": "Logement",
            "category_id": 291,
            "type": "COLLECTIF TYPE 1BIS",
            "type_id": 618,
            "real_space": 36,
            "living_space": 31,
            "unit_for_flat_space": null,
            "vacant": false,
            "vacant_from": null,
            "vacancy_reason": null,
            "construction_date": "-0001-11-30",
            "floor": null,
            "bk01": {
              "main_account_number": null,
              "property_account_number": null,
              "branch_account_number": null
            },
            "surface_for_hot_water_consumption": null,
            "metering_service_data": null
          },
          "contacts": []
        }
      ],
      "tenants": [],
      "insurances": [
        {
          "id": 334281,
          "name": "MAIF",
          "insurance_policy": "2388193 H",
          "reference": "",
          "home": "",
          "start_date": "2021-01-01",
          "end_date": "2021-12-31"
        }
      ]
    },
    {
      "contract": {
        "id": 445147,
        "reference": "L|2190211",
        "label": "APREMIS",
        "status": null,
        "payment_mode": null,
        "address": {
          "street": "4 ALLEE PIERRE ROLLIN",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80000",
          "city": "AMIENS"
        },
        "billing_address": {
          "street": "4 ALLEE PIERRE ROLLIN",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80090",
          "city": "AMIENS"
        },
        "primary_bank_account": {
          "bank": "",
          "iban": "",
          "bic": "",
          "name_of_account_holder": "",
          "rib": "   ",
          "rum": "",
          "blz": null,
          "account_number": null
        },
        "dedicated_bank_account": {
          "bank": "",
          "iban": "",
          "bic": ""
        },
        "number": "2190211",
        "day_of_collection": 0,
        "direct_debit_start_date": "-0001-11-30",
        "validate": false,
        "balance": -908.28,
        "signed": true,
        "company": null,
        "contacts": [],
        "rent_components": []
      },
      "leases": [
        {
          "reference": null,
          "metering_service_data": null,
          "start_date": "2019-03-06",
          "end_date": "-0001-11-30",
          "presumed_end_date": "-0001-11-30",
          "signing_date": "2019-02-26",
          "expected_rent_deposit": 0,
          "actual_rent_deposit": 0,
          "rent_amount": 331.66,
          "vat": 0,
          "charge_amount": 122.48,
          "flat_category": "Logement",
          "flat_category_id": 291,
          "flat_type": "COLLECTIF TYPE 2",
          "flat_type_id": 619,
          "cost_contribution": 0,
          "tenant_rank": 8,
          "status": "P",
          "end_inspection": null,
          "number_of_occupants": null,
          "move_in_date": null,
          "handover_date": null,
          "move_out_date": null,
          "id": 837473,
          "leaving_reason": null,
          "notice_period": null,
          "flat": {
            "id": 331154,
            "reference": "OP80|SUDE|52|89|RO02|C|0|PRBLCRO058",
            "reference_label": "PRBLCRO058",
            "label": "PRBLCRO058",
            "flat_contact": [],
            "valid": {
              "from": "1980-10-16",
              "to": "-0001-11-30"
            },
            "address": {
              "street": "4 ALLEE PIERRE ROLLIN",
              "label": null,
              "kind": "main",
              "country": "",
              "federal_state": "",
              "postal_code": "80090",
              "city": "AMIENS"
            },
            "unique_credit_identifier": null,
            "parent_reference": "OP80|SUDE|52|89|RO02|C|0",
            "legal_model_space": "",
            "useful_space": 0,
            "corrected_space": 0,
            "new_rent_amount": null,
            "rental_charge": null,
            "condition": "",
            "location": "58",
            "immovable_property_valuation": 0,
            "valuation_year": 0,
            "comment": null,
            "category": "Logement",
            "category_id": 291,
            "type": "COLLECTIF TYPE 2",
            "type_id": 619,
            "real_space": 54,
            "living_space": 54,
            "unit_for_flat_space": null,
            "vacant": false,
            "vacant_from": null,
            "vacancy_reason": null,
            "construction_date": "-0001-11-30",
            "floor": null,
            "bk01": {
              "main_account_number": null,
              "property_account_number": null,
              "branch_account_number": null
            },
            "surface_for_hot_water_consumption": null,
            "metering_service_data": null
          },
          "contacts": []
        }
      ],
      "tenants": [],
      "insurances": [
        {
          "id": 334294,
          "name": "MAIF",
          "insurance_policy": "2388193 H",
          "reference": "",
          "home": "",
          "start_date": "2021-01-01",
          "end_date": "2021-12-31"
        }
      ]
    },
    {
      "contract": {
        "id": 445170,
        "reference": "L|2190237",
        "label": "APREMIS",
        "status": null,
        "payment_mode": null,
        "address": {
          "street": "34 RUE DU 31 AOUT 1944",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80000",
          "city": "AMIENS"
        },
        "billing_address": {
          "street": "34 RUE DU 31 AOUT 1944",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80090",
          "city": "AMIENS"
        },
        "primary_bank_account": {
          "bank": "",
          "iban": "",
          "bic": "",
          "name_of_account_holder": "",
          "rib": "   ",
          "rum": "",
          "blz": null,
          "account_number": null
        },
        "dedicated_bank_account": {
          "bank": "",
          "iban": "",
          "bic": ""
        },
        "number": "2190237",
        "day_of_collection": 0,
        "direct_debit_start_date": "-0001-11-30",
        "validate": false,
        "balance": -834.2,
        "signed": true,
        "company": null,
        "contacts": [],
        "rent_components": []
      },
      "leases": [
        {
          "reference": null,
          "metering_service_data": null,
          "start_date": "2019-03-05",
          "end_date": "-0001-11-30",
          "presumed_end_date": "-0001-11-30",
          "signing_date": "2019-03-01",
          "expected_rent_deposit": 0,
          "actual_rent_deposit": 0,
          "rent_amount": 311.21,
          "vat": 0,
          "charge_amount": 105.89,
          "flat_category": "Logement",
          "flat_category_id": 291,
          "flat_type": "COLLECTIF TYPE 4",
          "flat_type_id": 621,
          "cost_contribution": 0,
          "tenant_rank": 9,
          "status": "P",
          "end_inspection": null,
          "number_of_occupants": null,
          "move_in_date": null,
          "handover_date": null,
          "move_out_date": null,
          "id": 826780,
          "leaving_reason": null,
          "notice_period": null,
          "flat": {
            "id": 299105,
            "reference": "OP80|CENT|7|8|AO34|A|4|318LCAO024",
            "reference_label": "318LCAO024",
            "label": "318LCAO024",
            "flat_contact": [],
            "valid": {
              "from": "1958-11-01",
              "to": "-0001-11-30"
            },
            "address": {
              "street": "34 RUE DU 31 AOUT 1944",
              "label": null,
              "kind": "main",
              "country": "",
              "federal_state": "",
              "postal_code": "80090",
              "city": "AMIENS"
            },
            "unique_credit_identifier": null,
            "parent_reference": "OP80|CENT|7|8|AO34|A|4",
            "legal_model_space": "",
            "useful_space": 0,
            "corrected_space": 0,
            "new_rent_amount": null,
            "rental_charge": null,
            "condition": "",
            "location": "24",
            "immovable_property_valuation": 0,
            "valuation_year": 0,
            "comment": null,
            "category": "Logement",
            "category_id": 291,
            "type": "COLLECTIF TYPE 4",
            "type_id": 621,
            "real_space": 55,
            "living_space": 55,
            "unit_for_flat_space": null,
            "vacant": false,
            "vacant_from": null,
            "vacancy_reason": null,
            "construction_date": "-0001-11-30",
            "floor": null,
            "bk01": {
              "main_account_number": null,
              "property_account_number": null,
              "branch_account_number": null
            },
            "surface_for_hot_water_consumption": null,
            "metering_service_data": null
          },
          "contacts": []
        }
      ],
      "tenants": [],
      "insurances": [
        {
          "id": 334319,
          "name": "AXA",
          "insurance_policy": "2659495304",
          "reference": "",
          "home": "",
          "start_date": "2021-01-01",
          "end_date": "2021-12-31"
        }
      ]
    },
    {
      "contract": {
        "id": 445240,
        "reference": "L|2190322",
        "label": "APREMIS",
        "status": null,
        "payment_mode": null,
        "address": {
          "street": "26 -34 RUE DE LA DODANE",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80000",
          "city": "AMIENS"
        },
        "billing_address": {
          "street": "26 -34 RUE DE LA DODANE",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80000",
          "city": "AMIENS"
        },
        "primary_bank_account": {
          "bank": "",
          "iban": "",
          "bic": "",
          "name_of_account_holder": "",
          "rib": "   ",
          "rum": "",
          "blz": null,
          "account_number": null
        },
        "dedicated_bank_account": {
          "bank": "",
          "iban": "",
          "bic": ""
        },
        "number": "2190322",
        "day_of_collection": 0,
        "direct_debit_start_date": "-0001-11-30",
        "validate": false,
        "balance": -4489.57,
        "signed": true,
        "company": null,
        "contacts": [],
        "rent_components": []
      },
      "leases": [
        {
          "reference": null,
          "metering_service_data": null,
          "start_date": "2019-03-28",
          "end_date": "-0001-11-30",
          "presumed_end_date": "-0001-11-30",
          "signing_date": "2019-03-19",
          "expected_rent_deposit": 0,
          "actual_rent_deposit": 0,
          "rent_amount": 0,
          "vat": 0,
          "charge_amount": 0,
          "flat_category": "Foyer",
          "flat_category_id": 283,
          "flat_type": "COLLECTIF TYPE 1BIS",
          "flat_type_id": 618,
          "cost_contribution": 0,
          "tenant_rank": 1,
          "status": "S",
          "end_inspection": null,
          "number_of_occupants": null,
          "move_in_date": null,
          "handover_date": null,
          "move_out_date": null,
          "id": 840484,
          "leaving_reason": null,
          "notice_period": null,
          "flat": {
            "id": 301118,
            "reference": "OP80|CENT|89|149|DO26|A|1|DODDEDO012",
            "reference_label": "DODDEDO012",
            "label": "DODDEDO012",
            "flat_contact": [],
            "valid": {
              "from": "1993-08-01",
              "to": "-0001-11-30"
            },
            "address": {
              "street": "26 -34 RUE DE LA DODANE",
              "label": null,
              "kind": "main",
              "country": "",
              "federal_state": "",
              "postal_code": "80000",
              "city": "AMIENS"
            },
            "unique_credit_identifier": null,
            "parent_reference": "OP80|CENT|89|149|DO26|A|1",
            "legal_model_space": "",
            "useful_space": 0,
            "corrected_space": 0,
            "new_rent_amount": null,
            "rental_charge": null,
            "condition": "",
            "location": "",
            "immovable_property_valuation": 0,
            "valuation_year": 0,
            "comment": null,
            "category": "Foyer",
            "category_id": 283,
            "type": "COLLECTIF TYPE 1BIS",
            "type_id": 618,
            "real_space": 27,
            "living_space": 27,
            "unit_for_flat_space": null,
            "vacant": false,
            "vacant_from": null,
            "vacancy_reason": null,
            "construction_date": "-0001-11-30",
            "floor": null,
            "bk01": {
              "main_account_number": null,
              "property_account_number": null,
              "branch_account_number": null
            },
            "surface_for_hot_water_consumption": null,
            "metering_service_data": null
          },
          "contacts": []
        }
      ],
      "tenants": [
        {
          "person_id": 904316,
          "person_reference": "2162801",
          "person_first_name": "APREMIS",
          "person_last_name": "APREMIS",
          "birth_date": "1950-01-01",
          "title": "Association",
          "salutation": "ASSO",
          "status": "P",
          "arrival_date": "2019-03-28",
          "departure_date": null,
          "parent_link": null
        }
      ],
      "insurances": [
        {
          "id": 334394,
          "name": "MAIF",
          "insurance_policy": "2388193 H",
          "reference": "",
          "home": "",
          "start_date": "2021-01-01",
          "end_date": "2021-12-31"
        }
      ]
    }
  ]
}

A: I don't see LeaseStatus or LeaseStatus.Primary in your JSON data, but this works for me:
myActiveContractItems.results.filter(myActiveContractItem => myActiveContractItem.leases.some(lease => lease.status === "P"))

If myActiveContractItems is already the same as the results array, just remove the .results from my code above.
This filters the contract items to only contract items that have at least one lease with a status equal to "P".
As a result, one of the four contracts from your data is filtered out, returning the remaining three.

A: You should return a boolean value for the filter callback function. To detect at least one lease item have status is P (instead of p, I think so).
Demo:

const input = {
  "results": [
    {
      "contract": {
        "id": 445134,
        "reference": "L|2190197",
        "label": "APREMIS",
        "status": null,
        "payment_mode": null,
        "address": {
          "street": "1 RUE DES ALPILLES",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80000",
          "city": "AMIENS"
        },
        "billing_address": {
          "street": "1 RUE DES ALPILLES",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80090",
          "city": "AMIENS"
        },
        "primary_bank_account": {
          "bank": "",
          "iban": "",
          "bic": "",
          "name_of_account_holder": "",
          "rib": "   ",
          "rum": "",
          "blz": null,
          "account_number": null
        },
        "dedicated_bank_account": {
          "bank": "",
          "iban": "",
          "bic": ""
        },
        "number": "2190197",
        "day_of_collection": 0,
        "direct_debit_start_date": "-0001-11-30",
        "validate": false,
        "balance": -629.64,
        "signed": true,
        "company": null,
        "contacts": [],
        "rent_components": []
      },
      "leases": [
        {
          "reference": null,
          "metering_service_data": null,
          "start_date": "2019-03-05",
          "end_date": "-0001-11-30",
          "presumed_end_date": "-0001-11-30",
          "signing_date": "2019-02-20",
          "expected_rent_deposit": 0,
          "actual_rent_deposit": 0,
          "rent_amount": 217.83,
          "vat": 0,
          "charge_amount": 96.99,
          "flat_category": "Logement",
          "flat_category_id": 291,
          "flat_type": "COLLECTIF TYPE 1BIS",
          "flat_type_id": 618,
          "cost_contribution": 0,
          "tenant_rank": 9,
          "status": "P",
          "end_inspection": null,
          "number_of_occupants": null,
          "move_in_date": null,
          "handover_date": null,
          "move_out_date": null,
          "id": 837057,
          "leaving_reason": null,
          "notice_period": null,
          "flat": {
            "id": 332705,
            "reference": "OP80|SUDE|41|70|AL01|A|2|MISLCAL108",
            "reference_label": "MISLCAL108",
            "label": "MISLCAL108",
            "flat_contact": [],
            "valid": {
              "from": "1975-12-01",
              "to": "-0001-11-30"
            },
            "address": {
              "street": "1 RUE DES ALPILLES",
              "label": null,
              "kind": "main",
              "country": "",
              "federal_state": "",
              "postal_code": "80090",
              "city": "AMIENS"
            },
            "unique_credit_identifier": null,
            "parent_reference": "OP80|SUDE|41|70|AL01|A|2",
            "legal_model_space": "",
            "useful_space": 0,
            "corrected_space": 0,
            "new_rent_amount": null,
            "rental_charge": null,
            "condition": "",
            "location": "108",
            "immovable_property_valuation": 0,
            "valuation_year": 0,
            "comment": null,
            "category": "Logement",
            "category_id": 291,
            "type": "COLLECTIF TYPE 1BIS",
            "type_id": 618,
            "real_space": 36,
            "living_space": 31,
            "unit_for_flat_space": null,
            "vacant": false,
            "vacant_from": null,
            "vacancy_reason": null,
            "construction_date": "-0001-11-30",
            "floor": null,
            "bk01": {
              "main_account_number": null,
              "property_account_number": null,
              "branch_account_number": null
            },
            "surface_for_hot_water_consumption": null,
            "metering_service_data": null
          },
          "contacts": []
        }
      ],
      "tenants": [],
      "insurances": [
        {
          "id": 334281,
          "name": "MAIF",
          "insurance_policy": "2388193 H",
          "reference": "",
          "home": "",
          "start_date": "2021-01-01",
          "end_date": "2021-12-31"
        }
      ]
    },
    {
      "contract": {
        "id": 445147,
        "reference": "L|2190211",
        "label": "APREMIS",
        "status": null,
        "payment_mode": null,
        "address": {
          "street": "4 ALLEE PIERRE ROLLIN",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80000",
          "city": "AMIENS"
        },
        "billing_address": {
          "street": "4 ALLEE PIERRE ROLLIN",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80090",
          "city": "AMIENS"
        },
        "primary_bank_account": {
          "bank": "",
          "iban": "",
          "bic": "",
          "name_of_account_holder": "",
          "rib": "   ",
          "rum": "",
          "blz": null,
          "account_number": null
        },
        "dedicated_bank_account": {
          "bank": "",
          "iban": "",
          "bic": ""
        },
        "number": "2190211",
        "day_of_collection": 0,
        "direct_debit_start_date": "-0001-11-30",
        "validate": false,
        "balance": -908.28,
        "signed": true,
        "company": null,
        "contacts": [],
        "rent_components": []
      },
      "leases": [
        {
          "reference": null,
          "metering_service_data": null,
          "start_date": "2019-03-06",
          "end_date": "-0001-11-30",
          "presumed_end_date": "-0001-11-30",
          "signing_date": "2019-02-26",
          "expected_rent_deposit": 0,
          "actual_rent_deposit": 0,
          "rent_amount": 331.66,
          "vat": 0,
          "charge_amount": 122.48,
          "flat_category": "Logement",
          "flat_category_id": 291,
          "flat_type": "COLLECTIF TYPE 2",
          "flat_type_id": 619,
          "cost_contribution": 0,
          "tenant_rank": 8,
          "status": "P",
          "end_inspection": null,
          "number_of_occupants": null,
          "move_in_date": null,
          "handover_date": null,
          "move_out_date": null,
          "id": 837473,
          "leaving_reason": null,
          "notice_period": null,
          "flat": {
            "id": 331154,
            "reference": "OP80|SUDE|52|89|RO02|C|0|PRBLCRO058",
            "reference_label": "PRBLCRO058",
            "label": "PRBLCRO058",
            "flat_contact": [],
            "valid": {
              "from": "1980-10-16",
              "to": "-0001-11-30"
            },
            "address": {
              "street": "4 ALLEE PIERRE ROLLIN",
              "label": null,
              "kind": "main",
              "country": "",
              "federal_state": "",
              "postal_code": "80090",
              "city": "AMIENS"
            },
            "unique_credit_identifier": null,
            "parent_reference": "OP80|SUDE|52|89|RO02|C|0",
            "legal_model_space": "",
            "useful_space": 0,
            "corrected_space": 0,
            "new_rent_amount": null,
            "rental_charge": null,
            "condition": "",
            "location": "58",
            "immovable_property_valuation": 0,
            "valuation_year": 0,
            "comment": null,
            "category": "Logement",
            "category_id": 291,
            "type": "COLLECTIF TYPE 2",
            "type_id": 619,
            "real_space": 54,
            "living_space": 54,
            "unit_for_flat_space": null,
            "vacant": false,
            "vacant_from": null,
            "vacancy_reason": null,
            "construction_date": "-0001-11-30",
            "floor": null,
            "bk01": {
              "main_account_number": null,
              "property_account_number": null,
              "branch_account_number": null
            },
            "surface_for_hot_water_consumption": null,
            "metering_service_data": null
          },
          "contacts": []
        }
      ],
      "tenants": [],
      "insurances": [
        {
          "id": 334294,
          "name": "MAIF",
          "insurance_policy": "2388193 H",
          "reference": "",
          "home": "",
          "start_date": "2021-01-01",
          "end_date": "2021-12-31"
        }
      ]
    },
    {
      "contract": {
        "id": 445170,
        "reference": "L|2190237",
        "label": "APREMIS",
        "status": null,
        "payment_mode": null,
        "address": {
          "street": "34 RUE DU 31 AOUT 1944",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80000",
          "city": "AMIENS"
        },
        "billing_address": {
          "street": "34 RUE DU 31 AOUT 1944",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80090",
          "city": "AMIENS"
        },
        "primary_bank_account": {
          "bank": "",
          "iban": "",
          "bic": "",
          "name_of_account_holder": "",
          "rib": "   ",
          "rum": "",
          "blz": null,
          "account_number": null
        },
        "dedicated_bank_account": {
          "bank": "",
          "iban": "",
          "bic": ""
        },
        "number": "2190237",
        "day_of_collection": 0,
        "direct_debit_start_date": "-0001-11-30",
        "validate": false,
        "balance": -834.2,
        "signed": true,
        "company": null,
        "contacts": [],
        "rent_components": []
      },
      "leases": [
        {
          "reference": null,
          "metering_service_data": null,
          "start_date": "2019-03-05",
          "end_date": "-0001-11-30",
          "presumed_end_date": "-0001-11-30",
          "signing_date": "2019-03-01",
          "expected_rent_deposit": 0,
          "actual_rent_deposit": 0,
          "rent_amount": 311.21,
          "vat": 0,
          "charge_amount": 105.89,
          "flat_category": "Logement",
          "flat_category_id": 291,
          "flat_type": "COLLECTIF TYPE 4",
          "flat_type_id": 621,
          "cost_contribution": 0,
          "tenant_rank": 9,
          "status": "P",
          "end_inspection": null,
          "number_of_occupants": null,
          "move_in_date": null,
          "handover_date": null,
          "move_out_date": null,
          "id": 826780,
          "leaving_reason": null,
          "notice_period": null,
          "flat": {
            "id": 299105,
            "reference": "OP80|CENT|7|8|AO34|A|4|318LCAO024",
            "reference_label": "318LCAO024",
            "label": "318LCAO024",
            "flat_contact": [],
            "valid": {
              "from": "1958-11-01",
              "to": "-0001-11-30"
            },
            "address": {
              "street": "34 RUE DU 31 AOUT 1944",
              "label": null,
              "kind": "main",
              "country": "",
              "federal_state": "",
              "postal_code": "80090",
              "city": "AMIENS"
            },
            "unique_credit_identifier": null,
            "parent_reference": "OP80|CENT|7|8|AO34|A|4",
            "legal_model_space": "",
            "useful_space": 0,
            "corrected_space": 0,
            "new_rent_amount": null,
            "rental_charge": null,
            "condition": "",
            "location": "24",
            "immovable_property_valuation": 0,
            "valuation_year": 0,
            "comment": null,
            "category": "Logement",
            "category_id": 291,
            "type": "COLLECTIF TYPE 4",
            "type_id": 621,
            "real_space": 55,
            "living_space": 55,
            "unit_for_flat_space": null,
            "vacant": false,
            "vacant_from": null,
            "vacancy_reason": null,
            "construction_date": "-0001-11-30",
            "floor": null,
            "bk01": {
              "main_account_number": null,
              "property_account_number": null,
              "branch_account_number": null
            },
            "surface_for_hot_water_consumption": null,
            "metering_service_data": null
          },
          "contacts": []
        }
      ],
      "tenants": [],
      "insurances": [
        {
          "id": 334319,
          "name": "AXA",
          "insurance_policy": "2659495304",
          "reference": "",
          "home": "",
          "start_date": "2021-01-01",
          "end_date": "2021-12-31"
        }
      ]
    },
    {
      "contract": {
        "id": 445240,
        "reference": "L|2190322",
        "label": "APREMIS",
        "status": null,
        "payment_mode": null,
        "address": {
          "street": "26 -34 RUE DE LA DODANE",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80000",
          "city": "AMIENS"
        },
        "billing_address": {
          "street": "26 -34 RUE DE LA DODANE",
          "label": null,
          "kind": "main",
          "country": "",
          "federal_state": "",
          "postal_code": "80000",
          "city": "AMIENS"
        },
        "primary_bank_account": {
          "bank": "",
          "iban": "",
          "bic": "",
          "name_of_account_holder": "",
          "rib": "   ",
          "rum": "",
          "blz": null,
          "account_number": null
        },
        "dedicated_bank_account": {
          "bank": "",
          "iban": "",
          "bic": ""
        },
        "number": "2190322",
        "day_of_collection": 0,
        "direct_debit_start_date": "-0001-11-30",
        "validate": false,
        "balance": -4489.57,
        "signed": true,
        "company": null,
        "contacts": [],
        "rent_components": []
      },
      "leases": [
        {
          "reference": null,
          "metering_service_data": null,
          "start_date": "2019-03-28",
          "end_date": "-0001-11-30",
          "presumed_end_date": "-0001-11-30",
          "signing_date": "2019-03-19",
          "expected_rent_deposit": 0,
          "actual_rent_deposit": 0,
          "rent_amount": 0,
          "vat": 0,
          "charge_amount": 0,
          "flat_category": "Foyer",
          "flat_category_id": 283,
          "flat_type": "COLLECTIF TYPE 1BIS",
          "flat_type_id": 618,
          "cost_contribution": 0,
          "tenant_rank": 1,
          "status": "S",
          "end_inspection": null,
          "number_of_occupants": null,
          "move_in_date": null,
          "handover_date": null,
          "move_out_date": null,
          "id": 840484,
          "leaving_reason": null,
          "notice_period": null,
          "flat": {
            "id": 301118,
            "reference": "OP80|CENT|89|149|DO26|A|1|DODDEDO012",
            "reference_label": "DODDEDO012",
            "label": "DODDEDO012",
            "flat_contact": [],
            "valid": {
              "from": "1993-08-01",
              "to": "-0001-11-30"
            },
            "address": {
              "street": "26 -34 RUE DE LA DODANE",
              "label": null,
              "kind": "main",
              "country": "",
              "federal_state": "",
              "postal_code": "80000",
              "city": "AMIENS"
            },
            "unique_credit_identifier": null,
            "parent_reference": "OP80|CENT|89|149|DO26|A|1",
            "legal_model_space": "",
            "useful_space": 0,
            "corrected_space": 0,
            "new_rent_amount": null,
            "rental_charge": null,
            "condition": "",
            "location": "",
            "immovable_property_valuation": 0,
            "valuation_year": 0,
            "comment": null,
            "category": "Foyer",
            "category_id": 283,
            "type": "COLLECTIF TYPE 1BIS",
            "type_id": 618,
            "real_space": 27,
            "living_space": 27,
            "unit_for_flat_space": null,
            "vacant": false,
            "vacant_from": null,
            "vacancy_reason": null,
            "construction_date": "-0001-11-30",
            "floor": null,
            "bk01": {
              "main_account_number": null,
              "property_account_number": null,
              "branch_account_number": null
            },
            "surface_for_hot_water_consumption": null,
            "metering_service_data": null
          },
          "contacts": []
        }
      ],
      "tenants": [
        {
          "person_id": 904316,
          "person_reference": "2162801",
          "person_first_name": "APREMIS",
          "person_last_name": "APREMIS",
          "birth_date": "1950-01-01",
          "title": "Association",
          "salutation": "ASSO",
          "status": "P",
          "arrival_date": "2019-03-28",
          "departure_date": null,
          "parent_link": null
        }
      ],
      "insurances": [
        {
          "id": 334394,
          "name": "MAIF",
          "insurance_policy": "2388193 H",
          "reference": "",
          "home": "",
          "start_date": "2021-01-01",
          "end_date": "2021-12-31"
        }
      ]
    }
  ]
};

const filtered = input.results.filter(result => {
  return result.leases.some(l => l.status === 'P');
});

console.log(filtered);

A: First, don't forget that JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters. The character p is different from P. Leases value is P not p in your JSON data.
Solution
myActiveContractItems.results.filter((item)=>{
    return item.leases.filter((lease)=>{
        return lease.status ==='P'; // Or LeaseStatus.Primary
  }).length > 0;
});

*

*Act on myActiveContractItems.results array and filter it

*Filter item.leases by status (in this case equal to P)

*If Filtered Leases has items (length > 0), contract can be included in the main filter

Reusable Solution
Ideally, you can create a general function to filter by lease status and use some method instead of check the length of the elements with that status
let filterByLeaseStatus = (leaseStatus)=>
myActiveContractItems.results.filter((item)=>
item.leases.some((lease)=>lease.status ===leaseStatus));

and then use it filterByLeaseStatus('P') or filterByLeaseStatus(LeaseStatus.Primary)

A: By calling Array.map, in the inner function all you are doing is mapping the array elements to an array of boolean values.  As long as there is one lease in the collection then the contract item should get returned by Array.filter (since an empty array is falsey).
Instead use Array.some in the inner function which will return true if at least one element matches the predicate.
myActiveContractItems.filter((item) =>
  item.leases.some((lease) => lease.status === LeaseStatus.Primary));


text:
Q: MongoDB query returning more than expected for nmap data Here's an excerpt of an nmap scan that I've converted from xml into json format:
{
    "nmaprun": {
        "@scanner": "nmap",
        "@args": "nmap -T4 -F -sV -O -n --exclude 192.168.10.1 -oX nmap-00:90:a9:0e:87:21.xml 192.168.10.1/24",
        "@start": "1470812419",
        "@startstr": "Wed Aug 10 00:00:19 2016",
        "@version": "7.12",
        "@xmloutputversion": "1.04",
        "scaninfo": {
            "@type": "syn",
            "@protocol": "tcp",
            "@numservices": "100",
        "host": {
            "@starttime": "1470812419",
            "@endtime": "1470812462",
            "status": {
                "@state": "up",
                "@reason": "arp-response",
                "@reason_ttl": "0"
            },
            "address": [
                {
                    "@addr": "192.168.1.123",
                    "@addrtype": "ipv4"
                },
                {
                    "@addr": "18:B4:30:4C:94:1B",
                    "@addrtype": "mac"
                }
            ]
}

The return of the following query that attempts to look up and project the MAC address + address type has extra fields in it
db.nmaps.find({"nmaprun.host.address.@addr":"18:B4:30:4C:94:1B","nmaprun.host.address.@addrtype":"mac"},{"nmaprun.host.address.@addrtype":1, "nmaprun.host.address.@addr":1}).pretty()

Returns extra fields that do not match the  parameters of the query. Specifically, the ipv4 and ip address also get returned. Not sure why this is happening.
Return of query:
{
  "_id" : ObjectId("57acb4c35e18500dc5f4d7d8"),
  "nmaprun" : {
    "host" : {
      "address" : [
        {
          "@addr" : "",
          "@addrtype" : "ipv4"
        },
        {
          "@addr" : "18:B4:30:4C:94:1B",
          "@addrtype" : "mac"
        }
      ]
    }
  }
}

A: The reason you are getting both array elements is that the entire document is considered a match to the find criteria you've provided, and there is nothing in your projection to limit the results to only the matched array element.
A simple way to change what you have to get the expected results is to use the positional $ operator (https://docs.mongodb.com/manual/reference/operator/projection/positional/) in your projection:
db.nmaps.find({"nmaprun.host.address.@addr":"18:B4:30:4C:94:1B","nmaprun.host.address.@addrtype":"mac"},{"nmaprun.host.address.$":1}).pretty()

Another way to do it would be using aggregation:
db.nmaps.aggregate([
    {
        $unwind: "$nmaprun.host.address"
    },
    {
        $match:{
            "nmaprun.host.address.@addr":"18:B4:30:4C:94:1B",
            "nmaprun.host.address.@addrtype":"mac"
        }
    },
    {
        $project:{
            "nmaprun.host.address.@addrtype":1,
            "nmaprun.host.address.@addr":1
        }
    }
])


text:
Q: Windows version of Chrome 56 random "L" superscript sprinkled in text This is an original wordpress theme built for a client. On Windows only, Chrome is generating random L superscripts throughout the text.
Looked in the generated html, nothing erroneous, just literally a random L inserted in the DOM that isn't supposed to be there
Here is a view of the site. Any suggestions?

Thanks.


text:
Q: MYSQL + Change path + Update substring I have a question, i have table 'file' with a column 'path' in my DB called Pics.
Each path is like "C:\my folder\pics\pic1.jpg" etc.......
How i do to change:
C:\my folder\pics\

to
C:\my NEW folder\NEW pics\

I try a select for the path folder without the filename like this :
SELECT substring(c1,1,locate(substring_index(c1,'/',-1),c1)-1) FROM t1

that give me "C:\my folder\pics\".
Now i need to update all the column path. What is the correct query. I try this but dont work.
update foto set path = 'z' where path = (SELECT substring(path,1,locate(substring_index(path,'\\',-1),path)-1))

Thanks for sharing

A: Done.
update foto set path = REPLACE(path,(SELECT substring(path,1,locate(substring_index(path,'\\',-2),path)-1)),'" & TextBox2.Text & "'


text:
Q: How can I delete a set of records from sql table I have a table with the name column containing values like 'arthur_01', 'arthur_02', 'arthur_03'...'arthur_10' and many other values.
Is there a way to delete all the 'arthur_0x' in one query?
I know that the BETWEEN operator takes a range, but is there a way for it to take in a range where half the string is numeric?

A: You need the LIKE operator: http://www.w3schools.com/sql/sql_like.asp
DELETE FROM table WHERE column LIKE 'arthur_0%';

This solution makes somse assumptions about what data is beyond 'arthur_0.....'. Otherwise you may need RDBS specific functions.

A: There are different approaches to this and unfortunately most of them are vendor specific.
One approach is to extract the character of interest and compare to target value
DELETE FROM table1
 WHERE SUBSTRING(column_name, 9, 1) = x;

or for a range of values
DELETE FROM table1
 WHERE SUBSTRING(column_name, 9, 1) BETWEEN x AND y

Here is SQLFiddle demo (MySQL)
Here is SQLFiddle demo (SQL Server)
Note: the drawback of this approach is that the optimizer won't be able to use any indices you might have on this column.

Another approach is to leverage pattern matching, but it's not implemented the same way in different RDBMSes.
In SQL Server for example you can do
DELETE FROM table1
 WHERE column_name LIKE 'arthur_0[345]%';

Which will effectively delete any rows with values in column_name that start with
arthur_03 or arthur_04 or arthur_05.
Here is SQLFiddle demo
Same thing in MySQL might look like
DELETE FROM table1
 WHERE column_name RLIKE '^arthur_0[345]';

Here is SQLFiddle demo


text:
Q: Unable to read symbols warning after updating to 4.3.3 I just updated my device to iOS 4.3.3. Xcode 4 automatically updated when I plugged in my iPhone4 first time after iOS update.
When running my project I get a warning now:

warning: Unable to read symbols for
  /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.3
  (8J2)/Symbols/System/Library/AccessibilityBundles/AccessibilitySettingsLoader.bundle/AccessibilitySettingsLoader
  (file not found).

Why do I get this warning and how to solve this?

A: I also faced  this issue you should just delete that folder (/Developer/Platforms/iPhoneOS.platform/DeviceSupport//4.3.3), connect your device again, go to the XCode Organizer and it will ask you to collect the symbols from the device. After a couple minutes it will be done collecting and processing the symbols off the device, and you should be good to go.

A: As I've read elsewhere, making a symlink can take care of the problem. I had no success with refetching symbols from my ipad. This probably isn't the best solution, but it's working so far for me.
just run:
sudo ln  -s /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/Developer/
 /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.3 (8J2)/Symbols/Developer

A: You should open Organizer( Xcode > Window > Organizer ) and do something like "fetch symbols" I think when your phone is plugged in.


text:
Q: Rails sanitize user input in active record query Let's say I have following data:
models/supplier.rb
| -- | ---------------- |
| id | name             |
| -- | ---------------- |
| 1  | John Doe's Store |
| 2  | Jane             |
| -- | ---------------- |

I have following queries which are failing to sanitize user's input from search field:
@term = "John Doe's"

Query 1
Supplier.order("case when name LIKE :term 1 else 2 end, name asc", term: "#{@term}%")

ArgumentError: Direction "one's%" is invalid. Valid directions are: [:asc, :desc, :ASC, :DESC, "asc", "desc", "ASC", "DESC"]
from ~/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-4.2.7/lib/active_record/relation/query_methods.rb:1113:in `block (2 levels) in validate_order_args'

Query 2

Vulnerable to SQL Injection attack

Supplier.order("case when name LIKE '#{@term}%' then 1 else 2 end, name ASC").first

Supplier Load (2.6ms)  SELECT  "suppliers".* FROM "suppliers"  ORDER BY case when name LIKE 'John Doe's%' then 1 else 2 end LIMIT 1
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near "s"
LINE 1: ...uppliers"  ORDER BY case when name LIKE 'John Doe's%' then 1..

Query 3

It will success for normal inputs which don't have ' (special character) in them, but this query is still vulnerable to SQL injection attack

@term = "John"

Supplier.order("case when name LIKE '#{@term}%' then 1 else 2 end, name ASC").first

#<Supplier:0x007fe4bfd8d758
 id: 188,
 name: "John Doe's Store">

I am not able to figure out a solution for this problem, Please help me complete this query in secure way.

A: All you need to escape your input is to use
ActiveRecord::Base.connection.quote(value)

This works for all types and is what rails use.
@term =  ActiveRecord::Base.connection.quote("John Doe's" + "%" )

Supplier.order("case when name LIKE #{@term} then 1 else 2 end, name ASC").first

A: You can use the base connection quote which will sanitize the input
@term = "John Doe's"

like_value = ActiveRecord::Base.connection.quote(@term + '%')

Supplier.order("case when name LIKE #{like_value} 1 else 2 end, name asc")

Read about it here...
http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Quoting.html#method-i-quote

A: Rails offers sanitize_sql_like() for this.
So your example would look like this:
@term = "John Doe's"

like_value = sanitize_sql_like(@term + '%')

Supplier.order("case when name LIKE #{like_value} 1 else 2 end, name asc")

See:
https://api.rubyonrails.org/classes/ActiveRecord/Sanitization/ClassMethods.html#method-i-sanitize_sql_like

EDIT:
If you need to use it in a Controller, call it like this:
ActiveRecord::Base::sanitize_sql_like()


text:
Q: Flexbox parent is taller than its children I've built a small layout using flex and chunks form Bootstrap as well as a mini grid system but I'm having issues with situations where the children of that flexbox are not tall enough to actually fill it. In my case, if you go ahead and inspect the .demo-install-components, you can see that it has a higher height than its children. Surprisingly, if I add just another item .install-component-individual to the mix, it's fixed or if I remove the check icon .installed-component-check. To me, this smells very, very bad. It looks like this:

Here's the code (sorry for it being so long and on jsfiddle, wanted to provide everything I have):
JSFiddle code.
What exactly am I missing here? I feel as if my knowledge of flexbox isn't complete.

A: Margin from #components-to-install-list ends up under your container.
By removing the width and margin from #components-to-install-list (line 986-987 from CSS), the space underneath will disappear:


text:
Q: Стоит ли объявлять constexpr-переменные static? Существуют ли ситуации, когда локальные constexpr переменные имеет смысл объявить без ключевого слова static?
Т.е. есть ли смысл объявлять так:
void foo() {
  constexpr auto x = 42;

а не так:
void foo() {
  static constexpr auto x = 42;

Пример, когда со static gcc генерит лучше код.
Если использовать какой-нибудь ресурсоёмкий инициализатор типа std::array<double, 10000>{}, то разница ещё более заметна. Вариант без static будет вызывать memset на 80000 байт каждый вызов функции, в то время как со static - ссылаться на одну запись из .zero памяти. Пример.

A: Например, если вы берете адрес переменной (или ссылку) и переедаете ее за пределы функции, поведение отличается принципиально. Хотя это странный способ использования constexpr, но разрешенный стандартом.
Если адрес переменной x никак не используется, то в режиме оптимизации, компиляторы сгенерирую один и тоже код, в котором память под x не будет выделена ни на стеке, ни в сегменте констант.

A: Понятие лучше - понятие относительное. Если вы объявляете переменную со static, то получается переменная с глобальным временем жизни и локальной областью видимости. А без static - переменная с локальными временем жизни и областью видимости.
А constexpr - не панацея, потому что компилятор считает, что всегда в коде может встретиться const_cast<>. Опять-таки, в c/c++ - константность скорее возможность компилятора помочь программисту избежать ошибок.
Здесь скорее нужно выбирать, в какой переменной вы нуждаетесь, исходя из логики вашей программы.


text:
Q: Compile Error trying to bind a ABBYY RTR SDK.AAR file via Xamarin Android Binding project I get the error below when I try to bind the "abbyy-rtr-sdk-1.0.aar" downloaded from https://rtrsdk.com/#RTR.Android.Online using Xamarin Android Binding project in Visual Studio 2017, by following the link https://learn.microsoft.com/en-gb/xamarin/android/platform/binding-java-library/binding-an-aar
Severity    Code    Description    Project    File    Line    Suppression State
Error    CS0234    The type or namespace name 'IRecognitionContextHolder' does not exist in the namespace 'Com.Abbyy.Mobile.Ocr4' (are you missing an assembly reference?)    AbbyLib    C:\_MyLab\Xamarin\My\OCR\TextRecogniser\AbbyLib\obj\Debug\generated\src\Com.Abbyy.Mobile.Ocr4.IRecognitionManager.cs    481    Active

Severity    Code    Description    Project    File    Line    Suppression State
Error    CS0738    'IDataCaptureServiceInvoker' does not implement interface member 'IRecognitionService.ExtendedSettings'. 'IDataCaptureServiceInvoker.ExtendedSettings' cannot implement 'IRecognitionService.ExtendedSettings' because it does not have the matching return type of 'IRecognitionServiceExtendedSettings'.    AbbyLib    C:\_MyLab\Xamarin\My\OCR\TextRecogniser\AbbyLib\obj\Debug\generated\src\Com.Abbyy.Mobile.Rtr.IDataCaptureService.cs    679    Active

Error    CS0738    'ITextCaptureServiceInvoker' does not implement interface member 'IRecognitionService.ExtendedSettings'. 'ITextCaptureServiceInvoker.ExtendedSettings' cannot implement 'IRecognitionService.ExtendedSettings' because it does not have the matching return type of 'IRecognitionServiceExtendedSettings'.    AbbyLib    C:\_MyLab\Xamarin\My\OCR\TextRecogniser\AbbyLib\obj\Debug\generated\src\Com.Abbyy.Mobile.Rtr.ITextCaptureService.cs    681    Active

Update
Steps I use by following the link https://learn.microsoft.com/en-gb/xamarin/android/platform/binding-java-library/binding-an-aar
1 Add "abbyy-rtr-sdk-1.0.aar" under Jars folder
2 Set Build Action to LibraryProjectZip
3 Set Compile Using Android version: to Android 4.4 (KitKat) for the Binding project
4 Build the project
I get the errors above.
Below is the versions of IDE:
Window 7
Microsoft Visual Studio Enterprise 2017 (2)
Version 15.8.6
VisualStudio.15.Release/15.8.6+28010.2041
Microsoft .NET Framework
Version 4.7.03062
Xamarin 4.11.0.776
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.
Xamarin Designer 4.15.9
Visual Studio extension to enable Xamarin Designer tools in Visual Studio.
Xamarin Templates 1.1.116
Templates for building iOS, Android, and Windows apps with Xamarin and Xamarin.Forms.
Xamarin.Android SDK 9.0.0.19
Xamarin.Android Reference Assemblies and MSBuild support.
Xamarin.iOS and Xamarin.Mac SDK 12.0.0.15
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.


text:
Q: what are the components of the variable assignment log entry on finest, my log entry looks like this:
09:30:19.490 (8458283328)|VARIABLE_ASSIGNMENT|[231]|this|{"c":"0x2980752a","tasks":"0x6e159af1"}|0x3de7ae9e
It's a variable assignment in object.method().
I'm trying to figure out if 0x3de7ae9e is the pointer address for the object.  Hopefully it is, and I can tell which instance of an object a method is firing on.  Otherwise, is there a way to tell?  Also tasks is a List of tasks.  is 0x6e159af1 the address for this list?

A:
09:30:19.490 (8458283328)

The time at evaluation of that line of code.

VARIABLE_ASSIGNMENT

The specific op-code being evaluated.

[231]

The line which is being executed.

this

The target object. this means the current object context, it can also be a symbol, such as myClass.myProp.

{"c":"0x2980752a","tasks":"0x6e159af1"}

The value being assigned to the property.

0x3de7ae9e

The heap address of the object being used.

I'm trying to figure out if 0x3de7ae9e is the pointer address for the object.

Yes, as mentioned above.

Also tasks is a List of tasks. is 0x6e159af1 the address for this list?

Yes, it is. If you open the log viewer in the Developer Console, you can use the Debug > Switch Perspective > Debug (Predefined) perspective to see the variables in memory, search by the memory address/pointer, etc.


text:
Q: In Stanford Topic Modeling Toolkit (TMT), what does the number against a topic mean (in the output file "summary.txt")? A typical snippet from Stanford TMT's 'summary.txt' file is as follows:
Topic00   37.47500834475079
    term1 11.163093014855274
    term2 2.8478206435760547
    term3 1.905685547333616
    term4 1.8341840331688735

So far, the only information I have been able to get regarding the numbers is this (from http://nlp.stanford.edu/software/tmt/tmt-0.4):
[Snapshot]/summary.txt Human readable summary of the topic model, with top-20 terms per topic and how many words instances of each have occurred.
But what does the number against the topic mean? (In this example, Topic00   37.47500834475079)

A: According to the documentation in the source code it is "how many times each topic is seem overall"

A: For example your output have 30 topics. Each topic shows its top words, and the relative weight of these words per topic

A: I guess the value is the distribution in the topic. It can also express the importance in the topic. You can see the number after Topic 00, which is the sum of the weights of all terms. You can also check the topic-term-distributions.csv. You will see the sum of each row is equal to the number after "Topic **".


text:
Q: While implementing OLS in a a multiple regression with on dependnt variable and three independent variables Patsy error of numpy is there While implementing OLS in a  a multiple regression with on dependent variable and three independent variables  the following code is being faced

PatsyError: Error evaluating factor: IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices
     y ~ X1
     ^

#Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('data1.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].values

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

# Fitting Multiple Linear Regression to the Training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)

# Predicting the Test set results
y_pred = regressor.predict(X_test)

#OLS for multiple regression
import statsmodels.formula.api as sm
from statsmodels.api import add_constant
X1= add_constant(X)
regressor_OLS = sm.ols(formula = 'y ~ X1', data = X1)
regressor_OLSm = regressor_OLS.fit()
print(regressor_OLSm.summary())

enter image description here

A: learners problems i guess
in
regressor_OLS = sm.ols(formula = 'y ~ X1', data = X1)
i should have used fwg
regressor_OLS = sm.ols(formula = 'y ~ X1', data = datset)
sorry for bothering.
regards
all


text:
Q: YouTube Data Api Quota exceeded even if actually not Daily quota usage is app 50% under limit but still getting error "code: 400 - message: The user has exceeded the number of videos they may upload".
usage
limit
Anyone had similar problem?
Cheers,
DN

A: There are actually two separate quotas that youtube enforces.
From an application standpoint, every youtube api call consumes quota of which the cost is listed on the youtube support page.
Additionally, there is a separate floating quota (depending on a variety of factors) of the number of videos you are allowed to upload per day to a specific channel, this is rather poorly documented but depends on both the amount of verification you've provided Google as well as the traction (subscribers/views) that your channel has.
At the lower tiers, this will be around 10-15 videos and at the higher tiers may top out around 150.


text:
Q: How to get accurate encoder output for kmeans clustering of similar images I expected that if I trained similar images in an autoencoder the output from the encoder would be similar, hence if passed through a clustering algorithm they would form clusters around the same point. So what I did was to train the model with identical images (basically 60 duplicates of the same image). What I noticed, on the contrary, is that the values from the encoder appear different and when passed through kmeans clustering the points are scattered, which tells me nothing about how related my images are to each other.
kmeans clustering of 60 duplicate images
def autoencoderConv2D(input_shape=(228, 228, 1), filters=[32, 64, 128, 10]):
input_img = Input(shape=input_shape)
if input_shape[0] % 8 == 0:
    pad3 = 'same'
else:
    pad3 = 'valid'
x = Conv2D(filters[0], 5, strides=2, padding='same', activation='relu', name='conv1', input_shape=input_shape)(input_img)

x = Conv2D(filters[1], 5, strides=2, padding='same', activation='relu', name='conv2')(x)

x = Conv2D(filters[2], 3, strides=2, padding=pad3, activation='relu', name='conv3')(x)

x = Flatten()(x)
encoded = Dense(units=filters[3], name='embedding')(x)
x = Dense(units=filters[2]*int(input_shape[0]/8)*int(input_shape[0]/8), activation='relu')(encoded)
print (x.shape)
x = Reshape((int(input_shape[0]/8), int(input_shape[0]/8), filters[2]))(x)
print (x.shape)
x = Conv2DTranspose(filters[1], 3, strides=2, padding=pad3, activation='relu', name='deconv3')(x)

x = Conv2DTranspose(filters[0], 5, strides=2, padding='same', activation='relu', name='deconv2')(x)
print (x.shape)
decoded = Conv2DTranspose(input_shape[2], 5, strides=2, padding='same', name='deconv1')(x)
return Model(inputs=input_img, outputs=decoded, name='AE'), Model(inputs=input_img, outputs=encoded, name='encoder')

autoencoder, encoder = autoencoderConv2D()
pretrain_epochs = 50
batch_size = 2
autoencoder.compile(optimizer='adadelta', loss='mse')
autoencoder.fit(x, x, batch_size=batch_size, epochs=pretrain_epochs)

encoded = encoder.predict(x)

encoded.shape

(60, 10)
n_clusters = 1
kmeans = KMeans(n_clusters=n_clusters, n_init=20, n_jobs=4)
y_pred_kmeans = kmeans.fit_predict(encoded)

I also tried this with MNIST dataset with digit-2 being 5958 samples and digit-4 being 50 samples. Using k=2, the clustering gives the result as the figure below which shows no distinction between the two digits. Is there something I'm not doing right as I am looking to apply this technique for image filtering where dissimilar images are distinguished and filtered from the similar ones.


text:
Q: Visual C++ and exe icon size I have writed a small C++ program in Visual C++ 2012, I added a icon (contain multiple sizes and depths from 16x16 16bit to 256x256 32bit) but when compile, windows explorer doesn't show right icon size in other view modes (icon, detail, ...). How can i make my application icon change size in different explorer view mode or in different explorer zoom factor like notepad.exe (when you zoom the view, it get bigger or smaller)?
I have tried to build in VC++ 2010, VC++ 2008 but doesn't make better :-(


text:
Q: JQuery AJAX strange behaviour with parameters (Spring's @ModelAttribute) I'm trying to pass a Map< String, String> to Spring via Ajax using @ModelAttribute notation.
With IntelliJ's REST client, I just have to add the "infos[KEY]" param with value "VALUE" to get the corresponding key/value couple populated in the hashmap.
I'm trying to reproduce the same behaviour with JQuery
function update()
{
     $.ajax(
          {
            type: "PATCH",
            url: "url",
            dataType: "json",
            data: {"infos[TheAnswer]": "42"},
            success: function(data)
              {
                alert("OK");
              }
          });
}

But Spring controller can't get to populate my model.
Here it is (but i shouldn't be the problem because as I said IntelliJ's REST client works fine)
public class ExtraInfos implements Serializable
{
    protected HashMap<String, String> infos = new HashMap<String, String>();

    public HashMap<String, String> getInfos()
    {
        return infos;
    }

    public void setInfos(HashMap<String, String> infos)
    {
        this.infos = infos;
    }
}

Here's my controller's method:
@RequestMapping(value = "/{id}", method = RequestMethod.PATCH)
public
@ResponseBody
Contact updateContact(@PathVariable("id") Long id,
                      @ModelAttribute ExtraInfos infos)
{
    return this.service.update(id, infos);
 }

A: String modelAttribute doesn't receive the data the way you sent it (json object).
EDIT
The easiest way for you should be to the following:
AJAX:
$.ajax(
          {
            type: "PATCH",
            url: "url",
            dataType: "json",
            data: {TheAnswer: "42"},
            success: function(data)
              {
                alert("OK");
              }
          });

CONTROLLER:
public @ResponseBody Contact updateContact(@PathVariable("id") Long id,
                          @RequestBody ExtraInfos infos){
        }

A: Well using this controller
//Just an example
   @RequestMapping(value = "/test/{id}", method = RequestMethod.POST)
    public @ResponseBody Integer extra(@PathVariable("id") Long id, @RequestBody ExtraInfos extraInfos){
            System.out.println(id);
            System.out.println(extraInfos.getInfos());

            return 1;
        }

The thing here is as the other previously mentioned you need to send the object for ExtraInfos.
If we suppose that this is an example value for ExtraInfos
ExtraInfos = {infos:{"key":"value"}}

Our mapper will create the ExtraInfos object with it.
Doing this ajax call (in this case for this mapper).
$.ajax({
    url:"test/23123",
    type:"post",
    contentType: "application/json; charset=utf-8",
    data:JSON.stringify(ExtraInfos)
})

Output on the console:
23123
{key=value}


text:
Q: Calculate $ \sup_{ x\in X-\{0\}} \frac{d(x,E)}{\|x\|}$ , where $E \subseteq X$ is closed, proper subspace. Let $X$ be a normed $\mathbb K$-linear space and let $E \subseteq X$ be a closed, proper subspace. Calculate$$ \sup_{ x\in X-\{0\}} \frac{d(x,E)}{\|x\|}.$$
How can I calculate it? Please  give some hints.
Thank you..

A: Hint: since $E$ is  a subspace, $d(x,E)\le\|x\|$. This allows you to find an upper bound. To show that this upper bound is tight, you may apply Riesz's lemma.


text:
Q: Xamarin close Android application on back button I tried 3 different ways
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
    System.Environment.Exit(0);

public override void OnBackPressed()
{
    Finish();
}

public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
    if (keyCode == Keycode.Back)
    {
            System.Environment.Exit(0);
            return true;
    }
    return base.OnKeyDown(keyCode, e);
}

None of the above seems to be working

A: If you want to exit from App without killing and back to home screen, so that if you want to resume it back from where it get closed. you can do implementing as follows in your related activity.
  public override void OnBackPressed()
    {
        Intent startMain = new Intent(Intent.ActionMain);
        startMain.AddCategory(Intent.CategoryHome);
        startMain.SetFlags(ActivityFlags.NewTask);
        StartActivity(startMain);

    }

Hope this helps.

A: You can use a DepedencyService for closing an app when your physical back button is pressed:
In your UI (PCL), do the following:
protected override bool OnBackButtonPressed()
{
   if (Device.RuntimePlatform == Device.Android)
       DependencyService.Get<IAndroidMethods>().CloseApp();

   return base.OnBackButtonPressed();
}

Also create an Interface (in your UI PCL):
public interface IAndroidMethods
{
    void CloseApp();
}

Now implement the Android-specific logic in your Android project:
[assembly: Xamarin.Forms.Dependency(typeof(AndroidMethods))]
namespace Your.Namespace
{
   public class AndroidMethods : IAndroidMethods
   {
       public void CloseApp()
       {
            Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
       }
   }
}

A: I tried this code, it works from my side. Hope this code helps you.
protected override bool OnBackButtonPressed()
    {
        Device.BeginInvokeOnMainThread(async () =>
        {
            var result = await DisplayAlert("Alert!", "Do you really want to exit the application?", "Yes", "No");
            if (result)
            {
                if (Device.OS == TargetPlatform.Android)
                {
                    Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
                }
            }
        });
        return true;
    }

A: Try this in your activity:
this.FinishAffinity();

Good luck!!

A: Try this solution:
protected override bool OnBackButtonPressed()
{
    Device.BeginInvokeOnMainThread(async () =>
    {
        var res = await this.DisplayAlert("Do you really want to exit the application?", "","Yes", "No").ConfigureAwait(false);

        if (res) System.Diagnostics.Process.GetCurrentProcess().CloseMainWindow();
    });
    return true;
}

A: public override void OnBackPressed()
{
    Finish();
    Android.OS.Process.KillProcess (Android.OS.Process.MyPid ());
}

A: Finish();

Worked for me. Executed from the main activity.

A: You also can ask the user to confirm exit App:
public override void OnBackPressed()
{
    RunOnUiThread(
        async () =>
        {
            var isCloseApp = await AlertAsync(this, "NameOfApp", "Do you want to close this app?", "Yes", "No");

            if (isCloseApp)
            {
                var activity = (Activity)Forms.Context;
                activity.FinishAffinity();
            }
        });
}

public Task<bool> AlertAsync(Context context, string title, string message, string positiveButton, string negativeButton)
{
    var tcs = new TaskCompletionSource<bool>();

    using (var db = new AlertDialog.Builder(context))
    {
        db.SetTitle(title);
        db.SetMessage(message);
        db.SetPositiveButton(positiveButton, (sender, args) => { tcs.TrySetResult(true); });
        db.SetNegativeButton(negativeButton, (sender, args) => { tcs.TrySetResult(false); });
        db.Show();
    }

    return tcs.Task;
}

Xamarin.Android await AlertDialog.Builder


text:
Q: extracting return value from evimp in mars, earth r package Earth package in R:
Hello, I am running a loop to extract 1000 data subsets from my master database and run a series of MARS-based tests which I then summarize in a df. I want to pull the evimp return values (rows=variable name, cols=# subsets, GCV, RSS) that rank input variable importance for each run. But, I cannot extract or add these values to a dataframe because it is an "evimp" class. How can I pull these values and put them into a table?

A: That evimp class does make it harder to get at the data, but unclass will turn it into a matrix that you can handle.
Example:
library(earth)

data(ozone1)
earth.mod <- earth(O3 ~ ., data=ozone1, degree=2)
ev <- evimp(earth.mod, trim=FALSE)

evdf = as.data.frame(unclass(ev[,c(3,4,6)]))
evdf
         nsubsets        gcv       rss
temp           11 100.000000 100.00000
humidity        9  35.667541  38.88609
ibt             7  31.618413  33.98691
doy             7  31.618413  33.98691
ibh             6  33.432738  36.02932
dpg             6  27.452997  29.75686
vis             5  21.426773  24.09804
wind            2  10.263603  12.59467
vh              1   5.324573   7.65049


text:
Q: How can I store Geojson response into Postgres Database using node-express? NOTE: Geojson response contains coordinates datatype, which needs to be stored in Postgres as geometry datatype.
I don't want to use any 3rd party software like Qgis or ArcGIS, or command line tool such as geojson2psql in Postgis.

A: Use a jsonb column.
It's simple to query a jsonb column for specific attributes, using the -> operator. For example, assuming a column name of "geodata", this query:
SELECT geodata->'geometry'->'coordinates' AS coords FROM geo_example;

...would return [-104.99404, 39.75621] from this GeoJSON example I grabbed from Leaflet:
{
    "type": "Feature",
    "properties": {
        "name": "Coors Field",
        "amenity": "Baseball Stadium",
        "popupContent": "This is where the Rockies play!"
    },
    "geometry": {
        "type": "Point",
        "coordinates": [-104.99404, 39.75621]
    }
};

Here's a SQL Fiddle showing a couple examples.


text:
Q: What are Time To Refresh (TTR), Time To Live (TTL), and Time To Birth (TTB), Cascade Delete (CCD) in an AtKeys metadata for? These are a few Time To mechanisms that can have some light shun upon them as they can be quite useful to a developer. I will be answering them below in an attempt to explain what they can be used for and why on the @platform.

A: Time To Mechanisms (Attributes of Metadata)
Any data that is shared between @signs can go through several mechanisms. Some of these mechanisms include TTR (Time To Refresh), TTL (Time To Live), and TTB (Time To Birth).
Time To Refresh
TTR, which is an attribute of the metadata of a shared key, accepts an integer value which represents seconds. The subsequent refresh happens based on the given value: for example, if the set TTR value is 86400, then the refresh happens once in a day (there are 86,400 seconds in a day). Another very important attribute of the metadata is CCD (Cascade Delete), which is a boolean variable (a variable that accepts true or false values). For those who are well versed in SQL and database management, you will already have some understanding of what CCD does and how it functions.
If the CCD value is set as true when the sender deletes their original key, the cached key gets deleted on both the sender's server and the recipient's server. Correspondingly, if the CCD value is false when the sender deletes their original key, the cached key gets deleted on only the sender's server and remains cached on the recipient's server. But why is this useful? CCD is used to avoid unnecessary network calls. As an example: if @alice is in need of @bob's phone number, she does not need to make a request from her server to @bob's server to find it, but rather needs only to search locally on her device to find the phone number.
Let's consider a similar example: @alice shares her phone number with her friends @bob and @john. A few months later, however, @alice purchases a new phone plan, resulting in a new phone number. If @alice has her @sign's TTR variable set to true, once she updates her old phone number to match her new one, this updated value will also be reflected on @bob and @john's devices. @alice also has the ability to set a specific time, in seconds, for when the new phone number will be cascaded on shared servers (this is TTB, which is described later). This can be 10 minutes, a day, or whatever specific amount of time she defines.
This function can be quite handy, especially if someone is constantly updating values on their server. This prevents a high density of calls and requests whenever someone wishes to see what new values exist on a shared server.
Time To Live
TTL (Time To Live) is quite self-explanatory: it defines how long data will live on a server. Anyone with an @sign has the ability to upload information on their server and define how long it stays on the server before it is automatically deleted. If @alice wishes to share her summer vacation getaway location as her current location, she has the option to share that summer vacation location for as long as she plans on being there!
To really take advantage of a mechanism like this, developers can combine it with other Time To commands to make life for themselves and those they share their information with easier. Say for instance Alice lives in sunny San Francisco, and owns a vacation home in Spain. With mechanisms such as Time To Refresh and Time To Live, Alice has the ability of travelling to her vacation home for several weeks, uploading her current location as Spain, and setting that information to live on her server for the several weeks that she will be staying at that location.
Time To Birth
Another Time To mechanism that is utilized within the @protocol is the Time To Birth mechanism. This mechanism allows individuals to upload information to their secondary server and have it become activated after a specified amount of time, in seconds. During the time that the data is not 'active', any recipients of this information will see the 'null' value in place until the activation has occurred.
For example, if @alice wishes to upload a web URL of her personal website after she has completed it, she can simply specify that the URL value can be uploaded to her secondary in exactly 1 days' time. Until the value is updated a day later, @bob can only see that her website URL is 'null'.


text:
Q: How to smoothly rename a Phoenix Project? I've cloned a git repo and I need to start a new project based off of it.
How do I rename it, making sure everything is taken care of?
I'm using macOS.

A: Based off of nerdyworm's rename.sh, that uses ack I've adapted it to use git grep and run on macOS easily.
• OTP NAME: Snake Case (snake_case) name for the Application.
• NAME: Regular app name.
$ git grep -l $CURRENT_OTP | xargs sed -i '' -e "s/$CURRENT_OTP/$NEW_OTP/g"
$ git grep -l $CURRENT_NAME | xargs sed -i '' -e "s/$CURRENT_NAME/$NEW_NAME/g"

$ mv lib/$CURRENT_OTP lib/$NEW_OTP
$ mv lib/$CURRENT_OTP.ex lib/$NEW_OTP.ex

A: I do not know of any way to do this automatically with perfect accuracy, but these are the steps I follow manually when I need to rename Phoenix projects.
The commands below assume your code is in a git repo and the old application is my_app / MyApp and the new one is my_new_app / MyNewApp. The process is brittle -- if your application or module name can occur in many places (e.g. it's a single letter A or something), then this will not work.
# search replace both the application name and module name in all files indexed by git
$ git ls-files -z | xargs -0 perl -p -i -e 's/my_app/my_new_app/g; s/MyApp/MyNewApp/g;'
# rename `lib/my_app`
$ mv lib/my_app lib/my_new_app

After that I run mix test and fix any compilation errors or test failures.
Finally I do a quick review of git diff to make sure everything looks right.


text:
Q: How to deal with video frames in simulink I am working on videos in simulink.As we know that multimedia file block reads one frame at a time so when I will attach it with matlab function block it should read one frame at a time with imread command. If I double click the matlab function block (as shown at http://tinypic.com/view.php?pic=dggujd&s=6) then you will see that I have to give the name of the function as written in matlab mfile along with the input; which in this case is video(named as convid.avi). I am reading one frame at a time but I have given the whole video as an argument to the matlab function.This is the problem how can I resolve it.What should be given as an argument in matlab function block rather than the whole video.I have also uploaded my model at http://tinypic.com/view.php?pic=55jggw&s=6. The code which I am using for vidfunc is:
function h=vidfunc(u)
a=imread(u); % read frame
BW = edge(a,'sobel'); %sobel edge detection
[H,thetaa,rhoo]=hough(BW); % Hough Transform
P = houghpeaks(H,6,'threshold',ceil(0.5*max(H(:))));
lines=houghlines(BW,thetaa,rhoo,P,'FillGap',15,'Minlength',15)
figure,imshow(I),hold on
for k = 1:length(lines) % Draw lines
 xy = [lines(k).point1; lines(k).point2];
 z(k)=lines(k).point2(2);
 plot(xy(:,1),xy(:,2),'LineWidth',1,'Color','green');
 end
 h=z(k)

A: It looks like the meat of the work done in this "Simulink" model is actually being performed by your MATLAB function.  So the answer to this question is going to largely rely on what that function is actually doing.  Specifically, what is the expected input to vidfunc, and what is this function's output?  I suspect that this function may need to be revised to fit into your model.
To debug your model, it's useful to think about what the signal output is from each block.  At each time step, your From Multimedia File block will output a single image frame, which according to the doc looks to be structured as an

M-by-N-by-P color video signal where P is the number of color planes.

Moving downstream, we next come to the Color Space Conversion block, which in this case looks like it will most likely output an image frame in the form of an M-by-N matrix (where each element of the matrix corresponds to the image's intensity at that pixel).
Now we come to the interesting part -- the MATLAB Fcn block.  As we just saw, the input to this block will be an M-by-N matrix representing a single image frame.  When you look in the parameter dialog box for the MATLAB Fcn block, the input to this block is represented by the variable u.  Therefore, to execute the vidfunc function on the image frame being input to this block, you would simply enter vidfunc(u) for your MATLAB function.
Now, based on the input going to the MATLAB Fcn block, and the fact that you have a Video Viewer block connected to the output, vidfunc should be structured such that it operates on a single image frame as its input and outputs another single image frame.  If vidfunc is not structured in this way, you will need to edit it (or just re-implement the same functionality using Simulink blocks).
That said, let's assume that vidfunc is also returning an M-by-N matrix representing a processed image frame.  You will want to set the Output Dimensions parameter for your MATLAB Fcn block to -1 to indicate that the output will have the same dimensions as the input.  Also, (as indicated in the doc) you will want to make sure Collapse 2-D results to 1-D is unchecked or else your image output will be in the form of one long vector rather than an M-by-N matrix.
Provided that vidfunc is structured correctly, this should solve your problem.
NOTE: To make your life a lot easier, I would strongly suggest displaying the signal data type and dimensions in your Simulink model.  This can help to avoid a lot of confusion.  This doc describes exactly how to do this.
--UPDATE--
After looking at your code, this confirms my suspicion that the inputs/outputs of vidfunc are inconsistent with what your Simulink model expects. The way that you proceed is highly dependent on what your own design constraints are and what you actually want out of this system.  Basically, your Simulink model and MATLAB function disagree... which one is right? I'll give some general thoughts based on my best guesses at what you're aiming for.
First, Simulink is passing an image (in the form of an M-by-N matrix) into vidfunc. This means that vidfunc no longer needs to load an image at the start of the code.  So I believe that you could update the first few lines of code to be as such:
function h=vidfunc(a)
BW = edge(a,'sobel'); %sobel edge detection

See that now vidfunc is taking the actual image (not the filename that contains the image) as its input. Basically, you are removing the a=imread(u); line and jumping right in to processing a.
The other issue is the output of vidfunc. Simulink is expecting the output to be an image, but it is not. I'm not 100% sure what h is supposed to be in this code (when I first glanced at your code I thought these were handles to line objects but that doesn't seem to be the case).  It looks to possibly be the y coordinate of the endpoint of one of the houghlines.  Nevertheless, it's not what your Simulink model is expecting.  This one is not as straight-forward to fix.  Possibly you could try to use getframe to grab an image from the plot of your lines.
I actually feel that the best advice that I can give to you is to just scrap the MATLAB function and implement everything in Simulink. I think this will be a lot easier than trying to get vidfunc to play nicely with your model. vidfunc does not actually contain that much code, so this should not be too difficult of a task for you. Another benefit is that at the end of this process you'll have a nice Simulink model that explicitly shows all of the image processing steps that you are taking.
I believe that all of the image processing that you are doing with MATLAB functions can also be done with Simulink blocks (see the Simulink Blocks section of this doc).
Good luck.


text:
Q: ASP.NET Controls under the hood I want to learn (basically) about how ASP.NET controls work. I know the end result has to be some kinda rendered HTML. How do the controls encapsulate stuff? How does it tie in to the whole ASP.NET flow? My team has written a widgets library that wraps the native controls and then adds custom styling etc etc. and I need to be contributing to this library. Many thank you's

A: The two places I would start would be Truly Understanding Dynamic Controls and Truly Understanding Viewstate.

A: Learning the ASP.NET Page Life Cycle is important to answering your questions.

A: Nikhil Kothari has written the Bible for this, entitled "Developing Microsoft ASP.NET Server Controls and Components". You can pick up a copy here for less than a dollar :-)
http://www.amazon.com/gp/offer-listing/0735615829/ref=dp_olp_used?ie=UTF8&condition=used


text:
Q: In Laravel api.php file found code Route::middleware('auth:api')->get('/user', function (Request $request) ... what purpose it's have? In fresh installed Laravel api.php file found code
   Route::middleware('auth:api')->get('/user', function (Request $request) {
      return $request->user();
    });

What purpose does it have ?
I am using GET request to URL my-application/user,  no any Response, is something wrong ?
Can I delete that code ?

A: your-url/user url is protected by auth:api middleware
you have to pass token with http request to access this.
in your current route it will return authenticated user model data
for more read the document from laravel passport

A:
What purpose does it have ?

It is a sample route. It is to show, how to apply the authentication layer on api routes. And, retrieve the authenticated user.

I am using GET request to URL my-application/user, no any Response, is something wrong ?

You need to consider two thing here.

*

*All api routes are prefixed with /api/. So, the URL should be my-application/api/user
https://github.com/laravel/laravel/blob/2a483bbf60566cab6fbd0340fb3877fc09889bc3/app/Providers/RouteServiceProvider.php#L68

*Since auth:api middleware is applied, it expect a token to be presented.
If you remove the auth:api middleware and prefix with api, you could see a response.

Can I delete that code ?

Yes, you can delete.


text:
Q: How can I show an image on another page by clicking a button and saving it? What I want to do is like the save button on Instagram "the bookmark". so when I click on the button the image will display on another page and also it will be saved. I have the image on a page named menu what I want is when I click on the button the image will stay in the menu and when I open the folder page (the other page that will contain the image) I find the image.

          <lord-icon src="https://cdn.lordicon.com/wurbjznp.json" trigger="loop" delay="1000" colors="primary:#121331" style="width:32px;height:32px">
          </lord-icon>