text:
Q: bukalapak.com login using php curl im using curl to login at bukalapak.com .
but always redirect "you are being redirected" & i solve it  use curl followlocation true, but why not loged in after redirect?
help me & thanks before

<?php
function curl($url, $post){
$curl = curl_init();
curl_setopt_array($curl,
array(CURLOPT_URL => $url, //put your url here
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_RETURNTRANSFER => true,
//CURLOPT_ENCODING => "",
CURLOPT_POSTREDIR => 3,
CURLOPT_HEADER => true,
//CURLOPT_MAXREDIRS => 10,
//CURLOPT_TIMEOUT => 30,
//CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POST => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_COOKIEFILE => "cookie.txt",
CURLOPT_COOKIEJAR => "cookie.txt",
CURLOPT_POSTFIELDS => $post,
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"Content-type: text/html; charset=UTF-8"
),
));

$response = curl_exec($curl);
$info = curl_getinfo($curl);
$err = curl_error($curl);
curl_close($curl);
return $response;
}

$p = array(
"user_session[username]"=>"Myuser@gmail.com",
"user_session[password]"=>"Blablabla",
"commit"=>"Login",
"comeback"=>"%2F"
);

$login = curl("https://www.bukalapak.com/user_sessions", http_build_query($p));

echo $login;
?>

HTTP/1.1 302 Found Server: nginx Date: Fri, 03 Feb 2017 06:28:03 GMT Content-Type: text/html; charset=utf-8 Location: https://www.bukalapak.com/ Transfer-Encoding: chunked Connection: keep-alive Status: 302 Found Cache-Control: max-age=0, private, must-revalidate, no-transform X-We-Need-To-Talk: Hey, you need to check out https://www.bukalapak.com/careers :) Vary: Origin X-Permitted-Cross-Domain-Policies: none X-XSS-Protection: 1; mode=block X-Request-Id: 90f9ca9a-4ade-4c3d-a0ea-592effd5c2ee X-Download-Options: noopen X-Found-Something: Found any vulnerabilities in our system? https://www.bukalapak.com/bug_reports X-Frame-Options: SAMEORIGIN X-Content-Type-Options: nosniff Set-Cookie: _mkra_ctxt=8891a37006424c9c608a41bf3f6558de--302; path=/; max-age=5; HttpOnly Set-Cookie: lskjfewjrh34ghj23brjh234=RjhGMUlkUEpHb0NOaTNLeUFoT2x2RmxZeWxDTWRySEV6aUc4a0tBOWhqbGdZVS9kWUlOZHFOSXNVZWt2UmJCTkFBRXZLVW8wd21rUktrYXZQR05lUU01aHRuemdzVi91WnFqcUFid2s0MVhUbGhmQXk0cGIrVU5iaXR3UW1HQ21LeHJHRHhMRGZucGo3UUluZ2FLbjJMSWZiZVExODgyRmtUQXJaMTZjYVQxMXZSOWg5U3FGeHZZTGdxVllNTFp4MGtDcnJiaEEwL0NkTVNNT2lTWE8yQXNtNEIzWTVKc0h4NVdVeEVKYnZMSVFMQ29KcysyUGdnK2VZaWNLaVozL3NXYzVIcXlHWkY4SDZESjF4RXp6ak5wVXVOeXRXdjZ0YkZ1UWhPQVJNcjA9LS1od2k3aTgzM3pBSEx5TDVqcE9ZWUZ3PT0%3D--0f995ca0f739bbb3f94b4e92b6628da326a2cb5c; domain=.bukalapak.com; path=/; HttpOnly Strict-Transport-Security: max-age=31536000; includeSubdomains You are being redirected.

A: first off, to login, you need a valid cookie session id and "authenticity_token" combo. each cookie session has its own unique authenticity_token , and if you don't post the correct 1, you won't be able to log in.
your code makes no attempt to attain an authenticity_token.
you are also missing a bunch of login parameters, which might make login impossible. to mention a few, utf8, comeback, ab_keep_login and commit (and there's more)
also, your code use multipart/form-data encoding, but the website use application/x-www-form-urlencoded encoding, so fix that (use http_build_query to generate a valid x-www-form-urlencoded string)
first make a GET request to the login page, make sure cookies are enabled, parse out all the <input> tags that belong the the login request (but warning, there are several forms in the html containing <input> tags, you only want the inputs belonging to the login form, aka id new_user_session), their names and values (use DOMDocument for that), modify the username/password variables, and send the login POST request with all those tags, and make sure to use application/x-www-form-urlencoded encoding (aka what http_build_query gives you), just like a real browser does.
using hhb_curl from https://github.com/divinity76/hhb_.inc.php/blob/master/hhb_.inc.php , here's an example (it should work, provided a real username/password)
<?php
declare(strict_types = 1);
require_once ('hhb_.inc.php');
$hc = new hhb_curl ();
$hc->_setComfortableOptions ();
$hc->exec ( 'https://www.bukalapak.com/user_sessions' );
$html = $hc->getResponseBody ();
$domd = @DOMDocument::loadHTML ( $html );
$inputs = array ();
foreach ( $domd->getElementById ( "new_user_session" )->getElementsByTagName ( "input" ) as $input ) {
    $inputs [$input->getAttribute ( "name" )] = $input->getAttribute ( "value" );
}
var_dump ( $inputs );
assert ( array_key_exists ( 'authenticity_token', $inputs ) );
$inputs ['user_session[username]'] = 'Myuser@gmail.com';
$inputs ['user_session[password]'] = 'Blablabla';
$hc->setopt_array ( array (
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query ( $inputs ),
        CURLOPT_URL => 'https://www.bukalapak.com/user_sessions',
        CURLOPT_HTTPHEADER => array (
                'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
        )
) );
$hc->exec ();
$html = $hc->getResponseBody ();
hhb_var_dump ( $hc->getStdErr (), $hc->getResponseBody () );


text:
Q: Running order of multiple scripts in an HTML document? I have an HTML page that i ship to the browser and it contains a couple of script tag.
This is my index.html file:

And this is my src/index.js file:

In the HTML file, i define window.test after i run the src/index.js.
src/index.js will only print to the console if window.test is set to true, but that's being set only after, as the second script.
What is the order in which these scripts will run?
Is there a guarantee that window.test will always be set to true "just in time" for the if statement in src/index.js to print wow!?
CodeSandbox:
https://codesandbox.io/s/javascript-forked-utgh8?file=/index.html

A: In JS called from HTML file the order of the scripts are just like their order of writing in this file "always" will be in that order, which means that in your example window.test Will always have a null value in index.js so nothing will be printed in the console

A: to guarantee that test function is only call after variable is setted why not use a custom event

and in index.js

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why setting HashTable's length to a Prime Number is a good practice? I was going through Eric Lippert's latest Blog post for Guidelines and rules for GetHashCode when i hit this para:

We could be even more clever here; just as a List resizes itself when it gets full, the bucket set could resize itself as well, to ensure that the average bucket length stays low. Also, for technical reasons it is often a good idea to make the bucket set length a prime number, rather than 100. There are plenty of improvements we could make to this hash table. But this quick sketch of a naive implementation of a hash table will do for now. I want to keep it simple.

So looks like i'm missing something.  Why is it a good practice to set it to a prime number?.

A: You can find people that suggest the two opposite ends of the spectrum. On the one side, choosing a prime number for the size of the hash table will reduce the chances of collisions, even if the hash function is not too effective distributing the results. Note that if (in the simplest example to argue about) a power of 2 size is decided, only the lower bits affect the bucket, while for a prime number most bits in the result of the hash will be used.
On the other hand, you can gain more by choosing a better hash function, or even rehashing he result of the hash function by applying some bit operations, and using a power of 2 hash size to speed up calculations.
As an example from real life, Java HashTable were initially implemented by using prime (or almost prime sizes), but from Java 1.4 on, the design was changed to use power of two number of buckets and added a second fast hash function applied to the result of the initial hash. An interesting article commenting that change can be found here.
So basically:

*

*a prime number helps dispersing the inputs across the different buckets even in the event of not-so-good hash functions.

*a similar effect can be achieved by post processing the result of the hash function, and using a power of 2 size to speedup the modulo operation (bit mask) and compensate for the post processing.

A: Because this produces a better hash function and reduces the number of possible collisions. This is explained in Choosing a good hashing function:

A basic requirement is that the
  function should provide a uniform
  distribution of hash values. A
  non-uniform distribution increases the
  number of collisions, and the cost of
  resolving them.
The distribution needs to be uniform
  only for table sizes s that occur in
  the application. In particular, if one
  uses dynamic resizing with exact
  doubling and halving of s, the hash
  function needs to be uniform only when
  s is a power of two. On the other
  hand, some hashing algorithms provide
  uniform hashes only when s is a prime
  number.

A: Say your bucket set length is a power of 2 - that makes the mod calculations quite fast. It also means that the bucket selection is determine solely by the top m bits of the hash code. (Where m = 32 - n, where n is the power of 2 being used). So it's like you're throwing away useful bits of the hashcode immediately.
Or as in this blog post from 2006 puts it:

Suppose your hashCode function results in the following hashCodes among others {x , 2x, 3x, 4x, 5x, 6x...}, then all these are going to be clustered in just m number of buckets, where m = table_length/GreatestCommonFactor(table_length, x). (It is trivial to verify/derive this). Now you can do one of the following to avoid clustering:

...

Or simply make m equal to the table_length by making GreatestCommonFactor(table_length, x) equal to 1, i.e by making table_length coprime with x. And if x can be just about any number then make sure that table_length is a prime number.


text:
Q: Как дождаться завершения работы функции callback в js чтобы использовать возвращенное значение дальше Интересует такой вопрос, покажу на примере определения координат пользователя, но вопрос общий. Имеем простой скрипт на получение координат пользователя, который происходит в функции callback
var coord;
if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
   coord = position.coords;
   console.log("Первый " + coord.latitude);
});
console.log("Второй " + coord.latitude);

Так вот Второй выдаст ошибку, поскольку на тот момент работа функции callback не была завершена.
Как сделать так, чтобы получить значения в переменную и потом использовать их дальше, не опасаясь, что на момент использования данные еще не будут получены из функции обратного вызова?
Неужели все размещать только внутри функции callback как в случае с логом "Первый"?

A:
Неужели все размещать только внутри функции callback как в случае с логом "Первый"?

Да.
Также можно воспользоваться переписывальщиками кода или альтернативными компилирующимися в жабоскипт языками, которые позволят писать адекватный код с современным await, а не стандартную жабоскриптовую вермишель из колбэков. Если вы пишете на каком-нибудь TypeScript, есть возможность писать "линейный" код, работающий с колбэками, а преобразование человекочитаемого кода в callback hell становится заботой компилятора.

A: Как вариант: Promise. Но как писал Squidward: легче засунуть все в кэллбэк (на счет TypeScript, CoffeeScript и им подобных сказать ничего не могу т.к. не использую их).


text:
Q: Translating a simple UPDATE/JOIN from SQL into R I was given these crude database exports to fix up. In SQL have two tables that each have three columns: ID, first name and last name. In sheet1, the ID column is empty at the start whereas there are ID's in sheet2. I needed to join sheet1 and sheet2 where both first and last name matched and if there was an ID present in sheet2 from the match, to set it in the ID column in sheet1. Very simple SQL query:
UPDATE sheet1
JOIN sheet2
ON sheet1.NAME_LAST = sheet2.Last_Name
AND sheet1.NAME_FIRST = sheet2.First_Name
SET sheet1.CONSTITUENT_ID = sheet2.ID

As this is a task that needs to be done often, what I'd like to do is set up my less savvy co-workers with a simple R script. I'm still a total beginner at R however. At present, I've got sheet1 and sheet2 in two data.frames (oh-so-descriptively named book1 and book2) via the native R method: book2 = read.csv("sheet2.csv") Through some googling it was suggested I take a look at the data.table library, but I'm still at a bit of a loss for where to start. Can someone help me translate SQL in to R?

A: While SQL is a special-purpose language that for the most part id declarative and set-based, R is a functional programming language. It is often difficult to do direct language translations. Using base R, you would probably use a merge() command to bring different tables together.
If we have these sample tables
sheet1<-data.frame(
    NAME_LAST=letters[1:10],
    NAME_FIRST=letters[11:20],
    SEX=sample(c("M","F"), 10, replace=T)
)

sheet2<-data.frame(
    Last_Name=letters[1:10],
    First_Name=letters[11:20],
    ID = sample(100:200, 10)
)[sample(1:10), ]

sheet1;sheet2;

Then we can merge them with
mm<-merge(sheet1, sheet2,
    by.x=c("NAME_LAST","NAME_FIRST"),
    by.y=c("Last_Name","First_Name")
)
mm;

You can them probably subset this merged data set to get what you need.


text:
Q: How to insert a new column based on condition (NaN) I'm pretty new on Python and here's my issue. It's pretty basic !
I'm trying to create a new column (called "SectorCode") based on another column (called "Sector").
For example, if the column "Sector" contains "Materials" Then it should display "10" on my "SectorCode" column. If I have "Industrials", then "20", and so on...
I found other topics but it almost always includes conditions based on number like here, and not based on NaN :
https://www.dezyre.com/recipes/insert-new-column-based-on-condition-in-python
(That's where i got my inspiration to build my code)
Here's my failing code :
import pandas as pd
import numpy as np
sector = pd.read_csv (r"C:\Users\alexa\sector.csv")
sector

dframe = pd.DataFrame(sector)
dframe.columns
Index(['Ticker', 'Sector'], dtype='object')

Sectorcode = []
for row in dframe['Sector']:
    if row = ('Energy') : Sectorcode.append(10)
        elif row = ('Materials') : Sectorcode.append(15)
        elif row = ('Industrials') : Sectorcode.append (20)
        elif row = ('Consumer Discretionary') : Sectorcode.append (25)
        elif row = ('Cosumer Staples') : Sectorcode.append (30)
        elif row = ('Health Care') : Sectorcode.append (35)
        elif row = ('Financials') : Sectorcode.append (40)
        elif row = ('Information Technology') : Sectorcode.append (45)
        elif row = ('Communication Services') : Sectorcode.append (50)
        elif row = ('Utilities'): Sectorcode.append (55)
        elif row = ('Real Estate'): Sectorcode.append (60)
        else : Sectorcode.append (0)
df['Sectorcode']= Sectorcode`

I get this error message :
"  File "<ipython-input-8-98c65bbfd42a>", line 3
    if row = ('Energy') : Sectorcode.append(10)
       ^

SyntaxError: invalid syntax"
My actual table looks like this :
         Ticker         Sector
0         MSFT     Information Technology
2         AAPL     Information Technology
3         AMZN      Consumer Discretionary
4         FB       Communication Services
5         BRK.B        Financials
6         XOM             Energy
7         JNJ             Health Care

etc....
And I'd like to have something like this :
         Ticker         Sector                 SectorCode
0         MSFT     Information Technology       45
2         AAPL     Information Technology       45
3         AMZN      Consumer Discretionary      25
4         FB       Communication Services       50
5         BRK.B        Financials               40
6         XOM             Energy                10
7         JNJ             Health Care           35

etc....
Thank you for your help ! :)
EDIT :
The following code worked :
Sectorcode = []
for row in dframe['Sector']:
    if row == ('Energy') : Sectorcode.append(10)
    elif row == ('Materials') : Sectorcode.append(15)
    elif row == ('Industrials') : Sectorcode.append (20)
    elif row == ('Consumer Discretionary') : Sectorcode.append (25)
    elif row == ('Cosumer Staples') : Sectorcode.append (30)
    elif row == ('Health Care') : Sectorcode.append (35)
    elif row == ('Financials') : Sectorcode.append (40)
    elif row == ('Information Technology') : Sectorcode.append (45)
    elif row == ('Communication Services') : Sectorcode.append (50)
    elif row == ('Utilities'): Sectorcode.append (55)
    elif row == ('Real Estate'): Sectorcode.append (60)
    else : Sectorcode.append (0)
dframe['Sectorcode']= Sectorcode

A: You are using one = which stands for assignment when you need to use two == to test for a condition.


text:
Q: Infinite whitespace under my webpage content For some reasons one of my webpage can be scrolled down infinitely. My html/php is rather big so I don't think that should I post; I really can't find an answer online.
html {
  font-size: 62.5%;
  height: 100%;
}

body {
  font-size: 1.6rem;
  font-family: "Open Sans", sans-serif;
  -webkit-font-smoothing: antialiased;
  height:100%;
}

img {
  max-width: 100%;
}

a{
    text-decoration:none;
}

#content{
    min-height:100%;
    position:relative;
    background-color:#54B0D9;
}

table{
    margin-left:auto;
    margin-right:auto;
    border-collapse:collapse;
    font-weight: 400;

}

table, td, tr, th{

    border-style:solid;

    border-color:#E6E7F1;

    border-width:0px 1px 1px 0px;
}

td{
    text-align:center;
}

a{
    text-decoration:none;
    color:black;
}

td.count{
    min-width:50px;
}

td.count a{
    padding-top:15px;
    padding-bottom:15px;
    display:block;
}

td.delete{
    min-width:50px;
}

td.delete a{
    padding-top:15px;
    padding-bottom:15px;
}

td.name{
    min-width:300px;
}

td.name a{
    padding-top:15px;
    padding-bottom:15px;
    display:block;
}

td.efect{
    min-width:150px;
}

td.efect a{
    padding-top:15px;
    padding-bottom:15px;
    display:block;
}

.boldedShitForPykw{
    font-weight: 700;
}

tr.even{
    background-color:#F6F7FA;
}

tr.odd{
    background-color:#ffffff;
}

.table-container{
    padding-top:30px;
    background-color:#54B0D9;
}

I have a fixed navbar at the bottom, could that be the reason?

A: I was able to solve this by updating your CSS from
#content {
   min-height: 100%;
   position: relative;
   background-color: #54B0D9;
}

to:
#content {
   min-height: 100%;
   background-color: #54B0D9;
}

I was able to solve this by using Chrome's Developer Tools to amend the elements styles - this may come in handy next time!

A:
html, body {
    width:100%;
    min-height:100%;
    margin:0 auto;

then add media queries to make it responsive, add all of this to the end of you main css sheet
/*
  Based on:
  1. http://stephen.io/mediaqueries
  2. https://css-tricks.com/snippets/css/media-queries-for-standard-devices/
*/

/* iPhone 6 in portrait & landscape */
@media only screen
and (min-device-width : 375px)
and (max-device-width : 667px) {

}

/* iPhone 6 in landscape */
@media only screen
and (min-device-width : 375px)
and (max-device-width : 667px)
and (orientation : landscape) {

}

/* iPhone 6 in portrait */
@media only screen
and (min-device-width : 375px)
and (max-device-width : 667px)
and (orientation : portrait) {

}

/* iPhone 6 Plus in portrait & landscape */
@media only screen
and (min-device-width : 414px)
and (max-device-width : 736px) {

}

/* iPhone 6 Plus in landscape */
@media only screen
and (min-device-width : 414px)
and (max-device-width : 736px)
and (orientation : landscape) {

}

/* iPhone 6 Plus in portrait */
@media only screen
and (min-device-width : 414px)
and (max-device-width : 736px)
and (orientation : portrait) {

}

/* iPhone 5 & 5S in portrait & landscape */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 568px) {

}

/* iPhone 5 & 5S in landscape */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 568px)
and (orientation : landscape) {

}

/* iPhone 5 & 5S in portrait */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 568px)
and (orientation : portrait) {

}

/*
  iPhone 2G, 3G, 4, 4S Media Queries
  It's noteworthy that these media queries are also the same for iPod Touch generations 1-4.
*/

/* iPhone 2G-4S in portrait & landscape */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {

}

/* iPhone 2G-4S in landscape */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px)
and (orientation : landscape) {

}

/* iPhone 2G-4S in portrait */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px)
and (orientation : portrait) {

}

/* iPad in portrait & landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)  {

}

/* iPad in landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {

}

/* iPad in portrait */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {

}

/* Galaxy S3 portrait and landscape */
@media screen
  and (device-width: 320px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 2) {

}

/* Galaxy S3 portrait */
@media screen
  and (device-width: 320px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 2)
  and (orientation: portrait) {

}

/* Galaxy S3 landscape */
@media screen
  and (device-width: 320px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 2)
  and (orientation: landscape) {

}

/* Galaxy S4 portrait and landscape */
@media screen
  and (device-width: 320px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 3) {

}

/* Galaxy S4 portrait */
@media screen
  and (device-width: 320px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 3)
  and (orientation: portrait) {

}

/* Galaxy S4 landscape */
@media screen
  and (device-width: 320px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 3)
  and (orientation: landscape) {

}

/* Galaxy S5 portrait and landscape */
@media screen
  and (device-width: 360px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 3) {

}

/* Galaxy S5 portrait */
@media screen
  and (device-width: 360px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 3)
  and (orientation: portrait) {

}

/* Galaxy S5 landscape */
@media screen
  and (device-width: 360px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 3)
  and (orientation: landscape) {

}

/* HTC One portrait and landscape */
@media screen
  and (device-width: 360px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 3) {

}

/* HTC One portrait */
@media screen
  and (device-width: 360px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 3)
  and (orientation: portrait) {

}

/* HTC One landscape */
@media screen
  and (device-width: 360px)
  and (device-height: 640px)
  and (-webkit-device-pixel-ratio: 3)
  and (orientation: landscape) {

}

/*
  iPad 3 & 4 Media Queries
  If you're looking to target only 3rd and 4th generation Retina iPads
  (or tablets with similar resolution) to add @2x graphics,
  or other features for the tablet's Retina display, use the following media queries.
*/

/* Retina iPad in portrait & landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 2) {

}

/* Retina iPad in landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 2) {

}

/* Retina iPad in portrait */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 2) {

}

/*
  iPad 1 & 2 Media Queries
  If you're looking to supply different graphics or choose different typography
  for the lower resolution iPad display, the media queries below will work
  like a charm in your responsive design!
*/

/* iPad 1 & 2 in portrait & landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 1) {

}

/* iPad 1 & 2 in landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1) {

}

/* iPad 1 & 2 in portrait */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 1) {

}

/* iPad mini in portrait & landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 1) {

}

/* iPad mini in landscape */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1) {

}

/* iPad mini in portrait */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 1) {

}

/* Galaxy Tab 10.1 portrait and landscape */
@media
  (min-device-width: 800px)
  and (max-device-width: 1280px) {

}

/* Galaxy Tab 10.1 portrait */
@media
  (max-device-width: 800px)
  and (orientation: portrait) {

}

/* Galaxy Tab 10.1 landscape */
@media
  (max-device-width: 1280px)
  and (orientation: landscape) {

}

/* Asus Nexus 7 portrait and landscape */
@media screen
  and (device-width: 601px)
  and (device-height: 906px)
  and (-webkit-min-device-pixel-ratio: 1.331)
  and (-webkit-max-device-pixel-ratio: 1.332) {

}

/* Asus Nexus 7 portrait */
@media screen
  and (device-width: 601px)
  and (device-height: 906px)
  and (-webkit-min-device-pixel-ratio: 1.331)
  and (-webkit-max-device-pixel-ratio: 1.332)
  and (orientation: portrait) {

}

/* Asus Nexus 7 landscape */
@media screen
  and (device-width: 601px)
  and (device-height: 906px)
  and (-webkit-min-device-pixel-ratio: 1.331)
  and (-webkit-max-device-pixel-ratio: 1.332)
  and (orientation: landscape) {

}

/* Kindle Fire HD 7" portrait and landscape */
@media only screen
  and (min-device-width: 800px)
  and (max-device-width: 1280px)
  and (-webkit-min-device-pixel-ratio: 1.5) {

}

/* Kindle Fire HD 7" portrait */
@media only screen
  and (min-device-width: 800px)
  and (max-device-width: 1280px)
  and (-webkit-min-device-pixel-ratio: 1.5)
  and (orientation: portrait) {

}

/* Kindle Fire HD 7" landscape */
@media only screen
  and (min-device-width: 800px)
  and (max-device-width: 1280px)
  and (-webkit-min-device-pixel-ratio: 1.5)
  and (orientation: landscape) {

}

/* Kindle Fire HD 8.9" portrait and landscape */
@media only screen
  and (min-device-width: 1200px)
  and (max-device-width: 1600px)
  and (-webkit-min-device-pixel-ratio: 1.5) {

}

/* Kindle Fire HD 8.9" portrait */
@media only screen
  and (min-device-width: 1200px)
  and (max-device-width: 1600px)
  and (-webkit-min-device-pixel-ratio: 1.5)
  and (orientation: portrait) {

}

/* Kindle Fire HD 8.9" landscape */
@media only screen
  and (min-device-width: 1200px)
  and (max-device-width: 1600px)
  and (-webkit-min-device-pixel-ratio: 1.5)
  and (orientation: landscape) {

}

/* Laptops non-retina screens */
@media screen
  and (min-device-width: 1200px)
  and (max-device-width: 1600px)
  and (-webkit-min-device-pixel-ratio: 1) {

}

/* Laptops retina screens */
@media screen
  and (min-device-width: 1200px)
  and (max-device-width: 1600px)
  and (-webkit-min-device-pixel-ratio: 2)
  and (min-resolution: 192dpi) {

}

/* Apple Watch */
@media
  (max-device-width: 42mm)
  and (min-device-width: 38mm) {

}

/* Moto 360 Watch */
@media
  (max-device-width: 218px)
  and (max-device-height: 281px) {

}


text:
Q: Migrating OS and some games to new SSD while kepping everything else on old HDD Basically what I want to do is to migrate my OS (Windows 8.1 Home) and a game to my new Samsung 960 EVO M.2 SSD to make them boot and load faster. But I still want to keep all my other programs and documents etc. on my old HDD. Is it even possible to run this configuration?
Would it be possible if I back up my current HDD to another hard drive and then delete as much as possible except the OS and that game from it, then migrate it to the new SSD using Samsung's migration tool and then move over all the backup files that I want to my now empty HDD. Would this work or is there any other way that would?
I'm such a noob at storage and I'm sorry if my explanation is confusing, It's my first time posting a question like this. Any answers is very much appreciated. Thanks in advance.

A: My opinion is you use Clonezilla which you can download it in clonezilla.org and burn it in DVD or also in USB as bootable by using Rufus.
Basically clonezilla copies your entire old HDD drive (files & OS) included to your new SSD or you can chose to copy the OS partition only depending on your partition. You should be aware that SSD size should be greater than the HDD or partition size that you're copying from.
If you find clonezilla is too much complicated you can also find some other alternatives for it with much simpler options but beware some of it may cost you real money.


text:
Q: Setting up firebase in android studio gives error I am currently working on an app in android studio, and i need some simple server implementation to log some data. I've run through the setup tutorial on the firebase website: https://www.firebase.com/docs/android/quickstart.html, but when i try to run the app it gives me this error:
Error:Execution failed for task ':app:dexDebug'.

com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_60\bin\java.exe'' finished with non-zero exit value 2

I figured that maybe it has something to do with the .jar file that i had to place into my libs folder, or maybe i have the wrong jdk?
Any help would be appreciated

A: Add this in your gradle. This will solve the issue for me.
dexOptions{
    javaMaxHeapSize "4g"
}


text:
Q: SQL Server split string and get the value Hi all please help me the
Get result from
select details from table
enter code here

Result :
Title|Firstname|Lastname|Mobilephone~Mr|jack|steve|123456789~Mr|test|Ltest|123456789~Mrs|Demo|Ldemo|12345678~Mrs|Fname|Lname|1234567

i need the below result
Title    FirstName    LastName    Mobile
Mr       jack        steve        1234567789
etc...

A: You need to write stored procedure which will scan the complete line and give you pipe separated values in a loop.

A: One of solution to your problem is as given below :
DECLARE @PARAM_STRING VARCHAR(1000)=REPLACE('Title|Firstname|Lastname|Mobilephone~Mr|jack|steve|123456789~Mr|test|Ltest|123456789~Mrs|Demo|Ldemo|12345678~Mrs|Fname|Lname|1234567','|',''',''')+''''
DECLARE @DYNAMIC_QUERY VARCHAR(MAX)
DECLARE @TABLE TABLE(ID INT,DATA VARCHAR(MAX))
INSERT INTO @TABLE
SELECT 1 ID, 'SELECT '+DATA FROM (
SELECT A.B.value('.','VARCHAR(50)')DATA FROM
(SELECT CAST(''''+REPLACE(@PARAM_STRING,'~','''''')+'' AS     XML)COL)T
CROSS APPLY T.COL.nodes('/A') AS A(B))F WHERE DATA<>''
SELECT  @DYNAMIC_QUERY=STUFF((SELECT ' UNION ALL ' + CAST(DATA AS     VARCHAR(MAX))     [text()]FROM @TABLE WHERE ID = t.ID
    FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,10,' ')
FROM @TABLE t GROUP BY ID
EXECUTE(@DYNAMIC_QUERY)


text:
Q: How to compile and install this source without errors? Link in the description It's very important for me to install QCADesigner 2.0.3 on my linux system (Ubuntu 16.04). You can find the source here. When I tried to configure it by running ./autogen.sh as mentioned in the readme file, I got the following error:
automake: warning: autoconf input should be named 'configure.ac', not 'configure.in'
src/Makefile.am: installing './depcomp'
+ glib-gettextize -c
Copying file po/Makefile.in.in

Please add the files
  codeset.m4 gettext.m4 glibc21.m4 iconv.m4 isc-posix.m4 lcmessage.m4
  progtest.m4
from the /usr/share/aclocal directory to your autoconf macro directory
or directly to your aclocal.m4 file.
You will also need config.guess and config.sub, which you can get from
ftp://ftp.gnu.org/pub/gnu/config/.

But there isn't mentioned file (config.sub, config.guess) in the given link. Please someone help me to install this software.
Update: I've got the files config.sub and config.guess. But I have the following questions.
1) I don't have isc-posix.m4 in my /usr/share/aclocal directory. But I have printf-posix.m4 (I don't know if they're same). I have all other .m4 files. Where should I find isc-posix.m4?
2) Which is 'autoconf macro directory' ? OR
3) How to copy the above files to aclocal.m4 file?
4) Where should I put config.guess and config.sub files into?

A: If you go the mentioned URL you would find a README that contains the new location of both files. As the links might change I'm not including the links themselves.

A: There is a good chance that the aclocal.m4 file included with the source was generated with a different version of automake, or the paths were different on the original build system.
Either way, you can generate a new aclocal.m4 file with the autoreconf utility, which will point to the locations of those missing .m4 files.
$ cp aclocal.m4 aclocal.m4.bak # Back up the original just in case
$ autoreconf -ivf

You can then run your ./autogen.sh, and it should pick up the paths to the .m4 files.


text:
Q: Количество трисов в статистике Unity не соответствует реальному Вот кадр с запущенной игрой. Камера просто смотрит на стену с картиной. Объектов минимум. И тем не менее статистика показывает 1.1 миллиона треугольников.

Вот кадр из редактора, который демонстрирует, что здесь никак не может быть такое количество полигонов.

Я не понимаю, что происходит и как с этим бороться.


text:
Q: Autocomplete filter on FormArray - Angular4 Materials I'm a little new to angular 4 and super new to the materials library (literally installed this yesterday).
I am trying to create a list of dynamically added / removed input fields.  The idea is to have my admin create a list of users to delete from the database and hit the service once with an array of users to remove.
I have an array of users that gets populated from a service.  I have a formgroup created.  In that formGroup I have a FormArray that contains possible new FormControl elements.  Users can add and remove items in this array by clicking a button.  This creates input fields on the screen.  I want an autocomplete box to show up to pick a user from the list, and I want to start filtering the list as the admin begins typing into the input field.  The filter needs to be applied against a string created from the lastName and the firstName fields of my user object.  I'm getting the following error with my implementation.

RemoveUserComponent.html:11 ERROR Error: InvalidPipeArgument: '[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]' for pipe 'AsyncPipe'

Here is my RemoveUser.component.ts file:
export class RemoveUserComponent implements OnInit{

        users:User[];
        filteredOptions: Observable<User>;

        userForm = new FormGroup({
            usersToDelete : new FormArray([new FormControl()]),
        });

        get usersToDelete() : FormArray{return this.userForm.get('usersToDelete') as FormArray}

        constructor(private adminService:AdminService){}

        ngOnInit(){
            this.filteredOptions = this.usersToDelete.valueChanges
                .startWith(null)
                .map(user => user && typeof User === 'object' ? user.lastName : user)
                .map(name => name ? this.filter(name) : this.users.slice());

            this.adminService.getUsersByType()
                .subscribe((data:User[])=>{
                   this.users = data;
                   console.log("your user array");
                   console.log(this.users);
                });
        }

        addUser(){
            this.usersToDelete.push(new FormControl());
        }

        onDelete(i:number){
            this.usersToDelete.removeAt(i);
        }

        displayFn(user:User){
            return user ? user.lastName + ", " + user.firstName: user;
        }

        filter(name: string): User[] {
            return this.users.filter(option => new RegExp(`^${name}`, 'gi').test(user));
        }
       }

Here is the HTML template I am using:
<form [formGroup]="userForm" (ngSubmit)="deleteUsers()" *ngIf="users">

                                <md-input-container>
                                        <input type="text" [mdAutocomplete]="auto" mdInput [formControlName]="i">
                                </md-input-container>

                                <button class="btn btn-danger" type="button" (click)="onDelete(i)">-</button>

                               <md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn">
                                   <md-option *ngFor="let user of users | async" [value]="user">
                                      {{ user.lastName }} , {{user.firstName}}
                                   </md-option>
                                </md-autocomplete>

                    <button class="btn btn-success" (click)="addUser()">+</button>
</form>

I think this has to do with the items being an array of users and they need to be an observable, but I'm not positive what to do about it exactly.  I'm also positive my filter is hosed but I was going to deal with the adjustments on that once I got the code working.
I'm a little new to angular, so if you wouldn't mind being thorough in the explanation I would greatly appreciate it.  I really want to grasp what is happening, why it's happening, and where I took the left turn in my code so I can be a better developer.  Thanks folks!

A: Found the problem with the code.  It's actually in the  under the tag.
Original was
<md-option *ngFor="let user of users| async" [value]="user">

should have been
<md-option *ngFor="let user of filteredOptions | async" [value]="user">

Code is still broke, but it's how the filters are working now -- as I suspected previously.  Thanks if you stopped in to take a look.


text:
Q: How is one supposed to answer Java keystore questions that keytool asks? When creating a keystore file using Java's keytool program, it asks a series of questions about the identity to be associated with the keystore. These include some that I wonder if they are required, what they are used for (if anything, ever), how anyone will ever see/use them, and what context are they supposed to be answered from. For example:
"What is your first and last name?" So I wonder things like, Who do they mean? If our team has an IT tech run this program for us, should he put his name? Should it be the manager of our dev team or department? If we work at a company and the person who put their name left the company, what are we supposed to do?
"What is the name of your organizational unit?" What if there is none?
"What is the name of your organization?" What if I'm just a person making a program?
"What is the two-letter country code for this unit?" What unit? What effect does this have? Can I leave it blank?
Also, what agreements, rights and responsibilities are associated with providing this information, upon the person assigned? Or are these just trying to be helpful in case we want this info associated, and we can choose to leave any of them blank if they don't seem relevant or desired?
Is the answer different if it's a mobile app for the Android Play Store?

A: The purpose of those questions are to provide information about you / your organization to the person using that keystore file; for example the Android Play Store registration person.

How is one supposed to answer Java keystore questions that keytool asks?

In general, you should answer truthfully, providing the information that is necessary for the purpose.
In the your case, I think you are signing your application.  (Correct me if I'm wrong ...)  In that case, the purpose of the certificate is (according to this):

Android uses this certificate to identify the author of an app ...

so your answers should be sufficient to allow the Android Play Store administrators, and Android end-users to identify the app's author with sufficient specificity to make a decision as to whether to trust the app.
Obviously, under different circumstances the author might be identified as a person, a organizational unit or an organization.  It would be up to you (i.e the people publishing the software) to make that call.  If there is some guidance in Android documentation, I couldn't find it.  (Please add comments below if you can find anything "official" from Android / Google on this.)

Also, what agreements, rights and responsibilities are associated with providing this information, upon the person assigned?

AFAIK, none.  However, uploading your app certainly places certain obligations on you.

Or are these just trying to be helpful in case we want this info associated, and we can choose to leave any of them blank if they don't seem relevant or desired?

It is not clear.  However, leaving out information may cause people to decide that your certificate is untrustworthy.  Similarly, a self-signed certificate is liable to be viewed with suspicion1.

1 - For example, nothing stops you from writing an Android app for accessing the user's bank account.  And you can sign the app saying that it was published by the bank.  But if the certificate doesn't have a trust chain going back to a trusted root CA, then the user should treat your app with suspicion.

A: See:
http://developer.android.com/tools/publishing/app-signing.html
and
https://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html#CHDHBFGJ
and (if you really want to get into the details of the "subject")
http://www.ietf.org/rfc/rfc5280.txt
Those options allow you to sign something (like your Android apk) and verify your updates are the real deal to avoid fraud.
Just put in some appropriate values and no matter what happens (people leave, org name changes, whatever) you must use the same key store.

A: I just leave most fields blank if I can. You can do this by using the dname argument to keytool. For example:
keytool -genkeypair -alias foo -keyalg RSA -keystore mystore.p12 -dname CN=JoeBloggs
This will set the CN ("first and last name") to JoeBloggs, but leave all the other fields blank. You can see the result using a command such as: keytool -list -keystore mystore.p12 -v


text:
Q: On redirect notification - PHP/JS How can I make a Modal Box/Notification Box appear when I do header redirect or some other method of redirection to a page? Basically as a Success kind of thing. Like I click on send it opens a page and then brings them back to the same page where the send button is and will show a Success box? Any ideas?

A: If you need to trigger some code on a PHP page through an AJAX call you can do it without directly opening that URL. You just pass that PHP URL to a call, the PHP page code is executed and the response is returned back to the page where the request originated. It would look something like this:
Button

page.php
<?php
    echo "Hello from PHP!";
?>

A more detailed explanation with downloadable examples can be found here: jQuery Ajax POST example with PHP.

A: If it's just a login or something similar, you can store the message in a session on whatever page you're processing and then once the page has been redirected, put that session variable into a regular variable and unset your session.  Then you'll just print out whatever as HTML or Javascript.
On the page you submit to
//Do your processing
$_SESSION['someReturnMessage'] = 'Success!';
header('Location:./originalpage.php');

On originalpage.php
//Top of file
if(isset($_SESSION['someReturnMessage'])){
    $message = $_SESSION['someReturnMessage'];
    unset($_SESSION['someReturnMessage'];
}

...further down the page where you want the message to show...
if(isset($message){
    echo $message;
}

You could also use AJAX, which may be a better fit for doing simple tasks.
Using sessions can be a bad idea though, so make sure you don't use them when there are better solutions: Error messages stored in SESSION


text:
Q: Rails invalid datetime on model results in nil I have a model with a datetime attribute. I am trying to validate incoming JSON which would update the model. But ActiveRecord seems to be setting the value of the attribute to nil if it is an invalid datetime. I can't respond with the appropriate error because the attribute is allowed to be nil. What am I doing wrong?
Code:
class DatetimeValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    value.to_datetime rescue record.errors[attribute] << (options[:message] || "must be a date.")
  end
end

class Foo
   # column :my_date, :datetime
   validates :my_date, :allow_nil => true, :datetime => true
end

Console:
1.9.3p125 :001 > x = Foo.new
=> #<Foo id: nil, my_date: nil>
1.9.3p125 :001 > x.my_date = 'bad value'
=> 'bad value'
1.9.3p125 :001 > x.my_date
=> nil
1.9.3p125 :001 > x.valid?
=> true

As far as ActiveRecord is concerned, setting the datetime attribute to 'bad_value' is equivalent to setting it to nil, so I can't validate it, since my_date is not required. This seems like a bug to me. What is the best workaround?
Thanks!

A: One workaround would be to move the allow_nil part into the date_time validation:
class DatetimeValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    return if value.blank?
    value.to_datetime rescue record.errors[attribute] << (options[:message] || "must be a date.")
  end
end

class Foo
  validates :my_date, :datetime => true
end

Edit: I think it's an issue with typecasting - try this (adapted from the code for validates :numericality):
def validate_each(record, attribute, value)
  before_type_cast = "#{attribute}_before_type_cast"

  raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast.to_sym)
  raw_value ||= value

  return if raw_value.blank?
  raw_value.to_datetime rescue record.errors[attribute] << (options[:message] || "must be a date.")
end


text:
Q: How to calculate factorial with masm32 I'm working on a compiler from C to masm32 code, the task is to calculate the factorial of some number (9 in this case), here is the code that I have:
.386
.model flat, stdcall
option casemap:none
include     C:\\masm32\\include\\masm32rt.inc
.data
res dword ?
.code
multiplyNumbers proc C n:dword
cmp n,0
jge ElsePart0
mov eax, 1
ret
ElsePart0:
ret
push 1
push n
call multiplyNumbers
multiplyNumbers endp
main proc C
push 0
pop res
push 9
call multiplyNumbers
mov res, eax
fn MessageBox,0,str$(eax),"Factroial",MB_OK
mov eax, res
ret
main endp

start:
call main
end start

It looks messed up, as the compiler works like that for now...
The problem is that it's not calculating the factorial of 9 (nine is hardcoded) properly
I would be very thankful if somebody could fix that code with minimal code changes
Btw, here is similar C code:
int multiplyNumbers(int n) {
    if (n <= 0) {
        return 1;
    }
    return n * multiplyNumbers(n - 1);
}

int main() {
    int res = 0;
    res = multiplyNumbers(9);
    return res;
}

The expected result is the asm code properly calculating factorial of 9
9! = 362880
right now it outputs 1703884


text:
Q: How can I look up a string in a dictionary which has tuples of strings for its keys? I have this code:
import random
greetings_commands = ('hello', 'hi', 'hey')
compliment_commands = (' you look great', 'you are so good', 'you are amazing')

greetings_responses = ['hi sir', 'hello sir', 'hey boss']
compliment_responses = ['so as you sir', 'thanks, and you look beautiful', 'thanks sir']

commands_list = {greetings_commands: greetings_responses, compliment_commands: compliment_responses}

while True:
  user_input = input('Enter your message: ')   # user input or command or questions
  if user_input in commands_list: # check if user_input in the commands dictionary keys
    response = random.choice(commands_list[user_input]) # choose randomly from the resonpses list
    print(response) # show the answer

Right now, the if user_input in commands_list condition is not met, and no response is printed.
How can I make it so that if user_input is found in any of the tuples used for the dictionary keys, a response is chosen from the corresponding value in the dictionary?

A: Iterate through the keys and values of the dictionary, choosing a response once you find a key that contains the user input.
while True:
  user_input = input('Enter your message: ')   # user input or command or questions
  for commands, responses in commands_list.items():
    if user_input in commands:
      response = random.choice(responses) # choose randomly from the resonpses list
      print(response)
      break

Alternatively expand commands_list so that each key is a single command, to make look-up easier:
commands_list = {command: responses
  for commands, responses in commands_list.items()
  for command in commands}

Then your current code will work.


text:
Q: ion-toggle deshabilitar arrastre Hola muy buenas alguien sabe si es posible deshabilitar la opción de arrastrar el ion-toggle y que funcione solo al clikar.
<ion-toggle mode="ios" slot="start"   class="check_options"
            [(ngModel)]="product_item.standout"
            (click)="change_product_standout($event, product_item.standout, product_item.product_id)" ></ion-toggle>

pues tengo problemas ya que lo que deseo hacer me lo hace al cliclar pero hay un momento que el toggle necesita volver a su estado inicial si el la base de datos hay un 0 y resulta que al clicar funciona todo de maravilla pero si lo arrastro no me cumple lo que quiero.
 change_product_standout(event, isStandout, productId){

console.log('Change Product', event)

const data = {
  'user_id': this.api.userdata.user_id,
  'api_token': this.api.userdata.api_token,
  'product_id': productId
};

this.productService.change_product_standout(data, !Boolean(Number(isStandout))).subscribe(response => {
  if(response.status == 1){
    this.util.errorToast(response.msg);
    const product = this.product_list.find(product => product.product_id == productId);
    product.standout = 0;
  }
})

}

A: Hola buenas sigo con el problema ya que ion-toggle no he podido solucionar intente crear un componente toggle solo que ahora me encuentro que solo me realiza la función una vez la segunda vez que le doy no se desactiva automáticamente.
creo un componente de la siguiente manera:
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

@Component({
  selector: 'toggle-buttom',
  templateUrl: './toggle-buttom.component.html',
  styleUrls: ['./toggle-buttom.component.scss'],
})
export class ToggleButtom implements OnInit {

  @Input() isActive: boolean = false
  @Output() onChangeToggle = new EventEmitter<any>()

  constructor() { }

  ngOnInit() {}

  changeToggle(){
    if(this.isActive){
      this.isActive = false
    }else{
      this.isActive = true
    }
    this.onChangeToggle.emit({value: this.isActive})
  }

}

en html:

después en el ts donde va el componente:
  change_product_standout(event, productId){

    console.log('Change Product', event)

    const data = {
      'user_id': this.api.userdata.user_id,
      'api_token': this.api.userdata.api_token,
      'product_id': productId
    };

    this.productService.change_product_standout(data, (event.value)).subscribe(response => {
      if(response.status == true){
        this.util.errorToast(response.msg);
        const product = this.product_list.find(product => product.product_id == productId);
        product.standout = false;
      }
    })

  }

el el htm:
<ion-item lines = "none">

              <toggle-buttom [isActive]="product_item.standout" (onChangeToggle)="change_product_standout($event, product_item.product_id)" ></toggle-buttom>

              <ion-label class="general_txt">Destacar</ion-label>

            </ion-item>

y por ultimo en la api tengo esto:
public function set_product_standout(Request $request){
    $result=$this->check_usertoken($request->user_id,$request->api_token);
    if(!$result)    {
        return response()->json(['status'=>'0', 'msg'=>'Algo ha salido mal.']);
    }

    /*
     1. Destacar el producto cuando el usuario no sea Free
     2. Destacar cuando la Cantidad permitida del Plan no ha excedido
    */
    $user = Users::find($request->user_id);
    $quota = Quota::where('user_id', $user->user_id)->orderByDesc('end_date')->get()[0];
    $subscriptionPlan = SubscriptionPlans::find($quota->subscription_plan_id);

    if($user->subscription_type == 'Free'){
        return response()->json(['status'=>'1', 'msg'=>'Tu cuenta es Free, no es posible destacar productos']);
    }

    $productsStandoutOfUser = Product::where('user_id', $user->user_id)->where('standout', true)->count();
    if($subscriptionPlan->product_quantity == $productsStandoutOfUser){
        return response()->json(['status'=>'1', 'msg'=>'Cantidad limite de productos destacados ha excedido, Productos Limite:' . $subscriptionPlan->product_quantity]);
    }

    /* Cambiar el Producto a Destacado */
    $product =  Product::find($request->product_id);
    Product::where('product_id', $product->product_id)->update(['standout' => true]);

    return response()->json(['status'=>'0', 'msg'=>'Producto actualizado como Destacado', 'data' => true]);
  }

  public function set_product_not_standout(Request $request){

    $result=$this->check_usertoken($request->user_id,$request->api_token);
    if(!$result)    {
        return response()->json(['status'=>'1', 'msg'=>'Algo ha salido mal.']);
    }

    $product =  Product::find($request->product_id);
    Product::where('product_id', $product->product_id)->update(['standout' => false]);

    return response()->json(['status'=>'0', 'msg'=>'Producto cambiado a no destacado', 'data' => true]);

  }

vale esto es todo el funcionamiento es el siguiente tengo unos productos donde según la base de datos podemos destacar un numero X cuando apretar el toggle selecciono el producto a destacar y cuando sobrepasas la cantidad a destacar envió un aviso y el toggle retorna a su estado de apagado, así me funciona pero solo una vez al volver a seleccionar el toggle mas de dos veces no vuelve a su estado de apagado como que solo se repite una vez la función, con el toggle de ionic me funcionaba bien excepto cuando arrastraba el toggle no volvía a su estado, no se si alguien puede ayudarme se que es complicado pero gracias.


text:
Q: While loop for checking title and add a number if it already exists I want to get the title out of a form and write it to the database. But if the title already exists I want to add number 1 to the title. I can fix that on my own but the problem is how can I (after the 1 is added) check again and if title +1 already exists make it title +2 and so on...
Any ideas how I have to construct a while loop that does that?
$title = $_POST["title"];
$sql = "SELECT * FROM [my_table] WHERE title='$title'";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0) {
  $title = mysql_real_escape_string($_POST["title"]);
  //$title + add 1 to the title

} else {
  $title = mysql_real_escape_string($_POST["title"]);
}

A: One possible solution is to get the count of how many registers with the same title you have. For example:
$sql = "SELECT COUNT(*) AS count FROM [my_table] WHERE title='$title'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc( $result);
$count = $row['count'];

Then:
if($count > 0) {
  $title = mysql_real_escape_string($_POST["title"]);
  $title .= $count;

} else {
  $title = mysql_real_escape_string($_POST["title"]);
}

A: To do this entirely from PHP, I would get a list of all matching titles from the DB in one go, and then keep trying new numbers until one doesn't match:
$title = $_POST["title"];

//Get everything from the database that starts with $title
$sql = "SELECT title FROM [my_table] WHERE title like '$title%'";
$result = mysqli_query($con,$sql);

//Create a list of existing titles
$aTitles = array();
while($row = mysql_fetch_assoc($result)){
    $aTitles = $row['title'];
}

//Now see how many numbers we have

$iNum = 0;
$sTempTitle = $title;

while (in_array($sTempTitle, $aTitles)){
    //This one exists. Try the next number
    $iNum++;
    $sTempTitle = sprintf('%s %d', $title, $iNum);
}

$title = $sTempTitle;

A: Having title and number suffix as part of the title is not a good practice.
The better way to achieve that is to have a title column with count column, where you would increase count ON DUPLICATE KEY. You would have to set the title column to be UNIQUE. Then you can just build your title on SELECT by concatenating row['title'] . "-" . row['count'].
If for any reason you want to keep the current structure, i.e. the title is either:

*

*<title>

*or <title-count>
you would have to read in the existing title by using title LIKE 'some_title%.

*

*if it doesn't exist add it, if it exists, just add the new row;

*if it already exists, update the row by increasing the count (note that you would have to parse the title first, i.e. split by , and get last element - this is your number.

NOTE: This is not thread-safe and you would have to use SQL transactions for this  to work properly.


text:
Q: Switching an SSL configuration from my computer to an hosting server I am using Ruby on Rails 3 and I would like to know some good advice in developing an application in localhost in order to make and prepare that for future deployment.
Specifically in this question I would like to know something about switching an SSL configuration from my computer to an hosting server.
In localhost I use a self-signed SSL certificate, so to run a HTTPS request I must disable its verification (see the below example), but what should I do when the application is deployed and I bought a SSL certificate?
If in localhost I have (using Typhoeus gem)
Typhoeus::Request.get("https://users.pjtname.com", :disable_ssl_peer_verification => true,)

What I will have to do on a hosting server side?
Have I just to delete the :disable_ssl_peer_verification => true code and then set for Typheous a proper certificate like the following or some other thing?
Typhoeus::Request.get("https://users.pjtname.com",
  :ssl_cacert => "cacert.pem",
  :ssl_capath => "/"
)

... and, at all, it will be difficult to switch this kind of configuration?

A: You could just do an environment check to run different setups, quick example:
if Rails.env.development?
    args = {:disable_ssl_peer_verification => true}
else
    args = {:ssl_cacert => "cacert.pem", :ssl_capath => "/"}
end

Typhoeus::Request.get("https://users.pjtname.com", args)

Will disable peer verification if you are on the development environment, otherwise it will use the ssl_cacert and ssl_capath settings.


text:
Q: How does opposite $\sin60\unicode{176}$ have $0.866\ldots$ if hypotenuse is $1\,?$ I've approached in a few different ways to prove it, but couldn't get any good results.
When :
$d = 2\,,$
$\text{radius}=\dfrac d2\;\rightarrow\;r=1\,.$
Since hypotenuse is the same length with $\,r\,,$
$\sin(\theta)=\dfrac{\text{opp}}{\text{hyp}(r)}$
But divided by $\,1\,$ is simply meaningless, so it should be:
$\sin(\theta)=\dfrac{\text{opp}}1$
$\sin(\theta)=\text{opp}\;\;$ (still unknown)
This time, I used Pythagorean Theorem to get the other lengths directly.
By using the formula:
$c=\sqrt{a^2+b^2}$
$c^2=a^2+b^2$
$a^2=c^2-b^2$
$a=\sqrt{c^2-b^2}$
Since $\,c\,$ represents $\,r\,,$
$a=\sqrt{r^2-b^2}$
$a=\sqrt{1^2-b^2}$
$a=\sqrt{1-b^2}\;\;$ (still unknown)
At the end, both ways couldn't find out what numbers of $\,o\,$ and $\,a\,$ are as long as hypotenuse is $\,1\,.$
But when I tap the calculator, $\,\sin\left(60\unicode{176}\right)\,$ throws $\,0.866025\ldots\,$ which doesn't make sense.
If I given only hypotenuse length, how can I prove that $\,\sin(\theta)=x\,?$

A: As already mentioned by @lulu, I would construct a $30-60-90$ triangle on the unit circle first.
After we obtain all side lengths, we can use $\sin(\alpha) = \frac{\text{opposite}}{\text{hypotenuse}}$ to prove the value of $\sin(60°)$.
We first construct the triangle $\triangle ABC$, noting that the segment $AB$ has to be of length $1$, since that is the radius of the unit circle. By mirroring $\triangle ABC$ on the $x$-axis, we obtain $\triangle ACD$, noting that the segment $AD$ has to be of length $1$ too, for the same reason as above.
We now have a larger triangle $\triangle ABD$.
Notice that all the angles of $\triangle ABD$ are $60°$, that means $\triangle ABD$ is equilateral.
Thus, the side length of segment $BD$ is 1.
Since $BD$ is exactly twice the length of $BC$, we know that $BC$ is of length $\frac{1}{2}$.
Also, since $AB$ is of length 1, we know that $AC = \sqrt{1^2 - \left(\frac{1}{2}\right)^2} = \sqrt{\frac{3}{4}} = \frac{\sqrt{3}}{2}$.
Now, $\sin(60°) = \frac{AC}{1} = \frac{\sqrt{3}}{2}$.
Here is a picture (if you are on a screen reader, you can construct it on a unit circle like described above):

(Constructed with GeoGebra)

A: You may be thinking side-$a$ is the opposite. If you treat side-$a\,$ as the $\,x$-axis and side-$b\,$ as the
$y$-axis, then side-$b\,$ will give you the
$\dfrac{\sqrt{3}}{2}=0.866$ you expect.


text:
Q: Does Erlang support an "ask" operation? In Akka you got two different sending mechanisms: ! for telling the actor stuff, and ? for asking an actor about stuff, the main difference for those unfamiliar is that actor ! message is a fire-and-forget operation, and actor ? message returns a promise of a result that then at a later time needs to be resolved.
I haven't been able to find anything regarding this in Erlang as googling "Erlang ask operation" or simply "Erlang ask" yields less-than helpful results.

A: No, it does not, but what you request is easy to implement:
ask(Pid, M) ->
  Promise = erlang:monitor(process, Pid),
  Pid ! {ask, Promise, M},
  Promise.

Awaiting the result of the promise can now be done by:
force(Promise, Timeout) ->
  receive
    {result, Promise, R} ->
      erlang:demonitor(Promise, [flush]),
      {ok, R};
    {'DOWN', Promise, process, _, Reason} ->
      {error, {callee_died, Reason}}
  after Timeout -> {error, timeout}
  end.

If you don't want to do anything in between asking and the force, then you can use the OTP behavior gen_server which has a gen_server:call/3 essentially implementing these two functions in one go.
Note how in the above we request a monitor reference on the target Pid which allows us to monitor it if it dies. We also use this reference as a unique tag for the promise so we can find it among other messages that looks like it in the mailbox.

A: Erlang doesn't support promises nor futures. See this question for other examples of simulating them. Also see this article for explanation why Erlang uses Message Passing instead of Promises and Futures.

A: The ? in Akka is built using !. What it does is: It creates a new temporary actor which is used as the sender for a message being dispatched using ordinary !. If it does not receive anything in time, it sets the promise to failed. If it does it fulfuls the promise.
The asked actor will then reply to that temporary actor (which is how you know to which message was actually replied, otherwise you would have to keep track of that yourself in a map or something similar).
This is why you have to import the ask pattern explicitly and why it is called a pattern, not a built in primitive like ! is.
You could implement the same pattern in Erlang.


text:
Q: Error in glm() in R I would like to perform a logistic regression but get errors - don't know where the mistake might be.
The structure of my data:
'data.frame':   3911 obs. of  29 variables:
 $ vn1              : Factor w/ 2 levels "maennlich","weiblich": 1 1 2 1 1 2 1 1 1 1 ...
 $ vn2c             : int  1976 1943 1927 1949 1965 1977 1986 1976 1944 1994 ...
 $ vn35             : Factor w/ 7 levels "keine Angabe",..: 6 4 5 3 3 5 7 6 5 5 ...
 $ v39              : Factor w/ 8 levels "keine Angabe",..: 8 4 5 8 7 7 5 6 6 6 ...
 $ n39              : Factor w/ 9 levels "keine Angabe",..: 4 4 4 4 4 4 4 4 4 4 ...
 $ v41              : Factor w/ 7 levels "keine Angabe",..: 6 5 5 2 7 7 5 5 6 6 ...
 $ n41              : Factor w/ 7 levels "keine Angabe",..: 4 4 4 4 4 4 4 4 4 4 ...
 $ vn42a            : Factor w/ 8 levels "keine Angabe",..: 8 4 8 8 5 5 6 6 6 4 ...
 $ vn42b            : Factor w/ 8 levels "keine Angabe",..: 5 4 7 5 5 5 6 7 6 5 ...
 $ vn43a            : Factor w/ 8 levels "keine Angabe",..: 7 5 8 6 2 6 6 2 7 7 ...
 $ vn43b            : Factor w/ 8 levels "keine Angabe",..: 7 4 6 4 4 7 6 2 6 5 ...
 $ vn62             : Factor w/ 14 levels "keine Angabe",..: 8 11 9 2 3 3 8 6 5 7 ...
 $ vn119a           : Factor w/ 15 levels "keine Angabe",..: 6 3 8 14 10 8 14 8 6 6 ...
 $ ostwest          : Factor w/ 2 levels "Ost","West": 2 2 2 2 2 2 2 2 2 2 ...
 $ prefmerkel       : Factor w/ 2 levels "Steinbrueck",..: 1 2 2 NA NA NA 2 2 1 1 ...
 $ angst            : num  1 3 2 4 4 2 0 1 2 2 ...
 $ crisismerkel     : num  0 4 3 0 1 1 3 2 2 2 ...
 $ leadership42     : Factor w/ 5 levels "trifft ueberhaupt nicht zu",..: 5 1 5 5 2 2 3 3 3 1 ...
 $ leadership43     : Factor w/ 5 levels "trifft ueberhaupt nicht zu",..: 4 2 5 3 NA 3 3 NA 4 4 ...
 $ leadership       : num  1 -1 0 2 NA -1 0 NA -1 -3 ...
 $ trustworthiness42: Factor w/ 5 levels "trifft ueberhaupt nicht zu",..: 2 1 4 2 2 2 3 4 3 2 ...
 $ trustworthiness43: Factor w/ 5 levels "trifft ueberhaupt nicht zu",..: 4 1 3 1 1 4 3 NA 3 2 ...
 $ trustworthiness  : num  -2 0 1 1 1 -2 0 NA 0 0 ...
 $ ideology         : num  5 8 6 NA NA NA 5 3 2 4 ...
 $ pid              : Factor w/ 10 levels "none","CDU/CSU",..: 3 2 5 1 7 5 1 5 3 3 ...
 $ age              : num  37 70 86 64 48 36 27 37 69 19 ...
 $ agegroups        : Factor w/ 7 levels "bis 25 Jahre",..: 3 6 7 5 4 3 2 3 6 1 ...
 $ gender           : Factor w/ 2 levels "male","female": 1 1 2 1 1 2 1 1 1 1 ...
 $ region           : Factor w/ 2 levels "west","east": 1 1 1 1 1 1 1 1 1 1 ...

The regression command returns the following error:
summary(glm(prefmerkel~angst+crisismerkel+leadership+trustworthiness+ideology+pid+agegroups+gender+region,data=gles))

Error in glm.fit(x = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  :
  NA/NaN/Inf in 'y'

In addition: Warning messages:
1: In Ops.factor(y, mu) : '-' nicht sinnvoll für Faktoren
2: In Ops.factor(eta, offset) : '-' nicht sinnvoll für Faktoren
3: In Ops.factor(y, mu) : '-' nicht sinnvoll für Faktoren

A: If your variable is binomial mention 'family=binomial'. This will solve the problem

A: This page is showing up high on search for this error, so want to add another reason not to do with linear vs logistic regression. I had the same issue as Yulia, where I had log-transformed some of my predictors resulting in the error discussed here.
The reason for the error is that if you have any rows with value 0 before log-transforming, these become -Inf which results in the regression throwing an error. The solution is to refrain from log-transforming such variables, or to make sure you have no 0-valued rows (see e.g. discussion on stack exchange).

A: In my case it was none of the above. I have log-transformed on of the right-skewed variables and when I used it, log-regression resulted in this error. When I used the original (untransformed) variant - it worked perfect.

A: You can't have factor/categorical response variables.
Illustration:
> d=data.frame(f=factor(c(1,2,1,2,1,2)),x=runif(6))
> glm(f~x,data=d)
Error in glm.fit(x = c(1, 1, 1, 1, 1, 1, 0.351715633412823, 0.449422287056223,  :
  NA/NaN/Inf in 'y'
In addition: Warning messages:
1: In Ops.factor(y, mu) : - not meaningful for factors
2: In Ops.factor(eta, offset) : - not meaningful for factors
3: In Ops.factor(y, mu) : - not meaningful for factors

If you really want to do a logistic regression you should change them to 0 and 1, or FALSE and TRUE, and use family=binomial:
# recode d$f==2 as TRUE, else FALSE
d$f=d$f=="2"
# fit
glm(f~x,data=d,family=binomial)

Call:  glm(formula = f ~ x, family = binomial, data = d)

Coefficients:
(Intercept)            x
    -0.9066       1.8922

Degrees of Freedom: 5 Total (i.e. Null);  4 Residual
Null Deviance:      8.318
Residual Deviance: 8.092    AIC: 12.09


text:
Q: Shortening a for loop which pads first and last value of several lists I have 3 lists (EIRP,data3,data15) and I'm looking for a way to shorten this code:
ws=3

for i in range(ws):
    EIRP.insert(0, EIRP[0])
    EIRP.append(EIRP[-1])
    data3.insert(0,data3[0])
    data3.append(data3[-1])
    data15.insert(0,data15[0])
    data15.append(data15[-1])

A: li = [EIRP,data3,data15]
ws = 3
for i in range(ws):
    for j in li:
        j.insert(0, j[0])
        j.append(j[-1])

I hope that this is what you want

A: EIRP[0:0] = EIRP[:1] * 3
EIRP.extend(EIRP[-1:] * 3)

data3[0:0] = data3[:1] * 3
data3.extend(data3[-1:] * 3)

data15[0:0] = data15[:1] * 3
data15.extend(data15[-1:] * 3)

even shorter
EIRP = EIRP[:1] * 3 + EIRP[:] + EIRP[-1:] * 3
data3 = data3[:1] * 3 + data3[:] + data3[-1:] * 3
data15 = data15[:1] * 3 + data15[:] + data15[-1:] * 3


text:
Q: How to access non-fingerprinted version of an asset? To keep things simple, I created a new Rails application today (Rails 4.0.3, Ruby 2.1.1, Phusion Passenger/Nginx for production).
I have an image "logo.png" located in my_app/assets/images/logo.png.
Using the following code, the image displays correctly in development:
<img src="/assets/logo.png">

In production, I am getting a 404 error when trying to access this asset image file.
I ran the following code on the live production server:
rake assets:precompile RAILS_ENV=production

But still have had no luck.
I can access the image on production with:
<%= image_tag "logo.png" %>

But I am trying to access the non-fingerprint version of the asset.  The reasoning is that I'm using an HTML template and don't want to have to use all the rails helpers to fix all the paths.
Does anyone know how I can access the image using the /assets/logo.png path rather than using the built in rails helpers?  Thanks.

A: Just do it old school: Put that image into your /public folder. All images in asset folders need to be precompiled or they will not be reachable in production. Everything in the /public folder is returned without asset pipeline.
So when you have an image in /public/images/logo.png than you can download it from /images/logo.png


text:
Q: rsync command not found (while backing up Postgresql using barman) I am trying to use barman to schedule backups to be taken of my Postgresql database. The IPs of my DB server and backup server (both of which run Cent OS 7.2.1511) is 10.113.12.200 and 10.133.12.205 respectively. After studying Barman's documentation and Postgresql documentation for point-in-archiving, I set up the archiving in Postgresql configuation file as
archive_mode = on
wal_level = 'replica'
archive_command = 'rsync --rsync-path=/usr/bin/rsync -a %p barman@10.133.12.205:/var/lib/barman/incoming/my_database/%f'

I have also enabled password-less SSH from postgres@10.113.12.200 to barman@10.113.12.205 and vice-versa as the Barman docs say.
Below is an excerpt from my barman.conf's DB server section.
[my-database]
description = "My Database"
ssh_command = ssh postgres@10.113.12.200
conninfo = host=10.113.12.200 user=postgres
retention_policy_mode = auto
retention_policy = RECOVERY WINDOW OF 7 days
wal_retention_policy = main

I'm really very puzzled and confused over this error sh: rsync command not found. Now, I know what this error is after reading about on rsync and going through some questions here on SO including this one here https://unix.stackexchange.com/questions/198756/why-is-rsync-not-found
I SSHed to barman@10.113.12.205 from postgres@10.113.12.200 to find out the $PATH, executed which rsync and then only added --rsync-path as above. But still this issue. None of my WAL archives are getting copied as a result. Can someone shed some light? I think I miss something fundamental here.


text: Q: In linear regression, does the parameter confidence interval is based in the mean confidence interval? If I have a sample and calculate the interval for the A and B parameter of the linear regression for that sample, for a given x that is the independent variable of my real data, and Y that is the predicted value of the linear regression for this x value, does  Y +- (Upper/Bottom limit of the A parameter)*X + (Upper/Bottom limit of the B parameter) is the same as the confidence interval for the mean of y (dependent variable of the real data) for a given x?


text:
Q: Erro em aplicação Android NullPointerException Estou tentando criar uma aplicação android que gere botões dinamicamente na tela, mas estou recebendo um erro NullPointerException e não sei como tratá-lo.
Alguém que tenha paciência em me explicar coisas óbvias, pois sou novato no mundo da programação.
Aqui está a MainActivity.java:
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

    private ImageButton btn_ir_historico;
    private ImageButton btn_ir_produtos;
    private LinearLayout linearL;
    private Button addBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        linearL = (LinearLayout) findViewById(R.id.linearLayout_v);
        btn_ir_historico = (ImageButton) findViewById(R.id.img_b_vendas_d);
        btn_ir_historico.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, HistoricoActivity.class);
                startActivity(intent);
                finish();
            }
        });
        btn_ir_produtos = (ImageButton) findViewById(R.id.img_b_vendas_e);
        btn_ir_produtos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, ProdutosActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
    public void criar_btn(){
        addBtn = new Button(this);
        addBtn.setText("luan");
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        addBtn.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        linearL.addView(addBtn, lp);
    }
}

Aqui está a ProdutosActivty.java:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

public class ProdutosActivity extends AppCompatActivity {

    private ImageButton btn_ir_main;
    private Button btn_adc;
    /*private Button btn_limpar;
    private EditText nome_produtos;
    private EditText valor_produtos;*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_produtos);

        btn_adc = findViewById(R.id.btn_adc);
        btn_ir_main = findViewById(R.id.img_b_produtos_d);
        btn_ir_main.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ProdutosActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
        btn_adc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chamar();
                finish();
            }
        });
    }
    public static void chamar(){
        MainActivity main_act = new MainActivity();
        main_act.criar_btn();
    }
}

Aqui esta o LogCat:

Process: teste.luan.com.projeto_teste, PID: 10555
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
    at android.content.ContextWrapper.getResources(ContextWrapper.java:92)
    at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
    at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:542)
    at android.view.View.<init>(View.java:4038)
    at android.view.View.<init>(View.java:4169)
    at android.widget.TextView.<init>(TextView.java:947)
    at android.widget.Button.<init>(Button.java:112)
    at android.widget.Button.<init>(Button.java:105)
    at android.widget.Button.<init>(Button.java:101)
    at android.widget.Button.<init>(Button.java:97)
    at teste.luan.com.projeto_teste.MainActivity.criar_btn(MainActivity.java:46)
    at teste.luan.com.projeto_teste.ProdutosActivity.chamar(ProdutosActivity.java:44)
    at teste.luan.com.projeto_teste.ProdutosActivity$2.onClick(ProdutosActivity.java:37)
    at android.view.View.performClick(View.java:5697)
    at android.widget.TextView.performClick(TextView.java:10826)
    at android.view.View$PerformClick.run(View.java:22526)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:158)
    at android.app.ActivityThread.main(ActivityThread.java:7224)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
07-20 13:19:26.916 10555-10555/teste.luan.com.projeto_teste I/Process: Sending signal. PID: 10555 SIG: 9`


text:
Q: How can i set html in javascript to specific location in element I have a div just like this

 Hello this is content editable.... [cursor is blinking here] and more text

How can i set a data where cursor is blinking.
Thanks in advance.

A: You use execCommand with the insertHTML command:
document.execCommand("insertHTML", false, "the HTML to insert");

Live Example:

$("div").on("keydown", function(e) {
  if (e.ctrlKey && e.which == 81) {
    document.execCommand("insertHTML", false, "inserted");
    return false;
  }
});

Put your cursor in the relevant location below, then press Ctrl+Q:

 Hello this is content editable....  and more text

Sadly this doesn't seem to work on IE11. :-| For cross-browser support, you might look at Tim Down's rangy library.


text:
Q: MYSQL inner join of two tables with non-unique columns I have two tables (jos_table1 and jos_table2), which I want to do an inner join on element1 (from table 1) and element2 (from table2). Both tables contain a column called "parent_id" - I can't change this.
I want to count the number of rows which fulfil a certain where clause based on the parent_id element. The statement works fine if I omit the where clause, but when I have it there it doesn't work and returns the error "Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given"
Does anyone know why? Any help is most appreciated.
Kind regards,
Paul Hughes
$table="jos_table1";
$table2= "jos_table2";

MYSQL_CONNECT($server, $user, $password) or die ( "
Server unreachable
");

MYSQL_SELECT_DB($database) or die ( "
Database non existent
");

$aiders=MYSQL_QUERY('SELECT COUNT($table.element1) AS hpp FROM $table INNER JOIN $table2 ON $table.element1=$table2.element2
WHERE `$table.parent_id` = 134
');

$faid = mysql_fetch_array($aiders);
$total = $faid[0];
echo "The total is (".$total.")";

A: The backquotes need to go around just the table part and/or just the column part.
For example:
WHERE `$table`.`parent_id`=134


text:
Q: Why loading 4000 images into redis using spark-submit takes time (9 Minutes) longer than loading the same images into HBase (2.5 Minutes)? Loading Images into Redis should be much faster than doing the same thing using Hbase since Redis deals with RAM while HBase uses HDFS to store the data. I was surprised when I loaded 4000 images into Redis, it took 9 Minutes to finish! While the same process I've done using HBase and It took only 2.5 Minutes. Is there an interpretation for this? Any Suggestions to improve my code? Here is my code:
// The code for loading the images into Hbase (adopted from NIST)
val conf = new SparkConf().setAppName("Fingerprint.LoadData")
val sc = new SparkContext(conf)
Image.dropHBaseTable() Image.createHBaseTable()
val checksum_path = args(0)
println("Reading paths from: %s".format(checksum_path.toString))
val imagepaths = loadImageList(checksum_path) println("Got %s images".format(imagepaths.length))
imagepaths.foreach(println)
println("Reading files into RDD")
val images = sc.parallelize(imagepaths).map(paths => Image.fromFiles(paths._1, paths._2))
println(s"Saving ${images.count} images to HBase")
Image.toHBase(images)
println("Done")

} val conf = new SparkConf().setAppName("Fingerprint.LoadData") val sc = new SparkContext(conf) Image.dropHBaseTable() Image.createHBaseTable() val checksum_path = args(0) println("Reading paths from: %s".format(checksum_path.toString)) val imagepaths = loadImageList(checksum_path) println("Got %s images".format(imagepaths.length)) imagepaths.foreach(println) println("Reading files into RDD") val images = sc.parallelize(imagepaths) .map(paths => Image.fromFiles(paths._1, paths._2)) println(s"Saving ${images.count} images to HBase") Image.toHBase(images) println("Done")

} def toHBase(rdd: RDD[T]): Unit = {

     val cfg = HBaseConfiguration.create()
     cfg.set(TableOutputFormat.OUTPUT_TABLE, tableName)
     val job = Job.getInstance(cfg)
     job.setOutputFormatClass(classOf[TableOutputFormat[String]])
     rdd.map(Put).saveAsNewAPIHadoopDataset(job.getConfiguration)

}

//The code for Loading images intto Redis
  val images = sc.parallelize(imagepaths).map(paths => Image.fromFiles(paths._1, paths._2)).collect
        for(i <- images){
val stringRdd = sc.parallelize(Seq((i.uuid, new String(i.Png, StandardCharsets.UTF_8))))
        sc.toRedisKV(stringRdd)(redisConfig)
        stringRdd.collect}
        println("Done")


text:
Q: sql - count one column based on another column I have a dataset
case_id    subcase_id
1      | 1-1
1      | 1-2
1      | 1-3
1      | 1-6
2      | 2-1
2      | 2-7

I want the following output. The idea is to count the occurence of a subcase corresponding to a case.
case_id  subcase_id
1      | 1-1          | 1
1      | 1-2          | 2
1      | 1-3          | 3
1      | 1-6          | 4
2      | 2-1          | 1
2      | 2-7          | 2

A: You can try using row_number() function
select
   caseid,
   subcase_id,
   row_number() over(partition by caseid
      order by
      cast(SUBSTR(subcase_id, 1,INSTR(subcase_id, '-') -1) as number),
      cast(SUBSTR(subcase_id, INSTR(subcase_id, '-') +1) as number)) as rn
from tablename

A: You may use count() over (partition by .. order by ..) clause as :
    with t(case_id,subcase_id) as
    (
     select 1,'1-1' from dual union all
     select 1,'1-2' from dual union all
     select 1,'1-3' from dual union all
     select 1,'1-6' from dual union all
     select 2,'2-1' from dual union all
     select 2,'2-7' from dual
    )
     select t.*,
            count(*) over (partition by case_id order by subcase_id)
            as result
       from t;

    CASE_ID     SUBCASE_ID   RESULT
    -------     ----------   ------
       1            1-1        1
       1            1-2        2
       1            1-3        3
       1            1-6        4
       2            2-1        1
       2            2-7        2

where subcase_id is changes frequently and distinct for all values while case_id changes rarely.
Rextester Demo

A: Here is a query which should behave as you want.  We have to isolate the two numeric components of the subcase_id, and then cast them to integers, to avoid sorting this column as text.
SELECT
    case_id,
    subcase_id,
    ROW_NUMBER() OVER (PARTITION BY case_id
        ORDER BY TO_NUMBER(SUBSTR(subcase_id, 1, INSTR(subcase_id, '-') - 1)),
                 TO_NUMBER(SUBSTR(subcase_id, INSTR(subcase_id, '-') + 1))) rn
FROM yourTable
ORDER BY
    case_id,
    TO_NUMBER(SUBSTR(subcase_id, 1, INSTR(subcase_id, '-') - 1)),
    TO_NUMBER(SUBSTR(subcase_id, INSTR(subcase_id, '-') + 1));

Demo
It is not a good idea to treat the subcase_id column as both text and numbers.  If you really have a long term need to sort on this column, then I suggest breaking out the two numeric components as separate number columns.


text:
Q: How to animate multiple sprites in one direction using one geometry in Three.js? I'm trying to do something similar to this example, except instead of having the snow flakes flutter about in all directions I'm trying to animate these sprites in only one direction, like having the snow flakes fall to the ground.
The example above was able to load multiple sprites into one geometry since it can vary the rotations of the points object:
particles.rotation.x = Math.random() * 6;
particles.rotation.y = Math.random() * 6;
particles.rotation.z = Math.random() * 6;

However, this won't work if you're animating all the points in one direction. In this case, would I have to create a new geometry for each sprite, or is there a more efficient way to do this using just one geometry?

A: There are several options. Instead of rotating randomly, you could:

*

*Decrease the y position on each frame with particles.position.y -= 0.01;. When it crosses a certain threshold (For example: y <= -100), move them back up to the origin (y = 100). You'll have to stagger a few Sprite objects so you don't notice the jump.

*Rotate along the x-axis, so the spinning motion makes them go down when in front of the camera.
Since the snowflakes will spin up on the opposite side, you could use some fog to hide the far side, and give it a more wintry feel.

*Animating via custom shaders, although this is much more complex if you don't know GLSL shader code.


text:
Q: Does ice made with hot water melt faster than ice made with cold water? This is an other side of the coin question about the freezing of hot water vs cold water, called the Mpemba effect.

A: The Mpemba effect is the subject of significant controversy. Here is an example of an experiment that failed to demonstrate such an effect:
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5121640/
I myself attempted a simplistic experiment in high school that failed to demonstrate the Mpemba effect.
It is reasonable to assume that if a sample of hot water and a sample of cold water are subjected to the same cooling process, the initially hot water will end up slightly warmer and therefore melt sooner.

A: Ice made with hot water tends to contain less dissolved air. The latter tends to lower the freezing point, so ice made from cold water will melt at a higher temperature.

A: first of all ice made from hot water tends to freeze much earlier than water from cold water this is explained through Mpemba effect see this wikipeda article for more information
https://en.wikipedia.org/wiki/Mpemba_effect
Although i want to clearly state you that this effect is still not accepted by mainstream scientists today and is still debated As far as Melting of ice is concerned once it freezes at 0 degree celcius it does not really matter it is made of hot water or cold water both types of ice will melt at 0 degree celcius.The melting point of ice at 1 atmosphere of pressure is very close [3] to 0 °C (32 °F, 273.15 K); this is also known as the ice point.


text:
Q: Synapse: Cannot receive data from Socket I am using Synapse with blocking sockets and try to simply send text to the connected client. Here comes the code:
var
SServer: TTCPBlockSocket;
SClient: TTCPBlockSocket;

implementation
//Create and initialize the Sockets.
procedure TForm1.FormCreate(Sender: TObject);
begin
    SClient := TTCPBlockSocket.Create;
    SServer := TTCPBlockSocket.Create;
    SServer.Bind('127.0.0.1', '12345');
    SClient.Connect('127.0.0.1', '12345');
end;

//Wait for connections.
procedure TForm1.FormShow(Sender: TObject);
begin
    SServer.Accept;
    //SServer.Listen; <- Could also work here?
end;

//Send the string to the connected server.
procedure TForm1.Button3Click(Sender: TObject);
begin
    SClient.SendString('hi server');
end;

//Receive the string from the client with timeout 1000ms and write it into a memo
procedure TForm1.Button2Click(Sender: TObject);
var buf: string;
begin
    Memo1.Lines.Add(SServer.RecvString(1000));
end;

First, I click Button 3, then I click Button2. Doing so, there is nothing getting written inside the memo1 field.
Shouldn't this work?
#
****EDIT:****
#
According to skramads comment, I have now split it up into 2 programs. Here we go:
Client:
var
  SClient: TTCPBlockSocket;

implementation

procedure TForm2.Button1Click(Sender: TObject);
begin
  SClient.SendString(Edit1.Text);
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  SClient := TTCPBlockSocket.Create;
end;

procedure TForm2.FormShow(Sender: TObject);
begin
  SClient.Connect('127.0.0.1','12345');
end;

Server:
var
  Form1: TForm1;
  SSocket: TTCPBlockSocket;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  SSocket.Bind('127.0.0.1','12345');
  SSocket.Listen;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  Memo1.Lines.Add(SSocket.RecvString(1000));
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  SSocket := TTCPBlockSocket.Create;
end;

Still, this does not work as intended. I just get no data over there.
Any ideas?

A: You should read how socket communications work, for example here (English) or here (German). In short: the socket you listen() on on the server side is not used for the communication itself, you have to call accept() to open another socket as the partner for the client, and use that one to send and receive data. The listening socket is used solely to accept other connections from other clients, which you can then use to communicate between one server and several clients in parallel.
Maybe you should first examine a simple client/server demo application. The principles are the same, whether you use Synapse, Indy or low-level API programming.

A: if you break this into two separate programs, then it will work better.  Blocking calls do just that...they block until they complete.


text:
Q: VTK.js VR not display/showing an hand controller in Room I try to use VTK VR, but When I test it, I cant see controller in room, I can get action from controller like press or somthing, but without its seen for user in VR mode, how I can fix it?
Online Demo From Here.
    import 'vtk.js/Sources/favicon';

import vtkActor from 'vtk.js/Sources/Rendering/Core/Actor';
import vtkCalculator from 'vtk.js/Sources/Filters/General/Calculator';
import vtkConeSource from 'vtk.js/Sources/Filters/Sources/ConeSource';
import vtkFullScreenRenderWindow from 'vtk.js/Sources/Rendering/Misc/FullScreenRenderWindow';
import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper';
import { AttributeTypes } from 'vtk.js/Sources/Common/DataModel/DataSetAttributes/Constants';
import { FieldDataTypes } from 'vtk.js/Sources/Common/DataModel/DataSet/Constants';

import controlPanel from './controller.html';

// ----------------------------------------------------------------------------
// Standard rendering code setup
// ----------------------------------------------------------------------------

const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance({
  background: [0, 0, 0],
});
const renderer = fullScreenRenderer.getRenderer();
const renderWindow = fullScreenRenderer.getRenderWindow();

// ----------------------------------------------------------------------------
// Example code
// ----------------------------------------------------------------------------
// create a filter on the fly, sort of cool, this is a random scalars
// filter we create inline, for a simple cone you would not need
// this
// ----------------------------------------------------------------------------

const coneSource = vtkConeSource.newInstance({ height: 100.0, radius: 50.0 });
// const coneSource = vtkConeSource.newInstance({ height: 1.0, radius: 0.5 });
const filter = vtkCalculator.newInstance();

filter.setInputConnection(coneSource.getOutputPort());
// filter.setFormulaSimple(FieldDataTypes.CELL, [], 'random', () => Math.random());
filter.setFormula({
  getArrays: (inputDataSets) => ({
    input: [],
    output: [
      {
        location: FieldDataTypes.CELL,
        name: 'Random',
        dataType: 'Float32Array',
        attribute: AttributeTypes.SCALARS,
      },
    ],
  }),
  evaluate: (arraysIn, arraysOut) => {
    const [scalars] = arraysOut.map((d) => d.getData());
    for (let i = 0; i < scalars.length; i++) {
      scalars[i] = Math.random();
    }
  },
});

const mapper = vtkMapper.newInstance();
mapper.setInputConnection(filter.getOutputPort());

const actor = vtkActor.newInstance();
actor.setMapper(mapper);
actor.setPosition(20.0, 0.0, 0.0);

renderer.addActor(actor);
renderer.resetCamera();
renderWindow.render();

// -----------------------------------------------------------
// UI control handling
// -----------------------------------------------------------

fullScreenRenderer.addController(controlPanel);
const representationSelector = document.querySelector('.representations');
const resolutionChange = document.querySelector('.resolution');
const vrbutton = document.querySelector('.vrbutton');

representationSelector.addEventListener('change', (e) => {
  const newRepValue = Number(e.target.value);
  actor.getProperty().setRepresentation(newRepValue);
  renderWindow.render();
});

resolutionChange.addEventListener('input', (e) => {
  const resolution = Number(e.target.value);
  coneSource.setResolution(resolution);
  renderWindow.render();
});

vrbutton.addEventListener('click', (e) => {
  if (vrbutton.textContent === 'Send To VR') {
    fullScreenRenderer.getOpenGLRenderWindow().startVR();
    vrbutton.textContent = 'Return From VR';
  } else {
    fullScreenRenderer.getOpenGLRenderWindow().stopVR();
    vrbutton.textContent = 'Send To VR';
  }
});

// -----------------------------------------------------------
// Make some variables global so that you can inspect and
// modify objects in your browser's developer console:
// -----------------------------------------------------------

global.source = coneSource;
global.mapper = mapper;
global.actor = actor;
global.renderer = renderer;
global.renderWindow = renderWindow;

Note: Tested on Latest Version of Chrome & Firefox (64 bit). Controller Type is HTC Vive.
Update 1:
We found this option not development, so that I share updated link now Github Link