text:
Q: array wordpress when get is null I've set this code to manage filters from a page list of posts in wordpress.
This filter run if I have all the variables not null, like this: ?TYPE=Apartment&AREA=Chianti&PRICE=A
but when one of them are empty, code give me an empty result.
How can I fix?
if(isset($type_search) OR isset($area_search)  OR isset($prezzo_search)) {
    $posts = get_posts(array(
        'posts_per_page'    => -1,
        'meta_query'    => array(
            'relation'      => 'AND',
            array(
                'relation' => 'AND',
                array(
                    'key'       => 'villa_type_buy',
                    'value'     => $type_search,
                    'compare'   => '='
                ),
                array(
                    'key'       => 'Area',
                    'value'     => $area_search,
                    'compare'   => '='
                )
            ),
            array(
                'key'       => 'price_buy',
                'value'     => array( $start_price, $end_price ),
                'type' => 'numeric',
                'compare'   => 'BETWEEN'
            )
        )
    ));
}

A: One option is to use PHP function empty() and the AND / && operator to build your if check to be certain that all of the required parameters are present.
if (
    ! empty( $type_search ) &&
    ! empty( $area_search ) &&
    ! empty( $prezzo_search ) &&
) {

    // your ocde

}

P.s. type and area could be an excellent opportunity to use custom taxonomies and terms instead of post meta, if they can only have one or more predifned values and they are used to group posts together. Using custom taxonomies can provide you better performance, more on this for example here, https://tomjn.com/2016/12/05/post-meta-abuse/ (not written by me).


text:
Q: something is five times the size of something else - can only mean bigger and never smaller? A real-world example from a computer book that I've been reading recently:

Bitmaps do not use any compression and can be three or four times the size of the same image in other file types such as JPEG, TIFF or PNG.

When we use this construction, do we ALWAYS mean that something is a certain number of times BIGGER than something else? So, if I say something like this:

Now the size of the original file is five times the compressed file.

The only way this can be understood is the size of the original file is five times bigger than the size of the file that we got after compression? Correct?
Or maybe it's possible to denote whether the thing in question is bigger or smaller than other thing we're comparing it with by simply adding the words bigger and smaller? Like this:

Now the size of the file is five times smaller the size of the original file.

Am I making any sense?

A:
(The size of) A is five times (the size of) B.
  In this case, A is indeed always bigger than B. You can read the "five times" as follows:
The size of A is the size of B, plus the size of B, plus the size of B, plus the size of B, plus the size of B.

The sentence is showing that something is equal to something else:

(The size of) A is **equal to* five times (the size of) B.

If you want to use bigger or smaller, you need to use than:

(The size of) A is five times bigger than (the size of) B.
  (The size of) A is five times smaller than (the size of) B.

Note that these expressions are ambiguous: not everybody will understand the same thing, especially not in the case of x times smaller: how big is 4 times smaller than 100? If it is really important to not be misunderstood, use unambiguous formulations like:

A is one fifth the size of B.
  A is five times as big as B.

A: The form, X is [number] times the size of Y always means X is [number] times bigger than Y.
The form, [number] times smaller is perfectly acceptable, clear (not ambiguous in any way), and is often more popular or even the only idiomatic form in common usage. I'll call this the Times Smaller Form. The preference (aka "popularity") for this usage (instead of the Fraction Form) grows as [number] gets bigger.  This is demonstrated in the following Google Ngrams.
Google Ngram Three, Four

In these Ngrams, positive values means the Times Smaller Form is more popular and negative values means the Fraction Form is more popular. (See footnote #1 for an explanation of the Ngram equations.1)  Note above that the only instance (in this Answer) where the Fraction Form is more popular than the Times Smaller Form is "one third the size".  In all other cases (in this answer), the Times Smaller form is more popular.
Google Ngram Five, Ten

Note that these are at about 50%, which is higher than three and four.
Google Ngram One Hundred, One Thousand

Again, these are higher than the prior ngrams.  +100% here means all instances are in the Times Smaller Form.  The Fraction Form is non-idiomatic in this case.
Google Ngrams for Ten Thousand and One Million also show +100% of usage is in the Times Smaller Form indicating this is virtually an idiomatic form. On the other hand, it's grammatically correct to say "ABC is one ten-thousandth the size of XYZ".  Interestingly, the Fraction Form doesn't strike me as odd or wrong in any way, but the searches in Google Ngram (and various corpora at http://corpus.byu.edu/) suggests this usage is rare.
Also note that the Times Smaller Form has even more usage than shown here since it has two variants for large numbers: a hundred times smaller, one hundred times smaller, a thousand times smaller, one thousand times smaller, etc.  For example, it's natural to say "This is a thousand times smaller than that." See Google Ngram Variants

FOOTNOTE 1: Normalizing Google Ngram results.
In these Google Ngrams (A - B)/(A + B) shows a normalized difference from -1 to 1 (shown by Google Ngram as -100% to 100%).

*

*In all Ngrams, A = Times Smaller Form, B = Fraction Form

*0% means "no difference" in popularity between the two terms.

*Positive values mean the first term (A, the Times Smaller Form) is more popular.
(A value of +100% means there are only instances of A.)

*Negative values mean the second term (B, the Fraction Form) is more popular.
(A value of -100% means there are only instances of B.).

This method allows us to compare widely different result-counts on a common scale.

*

*Pair #1 is A=15, B=5.

*(15 - 5) / (15 + 5) = 10 / 20 = 50%.

*The difference 10 is 50% of the total 20.

*Pair #2 is A=3000, B=1000

*`(3000 - 1000)/(3000 + 1000) = 2000 / 4000 = 50%

*The difference 2000 is 50% of the total 4000.

Even though Pair #2 is far more common than Pair #1, they both demonstrate that A is more popular than B, and in the same relative ratio. A potential weakness is that smaller result counts are less accurate.  For example, A=3, B=1, also results in 50%, but this would be too small to be reliable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to send post parameters from yii2 gridview am new to yii2. I have been trying to send some parameters to an action from a view using the post method, unfortunately my action seems not to see/receive them. Help would be most appreciated.
my column action is something like this:
'buttons'=> [
    'password'=> function ($url, $model, $key){
    $url =$url = Url::toRoute(['users/reset-password', 'username' => $model->username]);
    return Html::a('',$url,[
                   'title'=>'Clave',
                   'data-confirm' => Yii::t('yii', 'Are you sure you want to change this password?'),
                   'data-method' => 'post',
                   'data' => ['username'=>$model->username, 'test-name'=>'this is just for testing'],
                        ]);
                },
.....

everything in the data parameter should be send by post, but I only get the csrf token ..
thank you in advance for help.

A: use below code
echo Html::a('Name', ['controller/action'], [
    'class'=>'classname',
    'data'=>[
        'method'=>'post',
        'confirm'=>'Are you sure? OK to continue Retract..',
        'params'=>[
            'param1'=>'value',
            .......,
        ],
    ]
]);

A: "everything in the data parameter should be send by post" why do you believe that? I cannot find anything in the docs that anything in 'data' will be sent by post.
You can either:

*

*use the get to send params OR

*create a form and wrap it around the link. It should be sent by post.

A: Try sent by session :
'buttons'=> [

    'password'=> function ($url, $model, $key){

     Yii::$app->session->set('username',$model->username);

     Yii::$app->session->set('test-name','this is just for testing');

    $url =$url = Url::toRoute(['users/reset-password', 'username' => $model->username]);

    return Html::a('',$url,[

                   'title'=>'Clave',

                   'data-confirm' => Yii::t('yii', 'Are you sure you want to change this password?'),

                   'data-method' => 'post',

                        ]);
                },

On Controller call this :
You can get session :
Yii::$app->session->get('username');

And remove session
Yii::$app->session->remove('username');


text:
Q: POST method to send RAW TEXT data and get HTML Response using Jquery AJAX Web Method and check with POSTMAN I'm Trying to do a POST Request using RAW TEXT.
I want to send POST Request from POSTMAN like, in body Section I've selected RAW(from radio buttons) and Text(from drop-down) and pass below simple string.
01JAINAM120112356598

Now, when we click on send in Postman, Response must come in HTML string "01" on success and "00" on error.
[Type of Request & Response I Need] https://imgur.com/bC26Pw7   (In photo URL is of .php page, but I'll pass my asp.net c# page (.aspx)).
I need to use JQuery ajax code to pass request & get proper response.
Something like,
$.ajax({
           url: "RFID.aspx/saveRFIDData",
           type: "POST",
           dataType: "text",
           success: function () {
            },
            error: function (response) {
                alert("Error")
            }
      });

But, when I call above URL as post method as same shown in Image above, my WebMethod in code behind is not called.
Instead, when I call same ajax call for JSON, my WebMethod is been called.
But, I don't want to pass JSON.
So, Can anyone help me to get it done with "dataType : text" & get HTML string response.

Note : If someone didn't Understand my question. Do comment first, to be more clear rather than DEVOTE this question

A: It seems to be "Unsupported Media Type" issue and status may be 415. Add supported media type, that might work.


text:
Q: How to check current UIViewController on navigation stack I am trying to figure out which UIViewController is currently on the top of the UINavigationController stack, I am passing these values over to my NSArray viewCtrls, when I log the top UIViewController I get this.
<SearchViewController: 0x1457c550>

So this is the code I am trying to use to figure out which UIViewController is at the top of the UINavigationStack
NSArray *viewCtrls = navcontroller.viewControllers;
UIViewController *vCtrl = [viewCtrls objectAtIndex:[viewCtrls count]-1];

NSLog(@"%@", vCtrl);

if ([vCtrl isKindOfClass:SearchViewController]) {
    NSLog(@"yes");
} else {
    NSLog(@"no");
}

However I am getting this error on the first line of the if statement.
Use of undeclared identifier 'SearchViewController'

I would like to know how I am supposed to declare the identifier? this is being called from a NSObjectClass, so I need to pass a parameter of self from the UIViewController that called this NSObjec class? or is there a better way of doing it?

A: You want [vCtrl isKindOfClass:[SearchViewController class]]

A: Mike's solution should have worked all right. Apparently, it is not able to understand what SearchViewController is, really.
Can you check putting a forward declaration
@class SearchViewController

for the SearchViewController class in the header file of the class where the above code is written, and then importing the SearchViewController.h file in the source file of the class where the above code is written.
#import "SearchViewController.h"


text:
Q: The Hessian matrix A may be Indefinite or what is known Positive Semidefinite or Negative Semidefinite We are about to look at an important type of matrix in multivariable calculus known as Hessian Matrices. We will then formulate a generalized second derivatives test for a real-valued function $z=f(x_1,x_2,...,x_n)$ of n variables with continuous partial derivatives at a critical point $a=(a1,a2,...,an)∈D(f)$ to determine whether $f(a)$ is a local maximum value, local minimum value, or saddle point of $f$
Definition: Let $x=(x1,x2,...,xn)$ and let $z=f(x1,x2,...,xn)=f(x)$ be an n variable real-valued function whose second partial derivatives exist. Then the Hessian Matrix of f is the n×n matrix of second partial derivatives of f denoted $$\mathcal H (\mathbf{x}) = \begin{bmatrix} f_{11} (\mathbf{x}) & f_{12} (\mathbf{x}) & \cdots & f_{1n} (\mathbf{x})\\ f_{21} (\mathbf{x}) & f_{22} (\mathbf{x}) & \cdots & f_{2n} (\mathbf{x})\\ \vdots & \vdots & \ddots & \vdots \\ f_{n1} (\mathbf{x}) & f_{n2} (\mathbf{x}) & \cdots & f_{nn} (\mathbf{x}) \end{bmatrix}$$.
a)$\mathcal H (\mathbf{x})$ is said to be $\textbf{Positive Definite}$ if $D_i>0$ for i=1,2,...,n.
b) $\mathcal H (\mathbf{x})$ is said to be $\textbf{Negative Definite}$ if $D_i<0$ for odd i∈{1,2,...,n} and Di>0 for even i∈{1,2,...,n}.
c) $\mathcal H (\mathbf{x})$ is said to be $\textbf{Indefinite}$ if $det(\mathcal H (\mathbf{x}))=D_n≠0$ and neither a) nor b) hold.
d) If $det(\mathcal H (\mathbf{x}))=D_n=0$, then $\mathcal H (\mathbf{x})$ may be Indefinite or what is known Positive Semidefinite or Negative Semidefinite.
I'm studying a function that has a $det(\mathcal H (\mathbf{x}))=D_n=0$
What is the appropriate way to classify critical points if $det(\mathcal H (\mathbf{x}))=D_n=0$
For example
Assume we have this function
$$f(x_1,x_2,x_3)=x_1 x_2+x_1 x_3-x_1x_2 x_3 $$
therefore, we found the critical point by solve this system
$$\begin{equation}
\begin{cases}
\frac{df}{dx_1}=x_2+x_3-x_3 x_2=0\\
\frac{df}{dx_2}=x_1-x_1 x_3 =0\\
\frac{df}{dx_3}=x_1-x_1 x_2 =0
\end{cases}
\end{equation}$$
we get $c=(0,0,0)$
,use the Hessian matrix of f
$$\mathcal H (\mathbf{f(x_i)})=\left(
\begin{array}{ccc}
 0 & 1-x_3 & 1-x_2 \\
 1-x_3 & 0 & -x_1 \\
 1-x_2 & -x_1 & 0 \\
\end{array}
\right)$$
$det(\mathcal H (\mathbf{f(x_i)}))=D_n=0$
This test fails to determine the type of critical points
Is there another way?
Or modification of the solution and correction.
Thanks for the help.

A: Compute the eigenvalues of the hessian.
If all the eigenvalues are nonnegative, it is positive semidefinite.
If all the eigenvalues are positive, it is positive definite.
If all the eigenvalues are nonpositive, it is negative semidefinite.
If all the eigenvalues are negative, it is negative definite.
Otherwise, it is indefinite.
Edit:
For that example, you have found $c=(0,0,0)$.
$$H(f(c))=\begin{bmatrix} 0 & 1 & 1 \\ 1 & 0 & 0 \\ 1 & 0 & 0\end{bmatrix}$$
$$H(f(c))-\lambda I= \begin{bmatrix} -\lambda & 1 & 1 \\ 1 & -\lambda & 0 \\ 1 & 0 & -\lambda\end{bmatrix}$$
\begin{align}\det(H(f(c))-\lambda I)&= \det\left(\begin{bmatrix}1 & 1 \\ -\lambda & 0 \end{bmatrix} \right) -\lambda \det \left( \begin{bmatrix}-\lambda & 1 \\ 1& -\lambda  \end{bmatrix} \right)
\\&=\lambda-\lambda(\lambda^2-1)
\\&=\lambda(2-\lambda^2)\end{align}
Hence, the eigenvalues are $0$, $\sqrt{2}$ and $-\sqrt{2}$. Hence it is indefinite.


text:
Q: Unknown error in c++ program I have a c++ program which opens an url depending in what the user inputs.
Here's the code:
#include <iostream>
#include <string>
using namespace std;

int main(){
    int i = 1;
    string google = "https://www.google.com/search?q=";
    string input;
    getline(cin, input);
    string changeSpace(string input)
    {
        for (int i = 0; i < text.length(); i++)
        {
            if (text[i] == ' ')
                text[i] = '+';
        }
        return text;
    }
    input = changeSpace(input);
    cout << input << endl;
    string url = string(google + input);
    system(string("start " + url).c_str());
    cout << url << endl;
}

The error is here:
string changeSpace(string input)
{

In the bracket it says it expected a " ; "
And I don't know why ocurrs that error, it may be a simple mistake, but I don't know it.
Please help me.

A: Your problem is because you're trying to define a function inside another function. You cannot do that.
Since C++11, the most similar thing you can do is using lambda.
int main() {
    // stuff...

    auto changeSpace = [] (string text) -> string
    {
        for (int i = 0; i < text.length(); i++)
        {
            if (text[i] == ' ')
                text[i] = '+';
        }
        return text;
    }

    input = changeSpace(input);

    // stuff...
}

But I bet that is not the only error in your code.

A: The Nesting of functions is not allowed in c++. Refer this: C++ can we have functions inside functions?
For using system(string("start " + url).c_str()); in your code you should include <cstdlib>. And also use return statement in main :return 0


text:
Q: SlickGrid Columns - Difference between id and field A simple question i cant workout. In a column definition whats the difference between the field property and the id property...Fx..
columns.push({ id: "officeId", name: "Office Id", field: "officeId", width: 40 });
When would they be different/why two?
Thanks?
Tim

A: The id is just a unique identifier for the column. You can set it to anything you want. It's only use is to provide an identifier when you want to refer to your columns from code.
The field specifies how the column binds to the underlying data.  Suppose your data looks like this:
data = [
         { firstName: "John", lastName: "Smith" },
         { firstName: "Fred", lastName: "Jones" }
       ];

When you define the column you can tell it which value you want to display from your data array.
columns.push({ id: "anythingyoulike", name: "Surname", field: "lastName", width: 40 });


text:
Q: Parsing HTML String with jQuery Is it possible to use a jQuery selector on an HTML string? I'm trying to get the html contents of the div, foo.
var code = "
1

2
";
alert( $(code).html( ) ); // returns 1 (not sure how...)

How can I get the html contents of foo and of bar in two different statements?

A: var code = $("
1

2
");

code.each(function() {
    alert( $(this).html() );
})

A: Try map?
var code = "
1

2
";
var html = $(code).map(function() { return $(this).html() });
html[0]; // "1"
html[1]; // "2"

Is that what you mean?


text:
Q: How Did GroupMe verify my number? I am working on an iPhone application where I need the user's phone number. From what I've read (here for instance - Programmatically get own phone number in iOS), the device's phone number is not available within your application's container. I've always had the user enter his or her own number. But when I joined GroupMe the other day, after clicking the Get Started button, my phone opened up a drafted text message to some US area code number "Send this text to verify your phone number(b2bd308eb7)" After I sent the text, the app knew my number....how does one implement a system like this?

A: What GroupMe does is use the MessageUI Framework ( http://developer.apple.com/library/ios/#DOCUMENTATION/MessageUI/Reference/MessageUI_Framework_Reference/_index.html) to send a text message to their servers.
Basically it works like this:

*

*The app is turned on and calls the server.

*The server responds with a code b2bd308eb7.

*The app sends that code via SMS to the server.

*The server gets the code and your phone number (from SMS) and confirms them.

*Your phone number and app are connected!

A: They send a text message to some service that they can query with their server. So by sending the code to the server, they can verify the number,


text:
Q: PHP not displaying data from function I am trying to make a call to the database so it displays a list with certain information, but for some reason it isn't working even though the same code was working before with other database.
It displays the following error:

Fatal error: Call to undefined function displayLabs() in C:\wamp\www\MyFirstProyect\labs.php on line 258

This is the code:
 function getLabs(){
$query = "SELECT bk.idlab , bk.capacidad, bk.carrera, bk.ubicacion FROM labs as bk";

$result = do_query($query);

   return $result;
 }

 function displayLabs(){

$labs = getLabs();

while($row = mysql_fetch_assoc($labs)){
echo '
' .
        '
"Nombre: "' . $row['idlab'] . '
' .
        '
"Capacidad: "' . $row['capacidad'] . '
' .
        '
"Carrera: "' . $row['carrera'] . '
' .
        '
"Ubicación: "' . $row['ubicacion'] . '
' .
     '
';
    }

}

Just in case this is html:

          Información de laboratorio
          x

            <?php displayLabs() ?>

          <input type = "button" value = "Eliminar" id = "btnEliminar" onclick="window.location='labEliminado.html';" />
          <input type = "button" value = "Modificar" id = "btnModificar"      onclick="window.location='modificarLab.html';" />

Any help would be very much appreciated.
EDIT: Something Mr.Fred told me gave me an idea and it worked, now it is displaying the information, BUT not of just one "Lab" But all of them XD So with the 4 test labs I entered into the database it is making 5 lists.
I guess I need to figure some kind of filter.

A: As per OP's request, comment to answer. (to close the question)
"Just in case this is html:" --- what's that file extension set as, .php? .html?
I see two file references labEliminado.html and modificarLab.html if you're trying to run PHP in those, it won't work, unless you've instructed Apache to treat .html as PHP.
Also, if your displayLabs() is inside another file besides your first body of code, then that's the reason why.


text:
Q: Race condition in react when updating redux state I am trying to create a chess game using React + Redux. I have a function called allValidMoves which is called when a piece is dragging. It updates redux state that stores all possible valid Moves. At the same time, I have 64 square components that are trying to access this Map as soon as the piece starts dragging. The problem is that
some Squares are getting the previous redux state; I am using react-dnd for drag and drop
const pieces = () => {

  if(isDragging){
   calculateValidMoves();
  }

}

function calculateValidMoves() {
   arr = {};
   ....

   store.dispatch(update_validMoves('UPDATE',arr))

}

const Squares = (props) => {

   arr = store.validMoves.getState()

   if(arr.get(props.index)){
      doSomething
   }

}

A: I see on your code, i think u wanna get store in action ?
Better use Redux Thunk for get State inside action.
And that redux-thunk is asynchronous. So you can avoid that race condition with await / callback on action redux.


text:
Q: Вопрос по WP - Woocommerce: где можно изменить кол-во дней для товаров-новинок? С помощью шорткода [recent_products] можно вывести последние товары (новинки). А где можно задать количество дней, на протяжении которого товар считается новинкой (по умолчанию даже не знаю сколько, но мне нужно 5)? Искал в админке, файле функций Woocommerce, но безуспешно.
UPD. Скорее всего данный шорткод выводит последние добавленные товары. Тогда вопрос - можно ли задать этим товарам лимит времени, если прошло 5 дней, то они переставали быть recent_products?

A: Нужный для изучения код находится в файлах
wp-content\plugins\woocommerce\includes\shortcodes\class-wc-shortcode-products.php и
wp-content\plugins\woocommerce\includes\wc-template-functions.php.
Вам нужно отфильтровать аргументы WP_Query для фильтра recent_posts. Добавьте следующий фильтр в functions.php вашей темы:
/**
 * Filter woocommerce_shortcode_products_query.
 *
 * @param array  $query_args Query arguments.
 * @param array  $attributes Attributes.
 * @param string $type       Shortcode type.
 *
 * @return array
 */
function my_woocommerce_shortcode_products_query( $query_args, $attributes, $type ) {
    if ( 'recent_products' !== $type ) {
        return $query_args;
    }

    $query_args['date_query'] = [
        [
            'after'  => '-5 days',
            'column' => 'post_date',
        ],
    ];

    return $query_args;
}

add_filter( 'woocommerce_shortcode_products_query', 'my_woocommerce_shortcode_products_query', 10, 3 );


text:
Q: How do I "roll over" weapons and unlock the rocket launcher? I am having trouble figuring out how to "roll over" my guns and stuff from my first play file and unlocking the infinite rocket launcher. I have completed the main adventure.
How do I get these features?
I am trying the game on professional and would like to have these features while playing it again.

A: It is not uncommon for games to only allow a "new game plus" on the difficulties which you have bested.
Your question hints you've only completed the game on normal. If so, you will not be able to carry all your weapons to professional, but will instead need to beat professional from scratch before being able to do that. If you were to try a new game in normal difficulty, you would be able to carry everything over. This is affirmed by the following FAQ, specifically:

(Q) Why can't I start Professional
  mode with all my weapon upgrades?
(A) You have to start a new game when
  first starting Professional mode, so
  all  the upgrades that were obtained
  on a previous normal save will not
  carry over.  Be sure to save your
  Professional mode bonus game once
  Professional mode is  completed.

The same FAQ states the way to unlock the infinite rocket launcher:

-- Infinite Rocket Launcher
Complete the main game and the
  merchant will sell it for 1000000
  pesetas in the  bonus game of Leon's
  main game on any difficulty.

Though it is not 100% clear whether that means that this unlockable will be available for purchase on all difficulties, or only on difficulties which you have finished once. Another quote hints that it is the latter:

(Q) Can I use my unlocked weapons on
  any mode?  For instance, can I unlock
  the  P.R.L. 412 on Professional and
  use it on normal mode?
(A) Yes.  Just make sure to keep a
  bonus game saved for each difficulty.

This is fairly easy to find out, however. Just get to the merchant on Professional and see if he has this.


text:
Q: Algorithm: Buying a collection of goods with vouchers I'm struggling to come up with a solution for this problem for an algorithms course:
You go to a store and want to buy n = {n1, n2, ..., nn} goods, where the items can be different or not.
The store has the following promotion: "If a customer buys two articles whose prices add up to a value which ends with 11, 33 or 55 cents, he will receive a voucher, worth the corresponding cent value."
The problem is to come up with an algorithm which computes an optimal strategy for buying a given collection of goods, where a minimization of the total cost is wanted.
For example:
If you need to buy 3 products (n1, n2, n3) with prices (1.01$, 2.10$ and 3$), you should buy n1 and n2 together and buy n3 separately, yielding a total cost of:
(1.01 + 2.10) + 3 - (0.11) = 6$.
No hint is given, but I think I can use some approach of flow-networks.

A: Sort items you want to buy by cent prices... i.e. (25.01$, 1.02$, ..., 0.99$).
And then check... whether any of the cents sums up to 0.99$...
This can be solved easily by two sum problem... You take .01$ and look for its compliment 0.98$ using binary search... Delete this pair and repeat until you find no pair of products with cents that sum up to 0.99$.
If this is done, delete found pairs of products... calculate your gain and check whether any of the cents sums up to 0.88$... The same way.
...
If this is done, delete found pairs of products... and check whether any of the cents sums up to 0.11$... The same way.
This is all O(nlogn) complexity ;)


text:
Q: jsf: change the whole div using ajax For now, I have the following structure of the web page:

Literally, the div with id "navigator" is for navigating use. I can choose such as "home", "login", "register", etc. I want to use ajax to refresh the whole div with id "content".
So what should I do?
1) Apparently, I need to have these separate divs. But in what form? Should I use ui:composition or else?
2) What should be the ajax part? Can you give me an example?


text:
Q: The number of grid points near a circle question I've just read The number of grid points near a circle.
I want to comment but I don't have the reputation so I have to post this as a question.
How do you prove that for each $x$ value less than $r\sqrt2/2$ there is a unique $y$ value and for each $y$ value less than $r\sqrt2/2$ there is a unique $x$ value?
My idea is that you could use the fact that the circle's gradient decreases from $0$ to $-1$ as $x$ goes from $0$ to $r\sqrt2/2$ and this implies that the line will not drop below one $y$ value for each $x$ value passed. However I can't think of how this can be formalized as a proof.

A:
for each $x$ value less than $r\sqrt2/2$ there is a unique $y$ value

At a given position $0\le x\le\frac{r}{\sqrt 2}$, the point $(x,y)$ with
$$y = \left\lfloor\sqrt{r^2-x^2}\right\rfloor$$
is within the circle, and the point $(x, y+1)$ is outside. So the point must be counted.
Now about the uniqueness. Suppose there were a different point $(x,y')$ which should be counted as well. Since that point must lie inside the circle, it must satisfy $0\le y'<y$. You can now consider points around it. $(x,y'+1)$ will be inside since $y'+1\le y$ and $(x,y)$ is inside. $(x-1, y')$ must be inside since $(x,y')$ is inside and the circle and we are in the first quadrant. Likewise for $(x,y'-1)$. Both arguments will need discussion of a special case for $x=0$ resp. $y'=0$, but I'll leave that as an excercise for now.
So $(x+1,y')$ would be the most likely candidate for a point outside the circle. So let's see whether it can be outside the circle.
\begin{multline*}
(x+1)^2+y'^2 \le (x+1)^2+(y-1)^2 = x^2+y^2 + 2x-2y+2 \\\le r^2+2x-2y+2
\le r^2+2(y-1)-2y+2 = r^2
\end{multline*}
There are three inequalities in there. The first is because $y'<y$, the second because $x^2+y^2\le r^2$ since $(x,y)$ is inside, and the third because $x<y$ since you are in the upper half of the first quadrant. The case of $x=y$ needs special treatment, but then $(x,y')$ would satisfy $x>y'$ and therefore already belong to the right half of the quadrant. Taken together, you have shown that $(x+1,y')$ cannot be outside the circle either, so $(x,y')$ will not be counted, so $(x,y)$ is unique for given $x$.

and for each $y$ value less than $r\sqrt2/2$ there is a unique $x$ value?

This is simply the same argument above, but with $x$ and $y$ changing their roles. So if you have one, you have both.


text:
Q: Regular expression that checks if characters are escaped I want to create the following rule in java: if a string contains a < or > the character before must be a \ (like checking if < and > are escaped).
Can anyone tell me a regular expression that finds strings where the \ is missing?
Thank you.
PS: It must be a regular expression, no indexOf() etc.

A: You can use this negative lookbehind based regex:
(?<!\\)[<>]

Regex Demo

A: You could try the below regex,
(?<!\\)[<>]

This would match < or > when it's not preceded by \
DEMO

A: Look behind you!
You can do it like:
/(?<!\\)(<|>)/


text:
Q: how to read URL behind element / object? I wonder if there is any .js / app to do this:
there is a hosting site site.aa which hosts many diferent URL's and one of those URL is site.bb/x and I would need to pin point that URL via URL mask (which I would set up in some settings) and copy it (into clipboard)
I'm just trying to avoid this procedure:
while on a site site.aa press ctrl+shift+i (chrome) >> locate site.bb/x in source code >> copy URL (>> open desktop player >> insert URL)

edit:
well its html5 video (mp4) and the idea is to send it into deafult desktop player which supports URL inputs. but I guess I would by fully satisfied if it would be some .js script which would be placed in right context menu (of the mouse) and also it would have some options or a place where I would insert my desired URL mask like " site.bb/x/* " so after I would right click on the element / object (on the site.aa) and via menu hit that button (in context menu), that script would read out the URL behind element / object which matches with a mask (I set up), it would store it into clipboard so all I would need to do is open desktop player and hit paste.


text:
Q: Linear Algebra dimension of vector space I have an argument about what is the correct answer for the question below:
We have four vectors $v_1,v_2,v_3,v_4$ such that each set of three of these vectors are linearly independent over $\mathbb{C}$.
Now we given that $W = \operatorname{span}(w_1,w_2,w_3,w_4)$ with
\begin{align*}
w_1 &= v_1 + iv_2 - v_3\\
w_2 &= v_2+ iv_3 - v_4\\
w_3 &= iv_1 - v_4\\
w_4 &= iv_1 + v_2 + iv_3 - 2v_4
\end{align*}
The Question: What is the dimension of $W$?
The optional answers are:

*

*$1$

*$2$

*$3$

*$4$

*Can not be determined

My attempt:
At first I just used row operations and then got two rows of independent vectors so I did knew that $3$ and $4$ isn't the answer for sure. But - we are given that the set of 3 vectors are independent as I mention before. After a little bit of playing with those vectors, I got that $$v_4=-v_1+(1-i)v_2+(1+i)v_3.$$
After placing this $v_4$ as well in the matrix I got that I cannot determined if the dimension is $1$ or $2$, so my final answer is "can not be determined".

A: The dimension in general cannot be determined, it can be $1$ or $2$.
First notice that
$$w_3 = iw_1+w_2, \quad w_4 = iw_1+2w_2$$
so $\operatorname{span}\{w_1,w_2,w_3,w_4\} = \operatorname{span}\{w_1,w_2\}$.

*

*If $\{v_1,v_2,v_3,v_4\}$ is linearly independent, then from $\alpha w_1+\beta w_2 =0$ we get
$$0 = \alpha(v_1 + iv_2 - v_3)+\beta(v_2+ iv_3 - v_4) = \alpha v_1+(i\alpha+\beta)v_2+(-\alpha+i\beta)v_3-\beta v_4 \implies \alpha=\beta=0$$
so $\{w_1,w_2\}$ is linearly independent.

*If $v_1,v_2,v_3$ are linearly independent and e.g. $v_4 = -v_1+(1-i)v_2+(1+i)v_3$ then all four sets
$$\{v_1,v_2,v_3\},\{v_1,v_2,v_4\},\{v_1,v_3,v_4\},\{v_2,v_3,v_4\}$$
are all linearly independent but
$$w_2 = v_2+ iv_3 - v_4 = v_1 + iv_2 - v_3 = w_1$$
so $\{w_1,w_2\}$ are clearly linearly dependent.


text:
Q: Adding a static value to an array that is saved in the database in Laravel In Laravel, I have a database table named articles and a corresponding Model named Article.
Say, table articles have columns id, body, created_by
In the ArticleController controller I can save to DB as such:
    $data = request()->validate(['name'=>'required|min:5|max:10']);

    $article = new \App\Article();
    $article->name = request('name');
    $article->created_by = 1;
    $article->save();

    return redirect()->back();

Which I would like to shorten to:
    \App\Article::create(request()->validate(['name'=>'required|min:5:max:10']));
    return redirect()->back();

My problem is, the value for the column created_by will not be coming from the POST request, instead this value will be coming maybe from a session or a dynamic global variable.
How do I add the created_by column in the shortened version?

A: You can use Model Observers to listen to creating event and assign the created_at from the auth or session.
Checkout
https://laravel.com/docs/7.x/eloquent#observers
https://laravel.com/docs/7.x/eloquent#events

A: Several solution exists. Firstly as Alex Jose's response, you can use observer. You can use observer or events (in model). Secondly, you can default value on your table column. But why? your first way is very well. More readable, more expandable. Use the first way if you want to good developer. If you want to short your code, try this:
$data = request()->validate(['name'=>'required|min:5|max:10']);

\App\Article::create(array_merge($data,['created_by'=>1]));


text:
Q: How to avoid threads to starve Suppose I have a hotel with m Rooms.
Guests (Threads) come in and out the whole time.
A Room can have lots of people inside, but only one Room will have people. For example:

*

*Guest A (wants Room 1)

*Guest B (wants Room 2)

*Guest C (wants Room 1)
A can go to Room 1, once all rooms are empty;
B cannot go to Room 2 yet, given that there is another room with people still inside;
C can go to Room 1, because the Room C wants is the only Room with people inside;

*Given that A and C leave Room 1, B should be able to go to Room 2

*The last Guest to exit a room should stop every other Guests (avoiding them to come in while he is coming out) until it leaves, so the others can continue
How can I implement this somehow the threads will not starve?
For simplicity, suppose that, once the Guest comes inside a room, it sleeps for some seconds and then get out. Here is my (wrong) implementation:
import java.util.ArrayList;
import java.util.Random;

public class Guest extends Thread {
    static Rooms rooms = new Rooms(5);

    int id;

    Guest(int id) {
        this.id = id;
    }

    public void run() {

        rooms.join(this);

        nap();

        rooms.quit(this);
    }

    public void nap() {
        try {
            sleep((new Random().nextInt(4000) + 1000));
        } catch (InterruptedException e) {
        }
    }

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 20; i++) {

            Thread t = new Guest(i);
            t.start();

            Thread.sleep((long) new Random().nextInt(1500) + 1000);

        }

    }

}

class Rooms {

    Room[] rooms;
    int busy;

    Rooms(int m) {
        busy = -1;
        rooms = new Room[m + 1];
        for (int i = 0; i < m + 1; i++)
            rooms[i] = new Room();
    }

    void join(Guest h) {
        if (busy == -1) {
            busy = (new Random().nextInt(rooms.length));
        }

        rooms[busy].add(h);

        System.out.println("Guest " + h.id + " came inside room " + busy + " with " + rooms[busy].size() + " people");
    }

    void quit(Guest h) {

        if (rooms[busy].size() == 1) {
            setHandler(busy, h);
        } else {
            rooms[busy].remove(h);
            System.out
                    .println("Guest " + h.id + " came out of room " + busy + " with " + rooms[busy].size() + " people");
        }

    }

    synchronized void setHandler(int numQuarto, Guest ultimo) {
        System.out.println("(Last) Guest " + ultimo.id + " came out of room " + busy + " with "
                + rooms[numQuarto].size() + " people");
        rooms[numQuarto].remove(ultimo);
        busy = -1;
    }

}

class Room extends ArrayList<Guest> {
}

A: To do this with threads -- which is highly artificial, but I suppose it is an exercise -- you need to learn how to make a Thread wait on a condition, and how to notify one or more Threads that the condition they are waiting for may have been satisfied.  Conveniently, every object has methods wait(), notify(), and notifyAll() that serve these purposes.
One important consideration with wait / notify is that you must be careful to wait on and notify the correct object.  Generally, that's not the Thread you want to be affected, but rather some shared object that all threads involved rely upon for mutual synchronization.  In this particular case, it looks like Guest.rooms would do nicely.
The general idea would be that in Rooms.join(), the current thread tests whether it can immediately take a room.  If so, it does, and continues as now.  If not, however, it invokes wait() (on the Rooms instance, which at that point is this).  Whenever that wait() returns, the thread must again check whether it can immediately take the room it wants; if not, it must wait again.
The other half would be in Rooms.quit().  Whenever a thread running that method is the last one out of the room, it must reset busy to indicate that no room is occupied, and then, importantly, invoke notifyAll() to let all threads waiting at that time know that there's a chance to get a room.
You will find that you need to employ proper synchronization for this.  In particular, you can invoke wait() and notifyAll() (and notify()) only while holding the monitor of the target object (it will be released for the duration of the wait, and reacquired before wait() returns).  You will also need to ensure that you properly synchronize all manipulation of shared objects, however, in this case mainly the Rooms and its members, without preventing threads from proceeding when otherwise they could.  In particular, be aware that threads that sleep() do not for that reason release any monitors they may hold.
The rest is up to you.  I've given you rather a lot more of a hint than maybe I should, but it truly is a bit tricky to learn how to use wait / notify properly.

A: You can't. Based on what you've given, other mechanisms would need to be implemented which guarantee no starvation can occur. For example,

Guests (Threads) come in and out the whole time.

So, it's possible that n threads come in for Room m possibly the whole time. It's possible, too, that during that time more threads come in wanting another room. However, they cannot access the room until Room m is first emptied (which may never actually happen). This can continue for any number of rooms and threads. This is the case even if...

For simplicity, suppose that, once the Guest comes inside a room, it
  sleeps for some seconds and then get out.

And that's because...

C can go to Room 1, because the Room C wants is the only Room with
  people inside;

Which implies that another thread may enter an already occupied room with one or more threads with t time left to sleep. The new thread goes to sleep and won't wake up until after the previous one. While sleeping n more threads may enter the room potentially causing other threads waiting for other rooms to starve.


text:
Q: Uncaught SyntaxError: JSON.parse - An AJAX Function that has always worked for me used on a new site is throwing a nasty error This is about a script that I've used for a while now. I have a website where this code still works without any errors (I even copied the code from that project's scripts, because why reinvent the wheel once you've already done it right?), but for some reason now on my new project, I'm getting some very nasty errors! I'd post an image directly on here, but I don't have enough reputation for that it seems. XD https://rellawings.com/error.JPG The important details of what's in the image left are below:
Highlighted Above:  var res = JSON.parse(response);

Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
    success https://rellawings.com/books/2/Superluminal/1/1.01-What-is-Love?/:2045
    jQuery 6
    <anonymous> https://rellawings.com/books/2/Superluminal/1/1.01-What-is-Love?/:2038
    dispatch jQuery
    h https://rellawings.com/books/2/Superluminal/1/1.01-What-is-Love?/ line 507 > injectedScript:6
    f https://rellawings.com/books/2/Superluminal/1/1.01-What-is-Love?/ line 507 > injectedScript:15
    c https://rellawings.com/books/2/Superluminal/1/1.01-What-is-Love?/ line 507 > injectedScript:6
    c https://rellawings.com/books/2/Superluminal/1/1.01-What-is-Love?/ line 507 > injectedScript:5
    jQuery 8
    <anonymous> https://rellawings.com/books/2/Superluminal/1/1.01-What-is-Love?/:2027
1.01-What-is-Love:2045:28

I know that the problem is with this particular line/function: var res = JSON.parse(response);
But this feels so out of left field to suddenly have problems with it while coding my project. It's very strange since it's always worked flawlessly and still does on my other site. This AJAX script is simple and easy to use... at least until you get errors while coding with it in 2022. XD
The jQuery version used is the same as my other site. The only difference is that I'm not including jQuery UI, which frankly should not make a difference, right? The newest version is commented out, because I've tried switching them. But that doesn't change anything that I can see.
This is included in the header html script.

And here's the 'problematic' AJAX script that's always worked for me:

And lastly, here's the AJAX PHP script. I'm not 100% sure it's error-free, but I can't get any response from the AJAX under the circumstances.
With this, I'm experimenting to see if I can feed back html formatted content to refresh the comments on the page. If so, I can implement a refresh button that does the same thing, just updating the divs. I've reduced the shared code because if I put up everything that generates comments (and shouldn't be relevant to resolving this issue), this request for help would be longer than necessary.
<?php
include "dbcon.php"; include "functions.php"; session_start();

if($_SESSION['theme'] == "dark"){
    $bordercolor = "#DEDEDE";
}
if($_SESSION['theme'] == "light"){
    $bordercolor = "#000000";
}
if($_SESSION['theme'] == "sepia"){
    $bordercolor = "#5F4B32";
}

$commentsQ = "SELECT * FROM `comments` WHERE `b_id` = '$b_id' && `c_id` = '$c_id' && `parent` = '0' ORDER BY COALESCE(NULLIF(`upvote` - `downvote`,'0'), `updated`) DESC LIMIT 10";
$commentsR = $conn->query($commentsQ);
$commentsnum = $commentsR->num_rows;

$contentrefresh = '';

while($comment = $commentsR->fetch_assoc()){
    $likes = $comment[upvote] - $comment[downvote];
    if($likes == 0){
        $likes = "";
    }else{
        $likes = " · '.$likes.' Upvotes";
    }
    $time = date('m/d/y',$comment['updated']);
    $contentrefresh .= '

                        '.$comment[uname].''.$time.'

                        '.parseemoji($comment[message]).'

                        Reply'.$likes.' · thumb_up · thumb_down

';
            /* If There Are Any Replies */
                $comments2Q = "SELECT * FROM `comments` WHERE `b_id` = '$b_id' && `c_id` = '$c_id' && `parent` > '0' ORDER BY `updated` DESC LIMIT 10";
                $comments2R = $conn->query($comments2Q);
                $comment2 = $comments2R->fetch_assoc();
                $commentsnum2 = $comments2R->num_rows;

                if($comment['id'] == $comment2['parent']){
                    while($comment2 = $comments2R->fetch_assoc()){
                        $likes = $comment2[upvote] - $comment2[downvote];
                        if($likes == 0){
                            $likes = "";
                        }else{
                            $likes = " · '.$likes.' Upvotes";
                        }
                        $time = date('m/d/y',$comment2['updated']);
                        $body .= '

                                            '.$comment2[uname].''.$time.'

                                            '.parseemoji($comment2[message]).'

                                            Reply'.$likes.' · thumb_up · thumb_down

                        ';
                    }
                }
    $contentrefresh .= '

    ';
}

$b_id = htmlentities(trim($_POST['b_id']), ENT_NOQUOTES);
$c_id = htmlentities(trim($_POST['c_id']), ENT_NOQUOTES);
$parent = htmlentities(trim($_POST['parent']), ENT_NOQUOTES);
$message = htmlentities(trim($_POST['message']), ENT_NOQUOTES);

if(empty($parent)){
    $parent = "0";
}

if(isset($_SESSION['uname'])){

    $uiden = $_SESSION['uiden']; $uname = $_SESSION['uname']; $avatar = $_SESSION['avatar'];
    $posted = time(); $updated = $posted;

    $update = "INSERT INTO `comments` (`b_id`, `c_id`, `parent`, `uiden`, `uname`, `avatar`, `message`, `posted`, `updated`)
    VALUES ('$b_id', '$c_id', '$parent', '$uiden', '$uname', '$avatar', '$message', '$posted', '$updated')";
    if ($conn->query($update) === TRUE) {
        $response = ['return'=>'1', 'contentrefresh'=>$contentrefresh];
        echo json_encode($response);
    }else{
        $response = ['return'=>'0', 'contentrefresh'=>$contentrefresh];
        echo json_encode($response);
    }
}
?>

I really hope that I don't have to implement some needlessly complex pure javascript solution to get the job done. What is going on with jQuery and it's lovely simplification of the language?

A: This is the first time I've tinkered with .htaccess and doing symlinking. So my site uses fake directories so it doesn't show ugly ?mode=etc etc... But this comes with some caveats. XD I have to link directly to MANY resources. Including AJAX php scripts! LOL! How hilarious! This actually got rid of the error and now I have a response! It'll be up to debugging the AJAX PHP script next. '^^
Thanks for replying! I think our conversation led to my getting a moment of eureka here.
    jQuery.ajax({
        method: "POST",
        url: "https://rellawings.com/post-comment.php",
        data: {b_id: b_id, c_id: c_id, parent: parent, message: message},
        dataType: "text",
        cache: false,
        success: function(response){
            console.log(response);
            var res = JSON.parse(response);
            if (res.return === "1") {
                $("#allcomments").html(res.contentrefresh);
            } else {
                $("#errorbox").html("There was a problem and your comment could not be posted.").show().delay(8000).fadeOut();
            }
        }
    });


text:
Q: managing array prop in react I've a react application, and i've found a bug where i'm filtering an array for searching the current item the user has selected and then i'm going to do stuff with it...but, didn't know that filter function return a reference to the array's item, so, every change i made to the selected item i'm doing the same to the prop array.
const pippo = maledettoArray.filter(item => item.id === idInfame)[0];

How can i filter the prop array to get the specific item without changing it?

A: You can use find method instead of filter which returns first match and exits the loop.
const pippo = maledettoArray.find(item => item.id === idInfame)

To create shallow copy of the object you can use Object.assign or spread syntax.
const clone = {...pipo}

If you want to create deep copy of the nested object then you could use Lodash _.cloneDeep(value) method.

A: First of all, I would recommend you use the find function instead of filter to avoid the empty array return and undefined at [0]
Secondly, yes, the object reference would be returned. To avoid this, you can use Object.assign({}, originalObject) or using the spread syntax {...originalObject} . A potential problem would be with nested objects which could still be a problem.
Probably this article can help you in such case https://medium.com/@Farzad_YZ/3-ways-to-clone-objects-in-javascript-f752d148054d


text:
Q: Delphi XE + SOAP + SSL I have a program that was written on Delphi 2009. It uses SOAP over HTTP over SSL. So it is the SOAP request that triggers an HTTP request, which is handled by Microsoft Internet Explorer via a DLL. MSIE will then make a popup that asks for login.
But now I need to compile it in Delphi XE and I got a problem. program does not want to login in SSL. No popup at all. So, it seems that trigger doesn't want to work.
The error appears in the second line of this code:
mantis:=GetMantisConnectPortType(false, mantisurl);
mi := mantis.mc_issue_get(username,password,MantisIssue);

The error is
Project IssueReporter.exe raised exception class ESOAPHTTPException with message 'Authorization Required (401) - 'https://***/mantis/api/soap/mantisconnect.php''.

Listing of the connection procedure is
function GetMantisConnectPortType(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): MantisConnectPortType;
const
  defWSDL = 'https://***/mantis/api/soap/mantisconnect.php?wsdl';
  defURL  = 'https://***/mantis/api/soap/mantisconnect.php';
  defSvc  = 'MantisConnect';
  defPrt  = 'MantisConnectPort';
var
  RIO: THTTPRIO;
begin
  Result := nil;
  if (Addr = '') then
  begin
    if UseWSDL then
      Addr := defWSDL
    else
      Addr := defURL;
  end;
  if HTTPRIO = nil then
    RIO := THTTPRIO.Create(nil)
  else
    RIO := HTTPRIO;
  try
    Result := (RIO as MantisConnectPortType);
    if UseWSDL then
    begin
      RIO.WSDLLocation := Addr;
      RIO.Service := defSvc;
      RIO.Port := defPrt;
    end else
      RIO.URL := Addr;
  finally
    if (Result = nil) and (HTTPRIO = nil) then
      RIO.Free;
  end;
end;

mc_issue_get is a part of
MantisConnectPortType = interface(IInvokable)

an has the declaration:
function  mc_issue_get(const username: string; const password: string; const issue_id: Int64): IssueData; stdcall;

In the browser and in the old exe compiled in 2009 all works fine. Help please to resolve this problem.
Taras, Kyiv

A: If the Delphi 2009 exe "works fine" from the same pc as you're testing the Delphi XE exe, then some code has probably (most likely) changed between the time the Delphi2009.exe was compiled and the time you compiled the DelphiXE.exe.
To test if the code is the problem, try to recompile new code (from Delphi XE version) in Delphi 2009 and see if that works. If it works, then Delphi XE probably handles certificates differently to Delphi 2009. If it doesn't work then the code has changed substantially, in which case you'll need to debug the code that picks up the certificate from the certificate store.
Certificates can be installed into various locations within the built-in Windows certificate store. Sometimes, people just double-click, and keep the defaults in the certificate import wizard (thereby selecting Automatically choose certificate location) which may result in the certificate being installed in the current_user's certificate store. If that happens, then the exe will only be able to pick up the certificate if running under the same windows user account.
The fact that you got an Authorization Required message points to a certificate issue. However if you're testing from different PC's then there could also be firewall/enterprise security issues.

A: Your code works fine also in Delphi XE2 and "Authorization Required" might that you can't login into mantis
May be you changed your own password in mantis account.


text:
Q: C Sockets recv: connection reset by peer I'm trying to use sockets to get a small JSON test file, which is hosted on my website (http://a-cstudios.com/text.json). When I do this
long numbytes;
char *request = malloc(sizeof(char) * 300);
sprintf(request, "GET %s \r\nHOST:%s \r\n\r\n", restOfURL, baseServer);
// restOfURL = "/text.json" baseServer = "www.a-cstudios.com"
send(sockfd, request, strlen(request) + 1, 0);
char buf[1024];
if ((numbytes = recv(sockfd, buf, 1024-1, 0)) == -1) {
    perror("recv");

}

I get recv: connection reset by peer. But if I use the same code, where restOfURL is /index.html and baseServer is www.google.com, this works fine, and buf will contain the text of index.html. Why won't this work for the file on my website?

A: Since you didn't post full code, I am going to take a stab at it and make an assumption:
You populate the format string of "GET %s \r\nHOST:%s \r\n\r\n" with restOfURL and baseServer
However, during the time of the sprintf call restOfURL isn't initilized so you're pushing garbage data into the first %s
Either post more of your code or make sure you initialize resOfURL

A: As @Kninnug pointed out, you need the HTTP version field (e.g., HTTP/1.1) at the end of the first line of the request. I just want to point out that you should not include the null terminator when you send the request. That is, change the send statement to
send(sockfd, request, strlen(request), 0);

Also, it is a good practice to always use snprintf instead of sprintf to prevent buffer overflow, although to be really safe you still need to check for truncation.


text:
Q: remove break line before prompt How can I remove the new line before the prompt.
I don't exactly know how to formulate the question, so here's an example.
I want to pass from
%> echo "hello world"
hello world
%>

to
%> echo "hello world"
hello world%>

I tried sed 's/\\n//' to subtitute the new line. Even with \\r and with tr.
Maybe the cut fonction will be accurate ??
echo -n method  I get
  %> echo -n "hello world"
  hello world%                     #note the new character % just appeared
  %>

A: You can use the -n switch that will not add the eol
echo -n "hello world"

A: You can simply do this,
printf "hello world"


text:
Q: Is there a way to refresh extensions in Inkscape Hope I am asking this question in the right area, I am developing a couple of extensions for Inkscape and I was wondering if there is a way to refresh the extensions like GIMP has for script-fu? I have searched the web and documentation on Inkscape but couldn't find anything.
Thanks allot!

A: I was wondering the same thing, and found this answer:

The INX files are only loaded at session start - for any updates or
  newly installed extensions it is required to restart Inkscape.
If only script files of already installed extensions have been
  updated, there usually is no need to restart Inkscape - the content of
  the script files is not cached (the script file is launched with the
  external interpreter each time the extension is run).


text:
Q: Springers svmult template - chapter-wise bibliography with bibtex? I have exactly the same problem as that described in the following question, which was (weirdly) closed:
Springers svmult template - bibliography with bibtex?
Can this question please be re-opened?
I'm sure it's an issue that is encountered by many multi-author volume editors!
Kind regards,
Dave


text:
Q: Create user inactive as default (is_active default False) I have facebook authentication in my website which I use omab / django-social-auth
I want to redirect users to another website to make them fill their details. So I want to have users as inactive when they first authenticate with their facebook accounts, then after they complete the form I save them as active users.
I manipulated the django/contrib/auth/models.py under my enviroment as with is_active fields as default=False; but they are saved as active user
but still the same result, even I add a normal user from the admin panel. Is there something I am missing?
class User(models.Model):
    """
    Users within the Django authentication system are represented by this
    model.

    Username and password are required. Other fields are optional.
    """
    username = models.CharField(_('username'), max_length=30, unique=True,
        help_text=_('Required. 30 characters or fewer. Letters, numbers and '
                    '@/./+/-/_ characters'))
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('e-mail address'), blank=True)
    password = models.CharField(_('password'), max_length=128)
    is_staff = models.BooleanField(_('staff status'), default=False,
        help_text=_('Designates whether the user can log into this admin '
                    'site.'))
    is_active = models.BooleanField(_('active'), default=False,
        help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.'))
    is_superuser = models.BooleanField(_('superuser status'), default=False,
        help_text=_('Designates that this user has all permissions without '
                    'explicitly assigning them.'))
    last_login = models.DateTimeField(_('last login'), default=timezone.now)
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
    groups = models.ManyToManyField(Group, verbose_name=_('groups'),
        blank=True, help_text=_('The groups this user belongs to. A user will '
                                'get all permissions granted to each of '
                                'his/her group.'))
    user_permissions = models.ManyToManyField(Permission,
        verbose_name=_('user permissions'), blank=True,
        help_text='Specific permissions for this user.')
    objects = UserManager()

 def create_user(self, username, email=None, password=None):
    """
    Creates and saves a User with the given username, email and password.
    """
    now = timezone.now()
    if not username:
        raise ValueError('The given username must be set')
    email = UserManager.normalize_email(email)
    user = self.model(username=username, email=email,
                      is_staff=False, is_active=False, is_superuser=False,
                      last_login=now, date_joined=now)

    user.set_password(password)
    user.save(using=self._db)
    return user

A: Elegant solution when using django-allauth.
There is another very nice solution.. one that sounds very much like what you desire.
I have created a custom form (in my case a ModelForm) that I can hand over to django-allauth via the ACCOUNT_SIGNUP_FORM_CLASS setting. What this does.. is ask the new potential user to supply additional fields during the signup process.
That has some very nice advantages:

*

*You can add some fields very elegantly in addition to the default stuff.

*It works for both social and "normal" signup.

*No patching of 3rd party apps required.

*You are still able to modify and maintain everything in the admin.

*In the custom form you get access to the new user instance before it gets saved to the
database. This means you can even process the provided information do things like create a profile object for him and set the user as inactive ..all in one go.
This works because you can check if everything is ok.. and only then commit to do all these steps or reject the form with a validation error. :)

Well.. sounds good right?
But how exactly does it work (i.e. look like)?
I am glad you asked.. ^_^
For your use case it might look something like this:
settings.py
[...]
ACCOUNT_SIGNUP_FORM_CLASS = "<your_app>.forms.SignupForm"
[...]

forms.py
class SignupForm(forms.Form):
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)

    def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.is_active = False
        user.save()

A: *

*Avoid modifying built-ins. There are better ways to do things.

*Like signals. Signals are awesome.

*In this case, I'd attach to the pre_save signal of django.contrib.auth.models.User, and manually correct the is_active property of the model instance (if the object is new).

*This way, you can add some logic to make sure you're properly marking a user as not active.

*Because user's added within the Admin should probably be active, if the admin marks them as active.

A: jack_shed suggested signals, which helped me find the direction to take it.  But there was still work from there to figure out how exactly to test and modify after receiving the signal.
Here's what worked for me.
from django.dispatch import receiver
from django.db.models.signals import pre_save
from django.contrib.auth.models import User

@receiver(pre_save, sender=User)
def set_new_user_inactive(sender, instance, **kwargs):
    if instance._state.adding is True:
        print("Creating Inactive User")
        instance.is_active = False
    else:
        print("Updating User Record")

This will catch the action of creating a user before the save occurs, then test if this instance state is "adding" or not.  That differentiates between creating and updating a model instance.
If you don't do this test, updating the user sets is_active to False also, and there ends up being no way to activate them through django.

A: I think a better approach would be to customize your own model manager by leaving the user value inactive as default.
Create in your app: project_app/managers.py:
# project_app/managers.py

from django.contrib.auth.base_user import  BaseUserManager

class UserManager(BaseUserManager):

        def create_user(self, username, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        extra_fields.setdefault('is_active', False)
        return self._create_user(username, email, password, **extra_fields)

and in you models:
#project_app/models.py
from .managers import UserManager
from django.contrib.auth.models import AbstractUser

class UserManager(AbstractUser):
    objects = UserManager()
    # your custom fields go here.


text:
Q: JSON deserialize array with custom objects in it Hi this is my JSON file I would like to parse in C#:
 {
  "modelParam": {
    "defaultConfigFilePath": "../modelParam.json",
    "actionType":[
            {
            "showText":
                {
                    "feld": "input" ,
                    "text": "Port",
                    "value": 4
                }
            },
            {
            "showText":
                {
                    "feld": "input" ,
                    "text": "TestTest",
                    "value": 78
                }
            }
        ]
    }
  }

Does anyone have an idea how to parse/deserialize this file?
Best regards
C.O

A: First you have to create this c# classes.
   public class Model
{
    public Modelparam modelParam { get; set; }
}

public class Modelparam
{
    public string defaultConfigFilePath { get; set; }
    public Actiontype[] actionType { get; set; }
}

public class Actiontype
{
    public Showtext showText { get; set; }
}

public class Showtext
{
    public string feld { get; set; }
    public string text { get; set; }
    public int value { get; set; }
}

After that you can deserialize(parse) it to c# object. For this:
var model =System.Text.Json.JsonSerializer.Deserialize<Model>("your json source");


text:
Q: Cross browser compatibility with SVG background I work on a app which supports on IE 10 and Chrome. For background images we go with svg sprite.Wherever we need to position icons we have defined a common class for the image and also defined class based on the icon.
Once we build the app, we found the positioning is fine on chrome browser and for IE we need to write a separate css fix based on the browser.
html

Home

My css looks like
.pico:after{
  background:('sprite.svg') 0 0 no-repeat;
  background-size: 280px 660px;
  position:absolute;
  content:""
}

.pico.menu:after{
  background-position:-106px 6px;
}

.ie .pico.menu:after{
   background-position:-110px 6px;
}

Is there anyway to have a generic styles for IE and Chrome ?. Or is the default behavior of the browsers.
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="300px" height="650px" viewBox="561 165 246 580" enable-background="new 561 165 246 580" xml:space="preserve">
<g>
    <g>
        <polygon fill="#F47621" points="580.3,230 585.5,235.2 590.8,230 589.8,229 585.5,233.1 581.3,229         "/>
    </g>
    <g>
        <polygon fill="#F47621" points="580.3,225.5 585.5,230.7 590.8,225.5 589.8,224.6 585.5,228.8 581.3,224.6         "/>
    </g>
</g>
</svg>

A: Here i cleaned up some of the code. Don't use the external url for your images of course.
Tested in chrome and IE 11 and IE 10. Both will display the image correctly.

.pico::after {
  background: url(http://imgh.us/test_55.svg) 0 0 no-repeat;
  background-size: 280px 660px;
  position: absolute;
  content: "";
  display: inline-block;
  width: 30px;
  height: 20px;
}
.pico.menu::after {
  background-position: -10px -65px;
}
svg {
  border: 5px solid black;
}

Home

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="300px" height="650px" viewBox="561 165 246 580" enable-background="new 561 165 246 580" xml:space="preserve">
  <polygon fill="#F47621" points="580.3,230 585.5,235.2 590.8,230 589.8,229 585.5,233.1 581.3,229         " />
  <polygon fill="#F47621" points="580.3,225.5 585.5,230.7 590.8,225.5 589.8,224.6 585.5,228.8 581.3,224.6         " />
</svg>


text:
Q: How to make PHP to handle multiple lines output? I'm struggling with this for a day now...
I have an OS command that returns several lines of output:
root@downloader:/var/www/html# /usr/local/bin/sdm120c -a 1 -P N -S 2 -j 20 /dev/ttyUSB0
Voltage: 248.00 V
Current: 16.29 A
Power: 4000.40 W
Active Apparent Power: 4014.28 VA
Reactive Apparent Power: -339.60 VAR
Power Factor: 1.00
Phase Angle: 0.00 Degree
Frequency: 50.00 Hz
Import Active Energy: 22726178 Wh
Export Active Energy: 252806 Wh
Total Active Energy: 22978984 Wh
Import Reactive Energy: 1136648 VARh
Export Reactive Energy: 2343577 VARh
Total Reactive Energy: 3480225 VARh
OK

I'm now trying to get this output via web through a simple PHP script, so I'm doing:
<?php
echo (exec('/usr/local/bin/sdm120c -a 1 -P N -S 2 -j 20 /dev/ttyUSB0'));
?>

However, the result is always "OK", which is the last line of the output.
My first idea was to "grep" the needed info in the OS command, and run it multiple times as needed, like:
echo (exec('/usr/local/bin/sdm120c -a 1 -P N -S 2 -j 20 /dev/ttyUSB0 | grep -i Power:'));
and it would suffice if I just needed one line of output.
The problem is that I can't run the OS command more often than once every 3 or 4 seconds, so since I need multiple lines, I can't really use this alternative...
Any idea how to get all the OS command output to be shown in the PHP request?

A: As per the comments from @RiggsFolly and @Dave, the following snipped works:
<?php
exec('/usr/local/bin/sdm120c -a 1 -P N -S 2 -j 20 /dev/ttyUSB0', $output);
print_r($output[2]);
print_r($output[4]);
 ?>


text:
Q: Best Practice for Exception Handling Need know the difference between below two approach in exception handling in side method and also need to know which is the best way to follow
        public string TestMethod()
        {
            try
            {

            }
            catch (Exception exception)
            {
                // Log error here
                throw new Exception("error message");
            }

            return null;
        }

        public string TestMethod2()
        {
            try
            {

            }
            catch (Exception exception)
            {
                // Log error here
                throw;
            }

            return null;
        }

A: The best is depends on situation, but it's necessary to stress the benefit of the second one:
When you simply use throw, you do not create a new exception, so on the top of the calling stack if someone handles this exception, he knows the exact source of the exception, so can act accordingly.
That is completely different from the first approach, where you are creating a new exception instance, with a new "history".


text:
Q: After migrating magento 1 to magento2 when try to reindex, i got an error Customer Grid indexer process unknown error:

SQLSTATE[42000]: Syntax error or access violation: 1170 BLOB/TEXT column 'created_in' used in key specification without a key length, query was: CREATE TABLE IF NOT EXISTS customer_grid_flat (
    entity_id int UNSIGNED NOT NULL COMMENT 'Entity ID' ,
    name text NULL COMMENT 'Name' ,
    email varchar(255) NULL COMMENT 'Email' ,
    group_id int NULL COMMENT 'Group_id' ,
    created_at timestamp NULL default NULL COMMENT 'Created_at' ,
    website_id int NULL COMMENT 'Website_id' ,
    confirmation varchar(255) NULL COMMENT 'Confirmation' ,
    created_in text NULL COMMENT 'Created_in' ,
    dob date NULL COMMENT 'Dob' ,
    gender int NULL COMMENT 'Gender' ,
    taxvat varchar(255) NULL COMMENT 'Taxvat' ,
    lock_expires timestamp NULL default NULL COMMENT 'Lock_expires' ,
    shipping_full text NULL COMMENT 'Shipping_full' ,
    billing_full text NULL COMMENT 'Billing_full' ,
    billing_firstname varchar(255) NULL COMMENT 'Billing_firstname' ,
    billing_lastname varchar(255) NULL COMMENT 'Billing_lastname' ,
    billing_telephone varchar(255) NULL COMMENT 'Billing_telephone' ,
    billing_postcode varchar(255) NULL COMMENT 'Billing_postcode' ,
    billing_country_id varchar(255) NULL COMMENT 'Billing_country_id' ,
    billing_region varchar(255) NULL COMMENT 'Billing_region' ,
    billing_street text NULL COMMENT 'Billing_street' ,
    billing_city varchar(255) NULL COMMENT 'Billing_city' ,
    billing_fax varchar(255) NULL COMMENT 'Billing_fax' ,
    billing_vat_id varchar(255) NULL COMMENT 'Billing_vat_id' ,
    billing_company varchar(255) NULL COMMENT 'Billing_company' ,
    PRIMARY KEY (entity_id),
    INDEX CUSTOMER_GRID_FLAT_GROUP_ID (group_id),
    INDEX CUSTOMER_GRID_FLAT_CREATED_AT (created_at),
    INDEX CUSTOMER_GRID_FLAT_WEBSITE_ID (website_id),
    INDEX CUSTOMER_GRID_FLAT_CONFIRMATION (confirmation),
    INDEX CUSTOMER_GRID_FLAT_CREATED_IN (created_in),
    INDEX CUSTOMER_GRID_FLAT_DOB (dob),
    INDEX CUSTOMER_GRID_FLAT_GENDER (gender),
    INDEX CUSTOMER_GRID_FLAT_LOCK_EXPIRES (lock_expires),
    INDEX CUSTOMER_GRID_FLAT_BILLING_COUNTRY_ID (billing_country_id),
    FULLTEXT FTI_76EE125693165A11F2D49A0116049156 (name, email, taxvat, shipping_full, billing_full, billing_firstname, billing_lastname, billing_telephone, billing_postcode, billing_region, billing_city, billing_fax, billing_vat_id, billing_company)
  ) COMMENT='customer_grid_flat' ENGINE=INNODB charset=utf8 COLLATE=utf8_general_ci

A: Please see OMG Ponies' answer for the reason of this error: https://stackoverflow.com/questions/1827063/mysql-error-key-specification-without-a-key-length
To solve it, run this query before the first reindexing:
CREATE TABLE IF NOT EXISTS `customer_grid_flat` (
  `entity_id` int(10) unsigned NOT NULL COMMENT 'Entity ID',
  `name` text COMMENT 'Name',
  `email` varchar(255) DEFAULT NULL COMMENT 'Email',
  `group_id` int(11) DEFAULT NULL COMMENT 'Group_id',
  `created_at` timestamp NULL DEFAULT NULL COMMENT 'Created_at',
  `website_id` int(11) DEFAULT NULL COMMENT 'Website_id',
  `confirmation` varchar(255) DEFAULT NULL COMMENT 'Confirmation',
  `created_in` text COMMENT 'Created_in',
  `dob` date DEFAULT NULL COMMENT 'Dob',
  `gender` int(11) DEFAULT NULL COMMENT 'Gender',
  `taxvat` varchar(255) DEFAULT NULL COMMENT 'Taxvat',
  `lock_expires` timestamp NULL DEFAULT NULL COMMENT 'Lock_expires',
  `shipping_full` text COMMENT 'Shipping_full',
  `billing_full` text COMMENT 'Billing_full',
  `billing_firstname` varchar(255) DEFAULT NULL COMMENT 'Billing_firstname',
  `billing_lastname` varchar(255) DEFAULT NULL COMMENT 'Billing_lastname',
  `billing_telephone` varchar(255) DEFAULT NULL COMMENT 'Billing_telephone',
  `billing_postcode` varchar(255) DEFAULT NULL COMMENT 'Billing_postcode',
  `billing_country_id` varchar(255) DEFAULT NULL COMMENT 'Billing_country_id',
  `billing_region` varchar(255) DEFAULT NULL COMMENT 'Billing_region',
  `billing_street` varchar(255) DEFAULT NULL COMMENT 'Billing_street',
  `billing_city` varchar(255) DEFAULT NULL COMMENT 'Billing_city',
  `billing_fax` varchar(255) DEFAULT NULL COMMENT 'Billing_fax',
  `billing_vat_id` varchar(255) DEFAULT NULL COMMENT 'Billing_vat_id',
  `billing_company` varchar(255) DEFAULT NULL COMMENT 'Billing_company',
  PRIMARY KEY (`entity_id`),
  KEY `CUSTOMER_GRID_FLAT_GROUP_ID` (`group_id`),
  KEY `CUSTOMER_GRID_FLAT_CREATED_AT` (`created_at`),
  KEY `CUSTOMER_GRID_FLAT_WEBSITE_ID` (`website_id`),
  KEY `CUSTOMER_GRID_FLAT_CONFIRMATION` (`confirmation`),
  KEY `CUSTOMER_GRID_FLAT_DOB` (`dob`),
  KEY `CUSTOMER_GRID_FLAT_GENDER` (`gender`),
  KEY `CUSTOMER_GRID_FLAT_BILLING_COUNTRY_ID` (`billing_country_id`),
  FULLTEXT KEY `FTI_8746F705702DD5F6D45B8C7CE7FE9F2F` (`name`,`email`,`created_in`,`taxvat`,`shipping_full`,`billing_full`,`billing_firstname`,`billing_lastname`,`billing_telephone`,`billing_postcode`,`billing_region`,`billing_city`,`billing_fax`,`billing_company`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='customer_grid_flat';

Let me know if this helps


text:
Q: Actionscript 2, private function set, returning the error "A member attribute was used incorrectly." In Actionscript 2 I find that I cannot have a "private function set" without returning the error "A member attribute was used incorrectly." If I change it to "public function set" I'm fine but that defeats the goal of trying to protect the function from setting externally.
Anyone have a simple fix/alternative?

A: It's a known bug:
https://bugs.adobe.com/jira/browse/ASC-3601
You can't mix a public getting with a private setter. Since you're only accessing it from that class, just make the variable private and set its value without using a setter. The main reason to have a setter anyway would be to expose the ability to change its value from outside of your class, via the public declaration (there's probably other reasons, but that's the main one), so if you only want to change it internally, then just change the value (I know, then it's not consistent and in 1 place - but yeah, ya know...)


text:
Q: GCC Linker . CC3200 - why data is copied from Application Image in SRAM to another location in SRAM? I have noticed that in the TI for the CC3200 (ARMv8 / ARM Cortex M4) examples of the startup_gcc.c the actual data section within the application image is copied to a different location. The application image itself is copied from flash to SRAM by the cc3200s internal bootloader.
The application image itself is loaded into SRAM and run this way.
So in my opinion this is a total waste of memory, as the copies the data section to another place in SRAM. Am I missing something? Would the removing the code section out of the ResetISR and altering the Linker file would work fine and just use the memory within the application image in SRAM itself?
ResetISR:
uint32_t *pui32Src, *pui32Dest;
pui32Src = &__init_data;
for(pui32Dest = &_data; pui32Dest < &_edata; )
{
    *pui32Dest++ = *pui32Src++;
}

Linker:
.text :
{
    _text = .;
    KEEP(*(.intvecs))
    *(.bss.gpCtlTbl)
    *(.text*)
*(.ARM.extab* .gnu.linkonce.armextab.*)
. = ALIGN(8);
    _etext = .;
} > SRAM

.rodata :
{
*(.rodata*)
} > SRAM

.ARM : {
__exidx_start = .;
  *(.ARM.exidx*)
  __exidx_end = .;
} > SRAM

__init_data = .;

.data : AT(__init_data)
{
    _data = .;
    *(.data*)
. = ALIGN (8);
    _edata = .;
} > SRAM

Edited Linker without copy (and changing the linker):
.data
{
    _data = .;
    *(.data*)
. = ALIGN (8);
    _edata = .;
} > SRAM

A: This kind of thing is normal when you are loading to ROM.  I would expect __init_data to point to an address in ROM, in which case the copy loads it from there to RAM.
In your case it appears that everything is already in SRAM, so there is no need to do a copy of the initialized data.
The only question is, how does the internal bootloader know how big the image is and how much to copy?  As long as it includes the data section in its image size then you should be fine to remove the copy loop, and the : AT(__init_data).
It should be easy to test, just define a static int x = 42; and then if (x == 42) { led(on); } or similar.

A: I am not aware of the capabilities of the particular processor you are using but on X86 for example doing this allows the image to be loaded read-only. The data is then copied to pages that can be written to (actually for X86 in particular, copy-on-write is generally used for these pages so that multiple processes can initialize .data from the same memory and not copy pages that aren't actually changed).
In order to not need this step the image would need to be written with the various sections padded to page-alignment but people generally prefer that the image be as small as possible while containing all needed information.


text:
Q: how to pass jsonarray to adapter in android Hi in the below code how to pass array to the adapter. after passing values is an json array it was showing error values.
can any one help me
json resp
{
  "RESULT": "SUCCESS",
  "PLACE": [
    "Bangalore",
    "Kochi"
  ]
}

URL = "";

        Map<String, String> valuesMap = new HashMap<String, String>();

        Gson gson = new GsonBuilder().create();
        String json1 = gson.toJson(valuesMap);
        Log.d("Gson Json", json1);

        // result is the response result that we get from server for List of Brand
        result = UrlRequester.post(getActivity(), URL, json1);
        Log.d("res", result);

        // JSON parsing for the request we got for Brand
        try {
            jsonObj = new JSONObject(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {

            values = jsonObj.getJSONArray("PLACE");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        final ArrayAdapter adapterSearch = new ArrayAdapter(getActivity().getBaseContext(),
                android.R.layout.simple_list_item_1, values);
        mACtxt_City.setAdapter(adapterSearch);

A: Replace following code:
// JSON parsing for the request we got for Brand
        try {
            jsonObj = new JSONObject(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {

            values = jsonObj.getJSONArray("PLACE");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        final ArrayAdapter adapterSearch = new ArrayAdapter(getActivity().getBaseContext(),
                android.R.layout.simple_list_item_1, values);

With this one:
ArrayList<String> list = new ArrayList<>();
        try {
            jsonObj = new JSONObject(result);
            values = jsonObj.getJSONArray("PLACE");

            for(int i= 0; i<values.length(); i++)
            {
                list.add(values.getString(i));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        final ArrayAdapter adapterSearch = new ArrayAdapter(getActivity().getBaseContext(),
                android.R.layout.simple_list_item_1, list);

Just parsed the array and stored in list and pass to constructor
I did not run this because of time.
Hope this will help.
Thanks


text:
Q: Find Missing Values by Index Without NaNs I have a pandas Dataframe with 3 columns: pd.DataFrame(data, columns=['Date', 'Name', 'Payment']) where I have made Date the index.  If I have a list of all Name values that are possible, how can I find indexes (in this case Dates) that are missing names from the possible universe and list which names they are specifically missing?
To be clear, there are not NaNs or Nulls in Payment so I'm not able to utilize boolean indexing in this case (as far as I know).
poss_names=['James', 'Patrick']

Example data: [['2010-01-01', 'Patrick', 20],['2010-01-02', 'James', 20]]
Expected output would show [['2010-01-01', 'James'], ['2010-01-02', 'Patrick']

A: I think I get what you're trying to achieve. I've made a longer example which I think is better for comprehensive testing. I have not set the date as the index, as I will need to use it (I don't know if you have to do this for other reasons, but you can reset_index for this):
         Date     Name  Payment
0  2010-01-01  Patrick       20
1  2010-01-02    James       20
2  2010-01-02  Patrick       20
3  2010-01-03    James       20
4  2010-01-03  Patrick       20
5  2010-01-03      Joe       20

poss_names=['James', 'Patrick', 'Joe']

Firstly, I've used pandas groupby() to group the data by each Date, and used a function to put all the names for that date into a list as below:
df2 = df.groupby('Date').agg({'Name':lambda s: list(set(s))})

                             Name
Date
2010-01-01              [Patrick]
2010-01-02       [Patrick, James]
2010-01-03  [Patrick, Joe, James]

I've then used an apply function to get the rows of Name that contain all the possible names, and used .loc[] to filter these out:
df2 = df2.loc[~df2['Name'].apply(lambda x: set(poss_names) == set(x))]

                        Name
Date
2010-01-01         [Patrick]
2010-01-02  [Patrick, James]

Finally, I've used another apply function with list comprehension to go through the possible names and work out which are missing for each date:
df2 = df2['Name'].apply(lambda x: [i for i in poss_names if i not in x])

Date
2010-01-01    [James, Joe]
2010-01-02           [Joe]
Name: Name, dtype: object

Full Code:
df2 = df.groupby('Date').agg({'Name':lambda s: list(set(s))})
df2 = df2.loc[~df2['Name'].apply(lambda x: set(poss_names) == set(x))]
df2 = df2['Name'].apply(lambda x: [i for i in poss_names if i not in x])


text:
Q: R: Submit Form then Scrape Results I'm trying to write code in R that will allow me to submit a query on http://nbawowy.com/ and scrape the resulting data. I'd like to be able to input values for at least the "Select Team", "Select Players On", and "Select Players Off" fields and then submit the form. As an example, if I select the 76ers as my team, and Ben Simmons as the "Player On", the resulting query is found here: http://nbawowy.com/#/z31mjvm5ss. I've tried using the following code, but it provides me with an unknown field names error:
library(rvest)

url <- "http://nbawowy.com/#/l0krk654imh"
session <- html_session(url)

form <- html_form(read_html(url))[[1]]

filled_form <- set_values(form,
                      "s2id_autogen1_search" = "76ers",
                      "s2id_autogen2" = "Ben Simmons")

session1<-submit_form(session, filled_form, submit='submit')

Since I can't seem to get passed this initial part, I'm looking to the community for some help. I'd ultimately like to navigate the session to the resulting url and scrape the data.

A: This is not a problem with your code. If you check the form returned by the website, you will see that not only there are no list elements named "s2id_autogen1_search" or "s2id_autogen2", in fact, the whole form is unnamed. Furthermore, what seems like one form in the browser, are, in fact, multiple forms (so the players' names cannot be even entered into the html_form(read_html(url))[[1]] element). Get to know the object to which you are trying to set the values with str(form). Alternatively, try to scrape using RSelenium.


text:
Q: .htaccess Pages open even though the URL is broken I have a problem with my website opening pages that should show 404 error. It seems that only the first part of the URL is taken into account.
Here's an example
example.com/page.php - (opens - correct)
example.com/asdasd.php - (error 404 - correct)
example.com/asdasd.php/asdasd - (error 404 - correct)

example.com/page.php/asdasd - (opens - incorrect)
example.com/page/ - (opens - incorrect)
example.com/page/asdasd (opens - incorrect)

I would like to get an Error 404 and if I feel that the URL is important  also be able to Redirect it. Now I can't even Redirect URLs that for example look like this "example.com/page.php/asdasd"
The closest answer that I found was this:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=302,L]

RewriteCond %{THE_REQUEST} ^(?:GET|HEAD)\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+?)/?$ $1.php [L]

But the problem was that I got something like this:
Input URL
example.com/page.php/asdasd
Output URL
example.com/page

I need it for the .php extention to stay. And if possible instead of "Redirecting" to the example.com/page.php, I'd like to get an Error 404
This is what I currently have in the htaccess file:
ErrorDocument 404 /404.php
ErrorDocument 401 /404.php
ErrorDocument 403 /404.php

Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*) http://www.example.com/$1 [L,R=301]

RewriteRule ^index\.php$ / [R=301,L]

Sorry if this is a duplicate but I don't even know what I should look for.

A:
example.com/page.php/asdasd - (opens - incorrect)

This is due to a feature called Path Info - if Apache manages to match the first part of the requested URL to an existing file, then it will serve that file, and pass the rest of the path along via environment variables (so that a script could in theory make use of this information.)
The AcceptPathInfo directive makes it possible to disable this behavior.
https://httpd.apache.org/docs/2.4/mod/core.html#acceptpathinfo


text:
Q: How do I use underscores and lowercase letters in URLs in Codeigniter 3? I am annoyed with encountering mysterious problem.
My development environment has been created with the following directory structure.
document_root
 └ project
  ├ application
  │├ controllers
  ││└ admin
  ││ ├ Users.php
  ││ ├ Facility_Categories.php
  ││ └ Facilities.php
  │└ views
  │ └ admin
  │  ├ users
  │  │└ index.twig
  │  ├ facility_categories
  │  │└ index.twig
  │  └ facilities
  │   └ index.twig
  └ public
   └ index.php

In the development environment, these URLs appeared as expected.
https://www.example.com/project/admin/users/
 -> load admin/Users.php index function
https://www.example.com/project/admin/facilities/
 -> load admin/Facilities.php index function
https://www.example.com/project/admin/facility_categories/
 -> load admin/Facility_Categories.php index function

Recently, when I upload these files to a test environment.
URL were not displayed correctly that contained "underscore".
It looks like controller is not loaded.
https://www.example.com/project/admin/users/
 -> load admin/Users.php index function
https://www.example.com/project/admin/facilities/
 -> load admin/Facilities.php index function
https://www.example.com/project/admin/facility_categories/
 -> 404 Page Not Found (display codeigniter show_404 function)

By the way, if the URL is capitalized, the controller will load but View will not.
(view is also displayed if view's direcotry name is capitalized.)
https://www.example.com/project/admin/Facility_Categories/
 -> 500 Internal Server Error
      (Twig\Error\LoaderError : Unable to find template "admin/Facility_Categories/index.twig")

I want to access with lower case URL. How can I solve the problem?

A: I solved this problem on my own to read following url
CodeIgniter Controller Case-Sensitive
CodeIgniter3 seemed to have to capitalize only the first letter of the controller name and all lowercase after that. (OK: Facility_categories.php NG: Facility_Categories.php)
I just changed 2 points.

*

*Change Controller File Name From Facility_Categories.php To Facility_categories.php

*Change Controller Class Name From class Facility_Categories To class Facility_categories
Now I can access to url that contain lowercase and underscores
https://www.example.com/project/admin/facility_categories/


text:
Q: mongoose model fields not appearing in mongoDB I'm working on a personal project building a web application and teaching myself node.js. The part I'm working on involves uploading a CSV file, changing the CSV data into a JSON object and saving it in a field in mongodb
using mongoose I have this model defined. I'm using Robomongo to look at the contents of the DB and I can see email and passwordfields not problem
var userDataModel = new schema({
        email: {
                    type: String,
                    required: true,
                    unique: true,
                    validate: [validator.email, 'Not a valid email address!']
                },

            hashedPassword: {
                                type: String,
                                required: true,
                                validate: [checkLength, 'The Password is too short! Passwords must be at least '+REQ_PASS_LENGTH+' characters!']
                            },
            savedGraphs:{},
            uploadedFiles:{}
        })

The following is a file-handling module I wrote to call to be used during my route handling on the post request from the form containing the csv file.
var Converter               =   require("csvtojson").core.Converter
var currentdate             =   new Date()
exports.verifyFileTypeCSV   =   verifyFileTypeCSV
exports.saveFileDataCSV     =   saveFileDataCSV

function verifyFileTypeCSV(fileType){
    if(fileType!='application/csv'){
        return false
    }
    else{
        return true
    }
}

function saveFileDataCSV(file, username, password, model){
    model.findOne({ email :  username },
        function(err, user) {
            if (err){
                console.log('err')
            }
            if (!user){
                console.log('no user found!')
            }
            else{
                var csvConverter = new Converter()
                csvConverter.on("end_parsed",function(jsonObj){
                    jsonObj.date = currentdate.getDate()
                    user.uploadedFiles = jsonObj
                })
                csvConverter.from(file)
            }
    })
}

All the code seems to execute and I'm doing the exact same thing as I did the save the username/pass but once I run through it and check the DB, the userModel wont contain the parsed CSV data. I've printed the data to the console etc. so it's being parsed correctly and that's not my problem.
P.s
This is code I'm currently playing with, hence the if/else sections having console statements and nothing else.

A: You´re missing to save the user-object back to MongoDB.
Try to add:
   csvConverter.on("end_parsed",function(jsonObj){
         jsonObj.date = currentdate.getDate();
         user.uploadedFiles = jsonObj;
         user.save();
   });

I would also recommend you to add semicolons to the end of your statements, as it makes your code more readable.


text:
Q: UscrollView: bad scroll on iPhone 6 plus I have a problem. I use a UIScrollView with 1 image and 2 tableview inside.
The scroll works correctly on an iPhone 5 but on an iPhone 6Plus the scroll has a problem not so easy to explain. If I tap in light way the scroll is ok, but if I tap in a little long way the screen the scroll doesn't works. Here the code that I used.
 self.scrollView = [[UIScrollView alloc] initWithFrame:self.frame];
 self.scrollView.scrollEnabled = YES;
 self.scrollView.delegate = self;
 [self addSubview:self.scrollView];

 self.theImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, lenghtImage, hightImage)];
 self.theImage.image = [UIImage imageNamed:@"theImage.png"];
 [self.scrollView addSubview:self.theImage];

 self.tableA = [[UITableView alloc] initWithFrame:CGRectMake(0, yPosA, self.bounds.size.width, heightA];
 self.tableA.delegate = self;
 self.tableA.dataSource = self;
 self.tableA.scrollEnabled = NO;
 [self.scrollView addSubview:self.tableA];

 self.tableB = [[UITableView alloc] initWithFrame:CGRectMake(0, yPosB, self.bounds.size.width, hightB)];
 self.tableB.delegate = self;
 self.tableB.dataSource = self;
 self.tableB.scrollEnabled = NO;
 [self.scrollView addSubview:self.tableB];

 self.scrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, heightA + heightB);

A: can your tableviews be eating the touches? have you tried with tableView.userInteractionEnabled = false to see if it works ?


text:
Q: stat & S_IFREG in C++ void fun1(char *fl){
//flNamep : stores the path of our directory
DIR *dip;
struct dirent *dit;
dip = opendir(fl);
if (dip==NULL) {cerr<<"Error\n";exit(-1);}

while ((dit=readdir(dip)))
 {
    string trun = (dit->d_name);
    struct stat buff;
    stat(dit->d_name, &buff);

    if  (((buff.st_mode & S_IFREG)==S_IFREG))
        {cout<<"File"<<endl;}
    else if (((buff.st_mode & S_IFDIR)==S_IFDIR))
        {cout<<"Dir"<<endl;}
     }
closedir(dip);
}

Code does not differentiate in dir and files. Am i missing something? I can not use Boost or any other STL. only C Posix Supported files. Need to know were i am wrong.
Updated code as per answer
    DIR *dip;
struct dirent *dit;
dip = opendir(flNamep);
if (dip==NULL) {cerr<<"Err\n";exit(-1);}

while ((dit=readdir(dip)))
 {
    string trun = (dit->d_name);
    string fullpath = flNamep;
    fullpath+='/';
    fullpath+=trun;

    if((trun==".") || (trun=="..")) {cout<<"";}
    else
    {
    struct stat buff;

    stat(dit->d_name, &buff);
        if (((buff.st_mode & S_IFDIR)==S_IFDIR))
        {cout<<"Dir"<<endl;}
        else
        {cout<<"File"<<endl;}

    }

A: I suspect that the stat actually fails with ENOENT (no such file) so buff doesn't contain anything useful.
stat(dit->d_name, &buff); /* dirent.d_name is just the name, not the full path */

You probably want to concatenate fl, "/", d_name. But first of all, check the value returned by stat.


text:
Q: Leaflet.Draw - GeoJSON to KML I have made a map using the Leaflet Draw plugin which allows the user to download their drawn items. These drawnItems are exported as GeoJSON using the following code from here:
document.getElementById('export').onclick = function(e) {
// Extract GeoJSON from featureGroup
var data = featureGroup.toGeoJSON();

// Stringify the GeoJSON
var convertedData = 'text/json;charset=utf-8,' +
encodeURIComponent(JSON.stringify(data));

// Create export
document.getElementById('export').setAttribute('href', 'data:' + convertedData);
document.getElementById('export').setAttribute('download','data.geojson');
}

This works perfectly, but it would be even more ideal if the GeoJSON was converted to .kml before being exported. I am aware of the toKml plugin but I am struggling to get it to work (I am still quite new to all of this). Where would I add:
var kml = tokml(geojsonObject);

And I am sure I would have to edit the //create export part of the GeoJSON code

A: var data = featureGroup.toGeoJSON();
var kml = tokml(data);

var convertedData = 'application/xml;charset=utf-8,' +
encodeURIComponent(kml);

// if you want to use the official MIME type for KML
// var convertedData = 'application/vnd.google-earth.kml+xml;charset=utf-8,'+
// encodeURIComponent(kml);

document.getElementById('export').setAttribute('href', 'data:' + convertedData);
document.getElementById('export').setAttribute('download', 'data.kml');