text:
Q: To answer the question ((What is your name?)) There is this problem I came up with in one of my classes.
How common is it to answer the question "What's your name?" with

It's ________.

Instead of

My name's ________.

I would appreciate knowing if native speakers find both forms of answer natural.

A: There's always going to be a problem about asking "how common" something is in speech. It depends on a person's dialect and the area where they live, it depends on the situation, and it depends on personality. Both forms, cited by the OP, are common though.

Speaker A: Hello, what's your name?

*

*Marilou

*It's Marilou

*Hi, I'm Marilou.

*My name's Marilou

The phrase My name is Marilou has a quite formal tone, the only time I've used it was in presentations, or when I had to teach about introducing yourself in English.
This American English video, which was made by a teacher called Rachel, is really good. It also explains  which syllables should be stressed in the phrase. my NAME's MArilou

Some non-native speakers don't want to use contractions because they don't think it's clear enough, but we really do want to use the contraction "I'm", and not "I am" because it can be much quicker, I'm, which puts the emphasis on the name, the most important part.  This will also help smooth out your speech.

A: In everyday conversation, I would say "It's Mick," since everyone knows me by that name. I would never say "My name is Mick." If I had to introduce myself [very] formally, I would use my surname, as in the most famous introduction of all:

My name is Bond, James Bond.

A: It's a very informal way to answer, like if someone you think is attracted to you asks you

What is your name?
  It's David.

If there's a question of what you might be called, for example your name is Jonathan but you would rather be called Jon, you could say

My name is Jon (not Jonathan).
  I use the name Jon.
  Most people call me Jon.
  Please call me Jon.

A: To add to the other answers, with regard to nicknames or common abbreviations of first names:
Once they know my name, people often ask me, "Do you go by Andrew or Andy?"  To which I reply, "I'm an Andrew.  I'm also not a Drew."  Similarly, someone might say "It's Bob not Robert," or, "I'm actually Eustacia but please just call me Stacy."


text:
Q: Export specific mysql tables to excel in php I have to export three specific tables to an Excel sheet, but all the data is pretty much dumped in one field, creating a large mess. Is it be possible to export the content of the three tables AND format them in Excel through PHP? Basically so that I could get:
Date:            Subject             Participants
Start - End      Subject Title       User 1
                                     User 2
                                     User 3

Basically so that everything is like that? To make it clear and visible (though this might cause issues with larger numbers of participants).
Also, I'll share my code, maybe someone can see what I'm messing up this time.

        <form method="post">

                    Begin datum:
                    <input type="date" id="BeginDate" name="BeginDate" placeholder="DD-MM-YYYY">
                    <input type="hidden" id="startDate" name="startDate" value="<?= $startdate; ?>"/>

                    Eind datum:
                    <input type="date" id="EindDate" name="EindDate" placeholder="DD-MM-YYYY">
                    <input type="hidden" id="endDate" name="endDate" value="<?= $enddate; ?>"/>

                    <input type="submit" name="generate" value="Jaarverslag genereren"/>

        </form>

And the function:
<?php
public function generateReport($startDate = null, $endDate = null) {
    if (empty($startDate) && empty($endDate)) {
        $time = strtotime("-1 year", time());
        $startDate = date("Y-m-d", $time);
        $endDate = date("Y-m-d");
    }
    $this->generator->create('Jaaroverzicht-' . $startDate . '-' . $endDate);
    $data = array(
        "Datum" . '' . "Aanwezigen" . '' . "Bijscholing"
    );
    foreach ($this->dbSchooling->getYearReport($startDate, $endDate) as $row) {
        $users = "";
        $participants = $this->dbSchooling->getParticipants($row['bijscholing_id']);
        foreach ($participants as $participant) {
            $users .= $participant;
            if ($participant == end($participants)) {
                $users .= ', ';
            }
        }
        $myDateTime = \DateTime::createFromFormat('Y-m-d', $row['bijscholing_begindatum']);
        $newDateString = $myDateTime->format('d-m-Y');
        array_push($data, ($newDateString . "." . $users . "." . '.' . $row['bijscholing_titel']));
    }
    foreach ($data as $line) {
        $this->generator->store(explode('.', $line));
    }
    return $this->generator->close();
} ?>

A: The code has been edited to use semicolons.
public function generateReport($startDate = null, $endDate = null) {
    if(empty($startDate) && empty($endDate)) {
        $time = strtotime("-1 year", time());
        $startDate = date("Y-m-d", $time);
        $endDate = date("Y-m-d");
    }
    /**
     * Title
     */
    $this->generator->create('Jaaroverzicht-'. $startDate . '-'. $endDate);
    $data = array(
        "Datum;Bijscholing;Instructeur;Aanwezigen"
    );
    /**
     * Kopstukken + inhoud
     */
    foreach($this->dbSchooling->getYearReport($startDate, $endDate) as $row) {
        $users = "";
        $participants = $this->dbSchooling->getParticipantsVoornaam($row['bijscholing_id']);
        foreach($participants as $participant) {
            $users .= $participant;
            if($participant !== end($participants)) {
                $users .= ', ';
            }
        }
        $myDateTime = \DateTime::createFromFormat('Y-m-d', $row['bijscholing_begindatum']);
        $newDateString = $myDateTime->format('d-m-Y');
        array_push($data, ($newDateString . ";" . $row['bijscholing_titel'] . " ; " . $row['bijscholing_presentator'] . ' ; ' . $users));
    }
    foreach ($data as $line)
    {
        $this->generator->store(explode(';', $line));
    }
    return $this->generator->close();
}

The encountered problem was only in a specific version of Excel. The file is correctly configured in Open Office Calc. By using a semicolon as a seperator it was easy to figure out the rest. Hope this helps anyone else with similar issues.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apparent verbosity of Boolean return from Javascript function A common idiom in much Javascript code I've studied is
function () {
    ...
    if (some big expression or something) {
        return true;
    } else {
        return false;
    }
}

Why not just:
function () {
    ...
    return some big expression or something;
}

I know that some people prefer the former for debugging or something but the pattern seems to be more frequent in Javascript code and I wondered if it was a workaround or idiom for some reason.
Sometimes it might be to force a non-Boolean to Boolean but frequently the expression is definitely already Boolean such as
    if (complicatedFunctionCall(para1) > 0) ...

so conversion/casting isn't required.


text:
Q: Case-insensitive matching with Eshell? How can you do case-insensitive pattern matching with Eshell? With Zsh, one can use "globbing tags" (i.e., if the extended_glob is turned on) such as in
print L(#i)in(#I)ux

which would match LINux for instance.
Is there anything like that for Eshell? From what I know Eshell doesn't have a support for something like Zsh's "globbing tags", but do you know if there is an Eshell predicate for case-insensitive matching? If there isn't, do you have any suggestion of how to define a predicate in Eshell to do that?
Thanks!

A: (setq eshell-glob-case-insensitive t) Does not work.
(setq eshell-cmpl-ignore-case t) This works. Put it in your .emacs or .emacs.d/init.el.

A: You can set the variable eshell-glob-case-insensitive to true to enable case-insensitive globbing in eshell.


text:
Q: Updating database when editing a field in a table I have a table, for which the data are pulled from a database and users can edit the data in each cell. So  when user edits a field of the table, how should I update the database? I have to mention for editing, I use prompt() method. Should I use ajax? I know my question is so general but I just need some clue.
Updating my question:
This is part of my code: (My table has more cells, the following is just one cell of my table).
    while($array=mysql_fetch_array($res))

            {

                           <?php
                                $var=$array['Legacy Data Conversion Required?'];
                                 if($var)
                                    echo
                                    "
" . $var  .   "
" . "";

                                else
                                    echo
                                      "
" . " " . "
" . ""  ;
                            ?>

 }

and this is part of the Javascript section:
   function legacyFunction($idl) {
var data1 = prompt("Legacy Data Conversion Required?Yes/No");
if (data1 != null) {
    document.getElementById($idl).innerHTML =
    data1;
   }
};

So when the user clicks on the edit image there will be a pop up message with input box (I used prompt() method), and after user clicks on OK button, the data in the cell of the table will change, but I also need to  update the database. So how can I do that?I mean after what action should I call the ajax function to update the database?

A: It would be nice if you could provide your code. How is the table cell being edited? Is it with content edible or a textbox or textarea? Here is my suggestion from the information provided from you. Do this: <input type="text" oninput="save(this.value);">
function save(textValue)
{
  //put your ajax request here
}

If this doesn't work then just tell me and I will try again. Good luck :-) Merry Christmas!

A: Create a form and set the action attribute of that form to your server side file such as writeToDatabase.php.  In your form, have all the necessary inputs and fields that you want updated in your database.  You may submit the form via AJAX or simply by a POST/GET method.  Assuming you are using PHP for your server side, establish a connection to your database and update/write the data to the database. Here is more info:
Database connection: http://www.w3schools.com/php/php_mysql_connect.asp
Form Handling: http://www.w3schools.com/php/php_forms.asp
Updating Data: http://www.w3schools.com/php/php_mysql_update.asp


text:
Q: Logging errors and exceptions on AWS Lambda I have some AWS Lambda functions that get run about twenty thousand times a day. So I would like to enable logging/alert to monitor all the errors and exceptions.
The cloudwatch log is giving too much noise, and difficult to see the error.
Now I'm planning to write the log to AWS S3 Bucket, this will have an impact on the performance.
What's the best way you suggest to log and alert the errors?

A: An alternative would be to leave everything as it is (from application perspective) and check AmazonCloudWatch Logs Filter.

You use metric filters to search for and match terms, phrases, or
  values in your log events. When a metric filter finds one of the
  terms, phrases, or values in your log events, you can increment the
  value of a CloudWatch metric.

If you defined your filter you can create a CloudWatch Alarm on the metric and get notified as soon as your defined threshold is reached :-)
Edit
I didnt check the link from @Renato Gama. Sorry. Just follow the instructions behind the link and your problem should be solved easily...

A: If you did not try this already I suggest that you try creating CloudWatch alerts based on custom metric filters; Have a look here; https://www.opsgenie.com/blog/2014/08/how-to-use-cloudwatch-to-generate-alerts-from-logs
(Of course you don't have to use OpsGenie service as suggested on the post I linked, you can implement anything that will help you debug the problems)


text:
Q: excel to html SheetJS I'm trying to convert a excel file (which user upload it in a input file tag) to a html table tag.
I found a code on "redstapler" but it doesn't work.
I don't know where is the problem.

<link rel="stylesheet" type="text/css" href="styles.css">

Red Stapler - SheetJS

        <input type="file" id="input-excel" />

A: It works for me...
I downloaded and embedded the xlsx.mini.js from https://github.com/SheetJS/sheetjs
Make sure your path is correct here:

And also check the name of your sheet which you want to read.
sheet:"sheet no1"


text:
Q: Creating a memory-based game from two previous games I'm developing a set of games to help children with deficiencies learn faster: The first game consists in a set of colors, and the user has to pick the right one from a set of four; the second one plays a sound and the user has to pick the animal/vehicle that is making that sound.
Each game consists in 6 levels of difficulty. For each level, the user has 3 chances to pick the correct answer. The games are played one after another (if the user can't pass one level in the first game, it will continue with the second game).
For the third game, I want to make a memory game from the previous two. Let's say the user didn't pass level 2 in the first game and level 3 in the second game. Then the third game will have 2 Intents: the first one will be randomly selected from the levels in the first game that he passed (in this case it will be the first or the second level), and the second one, from level 1, 2 or 3 -in this case- from the second game.
I was thinking in sending an integer through an Intent in every game after the user fails to pass it and use that number to select a level for the third game.
So far, I tried using this:
This is the first game:
if(contor2 == 3) //the user has no more chances left
    {
        Intent intent1 = new Intent(FirstGame2.this, ThirdGame.class);
        intent1.putExtra("var1", 2); //the value of the current level

        Intent intent = new Intent(FirstGame2.this, SecondGame1.class);
        startActivity(intent); //start the second game
    }

And in the second game:
if(contor == 3) //the user is out of chances
    {
        Intent intent1 = new Intent(SecondGame3.this, ThirdGame.class);
        intent1.putExtra("var2", 3); //in the second game he didn't pass level 3, so we're sending the value "3"
        startActivity(intent1); //start the third game
    }

In the third game I have the following code:
    Intent intent = getIntent();
    final int intValue = intent.getIntExtra("var1", 0);

    Intent intent2 = getIntent();
    final int intValue2 = intent2.getIntExtra("var2", 0);

    Toast.makeText(getApplicationContext(),"The value of var1 is "+ intValue, Toast.LENGTH_LONG).show();

But it returns "0", instead of "2", so I guess the data isn't sent after all....
Any other ideas of how can I implement the third game? Thank you very much!

A: In the first game, you put extra to intent1 but you start activity with intent. So, you are not using this part of code:
     Intent intent1 = new Intent(FirstGame2.this, ThirdGame.class);
     intent1.putExtra("var1", 2); //the value of the current

And that's why you see the default value: 0.
If you want to pass something you can go directly to the third game or you pass var1 to second game, you collect it and send again to the third game. Ex:
intent1.putExtra("var2", 3);
intent1.putExtra("var1", 2); or intent1.putExtra("var1", getIntent().getIntExtra("var2", 0));


text:
Q: Why do the Specialists not employ firearms? In Fate: The Winx Saga, the Specialists, who appear to occupy soldier and police roles in the Otherworld, use a variety of weapons, including knives, swords, and homing bows. However, they do not seem to use firearms, despite their advantages, such as higher rate of fire.
The problem is clearly not that advanced technology does not function in the Otherworld or is culturally disfavored, since we see things like cell phones and modern vehicles being used around Alfea. In fact, some of it functions extraordinarily well (cell phone calls from the Otherworld to the First World, anyone?) For that matter, the Specialists themselves use what appears to be modern bulletproof body armor and military transport vehicles.
With that in mind, why do Specialists not employ any firearms?


text:
Q: Text across two pages
I am making a small book and I want to put a phrase in both pages like the picture above, I want to keep the chapter title and page numbers.
Could you give me a hand on this?

A: Assuming that you answer @Werners comment positive and that you are able to print to the next bigger paper size respectively to your desired one (for example, let's say it is a4; then you would need to be able to print a3 paper), you could do this:
\documentclass[oneside,notitlepage]{book}
\usepackage[a3paper,landscape]{geometry}% add the right paper size
\usepackage{fancyhdr}
  \pagestyle{fancy}
  \fancyhf{}
  \fancyfoot[L]{\hspace*{.25\textwidth}\thepage\stepcounter{page}}
  \fancyfoot[R]{\thepage\hspace*{.25\textwidth}}
  \renewcommand{\headrulewidth}{0pt}
\fancypagestyle{plain}{%
  \fancyhf{}
  \fancyfoot[L]{\hspace*{.25\textwidth}\thepage\stepcounter{page}}
  \fancyfoot[R]{\thepage\hspace*{.25\textwidth}}
  \renewcommand{\headrulewidth}{0pt}
}
\usepackage{lipsum}
\usepackage{etoolbox}

\makeatletter
\patchcmd{\@maketitle}{\vskip 2em}{\vskip 60\p@}{}{}
\renewcommand{\maketitle}{%
\twocolumn
\@maketitle
\thispagestyle{empty}
\onecolumn
}
\makeatother

\title{Book}
\author{Cesar}
\date{\today}

\begin{document}
\maketitle
\chapter{}
\lipsum\lipsum\lipsum\lipsum
\end{document}

Output

A: On the other way, if you answer @Werners comment negative, use \parshape to write even lines very far from odd lines:
\documentclass[notitlepage]{book}
\begin{document}
\chapter{}
\def\w{80mm}% configure the width of the text boxes.
\def\wplusmeter{1080mm}% should be 1000mm+\w
\setbox1=\hbox{% define box1 with:
\begin{minipage}{\wplusmeter}\parshape 24
0mm \w 1000mm \w% even lines will be printed on the far left.
0mm \w 1000mm \w% each line is \w long.
0mm \w 1000mm \w
0mm \w 1000mm \w
0mm \w 1000mm \w% you will have to repeat that line a lot more if you have a longer text.
0mm \w 1000mm \w
0mm \w 1000mm \w
0mm \w 1000mm \w
0mm \w 1000mm \w
0mm \w 1000mm \w
0mm \w 1000mm \w
0mm \w 1000mm \w
\Huge% So that the image is readable.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
\tiny\ %hack to have smaller interline space. You should find better for it.
\end{minipage}}
\noindent\hbox{\kern\textwidth\kern-\w\usebox1}% print box1 once with right box out of the right boundary of the page.
\newpage
\noindent\hbox{\kern-1000mm\usebox1}% print box1 a second time with left box out of the left boundary.
\end{document}

You will of course do something for the vertical placement of the right box, and also learn to impose half-interline space in latex.
Another solution may be multi-page footnote, it may already exist.


text:
Q: Sending form radio values to Java servlet, returns null When I want to send a radio value from a form on a HTML page to a Java Servlet, this always seems to be a null value, instead of "1" or "2" or...
Here is the HTML code I have:
<form method="post" action="/testWeb/animalsurvey" target="_blank">

What is your favorite pet?

<input type="radio" name="animal" value="1" />Dog

<input type="radio" name="animal" value="2" />Cat

<input type="radio" name="animal" value="3" />Bird

<input type="radio" name="animal" value="4" />Snake

<input type="radio" name="animal" value="5" checked="checked" />None

<input type="submit" value="Submit" />

This is the Java Servlet code:
protected void doPost(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException, IOException {

    PrintWriter out = response.getWriter();

    String value = request.getParameter("name");

    out.println(value);

}

Web.xml code, which show the servlet mapping:
<servlet>
    <servlet-name>animalsurvey</servlet-name>
    <description>A survey servlet.</description>
    <servlet-class>be.SurveyServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>animalsurvey</servlet-name>
    <url-pattern>/animalsurvey</url-pattern>
</servlet-mapping>

I don't know if I'm blind to see it here, but what am I doing wrong?

A: Looks like it is the parameter name:
Please try:
 String value = request.getParameter("animal");


text:
Q: Start and stop logger in python 3.2 In my application, I use two buttons: One for START recording of RS422 link messages and one for STOP the record.
The first time, the application runs correctly : Creation of a .txt file with the messages.
The second time, when I click on the START button, a new . txt file is created but, now, messages are recording in this file but also in the first .txt file.
See my code :
def start_clic(self):
    logger=logging.getlogger("CFD")
    stringfilename=datetime.now().strftime('log_%Y_%m_%H_%M.txt')
    filehandler=logging.FileHandler(stringfilename)
    formatter=logging.Formatter('%(asctime)s %(message)s')
    logger.addHandler(filehandler)
    logger.setLevel(logging.INFO)

def stop_clic(self):
    logger.setLevel(logging.WARNING)
    filehandler.close()

Does somebody have an idea?

A: You'll have to remove the handlers if you want to stop logging like that, using the Logger.removeHandler() method:
def stop_clic(self):
    logger=logging.getlogger("CFD")
    logger.setLevel(logging.WARNING)
    logger.removeHandler(filehandler)
    filehandler.close()

otherwise it'll continue to be used.

A: Not sure in 3.2, but in 3.6 you can do: logger.disabled = True


text:
Q: Callback in ios not returning for authentication I'm using swifter to grab the access token
swifter.authorize(with: URL(string: "callback://")!, presentFrom: self, success: { accessToken, response in
        print("HELLO")
        print(accessToken)
        // ...
    }, failure: { error in
        // ...
    })

I can log in successfully because the app opens up SFSafariViewController, but then I'm not directed back to my app, and the success callback is never being called
here's the code for swifter, I see that presentFrom is suppose to be SFSafariViewController, but the delgate methods for SFSafariViewController aren't being triggered
 public func authorize(with callbackURL: URL, presentFrom presentingViewController: UIViewController? , success: TokenSuccessHandler?, failure: FailureHandler? = nil) {
    self.postOAuthRequestToken(with: callbackURL, success: { token, response in
        var requestToken = token!
        NotificationCenter.default.addObserver(forName: .SwifterCallbackNotification, object: nil, queue: .main) { notification in
            NotificationCenter.default.removeObserver(self)
            presentingViewController?.presentedViewController?.dismiss(animated: true, completion: nil)
            let url = notification.userInfo![CallbackNotification.optionsURLKey] as! URL

            let parameters = url.query!.queryStringParameters
            requestToken.verifier = parameters["oauth_verifier"]

            self.postOAuthAccessToken(with: requestToken, success: { accessToken, response in
                self.client.credential = Credential(accessToken: accessToken!)
                success?(accessToken!, response)
                }, failure: failure)
        }

        let authorizeURL = URL(string: "oauth/authorize", relativeTo: TwitterURL.oauth.url)
        let queryURL = URL(string: authorizeURL!.absoluteString + "?oauth_token=\(token!.key)")!

        if #available(iOS 9.0, *) , let delegate = presentingViewController as? SFSafariViewControllerDelegate {
            let safariView = SFSafariViewController(url: queryURL)
            safariView.delegate = delegate
            presentingViewController?.present(safariView, animated: true, completion: nil)
        } else {
            UIApplication.shared.openURL(queryURL)
        }
    }, failure: failure)
}

A: does it just wait and say "redirecting you back to the application" but never actually goes back to application?
You need to add both of these functions to the Appdelegate
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    Swifter.handleOpenURL(url)
    return true
}

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    Swifter.handleOpenURL(url as URL)

    return true
}

also try look at this for further assistance: How to Authorize Twitter with Swifter


text:
Q: I need update the spinner text in another textview I have an spinner in the adapter to get the quantity of the food item. Now, I want to get the spinner text and multiply it with the price to get the total price. How should I do that?
 override fun onBindViewHolder(holder: View_Holder, position: Int) {
    val data = list[position]
    holder.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {
            holder.spinner.setSelection(1)
        }

        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            val text:Int = parent?.getItemAtPosition(position) as Int
            holder.spinner.setSelection(text)
        }

    }
    holder.name.text = data.itemName
    holder.price.text = holder.spinner.onItemSelectedListener.toString()

This is the createviewholder function where I have used spinner.
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): View_Holder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.single_item, parent, false)
        res_name.text = "Ordering From "+list[0].itemRes
        val adapter = ArrayAdapter.createFromResource(
            context,
            R.array.quantity,
            android.R.layout.simple_spinner_item
        )
        val spinner = view.findViewById<Spinner>(R.id.spinner)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinner.adapter = adapter

                return View_Holder(view)
    }

A: Take a reference from following code it will help
override fun onItemSelected(arg0:AdapterView<*>, arg1:View, position: Int, id:Long) {
    val text:String = arg0?.getItemAtPosition(position).toString()
    //you should update view from here
    holder.name.text = data.itemName
    holder.price.text = "₹ " + data.itemPrice + "/-"
}


text:
Q: fish shell. How to check if a variable is set/empty? How can I do something like
set variable (some_command_that_may_return_a_string)
if [ variable is set ]
    do_something

and inversely how do I check if the variable is empty?

A: @faho provided an awesome answer but I thought it would be easier if there's a code example.
function if-test-no-arg
  set var

  if set -q var
    # true
  end

  if set -q var[1]
    # false
  end

  # Always put quotation marks
  if test -n "$var"
    # false
  end

  if test -z "$var"
    # true
  end
end

function if-test-empty-arg
  set var ""

  if set -q var
    # true
  end

  if set -q var[1]
    # true
  end

  if test -n "$var"
    # false
  end

  if test -z "$var"
    # true
  end
end

function if-test-valid-arg
  set var "hello"

  if set -q var
    # true
  end

  if set -q var[1]
    # true
  end

  if test -n "$var"
    # true
  end

  if test -z "$var"
    # false
  end
end

function if-test-no-set
  if set -q var
    # false
  end

  if set -q var[1]
    # false
  end

  if test -n "$var"
    # false
  end

  if test -z "$var"
    # true
  end
end

A: *

*set -q var (note the missing "$" - this uses the variable name) can be used to check if a variable has been set.

*set -q var[1] can be used to check whether the first element of a variable has been assigned (i.e. whether it is non-empty as a list).

*test -n "$var" [fn0] (or [ -n "$var" ]) can be used to check whether a variable expands to a non-empty string (and test -z is the inverse - true if it is empty).
These will be true/false in slightly different circumstances.
When no set var has been performed at all (and it has not been inherited from the parent process), set -q var, set -q var[1] and test -n "$var" will be false, test -z "$var" will be true.
When something like set var has been done (without any additional arguments), set -q var will be true, set -q var[1] will be false.
When something like set var "" has been done, both set versions will be true.
When something like set var "somestring" (or even set var "" "" [fn1]) has been done, the sets will be true and test -z "$var" will be false.

[fn0]: You never want to use test (or [) without quoting the variable. One particularly egregious example is that test -n $var will return true both if the variable contains something and if it is list-empty/unset (no set at all or set var without arguments). This is because fish's test is one of the few parts that follow POSIX, and that demands that test with any one argument be true. Also it does not handle lists properly - test -n $var will have weird results if var has more than one element.
[fn1]: This is because a list will be expanded as a string by joining the elements with spaces, so the list consisting of two empty strings will expand to " " - one space. Since that isn't empty, test -z returns false.

A: The modern version of fish shell (3.5.1) has string commands.

*

*string length --quiet $var checks that the variable is not empty

*not string length --quiet $var checks that the variable is empty


text:
Q: Why are my 2 sites on the same server (randomly?) switching PHP versions with PHP-FPM My issue is as follows:
1 server running Debian 11 in a virtual machine (though I've tested with 9 and 10 and they both show the same behaviour)
with 2 websites both configured to run with php-fpm & apache. Each site has a single index.php file and the contents of those files is <?php phpinfo(); ?>. 1 site has been set to run php8.0 and the other php8.1, this represents a real world situation that I'm dealing with. This has been set up by including an apache config file into my main apache config file for each site with the contents:
<IfModule proxy_fcgi_module>
# Enable http authorization headers
<IfModule setenvif_module>
SetEnvIfNoCase ^Authorization$ "(.+)" HTTP_AUTHORIZATION=$1
</IfModule>

<FilesMatch ".+\.ph(ar|p|tml)$">
    <If "-f %{REQUEST_FILENAME}">
        SetHandler "proxy:unix:/run/php/php8.0-fpm.sock|fcgi://localhost"
    </If>
</FilesMatch>
<FilesMatch ".+\.(phps|inc)$">
    # Deny access to raw php sources by default
    # To re-enable it's recommended to enable access to the files
    # only in specific virtual host or directory
    Require all denied
</FilesMatch>
# Deny access to files without filename (e.g. '.php')
<FilesMatch "^\.ph(ar|p|ps|tml)$">
    Require all denied
</FilesMatch>

The config file for php8.1 then uses the php8.1-fpm.sock. ps aux shows the following:
root      114787  0.0  0.3 222780 27312 ?        Ss   17:10   0:00 php-fpm: master process (/etc/php/8.0/fpm/php-fpm.conf)
www-data  114788  0.0  0.5 247140 48664 ?        S    17:10   0:03 php-fpm: pool www
www-data  114789  0.0  0.5 247128 48592 ?        S    17:10   0:03 php-fpm: pool www
www-data  114790  0.0  0.6 247136 48748 ?        S    17:10   0:03 php-fpm: pool www
www-data  114791  0.0  0.5 247128 48676 ?        S    17:10   0:05 php-fpm: pool www
www-data  114792  0.0  0.5 247132 48548 ?        S    17:10   0:04 php-fpm: pool www
root      114802  0.0  0.3 227196 28120 ?        Ss   17:10   0:00 php-fpm: master process (/etc/php/8.1/fpm/php-fpm.conf)
www-data  114803  0.0  0.3 227764 26744 ?        S    17:10   0:00 php-fpm: pool www
www-data  114804  0.0  0.1 227196  8896 ?        S    17:10   0:00 php-fpm: pool www
www-data  114805  0.0  0.1 227196  8896 ?        S    17:10   0:00 php-fpm: pool www
www-data  114806  0.0  0.1 227196  8896 ?        S    17:10   0:00 php-fpm: pool www

Contents of /etc/php/8.0/fpm/pool.d/www.conf:
[www]

user = www-data
group = www-data

listen = /run/php/php8.0-fpm.sock

listen.owner = www-data
listen.group = www-data

pm = dynamic

pm.max_children = 5

pm.start_servers = 2

pm.min_spare_servers = 1

pm.max_spare_servers = 3

The contents of /etc/php/8.1/fpm/pool.d/www.conf are exactly the same except that listen is = /run/php/php8.1-fpm.sock
Contents of /etc/php80/apache-include.conf (replace with 81 for php8.1):
Alias   /php80 /etc/php80/htdocs
<Directory /etc/php80/htdocs>
    <IfModule proxy_fcgi_module>
        Include /etc/php80/etc/php-apache2-fpm.conf
    </IfModule>
</Directory>
<Location  /php80 >
    Options FollowSymLinks
    <IfModule mod_php7.c>
        Include /etc/php80/etc/php-apache2.conf
    </IfModule>
        SetEnv  st_config_filepath /etc/php80/config.ini
    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteOptions inherit
        # Maintenance for this installation
        RewriteCond /etc/php80/maintenance -f
        RewriteCond %{HTTP_USER_AGENT} !Maintenance_Override
        RewriteRule ^.*$ /maintenance/?  [L,R=307]
    </IfModule>
</Location>
# Deny access to simplesaml directories
<DirectoryMatch "^/etc/php80/htdocs/libraries/simplesamlphp/(?!(auth|resources|module.php)).+">
        Order deny,allow
        Deny from all
</DirectoryMatch>

Contents of /etc/apache2/sites-enabled/ssl.conf
<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerAdmin webmaster@*.*
    ServerName ${APACHE_LOCALFQDN}
    ServerAlias ${APACHE_HOSTNAME}
    DocumentRoot /var/www/html/
    <Directory />
        Options
        AllowOverride None
    </Directory>
    <Directory /var/www/html/>
        Options FollowSymLinks
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>
# Logging

# For proxied requests, log different information:
    SetEnvIf X-Forwarded-For "^.*\..*\..*\..*" forwarded

# Proxied access log:
    LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" proxy
    CustomLog ${APACHE_LOG_DIR}/${APACHE_LOCALFQDN}-ssl.access-proxy.log proxy env=forwarded

# SSL Configuration
SSLEngine on
SSLOptions StdEnvVars OptRenegotiate
SSLCertificateFile /etc/ssl/private/${APACHE_LOCALFQDN}.crt
SSLCertificateKeyFile /etc/ssl/private/${APACHE_LOCALFQDN}.key

<FilesMatch "\.(php)$">
    SSLOptions +StdEnvVars
</FilesMatch>
BrowserMatch "MSIE [2-6]" \
    nokeepalive ssl-unclean-shutdown \
    downgrade-1.0 force-response-1.0
BrowserMatch "MSIE [7-9]" ssl-unclean-shutdown

################################################################################
# SSL hardening options
#Probably not relevant to show here

</VirtualHost>
</IfModule>

I have a php.sh file in the php80/ and php81 directories:
#!/bin/sh -e
. /etc/php80/etc/php-cli.sh

env config_filepath=/etc/php80/config.ini /usr/bin/${PHPVERSION:=php7.3} ${PHPOPTIONS} $*

The contents of php-cli.sh is:
PHPOPTIONS="-d magic_quotes_gpc=off -d register_globals=off -d safe_mode=off -d session.use_trans_sid=off -d output_buffering=off -d zlib.output_compression=off -d ignore_user_abort=on -d upload_max_filesize=1500M -d post_max_size=1500M -d memory_limit=-1 -d date.timezone=Europe/Berlin"

PHPVERSION="${FORCE_PHP_VERSION:-php8.0}"

php81 then has the relevant parts set correctly.
What I really don't understand and where my problem lies is, why when I keep refreshing the individual pages do I sometimes see the 8.0 site showing that it is using php8.1 and vice versa. I sometimes have to refresh the pages 10-20 times before it switches but it never fails to show up sooner rather than later.
How would I go about figuring out why this is happening, or is there something very obvious that I'm missing?
Many thanks in advance!
Further research/Possible explanations:
1. The php fpm master processes are all running as root and all child processes are running as www-data (as can be seen above in the ps aux output). Initial reading of https://www.binarytides.com/php-fpm-separate-user-uid-linux/ would suggest that it may actually be possible for any pool to be used for a request despite using different sockets since they are all running under the www-data user:

"Running each site with its own uid/gid is more secure and easier to
deal with. If all sites ran with same user, then php on one site could
read/write the files of other users."

1.1. Upon further experimentation I see that changing the name of the pool for either php8.0 or 8.1 is not sufficient to decouple it from the any of the master processes which lends, in my eyes, credibility to the previously referenced article that says that different users/groups also need to be set.
1.1.1. Ok scratch that last item, I hadn't cottoned on to ps aux not showing the relationships between processes. ps afx shows that the child processes are correctly assigned. Unfortunate since what I though I had found, I had in fact not.
 161186 ?        Ss     0:01 php-fpm: master process (/etc/php/8.0/fpm/php-fpm.conf)
 161191 ?        S      0:10  \_ php-fpm: pool php80
 161192 ?        S      0:11  \_ php-fpm: pool php80
 161193 ?        S      0:07  \_ php-fpm: pool php80
 161205 ?        Ss     0:01 php-fpm: master process (/etc/php/8.1/fpm/php-fpm.conf)
 161206 ?        S      0:00  \_ php-fpm: pool www
 161207 ?        S      0:00  \_ php-fpm: pool www

I have now tested setting a different user and group and still see the same behaviour
2. It seems this issue has actually been encountered before.

Tried phpinfo() page and got PHP 7.4.15 instead of expected 5.6.40. We did the same with a 7.3 and got the same 7.4 on phpinfo() using SetHandler of php7.3 as well.

The solution presented (move away from linux sockets and use network communication instead) I have tested and can confirm as working. It is unfortunately not an ideal solution and doesn't explain why using sockets doesn't work as it should. The solution involving <If "-f %{REQUEST_FILENAME}"> I already had present anyway and has no effect.
3. I have found 2 further systems that we have set up which use Debian 10.12 and Apache 2.4.54 (as opposed to apache 2.4.53 as in the example above), and Debian 11.4 and Apache 2.4.54. For those systems we use .htaccess files instead of individual Apache configs per site, the issue issue is not reproducible under these conditions


text:
Q: Android Firebase cannot download images and add them to a Bitmap Array I am currently working on a matching card game where I need to store the images on Firebase. I am uploading the images by a button click when I start the game(doing it automatically creates same problem but the button one is safer) I think the Image isn't getting downloaded fast enough to show on the card face or it might not be working in a sequence with the whole app so the bitmap array gets zero elements inside. My current code is:
class game2x2 : AppCompatActivity() {
    private lateinit var database: DatabaseReference
    private lateinit var buttons: List<ImageButton>
    //private lateinit var bitmapArray: ArrayList<Bitmap>
    private var bitmapArray = mutableListOf<Bitmap>()
    private lateinit var button1: ImageButton
    private lateinit var button2: ImageButton
    private lateinit var button3: ImageButton
    private lateinit var button4: ImageButton
    private lateinit var upload: Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_game2x2)

        val min = 1
        val max = 45
        val database = FirebaseDatabase.getInstance()
        val imageID1 = Random().nextInt(max - min + 1) + min
        val imageID2 = Random().nextInt(max - min + 1) + min
        val aDatabase = FirebaseStorage.getInstance().getReference("all/$imageID1.jpg")
        val sDatabase = FirebaseStorage.getInstance().getReference("all/$imageID2.jpg")

        upload = findViewById(R.id.uploadButton)
        button1 = findViewById(R.id.imageButton1)
        button2 = findViewById(R.id.imageButton2)
        button3 = findViewById(R.id.imageButton3)
        button4 = findViewById(R.id.imageButton4)
        buttons = listOf(button1, button2, button3, button4)

        upload.setOnClickListener(View.OnClickListener {
            try {
                val localfile = File.createTempFile("tempfile", ".jpg")
                aDatabase.getFile(localfile).addOnSuccessListener {
                    val bitmap = BitmapFactory.decodeFile(localfile.absolutePath)
                    bitmapArray.add(bitmap)
                }.addOnFailureListener {
                    Log.w("myapplication", "ERROR RETRIEVING IMAGE")
                    Toast.makeText(this, "ERROR RETRIEVING IMAGE", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

            try {
                val localfile = File.createTempFile("tempfile1", ".jpg")
                sDatabase.getFile(localfile).addOnSuccessListener {
                    val bitmap = BitmapFactory.decodeFile(localfile.absolutePath)
                    bitmapArray.add(bitmap)
                }.addOnFailureListener {
                    Log.w("myapplication", "ERROR RETRIEVING IMAGE")
                    Toast.makeText(this, "ERROR RETRIEVING IMAGE", Toast.LENGTH_SHORT).show()
                }
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
            ///    DUPLICATE
            bitmapArray.addAll(bitmapArray)
            ///SHUFFLE
            bitmapArray.shuffle()
            Log.w("myapplication", bitmapArray.size.toString())
        })

        buttons.forEachIndexed { index, button ->
            button.setOnClickListener(View.OnClickListener {
                button.setImageBitmap(bitmapArray[index])
            })
        }
    }
}

Is there any other way to retrieve image from the Firebase Storage besides downloading and adding it to a temporary file and then decoding it to a bitmap?
I tried anything that I could find. I even tried adding the access tokens of the images to a realtime database and then getting them from there but I failed terribly. Thanks in advance for helping!

A: Since getFile() an asynchronous task I would imagine your log statement Log.w("myapplication", bitmapArray.size.toString()) is executing while the bitmapArray is still empty? This would happen because the aDatabase.getFile().addOnSuccessListener {} and sDatabase.getFile().addOnSuccessListener {} won't execute until the download finishes, but allow the rest of your function to continue to execute.
What you need to do is await the results of the downloads before continuing with the duplicate and shuffle portions.
getFile() returns a FileDownloadTask, which inherits from StorageTask. StorageTask has an isComplete() method -- and a few others the may be useful for errors cases. One option would be to capture the FileDownloadTask in a variable and not continue executing until your downloads are finished. However, be warned this might freeze up your main thread.
Edit: Instead of checking status on the main thread, you might want to try something like disabling the buttons until the images are ready. See edit comments:
class game2x2 : AppCompatActivity() {
    private lateinit var database: DatabaseReference
    private lateinit var buttons: List<ImageButton>
    //private lateinit var bitmapArray: ArrayList<Bitmap>
    private var bitmapArray = mutableListOf<Bitmap>()
    private lateinit var button1: ImageButton
    private lateinit var button2: ImageButton
    private lateinit var button3: ImageButton
    private lateinit var button4: ImageButton

    private val numImages = 2 // EDIT total number of images we need to download
    private val numImagesReady = AtomicInteger(0) // EDIT count of how many images are currently ready

    private lateinit var upload: Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_game2x2)

        val min = 1
        val max = 45
        val database = FirebaseDatabase.getInstance()
        val imageID1 = Random().nextInt(max - min + 1) + min
        val imageID2 = Random().nextInt(max - min + 1) + min
        val aDatabase = FirebaseStorage.getInstance().getReference("all/$imageID1.jpg")
        val sDatabase = FirebaseStorage.getInstance().getReference("all/$imageID2.jpg")

        upload = findViewById(R.id.uploadButton)
        button1 = findViewById(R.id.imageButton1)
        button2 = findViewById(R.id.imageButton2)
        button3 = findViewById(R.id.imageButton3)
        button4 = findViewById(R.id.imageButton4)
        buttons = listOf(button1, button2, button3, button4)

        // EDIT disable buttons until all images are ready
        buttons.forEach {
            it.setEnabled(false)
        }

        upload.setOnClickListener(View.OnClickListener {
            try {
                val localfile = File.createTempFile("tempfile", ".jpg")
                aDatabase.getFile(localfile).addOnSuccessListener {
                    val bitmap = BitmapFactory.decodeFile(localfile.absolutePath)
                    bitmapArray.add(bitmap)

                    // EDIT add the image twice here instead of duplicating later
                    bitmapArray.add(bitmap)

                    // EDIT count this image as ready
                    val totalImagesReady = numImagesReady.incrementAndGet()

                    // EDIT once all images are ready, shuffle and enable the buttons
                    if (totalImagesReady == numImages) {
                        bitmapArray.shuffle()
                        buttons.forEach { it.setEnabled(true) }
                    }

                }.addOnFailureListener {
                    Log.w("myapplication", "ERROR RETRIEVING IMAGE")
                    Toast.makeText(this, "ERROR RETRIEVING IMAGE", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

            try {
                // SUGGESTION especially if this will be implemented 8x8, you might want to try implementing this in a loop instead of duplicating code
                val localfile = File.createTempFile("tempfile1", ".jpg")
                sDatabase.getFile(localfile).addOnSuccessListener {
                    val bitmap = BitmapFactory.decodeFile(localfile.absolutePath)
                    bitmapArray.add(bitmap)

                    // EDIT add the image twice here instead of duplicating later
                    bitmapArray.add(bitmap)

                    // EDIT count this image as ready
                    val totalImagesReady = numImagesReady.incrementAndGet()

                    // EDIT once all images are ready, shuffle and enable the buttons
                    if (totalImagesReady == numImages) {
                        bitmapArray.shuffle()
                        buttons.forEach { it.setEnabled(true) }
                    }

                }.addOnFailureListener {
                    Log.w("myapplication", "ERROR RETRIEVING IMAGE")
                    Toast.makeText(this, "ERROR RETRIEVING IMAGE", Toast.LENGTH_SHORT).show()
                }
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
// EDIT moved            ///    DUPLICATE
// EDIT refactor         bitmapArray.addAll(bitmapArray)
// EDIT moved            ///SHUFFLE
// EDIT moved            bitmapArray.shuffle()
// EDIT remove           Log.w("myapplication", bitmapArray.size.toString())
        })

        buttons.forEachIndexed { index, button ->
            button.setOnClickListener(View.OnClickListener {
                button.setImageBitmap(bitmapArray[index])
            })
        }
    }
}


text:
Q: Как правильно написать URL из разных типов данных {%url var:str %} Я новичок в Django - не судите строго.
В шаблоне есть такой url, он работает:
{% url 'software:index' %}

Но мне нужно 'software' записать в качестве переменной, а именно {{menu.name}}
То есть как-то так {% url menu.name:'index' %}, где menu_name - переменная, а index - текст.
Не пойму синтаксиса как это сделать. Не получается слить оба значения в единое значение, чтобы Django правильно его прочёл.
Прошу помощи у экспертов.

A:
В шаблоне есть такой url, он работает:
{% url 'software:index' %}

Здесь используется так называемы namespace-адреса (подробнее). А вы, если я правильно понял, хотите передать переменную в ваше представление. Тогда это не то, что вам нужно.
url-адреса с аргументами задаются в шаблоне в таком виде:
{% url 'path_name' some_arg='some_value' %}

В кавычках вы задаете имя пути, а после передаете необходимые аргументы.
Для этого path или url должен иметь примерно такой вид:
urlpatterns = [
    ...
    path('page/<some_arg>/', views.some_view, name='path_name'),
]

Вы также можете указывать Django только те типы передаваемых аргументов, которые вам нужны. Если вы хотите получать в качестве переменной только строку, исправьте предыдущий пример на это:
urlpatterns = [
    ...
    path('page/<str:some_arg>/', views.some_view, name='path_name'),
]

Если вы хотите передать больше переменных, то разделите их в тэге шаблона пробелами:
{% url 'path_name' some_arg='some_value' second_arg=2 %}

и не забудьте добавить эти аргументы в путь:
urlpatterns = [
    ...
    path('page/<str:some_arg>/<int:second_arg>', views.some_view, name='path_name'),
]

Прочитайте подробнее о url-адресах и диспетчере url в официальной документации


text:
Q: Error in addResourcePath(LIB$name, LIB$url) : addResourcePath called with invalid prefix; please see documentation I'm an inexperienced programmer that is completely new to Shiny. For transparency, I am doing this as part of a school assignment, but also want to really learn how to use ShinyApps and data visualization tools. Any assistance would be appreciated.
Server.R - For this one, I start to receive errors when I begin the render plots. When I look at other examples of code for time series plots, there is a string($) that follows output.  I am not sure if that works with my plots. I also think there is an issue with 'plot_impact_by_year'.  Again, I don't know if I should be referencing something else or nothing at all.
library(shiny)
library(ggplot2)
library(rCharts)

# Load data
dt <- read.csv("NBAdata.csv", header=TRUE)

# Shiny server
shinyServer(function(input, output, session) {
})

# Prepare datasets
        # Prepare for time series
        dt.agg.year <- reactive({
                aggregate_by_year(dt, input$range[1], input$range[2])
        })

# Render Plots
        # 3-Pointers by Year
        output <- renderChart({
                plot_impact_by_year(
                        dt = dt.agg.year() %>% select(Year, 3PM, 3PA),
                        yAxisLabel = "3-Pointers Per Game",
                        desc = TRUE
                )
        })

        # Fouls versus Pace and Points by Year
        output <- renderChart({
                plot_impact_by_year(
                        dt = dt.agg.year() %>% select(Year, PF, Pace, Pts),
                        yAxisLabel = "Per Game Statistics",
                        desc = TRUE
                )
        })

ui.R - When I run the code individually, I receive the following error when I enter the very last closed parentheses:
Error in addResourcePath(LIB$name, LIB$url) :
  addResourcePath called with invalid prefix; please see documentation
library(shiny)
library(rCharts)

# Load the dataset
dt <- read.csv("NBAdata.csv", header=TRUE)

shinyUI(
        navbarPage("3-Pointers and Pace of Play in the NBA",
                   tabPanel("Plot",
                            sidebarPanel(
                                    sliderInput("Year", "Year:",
                                                min = 1979, max = 2015, value = c(1995, 2015),
                            ),

                            mainPanel(
                                    tabsetPanel(

                                            # Time series data
                                            tabPanel(p(icon("line-chart"), "By year"),
                                                     h4('Number of 3-pointers by year', align = "center"),
                                                     showOutput("3PM", "3PA")),

                                            tabPanel(p(icon("line-chart"), "By year"),
                                                     h4('Fouls versus Pace and Points by year', align = "center"),
                                                     showOutput("PF", "Pace", "Pts")),
                                        )
                                )
                        )
                )
        )
)


text:
Q: How to display window titles in Unity Super+W mode? GNOME 3 displays window titles in the spread, it helps if we can't identify the window by it's thumbnail, such as many Terminal windows open. Any way to display window titles in the Super+W screen?

A: It has gotten a bit more difficult. The new procedure is:

*

*Install compizconfig-settings-manager    and compiz-plugins    via the Sotware Center icons next to the package links or in a terminal:
sudo apt-get install compizconfig-settings-manager compiz-plugins

*Open CompizConfig Settings Manager

*Search for "Text" and enable the plugin

*Search for "Scale", enable and open the plugin

*In the Appearance Tab under Window Title select All Windows in the Dropdown

A: Install the package compizconfig-settings-manager, activate the plugin Scale Addons, go to the Appearance tab in the Scale Addons settings, open the Window Title area and change Window title display to All windows


text:
Q: How to remove or access the build timestamp of a plugin in the pom file I have a eclipse plugin with pom file which after building in jenkins, provides the jar in following format:
abc.xyz_1.2.3.201909251020.jar.
The product which I am build is eclipse based product(Plugin-development)
Requirement is either of the below:

*

*Build that plugin with no time stamp so that it will look like: abc.xyz_1.2.3.jar

*Get the timestamp "201909251020" in my pom file through any variable.

It will be helpful if I can get some help on it.Thank you.
Note1:
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd are used in the pom file.
Note2:
The plugins are built using org.eclipse.tycho:tycho-packaging-plugin:1.4.0:package-plugin


text:
Q: Wordpress: How to include a custom field in an array (SmplePie) Wordpress 2.8.4, Simple Pie Plugin 2.2.1
I'm having this:
<?php echo SimplePieWP(
array(
   'http://gdata.youtube.com/feeds/base/videos?q=fifa10%20trailer&client=ytapi-youtube-search&alt=rss&v=2'
),
array(
   'items' => '1')
); ?>

Instead of fifa10 I'd like to have the value of a custom field with the key name-of-game in there.
How can I do this?

A: You get the value of a Wordpress custom field with get_post_meta():
get_post_meta($post->ID, 'name-of-game', true)

To include it in your function call to SimplePieWP, use string concatenation with . (dot):
<?php echo SimplePieWP(array('http://gdata.youtube.com/feeds/base/videos?q=' .
get_post_meta($post->ID, 'name-of-game', true) .
'%20trailer&client=ytapi-youtube-search&alt=rss&v=2'),array('items' => '1')); ?>


text:
Q: how to use a column from select query result in "if condition" of Stored Procedure in SQL how to use a column from select query result in "if condition" of Stored Procedure in SQL.

A: for stored procedure :
    use cursor. get column values in variable and then use if condition.
example from mysql:
DELIMITER $$

CREATE PROCEDURE build_email_list (INOUT email_list varchar(4000))
BEGIN

 DECLARE v_finished INTEGER DEFAULT 0;
        DECLARE v_email varchar(100) DEFAULT "";

 -- declare cursor for employee email
 DEClARE email_cursor CURSOR FOR
 SELECT email FROM employees;

 -- declare NOT FOUND handler
 DECLARE CONTINUE HANDLER
        FOR NOT FOUND SET v_finished = 1;

 OPEN email_cursor;

 get_email: LOOP

 FETCH email_cursor INTO v_email;

 IF v_finished = 1 THEN
 LEAVE get_email;
 END IF;

 -- build email list
 SET email_list = CONCAT(v_email,";",email_list);

 END LOOP get_email;

 CLOSE email_cursor;

END$$

DELIMITER ;

for sql query :
    use subquery.


text:
Q: ArrayFire approx1 / approx2 examples Does anyone know how to use ArrayFire's approx1/approx2 functions? I can't find examples of their usage online, and so cannot figure out what exactly the interpolation position arrays should be. I have tried af::approx2(inArray, af::where(inArray some condition), af::where(inArray some other condition), AF_INTERP_NEAREST) along with similar examples where af::where() is replaced with something like af::isNaN() and no matter what I try, I cannot get approx1 or approx2 to work.
Thanks for the help!
Edit: The specific issue I am encountering is with the two af::array parameters, where above I state that I have tried af::where(...). I do not know what specific types of af::array to pass. The documentation's description of

array contains the interpolation locations

does not help in identifying what I need to pass to these functions. af::where() and af::isNaN(), both functions that return arrays describing positions of elements, cause an af::exception at runtime.

A: As stated in the docs, approx1 takes the following arguments:
af::approx1 ( const array & in,
        const array & pos,
        const interpType method = AF_INTERP_LINEAR,
        const float offGrid = 0.0f )

While in, method and offGrid are described, the exact effect of pos is not. The solution is straightforward: The input-data in array in are assumed to lie on a grid of spacing 1.
This means you have to scale your pos-array accordingly. Suppose your input data of length N were located at positions x with dx = x[i+1]-x[i] then the interpolated representation of your data lies on the grid x[i]/dx.
E.g. if the whole data were to be interpolated onto a grid xnew, the pos argument would need to be rescaled to pos = xnew/dx.
This implies, of course, that approx1 (and also approx2) can only work on evenly-spaced grids, which is also not mentioned in the docs.

A: This might not resolve your current issue, but we have tried address this shortcoming in the documentation and the fixes will be made public in our next feature release. We have detailed how approx functions work and added new version of the functions that lets you choose the dimension along which interpolation can be carried out.


text:
Q: Add more events to an existing fullcalendar with EventSources I'm working with Fullcalendar and I have an existing calendar, I want to add more events to it using the eventSources array.
calendarDiv.fullCalendar({eventSources: [ { url:url ,className: "class"}] })

But this creates a new calendar instead of putting all the events on the calendar that I already have. Can someone tell me how to add more events to the calendar using this? thank you.

A: I think you are overwriting all of the calendar events.
I believe you want addEventSource. https://fullcalendar.io/docs/event_data/addEventSource/
calendarDiv.fullCalendar('addEventSource', [
        {
            title  : 'event1',
            start  : '2010-01-01'
        },
        {
            title  : 'event2',
            start  : '2010-01-05',
            end    : '2010-01-07'
        },
        {
            title  : 'event3',
            start  : '2010-01-09T12:30:00',
            allDay : false // will make the time show
        }
    ])

A: Using the eventSources to add additional sources is not the proper way. The proper way, like Will said, is to use addEventSource, you're just not using it correctly. Since you have a URL you just need to pass the URL:
calendarDiv.fullCalendar('addEventSource', url);

Aditionally, if you want a specific className you should add that to the source (back-end).


text:
Q: Аргументы функции main Здравствуйте, меня интересует main функция с параметрами, часто вижу запись в чужых исходниках, да и в своих (пишу эту часть неосознанно)
 int main(int argc, char **argv)

Как эти параметры передаются в функцию при ее вызове и что они вобще значат, спасибо.
A: Это параметры, которые передаются программе при запуске.
argc - количество этих параметров.  argv - указатель на массив указателей на строки, каждая из которых содержит один параметр. Параметры передаются в виде строк Си. Еще бывает такая запись - char* argv[]
В структуре памяти процесса Линукса они находятся в стеке сразу за стеком функции main. Думаю, в других системах то же устройство.
A: Вам тут показали на примерах. Забыли правда про третий параметр main() ссылку на вектор переменных окружения ОС (environment, те, которые в Shell устанавливаются командой export).
Вообще полностью:
int main (int ac, char **argv, char **env)

Почитайте также man execl.
A: Если ваша прога будет называться myprog, то допустим вы вызываете ее с параметрами так:
myprog param1, param2, param3
Соответственно в main() вы получите:
argc=3 //количество параметров
argv[0]="param1"; //1-й параметр
argv[1]="param2"  //2-й параметр
argv[3]="param3"  //3-й параметр

При этом если при завершении проги вы вернете в main() return 2;
то ось получит exit code равное 2 (в Windows это называется errorlevel)
Update
Спорол лажу с примером - исправляю:
myprog param1 param2 param3
Соответственно в main() вы получите:
argc=4 //количество параметров
argv[0]="myprog"; //название запускаемого файла
argv[1]="param1"  //1-й параметр
argv[2]="param2"  //2-й параметр
argv[3]="param3"  //3-й параметр

A: Это стандртная вещь в C/C++

*

*argc - количество аргументов в командной строке

**argv[] - массив указателей на строки, содержащие эти аргументы

При этом argv[0] - это имя команды, а argv[argc] - это NULL.
A: baz.cpp:
#include <iostream>

int main(int argc, char** argv) {
    std::cout << "argc: " << argc << "\n";
    for (int i =0; i < argc; ++i)
        std::cout << i << ": " << argv[i] << "\n";
}

Смотрим:
$ g++ baz.cpp -o boo
$ ./boo foo
argc: 2
0: ./boo
1: foo


text:
Q: what do the us, idh, idv stand for in the MCMCglmm in R I am having hard time remembering the meaning of the us, idh, and idv functions in the MCMCglmm. I understand that these are the functions taking random variance-covariance structure into account, but are they abbreviations of some words in English? It would be helpful to know it to remember them and their underlying meaning. Thank you very much.

A: In the MCMCglmm package in R, we have, from page 19 of the documentation:

idv fits a constant variance across all components in formula. Both
idh and us fit different variances across each component in formula,
but us will also fit the covariances.

As far as I know, none of idh, idv, or us are related to any particular statistical terms. In fact, I cannot find any references to these terms outside of the MCMCglmm package.


text:
Q: ComboBox AutoComplete with Key/Value Pair I have a ComboBox with the following code:
private void comboBox1_TextChanged(object sender, EventArgs e)
{
    using (var service = WebServiceHelper.GetCoreService())
    {
        string physicianXml = service.SearchPhysicians(SessionInfo.Current.ClientCode, SessionInfo.Current.MachineName,
                                    SessionInfo.Current.Username, comboBox1.Text);

        var physicians = PhysicianItemList.FromXml(physicianXml);

        AutoCompleteStringCollection autoCompleteStringCollection = new AutoCompleteStringCollection();
        foreach (var physician in physicians.Items)
        {
            autoCompleteStringCollection.Add(physician.LastName + ", " + physician.FirstName);
        }

        comboBox1.AutoCompleteCustomSource = autoCompleteStringCollection;
        comboBox1.Select(comboBox1.Text.Length, 0);
    }
}

Basically, a user types the first few characters of a physician's name and it should populate the auto-complete list with the top 100 matching records.  It works great, but I need to associate it back to a key (either the PK from the table, or the Physician's NPI number).  It seems the AutoCompleteStringCollection doesn't support keys.  Can anyone suggest a way of doing this?  There are approximately 7 million records in the table, so I don't want to prepopulate the ComboBox.
Thanks

A: It looks like your problem is that AutoCompleteStringComplete was made specifically for strings (hence, the name).
You may want to look into the parents (IList, ICollection, IEnumerable) and see if you can homebrew something templated toward a key/value struct.

A: When you build your AutoCompleteStringCollection, build a Dictionary<String, int> for the name, id pairs as well. Then use some event (textbox validation or user submit/save click) to lookup and set the id. You could store the dictionary on the textbox Tag.
Edit
For some reason I thought you were working with a textbox control. Forget about the AutoCompleteStringCollection and just build a Dictionary<String, int>. For the combobox set your autocompletesource to ListItems, set the combobox display name and value and set the datasource to the dictionary.
combobox.DisplayMember = "key";
combobox.ValueMember = "value";
combobox.AutocompleteSource = AutocompleteSource.ListItems;
combobox.DataSource = myDictionary;

However you should only populate the datasource and autocomplete once when the user enters n characters in the combobox, otherwise it gets buggy. I tried to use this for a dynamic autocomplete once (eg the list clears if the user clear the text and retypes), but I had to forget about the combobox and use a hybrid textbox listbox approach much like this user

A: Too late but maybe someone will use this code :
this.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;

RNProveedor rnProveedor = new RNProveedor();
var listaProveedores = rnProveedor.Buscar();
Dictionary<int, String> dicTemp = new Dictionary<int, string>();

foreach (var entidad in listaProveedores)
{
    dicTemp.Add(entidad.ProvNro, entidad.ProNombre);
}

this.DataSource = new BindingSource(dicTemp, null);
this.DisplayMember = "Value";
this.ValueMember = "Key";

And to select the value
public int GetValorDecimal()
{
    KeyValuePair<int, string> objeto = (KeyValuePair<int, string>)this.SelectedItem;
    return objeto.Key;
}

With this example you won't have any problem with duplicated strings as the examples above


text:
Q: how to make a relationship table between 3 table (2 to 1) in SQL lets say we have 3 table in our database
tables:
table books:
book_id
book_title
...

table magazines:
magazine_id
magazine_title
...

and genres:
genre_id:
genre_name

and now we say want to know what book has what genre and what magazine has what genre, this is the way i know for two table
relation tables:
table book_genres:
genre_id
book_id

table magazine_genre:
genre_id
magazine_id

in this way we have to create several separate table for joining the books, magazine and maybe more tables. and i been told that always have 2 id column in join tables.
but i'm wondering about if i could do something like this
the table that not working!
table title_genres:
genre_id
book_id
magazine_id
...

this is more simple but i get an error when i insert a book genres that says magazine_id can't be empty NULL because its primary key.
its gonna be save me for creating a lot of tables. like if i decide to have a category table then i have to join books and magazine separately.
and my question: is the 2 column thing is a good practice or there is a better way for this?

A: You can absolutely store the records this way if you have a category field that has information such as (books, magazines etc). So, in other words your table is vertically partitioned by category field but logically it's a single table.
Only drawback I can see is if this table grows fast then query performance would be a problem because (a) the table will be huge so it will consume more memory even if you are only looking for specific categories and not all of them (b) you always have to use inline sub query since your category filter have to applied every time for every join and when you use inline queries for joins the database would not be able to make use of indexes will be affect the performance of the queries.
Note : You would not be able to store the records in any other way. For example even if a magazine and a book have same genre you have to have them in separate rows and not the same row because if you do that your model will get into other kind of troubles.

A: You use bridge tables to represent m:n relationships. If a book can have many genres and a magazine can have many genres, then you need bridge tables like the book_genres table you are showing.
And if books are very different from magazines in your database, then yes, have separate tables for books and magazines.
This leads to two bridge tables, just as you describe and I see nothing wrong with this.
Your idea to have one bridge table is generally possible, but doesn't solve any problem.
But well, let's see how we would construct such a multi bridge table. First of all you'll want a check constraint ensuring that always exactly one of the columns book_id and magazine_id is filled. Then you want a unique constraint on COALESCE(book_id, magazine_id), genre_id. This would usually be done with a function index, which MySQL doesn't support as far as I know. I suppose though, that you could create a generated column which you can index in MySQL.
And then you want to read the relations as quick as possible. With a bridge table like book_genres you have one row per book and genre and an index to get the relation as quick as possible. With a multi bridge table like title_genres you don't. You have one table containing relations you are interested in and others you are not interested in. You'd want a partial index like
create unique index idx on title_genres (book_id, genre_id) where book_id is not null;

but MySQL doesn't support partial indexes. You could
create unique index idx on title_genres (book_id, genre_id);

which leads to a larger index, but serves the purpose. You'd do the same with
create unique index idx2 on title_genres (magazine_id, genre_id);

And now, with all this work, what have you gained? Your database has become way more complicated than with the simple book_genres and magazine_genres tables. Keep it simple. Use these two tables instead of the multi bridge monster :-)


text:
Q: Printing the contents of the canvas tag I make an application canvas. I load more image (png, gif) in canvas. When I click print on my browser (opera), the contents of the canvas tag does not print. With other browsers (FF, IE, Chrome), there is no problem. Why?

A: this answer from Capture HTML Canvas as gif/jpg/png/pdf? might be useful.
var canvas = document.getElementById("mycanvas");
var img    = canvas.toDataURL("image/png");

with the value in IMG you can write it out as a new Image like so:
document.write('<img src="'+img+'"/>');


text:
Q: Tell me problems that can trick you I am looking for problems that can easily lead the solver down the wrong path.
For example take a circle and pick $N$, where $N>1$, points along its circumference and draw all the straight lines between them. No $3$ lines intersect at the same point inside the circle. The question is how many sectors do those lines divide the inside of the circle into. First it looks like $2^{N-1}$, which is true up to $5$ points, but with $6$ there's only $31$.

A: Question 1)
You are building a straight fence 100 feet long. There is a fencepost every 10 feet. Fence panels are 20 feet long.
How many fence panels do you need?
How many fenceposts do you need?
Question 2)
You are fencing a rectangular area 100ftx100 ft. There is a fencepost every 10 feet. Fence panels are 20 feet long.
How many fence panels do you need?
How many fenceposts do you need?
Folks often forget that the corners are special and count wrong, especially when presented with the first question immediately before the second.

A: I like tricking my friends with this one:
$S_n(\mathbb R) $ denotes the set of $n,n$ real symmetric matrices
$ S_n(\mathbb R) ^{++} $ denotes the set of positive definite matrices.
$ S_n(\mathbb R) ^{--} $ denotes the set of negative definite matrices.
What are the path-connected components of $S_n(\mathbb R) $?
They all answer $ S_n(\mathbb R) ^{++} $ and $S_n(\mathbb R) ^{--} $.
This is clearly wrong since $S_n(\mathbb R) $ is a vector space.

A: When asked to answer fast, in my experience people usually fail at this one:

$$P\implies \neg P\,\,\,\,\text{ tautology or contradiction?}$$

A: My favourite is the Monty Hall Problem.  It's an old one but a good one.  A game-show host has 3 boxes and knows that behind 1 is a car and behind the other 2 are donkeys.  You pick a box and he opens one of the other 2, always being sure to reveal a donkey.  He then asks if you would like to keep the box you first picked or switch to the other closed box.  What should you do?

 Instinctively many people will say it doesn't matter.  In truth you should always swap, there is a 1/3 chance that you originally chose the correct box and therefore a 2/3 chance that the other closed box contains a car. The thing which makes the probability counter-intuitive here is that the host knows where the car is and always removes a donkey so if you don't pick the donkey immediately you will always be left with a donkey in the other box at the end.

A: When my friends encountered with double factorial for the first time, almost all of them mistakenly interpreted $\color{blue}{n!!}$ as $\color{blue}{(n!)!}$.
Also this limit
$$
\Large\lim_{n\to\infty}e^{-n}\sum_{k=0}^n\frac{n^k}{k!}=1,
$$
which is incorrect because it is equal to $\dfrac{1}{2}$. We might think the term $\displaystyle\lim_{n\to\infty}\sum_{k=0}^n\frac{n^k}{k!}$ as $e^{n}$, but unfortunately it does not equal.
The last but not the least, the most classic and idiotic internet debate:
$$
\Large\color{blue}{6\div2(1+2)}
$$
is equal to $\Large\color{blue}1$ or $\Large\color{blue}9$??

ADDENDUM :
I forgot this one, the tricky question about simple arithmetic from my past IQ test. I also encountered this problem in many different variants on internet recently with fantastic hyperbole tagline: 99.99% FAILED!!

Suppose you have $100$ pounds of potatoes and these potatoes consist of  $99$% water. You decide to leave the potatoes outside and let them dehydrate until they consist of $98$% water. Now the potatoes should weigh a little less than they were before. How much do they weigh now?

The answer is, of course $\Large\color{blue}{50}$ pounds.
$$\\$$

$$\Large\color{blue}{\text{# }\mathbb{Q.E.D.}\text{ #}}$$

A: I get this math problem from 9GAG.

It is said that over $50\%$ of Harvard, Princeton, and MIT students get this wrong.


text:
Q: Follow-up: Underline + strike-through using soul This is a follow-up question to Mixing underline and strike-out. This time, I'm specifically interested in an implementation using soul (that doesn't require multiple compilations to stabilize).
I would like to use soul to create an (underline) + (strike-through) command \textulst that would combine \textul with \textst and still allow line-breaks within.
Thus far I'm unable to properly combine the two, as soul uses the same underlining for both the (regular) underline and the strike-through.
Here's my (unsuccessful) attempt at generating \textulst:

\documentclass{article}
\usepackage{soul}

\makeatletter
\def\SOUL@ulstunderline#1{{%
    \setbox\z@\hbox{#1}%
    \dimen@=\wd\z@
    \dimen@i=\SOUL@uloverlap
    \advance\dimen@2\dimen@i
    \rlap{% Draw underline
        \null
        \kern-\dimen@i
        \SOUL@ulcolor{\SOUL@ulleaders\hskip\dimen@}%
    }%
    \SOUL@stpreamble% Switch to draw over-strike
    \rlap{%
        \null
        \kern-\dimen@i
        \SOUL@ulcolor{\SOUL@ulleaders\hskip\dimen@}%
    }%
    \unhcopy\z@
}}
\def\SOUL@ulsteverysyllable{%
    \SOUL@ulstunderline{%
        \the\SOUL@syllable
        \SOUL@setkern\SOUL@charkern
    }%
}
\def\SOUL@ulstsetup{%
  \SOUL@ulsetup
  \let\SOUL@everysyllable\SOUL@ulsteverysyllable
}
\DeclareRobustCommand*\textulst{\SOUL@ulstsetup\SOUL@}

\makeatletter

\begin{document}
Here is \textul{some text}.

Here is \textst{some text}.

Here is \textulst{some text}.
\end{document}

A: I realize that this doesn't answer your question because it is not with soul, but rather this shows an alternative, using censor, based on several of my similar previous answers:
\documentclass{article}
\usepackage{censor}
\usepackage{stackengine}
\usepackage{xcolor}
\usepackage{scalerel}
\newlength\uldepth
\newlength\rlwd
\def\ulcolor{black}
\rlwd=.8pt
\censorruledepth=2.5pt
\uldepth=-2pt

\makeatletter
\def\stacktype{L}
\periodrlap=0pt\relax
\afterperiodlap=0pt\relax
\lletterlap=0pt\relax
\rletterlap=0pt\relax
\afterspacelap=1.0ex\relax

\renewcommand\censorrule[1]{%
\protect\textcolor{\ulcolor}{\stackon[0pt]%
  {\rule[\uldepth]{#1}{\rlwd}}{\rule[\censorruledepth]{#1}{\rlwd}}}%
}

\renewcommand\@cenword[1]{%
  \setbox0=\hbox{#1}%
  \stackon[0pt]{#1}{\censorrule{\wd0}}%
}

\def\censordot{\textcolor{\ulcolor}{\rlap{\@cenword{\phantom{.}}}}.}

\makeatother
\parindent 0in
\parskip 1em
\begin{document}

This shows linebreaking capability: aaa aaa aaa aaa aaa aaa aaa
\xblackout{bbb bbb bbb bbb. bbb bbb bbb bbb bbb bbb}
ccc ccc ccc ccc ccc ccc

Can this \xblackout{procedure go across paragraphs boundaries?

Why yes} it can.![enter image description here][1]

But gaps can arise if glue is stretched too far.

\afterspacelap=1.7ex\relax
\xblackout{%
This tests marking a multiline block of text.  This tests marking a multiline block of text.
This tests marking a multiline block of text.  This tests marking a multiline block of text.
This tests marking a multiline block of text.}

\end{document}

A: Here's a solution based on soul:
\documentclass{article}
\usepackage{soul}

\makeatletter
\newdimen\SOUL@ulstdp
\newdimen\SOUL@ulstht
\def\SOUL@ulstleaders{%
    \leaders
    \hbox
    {%
      \rlap{\vrule\@depth\SOUL@uldp\@height\SOUL@ulht\@width.1pt\relax}%
      \vrule\@depth\SOUL@ulstdp\@height\SOUL@ulstht\@width.1pt\relax
    }%
}
\def\SOUL@ulstpreamble{%
  \SOUL@ulpreamble
  \SOUL@ulstdp=\SOUL@uldp
  \SOUL@ulstht=\SOUL@ulht
  \SOUL@stpreamble
}
\def\SOUL@ulstsetup{%
  \SOUL@ulsetup
  \let\SOUL@preamble\SOUL@ulstpreamble
  \let\SOUL@ulleaders\SOUL@ulstleaders
}
\DeclareRobustCommand*\textulst{\SOUL@ulstsetup\SOUL@}

\makeatletter

\begin{document}
Here is \textul{some text}.

Here is \textst{some text}.

Here is \textulst{some text}.
\end{document}

It's based on the idea of "stacking" two rules immediately in the \leaders construction soul uses to overlay a rule. I wouldn't know how else to get two rules as soul relies heavily on \leaders especially to support stretching interword space.
The downside is that when using \leaders with a rule (as usual for \ul, \st, and \hl), the rule will just stretch as far as the dimension given as the leader length, while when using a box, the rule needs to have a predefined width, which then becomes the minimal length of the leaders construct. The box is then replicated as often as neccessary to span the given width.
I have used .1pt as the box width. That means, if soul tries to span something shorter than .1pt there will be a gap in the underline. On the other hand, using a narrower box will substantially enlarge execution time and file size.


text:
Q: Predicting future price in high inflation economies I am trying to create a machine learning model in a country which has high inflation. With this model, I am trying to predict the price of a second hand car. As my train data, I have second hand car sales from 2014 and 2015. As my test data, I use car sales from 2017 and 2018.
As features, I am using the attributes of a car: Horse Power, Engine Size, KM, Vehicle Type, Brand, Model... In addition, I am using 2 econometric features: Special Consumption Tax and Euro Currency.
These two features are positively correlated with the price of the car. If Euro Currency increases, second hand prices increase. It is also true for special consumption tax. You can see the change in Euro Currency for the last 5 years.

I am using XGBoost to create model. However, RMSE and MAE are very high. Should I change the algorithm? Or should I use more econometric features?


text:
Q: How does the "/n" switch of the "copy" command actually work on Windows Command Prompt? How does the "/n" switch of the "copy" command actually work on Windows Command Prompt?

It seems to say that it copies the 8.3 filename instead of the long filename.
I tried it, but after copying, the long filename is still there, rather than an 8.3 filename.

So how does it actually work? Is this feature broken?


text:
Q: Is there a codeigniter library user manager based on Ion_Auth? I implemented codeigniter Ion_Auth library for user registration and etc.  I noticed it does not have a built-in user manager such as edit user accounts. Does a user manager such as edit user accounts exist? I can always code one, but I rather not reinvent the wheel.

A: I use Ion Auth  too, it is pretty well coded I and I like writing code with it.
I also needed users editing, but I find it quite easy, because I needed only one simple form, because the library has update_user() and you need only to pass an array with your new data.

A: Download a CMS because it looks to me you have little or no experience with codeigniter or php for that matter. I dont mean that in a rude way by any means but if you cant perform simple CRUD operations, install a pre-built system as it will save you lots of headaches.

A: I've just started using CI and am also using Ion Auth for authentication. I'm handling user signup/authentication exclusively with ion auth and extending public profiles using Grocery CRUD. All public info can be viewed globally, but only edited by the user that owns it (as defined by linking the ion auth user table to the extended profile table). I don't know if this is the best way to do it, but it is what I'm doing so far.


text:
Q: C#: Question about protected and internal variables i am new to C# and reading this

*

*protected: Only derived types or members of the same type.

*internal: Only code within the same assembly. Can also be code external to object as long as it is in the same assembly.  (default for types)

*protected internal: Either code from derived type or code in the same assembly. Combination of protected OR internal.

whats protected internal for? doesn't internal also allow derived types to access the variables?
and whats an assembly?

A: Assemblies
An assembly is the .dll or .exe file that you get from compiling your code. If you have multiple projects within Visual Studio, then they will compile to different assemblies.
See Assemblies on the MSDN for more information.
Protected Internal
protected internal means it can be accessed both from sub-classes and classes within the same assembly. It is a more visible access modifier than protected or internal alone. If you want to restrict class members to only derived classes within the same assembly, then you must mark the class itself as internal and its members as protected.
See Access Modifiers (C# Programming Guide) for more information.

A: "Doesn't internal also allow derived types to access the variables?"
No, not if they're in different assemblies.  As assembly is essentially a CLR (common-language runtime) DLL or EXE.  You can think of it roughly as "library."


text:
Q: Not able to start emulator's front camera via web cam showing error.! while click on 'camera' icon in emulator the dialog box appears and then i click ok, its shows error:- "Unfortunately, Camera has Stop".
Find out snapshots here..!

A: Which version of android are you running in the emulator? Anything above 4.0 allows you to use the webcam as camera for the emulator. Check this post for more details.


text:
Q: Delete query end state lasts tens of seconds in innodb cluster I have an InnoDB cluster with three nodes running with 4GB ram and 80GB SSD on Linode.
I am trying to delete around 240000 of rows from MySQL InnoDB cluster in one go. However, it stuck at query end state for more than 100 seconds then it timeout at MySQLWorkbench side. The worst thing is sometime after timeout master node MySQL started to use all memory and swap then crashed.
If I delete by small chunk with below 20000 rows it worked but still took 60s. I know I can just delete in a small chunk and that's how people suggest typically. But I think 20000 rows is too small. It may indicate other potential problems as most of the query time goes to query end state.
The query is like this
delete A
from A left join B on fk_Btable_id=Btable_id
left join C on fk_Ctable_id=Ctable_id
where col1 = 'value';

The profile from delete around 20000 rows in one delete query.
sending data: 15.68s.
query end: 45.5s

When more than 30000 rows the delete query timeout at 180s at MySQLWorkbench side. But it still able to complete after some time. On slow query log, it said total 1488 seconds to complete the query. That's ridiculously long. Delete query itself completed within 20sec. Residual time goes to query end.
To test without a cluster, I spinned up another instance on Linode with same data, ran the same delete query and it completed within 20s. So my guessing is because of InnoDB cluster, probably network or some kind of sync mechanism but I can't find any proof for this.
Any idea would be helpful...either guess or the direction I can look into. Thanks a lot.


text:
Q: Tried both ng-repeat and ng-options for select dropdown; query results keep coming back empty First, let me make a couple of disclaimers:

*

*This is my very first time posting a question here. I only do so because I've tried numerous possible solutions to similar questions over the past 24 hours and gotten nowhere.

*I'm also a complete newbie to AngularJS (using 1.5.6). I'm starting to understand basic things like ng-repeat, but this one's got me stumped.

With that said, I'll try to provide as much info as I can, based on suggestions I've read out here. Hopefully someone will be able to quickly point out where I've gone wrong.

OVERVIEW:
I'm building a PHP/MySQL CRUD system with a fairly complex user form. The CRUD operations themselves are working fine, and they interact with a DB table I'll call tableA.
Now within the Create and Update forms, I have a SELECT drop-down list whose OPTIONs will be generated via a query from a second DB table I'll call tableB. (These tables both live within the same DB instance, called mapping.) So, this second table contains 61,405 records, of which I'll only need 41 to act as my OPTIONs. I've already successfully tested the SQL statement to return these 41 rows.
So after reading, watching and trying out several different approaches, I seem to be having trouble getting the SQL results carried over.
index.php

    Language primarily spoken:
    <select id="primaryLang" ng-model="selectedLanguage" ng-options="lang.langName for lang in langs" class="form-control">
        <option value="">Select one</option>
    </select>

NOTES:

*

*The LangController is defined within a page-wide TaskController because I thought maybe my $scope variables were getting conflated.

*In place of ng-options="lang.langName for lang in langs", I also tried explicitly defining <option ng-repeat="lang in langs" value="{{ lang.langID }}">{{ lang.langName }}</option>, to no avail.

app.js
app.controller('LangController', function ($scope, $http) {
    $scope.listLangs = function() {
        $scope.langs = [];
        $_PATH = '/mapping/assets/script/';

        $http.get($_PATH + 'langs.php')
            .then(function success(e) {
                $scope.langs = e.data;
                console.log($scope.langs);
            },
            function error(e) {
                $scope.errors = e.data.errors;
            });
    };

    $scope.listLangs();
});

langs.php
<?php

    require '../__/db.php';

    $output = array();
    $query = "SELECT DISTINCT * FROM tableB WHERE countryID = 'TR' AND nameType = 'L' ORDER BY langName";
    $result = mysqli_query($dbcon, $query);

    while ($row = mysqli_fetch_array($result)) {
        $output[] = $row;
    }

    echo json_encode($output);
?>

NOTES:

*

*I've confirmed that the DB connection parameters from ../__/db.php are being successfully captured.

*I confirmed in MySQL Workbench that the SQL query does return the 41 rows I wanted from TableB.

*In place of the $scope.listLangs(); statement in app.js, I also tried setting ng-init="listLangs()" on the LangController opening DIV in index.php, to no avail.

RESULTS

*

*According to Chrome web console, console.log($scope.langs); consistently returns an empty string (""). In other words, it doesn't look like $scope.langs = []; ever gets populated by echo json_encode($output);, despite verifying the DB connection strings and MySQL query results.

*This in turn results in a SELECT drop-down with only the Select one OPTION.

*Much of what I've written for this operation was copied directly from a similar ng-repeat under the TaskController I created for the CRUD operations because that one works perfectly OK. So I'm baffled by what I might have done wrong here. At first, I wrote this as another TaskController operation, but that produced a bunch of unintelligible JS console errors. Plus, since this isn't strictly a CRUD operation, I assumed it should probably go under a separate controller anyway to alleviate $scope confusion.

I'm not (yet) familiar with Plunker, so I don't have one to provide at this point. I'm hoping this will suffice as a call for help. I'm also hoping this is all due to something trivial and/or just plain stupid on my part. Again, I am a newbie to Angular (which I really like, by the way!).
Thanks so much in advance, and Happy New Year to all!
~ Eddie


text:
Q: Why isn't my button pushing from my app to Apple Maps? I have a navigation app I am working on which works like a normal maps app, allowing you to search for locations through a search table etc. In the app, the user can create annotations by clicking a result they want from my searchable.
QUESTION: When the user taps an annotation, a pop-up button should appear above it, as I have created it programmatically.  Upon click, it should push the user to the Apple Maps app with the route to the annotation they clicked preloaded in. It's not pushing me there anymore, which is weird because it used to work.  Here's the programmatically created button:
extension ViewController : MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?{
        if annotation is MKUserLocation {
            //return nil so map view draws "blue dot" for standard user location
            return nil
        }
        let reuseId = "pin"
        var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pinView?.pinTintColor = UIColor.red
        pinView?.canShowCallout = true
        let smallSquare = CGSize(width: 30, height: 30)
        let button = UIButton(frame: CGRect(origin: (CGPoint()), size: smallSquare))
        button.setBackgroundImage(UIImage(named: "car"), for: [])
        button.addTarget(self, action: #selector(getDirections), for: UIControlEvents.touchUpInside)

        pinView?.leftCalloutAccessoryView = button
        return pinView
    }
}

and this is supposed to carry it out (in the class)
@objc func getDirections(){
    if let selectedPin = selectedPin {
        let mapItem = MKMapItem(placemark: selectedPin)
        let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]
        mapItem.openInMaps(launchOptions: launchOptions)
    }
}

Could it be something weird with the Objective-C function? This is the code I recently added that potentially could have caused the issue, though I really don't know:
func resolveAddress(for averageCoordinate: CLLocationCoordinate2D, completion: @escaping (MKPlacemark?) -> () ) {

    let geocoder = CLGeocoder()
    let averageLocation = CLLocation(latitude: averageCoordinate.latitude, longitude: averageCoordinate.longitude)
    geocoder.reverseGeocodeLocation(averageLocation) { (placemarks, error) in
        guard error == nil,
            let placemark = placemarks?.first
        else {
            completion(nil)
            return
        }
        completion(MKPlacemark(placemark: placemark ))
    }
}

@IBAction func middleFinderButton(_ sender: Any) {

    let totalLatitude = mapView.annotations.reduce(0) { $0 + $1.coordinate.latitude }

    let totalLongitude = mapView.annotations.reduce(0) { $0 + $1.coordinate.longitude }

    let averageLatitude = totalLatitude/Double(mapView.annotations.count)

    let averageLongitude = totalLongitude/Double(mapView.annotations.count)

    let centerPoint = MKPointAnnotation()

    centerPoint.coordinate.latitude = averageLatitude
    centerPoint.coordinate.longitude = averageLongitude

    mapView.addAnnotation(centerPoint)

    resolveAddress(for: centerPoint.coordinate) { placemark in
        if let placemark = placemark {
            self.mapView.addAnnotation(placemark)
        } else {
            self.mapView.addAnnotation(centerPoint)
        }
    }

    print(totalLatitude)
    print(totalLongitude)
    print(averageLatitude)
    print(averageLongitude)
    print(centerPoint.coordinate)
}

github link: github.com/derekvandermark/VHNavigationAppOfficial-v-0.93
Anyone have an idea why this button isn't working and pushing the app to maps with a preset route? Could it be a glitch with the simulator? (It used to work so I doubt it...)

A: to push the user to the maps app you could try this:
func openMap(lat: String, lng: String){

    let lat1 : NSString = lat as NSString
    let lng1 : NSString = lng as NSString

    let latitude:CLLocationDegrees =  lat1.doubleValue
    let longitude:CLLocationDegrees =  lng1.doubleValue

    let regionDistance:CLLocationDistance = 10000
    let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
    let regionSpan = MKCoordinateRegion(center: coordinates, latitudinalMeters: regionDistance, longitudinalMeters: regionDistance)
    let options = [
        MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
        MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)
    ]
    let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
    let mapItem = MKMapItem(placemark: placemark)
    mapItem.openInMaps(launchOptions: options)
}


text:
Q: Invoke Lex Bot in Custom State from Amazon Connect I have a lex bot with multiple intents that gets invoked from Connect. If I know exactly why the caller is calling, is it possible for me to invoke the bot but start off eliciting a slot from a particular intent? Maybe if I could programatically invoke the bot from a lambda in an ElicitSlot state?

A: Amazon Connect gives you two options for calling Lex you may want to explore further:
 1. you can specify a subset of intents in the block that's calling Lex, so if your Connect flow already knows which intent needs to be called, then just specify that single intent.
 2. You can set session attributes in Amazon Connect that get passed to Lex. So you can put any context information there and have your Lex logic (implemented as Lambda validation function) make choices as to what to do next based on that information. This may not work for picking intents, but can be used for picking the right slot to fill next.


text:
Q: Issue when removing rows from JTable I made a JTable in my GUI application and i want to add rows and remove rows to it using add and remove buttons that i have already created, the problem is when removing a row I want to get the selected row index but I got a NullPointerException just when calling the getSelectedRow() method. I tried to google it and didn't found my question answer also I tried to read java documentation but I found that this method don't throw that exception in usual.
the code:
// creating the table
JTable table = new JTable(model);
    model.addColumn("NO.");
    model.addColumn("Name");
    model.addColumn("Status");
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setRowSelectionAllowed(true);
    table.setShowGrid(false);
    table.getColumnModel().getColumn(0).setPreferredWidth(28);
    table.getColumnModel().getColumn(1).setPreferredWidth(222);
    table.getColumnModel().getColumn(2).setPreferredWidth(100);
    table.setBackground(color);
    table.setPreferredScrollableViewportSize(new Dimension(350,250));
    table.setFillsViewportHeight(true);
    scroll = new JScrollPane(table);
    center.add(scroll);

// adding records to it
public class AddEvent implements ActionListener{
public void actionPerformed (ActionEvent event){

    String text = write.getText();

    if (!text.equals("") && !text.contains(" ")){
        String view = "http://www." + text;
        write.setText(null);
        model.addRow(new Object[]{model.getRowCount()+1, view,"Active"});
    }

}
}

// to remove the selected row
public class RemoveEvent implements ActionListener{
public void actionPerformed (ActionEvent event){
          int index = table.getSelectedRow(); // it throws the exception here
      table.clearSelection();
      System.out.println(index);
      if(index != -1){
      table.remove(index);
      }

    }

}

A: If the exception is being thrown here
int index = table.getSelectedRow();

then table is probably null. For the ActionListener to work the class member variable table should be assigned to the JTable instance. Check that you are not shadowing the variable when it is being instantiated. Replace
JTable table = new JTable(model);

with
table = new JTable(model);

A: Your posted code is not complete so all I can do is make a guess.
JTable table = new JTable(model);

This variable looks like a local variable, therefore it is not available to your other classes. Somewhere you probably defined a class variable:
JTable table; // this is null

Try this:
//JTable table = new JTable(model);
table = new JTable(model);

Also the data should be removed from the DefaultTableModel:
model.removeRow(...);