text:
Q: Ошибка при SimpleXMLElement Добрый вечер) Подскажите пожалуйста:
Что это за ошибка такая :
Fatal error: Uncaught Exception: String could not be parsed as XML in C:\xampp\htdocs\weather\index.php:124 Stack trace: #0 C:\xampp\htdocs\weather\index.php(124): SimpleXMLElement->__construct('https://www.yr....') #1 {main} thrown

И где я проморгала этот момент. Не подскажете как править мой код? Голову уже какое время сижу ломаю:/
код:
if (isset($_GET['city']))
{
    $url =  'https://www.yr.no/place/'. $_GET['city'] .'/forecast.xml';
    $data = new SimpleXMLElement(file_get_contents($url));

    $city = $data->location->name;
    $dir = 'xml/'.$city.'.xml';

    // проверка, на то, что дата должна быть не в прошлом
    if (strtotime(date('d.m.Y', $_GET['date'])) < strtotime(date('d.m.Y')))
    {
        echo " !!наша дата корректна";
        // проверка, есть ли у нас уже такой файл?
        if(file_exists($dir))
        {
            echo " !!у нас уже есть такой файл";
            $src = file_get_contents($dir);
            $data = new SimpleXMLElement($src);
            // если файл есть, проверяем на актуальность
            $lastupdate = $data->meta->lastupdate;
            if(strtotime(date('d.m.Y', $lastupdate)) <  strtotime(date('d.m.Y')))
            {
                echo "  !!наш файл устарел, скачиваем и парсим";
                // если файл устарел, скачиваем его и парсим
                file_put_contents($dir, $url);
                $src = file_get_contents($dir);
                $data = new SimpleXMLElement($src);
                $str = $data->forecast->tabular->time;
                foreach ($data->forecast->tabular->time as $str)
                {
                    if(strtotime($_GET["date"]) >= strtotime($str['from']) && strtotime($_GET['date']) <= strtotime($str['to']))
                    {
                        $forecast["Temperature:"] = (string) $str->temperature["value"];
                        $forecast["Precipitation:"] = (string) $str->precipitation["value"];
                        $windDirection = $str->windDirection["name"];
                        $forecast["Wind:"] = (string) $str->windSpeed["mps"] . " m/s from $windDirection";
                        $date = date ("d.m.Y H:i", strtotime($_GET['date']));
                        $city = $data->location->name;
                        $result = "OK";
                        break;
                    }
                    else  {
                        $result = "ERROR";
                        $error_message = "Not found";
                    }
                }
            }
            // если файл актуальный - парсим
            else {
                echo "  !!наш файл актуальный, парсим";
                $src = file_get_contents($dir);
                $data = new SimpleXMLElement($src);
                $str = $data->forecast->tabular->time;
                foreach ($data->forecast->tabular->time as $str)
                {
                    if(strtotime($_GET["date"]) >= strtotime($str['from']) && strtotime($_GET['date']) <= strtotime($str['to']))
                    {
                        $forecast["Temperature:"] = (string) $str->temperature["value"];
                        $forecast["Precipitation:"] = (string) $str->precipitation["value"];
                        $windDirection = $str->windDirection["name"];
                        $forecast["Wind:"] = (string) $str->windSpeed["mps"] . " m/s from $windDirection";
                        $date = date ("d.m.Y H:i", strtotime($_GET['date']));
                        $city = $data->location->name;
                        $result = "OK";
                        break;
                    }
                    else  {
                        $result = "ERROR";
                        $error_message = "Not found";
                    }
                }
            }
        }
        // если у нас нет такого файла, скачиваем и парсим
        else {
            echo "  !!у нас нет такого файла, скачиваем и парсим";
            file_put_contents($dir, $url);
            $src = file_get_contents($dir);
            $data = new SimpleXMLElement($src);
            $str = $data->forecast->tabular->time;
            foreach ($data->forecast->tabular->time as $str)
            {
                if(strtotime($_GET["date"]) >= strtotime($str['from']) && strtotime($_GET['date']) <= strtotime($str['to']))
                {
                    $forecast["Temperature:"] = (string) $str->temperature["value"];
                    $forecast["Precipitation:"] = (string) $str->precipitation["value"];
                    $windDirection = $str->windDirection["name"];
                    $forecast["Wind:"] = (string) $str->windSpeed["mps"] . " m/s from $windDirection";
                    $date = date ("d.m.Y H:i", strtotime($_GET['date']));
                    $city = $data->location->name;
                    $result = "OK";
                    break;
                }
                else  {
                    $result = "ERROR";
                    $error_message = "Not found";
                }
            }
        }
    }
    else {
        $result = "ERROR";
        $error_message = "Incorrect date or city";
    }
}
else {
    echo "else";
    $result = "";}


text:
Q: Ubuntu 18.04 unable to wake up after suspend I've tried many answers over here to solve this problem, but none of them work.
I use a HP-Pavillion with Intel 620 graphics, and have a 1tb ssd and 12 gigs of ram.
I've dual-booted the system with Windows 10, and the system does wake with Windows 10.
The system also used to wake up before I reinstalled Ubuntu.
I've noticed that the display is just completely black, but the keyboard does light up.
Ctrl-Alt F3 or F7 don't work either.
My swap space is as follows:
$sudo swapon --show
NAME           TYPE SIZE USED PRIO
/home/swapfile file 8.5G   0B   -2

I've tried setting noveau.modeset=0, and also switching to lightdm from gdm3, to no avail.
I checked system logs using journalctl | grep systemd-sleep and got this result.
Aug 12 21:58:30 abcd systemd-sleep[14314]: Suspending system...
Aug 12 23:32:31 abcd systemd-sleep[14314]: System resumed.
Aug 12 23:32:32 abcd systemd-sleep[14314]: /dev/sda:
Aug 12 23:32:32 abcd systemd-sleep[14314]:  setting Advanced Power Management level to 0x80 (128)
Aug 12 23:32:32 abcd systemd-sleep[14314]:  APM_level        = 128
Aug 12 23:32:33 abcd systemd-sleep[14314]: /dev/sda:
Aug 12 23:32:33 abcd systemd-sleep[14314]:  setting standby to 36 (3 minutes)
Aug 13 20:23:32 abcd systemd-sleep[7730]: Suspending system...
Aug 13 21:01:35 abcd systemd-sleep[7730]: System resumed.
Aug 13 21:01:35 abcd systemd-sleep[7730]: /dev/sda:
Aug 13 21:01:35 abcd systemd-sleep[7730]:  setting Advanced Power Management level to 0x80 (128)
Aug 13 21:01:35 abcd systemd-sleep[7730]:  APM_level        = 128
Aug 13 21:01:35 abcd systemd-sleep[7730]: /dev/sda:
Aug 13 21:01:35 abcd systemd-sleep[7730]:  setting standby to 36 (3 minutes)
Aug 13 21:43:40 abcd systemd-sleep[3007]: Suspending system...
Aug 14 22:05:42 abcd systemd-sleep[3004]: Suspending system...
Aug 15 19:43:55 abcd systemd-sleep[2051]: Suspending system...
Aug 15 22:42:15 abcd systemd-sleep[2051]: System resumed.
Aug 15 22:42:16 abcd systemd-sleep[2051]: /dev/sda:
Aug 15 22:42:16 abcd systemd-sleep[2051]:  setting Advanced Power Management level to 0x80 (128)
Aug 15 22:42:16 abcd systemd-sleep[2051]:  APM_level        = 128
Aug 15 22:42:16 abcd systemd-sleep[2051]: /dev/sda:
Aug 15 22:42:16 abcd systemd-sleep[2051]:  setting standby to 36 (3 minutes)
Aug 16 15:16:11 abcd systemd-sleep[1405]: Suspending system...
Aug 16 17:13:51 abcd systemd-sleep[1405]: System resumed.
Aug 16 17:13:51 abcd systemd-sleep[1405]: /dev/sda:
Aug 16 17:13:51 abcd systemd-sleep[1405]:  setting Advanced Power Management level to 0x80 (128)
Aug 16 17:13:51 abcd systemd-sleep[1405]:  APM_level        = 128
Aug 16 17:13:51 abcd systemd-sleep[1405]: /dev/sda:
Aug 16 17:13:51 abcd systemd-sleep[1405]:  setting standby to 36 (3 minutes)
Aug 16 17:15:04 abcd systemd-sleep[1567]: Suspending system...
Aug 16 17:21:07 abcd systemd-sleep[1567]: System resumed.
Aug 16 17:21:07 abcd systemd-sleep[1567]: /dev/sda:
Aug 16 17:21:07 abcd systemd-sleep[1567]:  setting Advanced Power Management level to 0x80 (128)
Aug 16 17:21:07 abcd systemd-sleep[1567]:  APM_level        = 128
Aug 16 17:21:07 abcd systemd-sleep[1567]: /dev/sda:
Aug 16 17:21:07 abcd systemd-sleep[1567]:  setting standby to 36 (3 minutes)
Aug 16 17:23:47 abcd systemd-sleep[1681]: Suspending system...
Aug 16 17:23:54 abcd systemd-sleep[1681]: System resumed.
Aug 16 17:23:55 abcd systemd-sleep[1681]: /dev/sda:
Aug 16 17:23:55 abcd systemd-sleep[1681]:  setting Advanced Power Management level to 0xfe (254)
Aug 16 17:23:55 abcd systemd-sleep[1681]:  APM_level        = 254
Aug 16 17:24:00 abcd systemd-sleep[1767]: Suspending system...
Aug 16 17:24:06 abcd systemd-sleep[1767]: System resumed.
Aug 16 17:24:07 abcd systemd-sleep[1767]: /dev/sda:
Aug 16 17:24:07 abcd systemd-sleep[1767]:  setting Advanced Power Management level to 0xfe (254)
Aug 16 17:24:07 abcd systemd-sleep[1767]:  APM_level        = 254
Aug 16 17:25:51 abcd systemd-sleep[1860]: Suspending system...
Aug 16 17:25:59 abcd systemd-sleep[1860]: System resumed.
Aug 16 17:26:00 abcd systemd-sleep[1860]: /dev/sda:
Aug 16 17:26:00 abcd systemd-sleep[1860]:  setting Advanced Power Management level to 0xfe (254)
Aug 16 17:26:00 abcd systemd-sleep[1860]:  APM_level        = 254
Aug 16 17:26:03 abcd systemd-sleep[1942]: Suspending system...
Aug 16 21:35:51 abcd systemd-sleep[9438]: Suspending system...
Aug 18 15:42:35 abcd systemd-sleep[1988]: Suspending system...
Aug 18 16:25:37 abcd systemd-sleep[4224]: Suspending system...
Aug 18 17:22:14 abcd systemd-sleep[3314]: Suspending system...
Aug 18 18:54:59 abcd systemd-sleep[3314]: System resumed.
Aug 18 18:55:00 abcd systemd-sleep[3314]: /dev/sda:
Aug 18 18:55:00 abcd systemd-sleep[3314]:  setting Advanced Power Management level to 0x80 (128)
Aug 18 18:55:00 abcd systemd-sleep[3314]:  APM_level        = 128
Aug 18 18:55:00 abcd systemd-sleep[3314]: /dev/sda:
Aug 18 18:55:00 abcd systemd-sleep[3314]:  setting standby to 36 (3 minutes)
Aug 18 18:55:24 abcd systemd-sleep[3477]: Suspending system...
Aug 18 19:25:17 abcd systemd-sleep[1488]: Suspending system...
Aug 18 20:11:47 abcd systemd-sleep[1488]: System resumed.
Aug 18 20:11:48 abcd systemd-sleep[1488]: /dev/sda:
Aug 18 20:11:48 abcd systemd-sleep[1488]:  setting Advanced Power Management level to 0x80 (128)
Aug 18 20:11:48 abcd systemd-sleep[1488]:  APM_level        = 128
Aug 18 20:11:48 abcd systemd-sleep[1488]: /dev/sda:
Aug 18 20:11:48 abcd systemd-sleep[1488]:  setting standby to 36 (3 minutes)
Aug 18 20:11:50 abcd systemd-sleep[1625]: Suspending system...

So it does in fact resume after sleeping
Does anyone have any idea on what's wrong. Any help will be appreciated. Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get custom_meta_data I hope someone can help, I've been trying to get information from my custom fields plugin on Woocommerce (using it with WooCommerce subscriptions).
I am trying to capture the details so I can JSON POST it to another platform.
I have managed to hook into the active status of the subscription, get the details via $subscription variable, JSON decoded it and then captured my custom fields part found in the 'meta_data' array.
This is now saved into a variable called $orderdata.
The variable looks like
array (
  0 =>
  array (
    'id' => 20992,
    'key' => '_billing_parent_first_name',
    'value' => 'Father First Name',
  ),
  1 =>
  array (
    'id' => 20993,
    'key' => '_billing_parent_last_name',
    'value' => 'Father Last Name',
  ),
  2 =>
  array (
    'id' => 20994,
    'key' => '_billing_parent_email',
    'value' => 'father@test.com',
  ),
  3 =>
  array (
    'id' => 20995,
    'key' => '_billing_parent_number',
    'value' => '12345678',
  ),
  4 =>
  array (
    'id' => 20996,
    'key' => '_billing_childs_first_name',
    'value' => 'test',
  ),
  5 =>
  array (
    'id' => 20997,
    'key' => '_billing_childs_last_name',
    'value' => 'test',
  ),
  6 =>
  array (
    'id' => 20998,
    'key' => '_billing_childs_email',
    'value' => 'test@gmail.com',
  ),
  7 =>
  array (
    'id' => 20999,
    'key' => 'is_vat_exempt',
    'value' => 'no',
  ),
  8 =>
  array (
    'id' => 21000,
    'key' => 'thwcfe_ship_to_billing',
    'value' => '1',
  ),
)

My goal is to save each field like _billing_parent_number into a variable so I can ship it off using POST.
Does anyone know of a way I can capture the fields I need?
I have tried numerous methods, from array searches to array column (I'm using error_log to test in Wordpress so I can see the result).
I got close with the foreach loop but I do not know how to get the following field in the object and get it's value, next() in this case didn't work :(
Any help is appreciated!
add_action( 'woocommerce_subscription_status_active', 'get_details_add_bundle' );

function get_details_add_bundle($subscription) {

   $obj = json_decode($subscription, true);

    error_log($obj);

    $orderData = $obj['meta_data'];

    foreach($orderData as $key => $value) {
       if($key == 'key' && $value="_billing_childs_email"){
         error_log(next($orderData)[2]);
        }

}

A: I think you may be thinking about this is a bit too much with keys and values and such. The array you posted is an Array of Arrays. This means you can run through it with a foreach loop, and would need a subloop (or other methods) to access the keys and values - but you shouldn't even need to go that far.
If we create a new array (that you'll eventually POST, so I assume you want just key => value pairs), we can push values from the sub-arrays into it, since they're single dimensional, this makes it really easy!
$postable = array(); // Create a new array (we'll eventually POST this)

// get each sub array, one at a time
foreach( $orderdata as $data ){
    /* The $postable "key" will be the value of $data['key'], and the value
       pair for it will be the value of $data['value'] */
    $postable[$data['key']] = $data['value'];
}

Now that we've pushed each of these pairs into the $postable array, we end up with a simple key => value paired associative array:
array(#) {
  ["_billing_parent_first_name"] => string(17) "Father First Name"
  ["_billing_parent_last_name"]  => string(16) "Father Last Name"
  ["_billing_parent_email"]      => string(15) "father@test.com"
  /* … */
}

Here's a working example (using a truncated array for brevity): https://3v4l.org/kWQnB

A: I got the solution, thank you for the answers!
function get_details_add_bundle($subscription) {

    $obj = json_decode($subscription, true);
    $orderData = $obj['meta_data'];
    $values = wp_list_pluck( $orderData, 'key', 'value');

    foreach($values as $key => $value) {
        if ($value == 'billing_childs_email') {
          $child_email1 = $key;
        }

    }

}


text:
Q: Question regarding singularity of a complex function Consider the function
$$f(z) = {1 \over (z-i)(z+i)}$$
with a Laurent series expansion at $z_0=i$ on a domain $\;\Omega=\left\{z\in \mathbb{C}:2\lt\left|z-i\right|\right\}$
$$\begin{eqnarray}f(z)={1 \over (z-i)(z+i)}={1 \over (z-i)}{1 \over (z+i)}={1 \over (z-i)}{1\over(z-i)+2i} \\={1 \over (z-i)}{1 \over (z-i)}{1\over1-\left(-{2i\over z-i}\right)}\\={1 \over (z-i)^2}\sum_{n=0}^\infty\left(-{2i\over z-i}\right)^n\\=\sum_{n=0}^\infty (-2i)^n\left({1\over z-i}\right)^{n+2}\\=\sum_{n=-\infty}^{-2}\left(\frac i2\right)^{n+2}(z-i)^n\end{eqnarray}$$
Just to make sure I'm getting everything correct. Obviously we have a singularity at $z=i$, however cannot determine its type, as $i\notin \Omega$. Is it true that we can't determine the type of this singularity on the restricted domain as it doesn't lie in this domain?

A: Set $z=i+w$, then
$$f(z) = g(w)={1 \over w(w+2i)}=\frac{1}{2iw (1+(w/2i))}=\frac{1}{2iw}\left(1-(w/2i)+(w/2i)^2-(w/2i)^3+\cdots\right)$$
So $w=0$($z=i$) is a pole of $g(w) (f(z))$.


text:
Q: Making the whole row clickable I was trying to make a whole row of my tables on jsp page clickable for it i wrote following code in jsp page :
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.beans.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>MY DATA</title>

<%!Connection con; %>
<%!PreparedStatement s; %>
<%!ResultSet rs; %>

<% String name=request.getParameter("q");
//out.println(name);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:SharedCryptography", "fyp", "fyp");

String groupidd = request.getSession().getAttribute("groupid").toString();

//out.println(groupidd);
/*String sql="select * from tbIndividual where I_NAME like ? "
        + "and I_ID in "
        + "(select I_ID from TBWAITINDIVIDUALS "
        + "where GROUP_ID <> '"+groupidd+"')";
*/
String sql="select * from tbIndividual where I_NAME like ?";

s = con.prepareStatement(sql);
s.setString(1, name + "%");
rs=s.executeQuery();
}
catch(Exception e){
e.printStackTrace();
}
%>

ID
NAME
FIRSTNAME
LASTNAME

<% while(rs.next())
{ %>
<%String storid=rs.getString(1);%>
<tr class="clickableRow" href="individualdetailstoadd.jsp?personid=<%=storid%>">
<%=storid%>
<%=rs.getString(2)%>
<%=rs.getString(4)%>
<%=rs.getString(5)%>

<% } %>

And included

at top of the page and in clickablerow.js i wrote :
jQuery(document).ready(function($) {
  $(".clickableRow").click(function() {
        window.document.location = $(this).attr("href");
  });
});

Am I doing something wrong? As this is not working.

A: first of all, you can reduce your jQuery ready call to:
$(function() {
}

its the exact same.
now, i think you would want to delegate your click handler, meaning you attach it to the document instead, so the document will search for the clickable row and handle its click events:
$(function() {
  $(document).on("click",".clickableRow",function() {
        window.document.location = $(this).attr("href");
  });
});

A: href is a wrong attribute for tr
You can use the concept of data
Example:
Prefix href with data
<tr class="clickableRow" data-href="

Write JQuery as below
$(".clickableRow").click(function() {
        window.document.location = $(this).data("href");
});


text:
Q: Why am I able to switch user only using hyphen? If I try to switch the user using sudo su - kshitiz it works, and doesn't ask me for any password.
But if I do sudo su kshitiz it asks me for that user's password.
Why is this? I understand that hyphen loads that user's environment variables where's no hyphen keeps my own.
So then why does it ask me for target user's password when I want to switch while keeping my own variables, but not when I switch and load target's profile?

A: In recent util-linux releases, su and su -l use different PAM configurations – /etc/pam.d/su and /etc/pam.d/su-l respectively. It's possible that the latter configuration is either missing on your system, or doesn't have the usual pam_wheel module (which normally allows root to switch to any other user).
Just use sudo -s -u kshitiz or sudo -i -u kshitiz directly; the su is redundant.


text:
Q: Issue with Fragment on Android Developer Page I was reading the documentation on Fragment on the Developer site. I created a new project targeting api 8:android 2.2. I have the Android Support Library install, and I added the android support library to the project. I started implementing the helper method showDetails, and I get the red squiggly line saying that "a_item could not be resolved". I don't remember the instruction saying  create an a_item variable or add a layout with a_item id.
In addition, in the detail activity, I am getting an error message too. (getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();) It says "The method add(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, DetailsFragment)". Did I miss something in the instructions?
Here are my sample codes:
package com.example.fragmentlayout;

import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;

public class DetailsActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(getResources().getConfiguration().ORIENTATION_LANDSCAPE == Configuration.ORIENTATION_LANDSCAPE )
        {
            finish();
            return;
        }
        if(savedInstanceState == null)
        {
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
        }
    }

}

Here is the Titles Fragment:
package com.example.fragmentlayout;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class TitlesFragment extends ListFragment {
   boolean mDualPane;
   int mCurCheckPosition =0;
    String[] titles = {"Title 1", "Title 2", "Title 3"};
    String[] Details = {"Details for one", "Details for two", "Details for Three"};

    @SuppressLint("InlinedApi")
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, titles));

        View detailsFrame = getActivity().findViewById(R.id.fragment2);
        mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

        if(savedInstanceState != null)
        {
            mCurCheckPosition = savedInstanceState.getInt("curChoise", 0);
        }

        if(mDualPane)
        {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            showDetails(mCurCheckPosition);
        }
    }

   private void showDetails(int index) {

        mCurCheckPosition = index;
        if(mDualPane)
        {
            getListView().setItemChecked(index, true);
            DetailsFragment details = (DetailsFragment) getFragmentManager().findFragmentById(R.id.fragment2);
            if(details == null || details.getShownIndex() != index)
            {
                details = DetailsFragment.newInstance(index);
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                if(index ==0)
                {
                    ft.replace(R.id.fragment2, details);
                } else
                {
                    ft.replace(R.id.a_item, details);
                }
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }
        } else
        {
            Intent intent = new Intent();
            intent.setClass(getActivity(), DetailsActivity.class);
            intent.putExtra("index", index);
            startActivity(intent);
        }
    }

@Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        showDetails(position);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

}

Here is the detailsFragment:
package com.example.fragmentlayout;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

public class DetailsFragment extends Fragment {
    String[] Details = {"Details for one", "Details for two", "Details for Three"};
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if(container == null)
        {
            return null;
        }
        ScrollView scroller = new ScrollView(getActivity());
        TextView text = new TextView(getActivity());
        int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,4, getActivity().getResources().getDisplayMetrics());
        text.setPadding(padding, padding, padding, padding);
        scroller.addView(text);
        text.setText(Details[getShownIndex()]);
        return scroller;

    //  return super.onCreateView(inflater, container, savedInstanceState);
    }

    public static DetailsFragment newInstance(int index)
    {
        DetailsFragment f = new DetailsFragment();
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex()
    {
        return getArguments().getInt("index", 0);
    }
}

Here is the land and portrait layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <fragment
        android:id="@+id/fragment1"
        android:name="com.example.fragmentlayout.TitlesFragment"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/fragment2"
        android:name="com.example.fragmentlayout.DetailsFragment"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

</LinearLayout>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <fragment
        android:id="@+id/fragment1"
        android:name="com.example.fragmentlayout.TitlesFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

A: Perhaps, it's a mistake. The answer is here
https://code.google.com/p/android/issues/detail?id=54837
The author of linked message advises to replace code fragment
if (index == 0) {
    ft.replace(R.id.details, details);
} else {
    ft.replace(R.id.a_item, details);
}

with code fragment
if (index == 0) {
    ft.add(R.id.details, details);
} else {
    ft.replace(R.id.details, details);
}

or maybe just
ft.replace(R.id.details, details);

A: *

*Your DetailsActivity should extend FragmentActivity

*You should use getSupportFragmentManager()

*If you nest fragments into other fragments consider using getChildFragmentManager()
(ok, i didn't look through all of the code, so not sure if 3 is applicable)

A: You need to use getSupportFragmentManager instead of getFragmentManager, because you are using support fragments.
The R.id.a_item references the id of the layout in your layout file. Instead of android:id="@+id/fragment1", make it android:id="@+id/a_item"


text:
Q: Why can't I catch only checked exceptions in java It is knows that Runtime excpetions should not be caught (usually),
For example NullPointer.
But if I have a catch block that catches the general class - Exception (not recommended, I know) it will catch both checked and unchecked excpetions.
The thing I don't understand is this:
One can catch only Runtime Excpetions by writing:
catch(RuntimeException ex)
 but not only checked excpetions, why?
(I mean, what is the logic behind this?)
Why there is no class called Checked Exception in Java that all checked excpetions will be derived from (just like RuntimeExcpetion) so I will be able to catch only those exceptions?

A: You could always rethrow the RuntimeExceptions:
try {
  //code that throws
} catch (Exception e) {
  if (e instanceof RuntimeException) throw (RuntimeException) e;
  //handle checked exceptions here
}

But I fail to think of a situation where that may be needed.
Catching all exceptions like this is typically done at the highest level in your code such that unexpected exceptions (a) don't crash your app and (b) can be handled (showing a message to the user or logging something for example). In that case you probably want to catch all exceptions, checked and unchecked.


text:
Q: Executing the openssl command with the c system function is different from executing the openssl command output on the terminal I'm using MacOS/10.13
My code on terminal:
echo -n this | openssl enc -aes-128-cbc -K 0 -iv 0 -base64

c code:
int main(){
   system("echo -n this | openssl enc -aes-128-cbc -K 0 -iv 0 -base64");
}

Running ScreenShot

A: The echo command has the problem that its behavior is not portable between different shells or environments. It is better to use printf instead, which is portable. In your case, replace the echo -n statement with printf, resulting in the following code:
#include <stdlib.h>
int main() {
    system("printf this | openssl enc -aes-128-cbc -K 0 -iv 0 -base64");
}

Building and running:
$ gcc test.c -o test
$ ./test
gc8X3os/mFxDE73AebmweQ==

as desired.


text:
Q: Query for records which have date within this month or next month of any year I am looking to get all accounts which have Last_Opp_Date__c fall within THIS_MONTH or NEXT_MONTH of any year.
Here is the query i have written
select Id,Name,Shipping_Address_Latitude__c,Shipping_Address_Longitude__c,Shipping_Address_Accuracy__c,Last_Opp_Amount__c,Last_Opp_Date__c,Last_Activity_Date__c FROM Account WHERE  Status__c ='Prospect' AND (CALENDAR_MONTH(Last_Opp_Date__c) = THIS_MONTH OR CALENDAR_MONTH(Last_Opp_Date__c) = NEXT_MONTH)

This is the error I am getting which means that the calendar month is expecting a number
> ='Prospect' AND (CALENDAR_MONTH(Last_Opp_Date__c) = THIS_MONTH OR ^ ERROR at Row:1:Column:252 value of filter criterion for expression
> CALENDAR_MONTH(Last_Opp_Date__c) must be of type integer and should
> not be enclosed in quotes

Any thoughts on how to get the records that fall within this month or next month of any year.

A: You dont need to use Calendar_Month function.
SELECT Id,Name,Shipping_Address_Latitude__c,Shipping_Address_Longitude__c,
Shipping_Address_Accuracy__c,Last_Opp_Amount__c,Last_Opp_Date__c,Last_Activity_Date__c FROM Account WHERE  Status__c ='Prospect'
AND (Last_Opp_Date__c = THIS_MONTH OR Last_Opp_Date__c = NEXT_MONTH)

Refer Date Formats and Date Literals

*

*THIS_MONTH - Starts 00:00:00 on the first day of the month that the current day is in and continues for all the days of that month.

SELECT Id FROM Account WHERE CreatedDate < THIS_MONTH

*

*NEXT_MONTH - Starts 00:00:00 on the first day of the month after the month that the current day is in and continues for all the days of that month.

SELECT Id FROM Opportunity WHERE CloseDate = NEXT_MONTH

A: CALENDAR_MONTHexpects an Integer, so you need to compare it actually to the month numbers.
Integer this_month = Date.today().month();
Integer next_month = (this_month == 12)?1:this_month+1;
List<Account> accts = [SELECT ID
                       FROM Account
                       WHERE CALENDAR_MONTH(CreatedDate) = :this_month OR
                             CALENDAR_MONTH(CreatedDate) = :next_month];

A: By iterating for loop, we can get the records which have date either in
current month or next month irrespective of any year -

List<Position__c> li = [select Close_Date__c from Position__c];
List<Position__c> finalList = new List<Position__c>();
Integer month = System.today().month();
Integer nextMonth = month+1;
System.debug('month is '+month);
for(Position__c pos : li){
    if(pos.Close_Date__c != null && (pos.Close_Date__c.month() == month ||
       pos.Close_Date__c.month() == nextMonth) ){
       finalList.add(pos);
    }
}
System.debug('test finalList is '+finalList);


text:
Q: iOS MapKit userLocation returning zero on first call, but I have a curious issue that I can't explain and was wondering if anybody has encountered the same problem.
I have a MKMapView that displays the user's current location, and is written to center the region over that location when loaded. When I load the view, the map defaults to lat zero and long zero (somewhere in Africa). When I leave the view to the previous screen on the stack, and then go back to it everything works properly and I get a mapview centered over Cupertino, California as expected.
Can anyone explain this?
Cheers! :D

A: mapView.showsUserLocation=YES;

Its Working Device Perfect when ever Location manager unable to Track The Location Then Its Shows Default Location Thats lat zero and long zero so Its Shows In Africa.
Check In Device It Will Work Fine.

A: UserLocation try to get the coordinate after map view loaded.
before getting the value, user location always is (0,0)
So do not add the setregion method in viewdidload
add it into method fllowing:
func mapView(MKMapView, didUpdate: MKUserLocation)


text:
Q: Angular - routable modals with Root in it I'm trying to make a modal that displays product info with a tab system inside, which is driven by rooting.
My ultimate goal is to have a root that looks like that:
'productList/productId/tab1'
which would redirect to my product list with the  product's modal open at the right tab
I am fairly new to all that is root related and I tried many solutions without success. I would like to have some advice on how I could do this.
Thanks


text:
Q: "Explain me" "Describe me" sound unidiomatic to me Sometimes while I am watching movies or YouTube videos I hear phrases like "Explain me what it is" or "Describe me the dish".
I feel that those phrases sound a bit unidiomatic to me. Are those phrases correct?
If so, are there other verbs that skip the preposition "to"?

A: Are those phrases correct?
No. They are unidiomatic.
Correct:

Explain what it is to me.
Describe the dish to me.

Are there other verbs that skip the preposition "to"?
Yes. A lot of verbs that take both a direct object and an indirect object, allow the indirect object to appear first, without the preposition "to" (or sometimes "for"). That construct is called the dative alternation.
The term "alternation" suggests that the construct with the direct object first, followed by "to" (or sometimes "for") + the indirect object, is the "standard" construct.
But when the stress in more on the direct object than on the indirect object, and when the indirect object is short (such as a simple personal pronoun or a name), I would say that the dative alternation constuct is the preferred form.
Examples:

Show me the money. (also correct: Show the money to me.)
Give her the toy. (also correct: Give the toy to her.)
Lend him some change. (also correct: Lend some change to him.)
Tell us the truth. (also correct: Tell the truth to us.)
Ask me anything. (also correct: Ask anything to me.)
Read them a story. (also correct: Read a story to them.)
Write him a letter. (also correct: Write a letter to him.)
Teach him a lesson. (also correct: Teach a lesson to him.)
Promise her the moon. (also correct: Promise the moon to her.)
Do me a favour. (also correct: Do a favour for me.)
Make me a sandwich. (also correct: Make a sandwich for me.)
Buy her a ring. (also correct: Buy a ring for her.)

The dative alternation constuct does not work with all verbs that take both a direct object and an indirect object. It's unidiomatic to use it with the verbs announce, attribute, confess, convey, declare, dedicate, deliver, describe, explain, introduce, mention, narrate, present, propose, recommend, refer, return, reveal, say, sell, submit, suggest, transfer, …
(Or with the verbs accustom, answer, ascribe, compare, condemn, confine, contribute, exhibit, liken, …)
Counterexamples:
People might feel differently about some of these verbs. For instance, Jonathan Swift wrote to rev. dr. Thomas Sheridan:

If your worship will please to explain me this rebus, …

And Jordan Belfort, the Wolf of Wall Street, challenges a few audience members:

Sell me this pen.


text:
Q: Searching for partial path\filename in bat Ok, so I've been bating (hehe) my head against a wall here.
I am looking for an option/code that would allow me to search for a partial path and/or filename from a .bat script that I would export to an outside file.
Now, "search", "export" and "outside file" is something I am fine with. The part that is giving me a headache is the "partial".
To elaborate.
I am looking for a folder called DATA and a file called userinfo.txt inside DATA.
Those are constant. So the path I have is DATA\userinfo.txt
I am also 99% certain that this folder will be in D:\ but thats not a concern right now. Where ever it is I'll find it.
But I cannot figure out how to look for a partial path\filename for the life of me.
Reason I have specified that DATA\userinfo.txt is a constant is due to other folders ability to be named arbitrarily. So in my below example 01-12-2016 does not have to be named according to that convention. For USA it would most likely be named 12-01-2016. It is also sometimes named 20161201 or 20160112 or on top of all that has a letter prefix such as d01-12-2016. On that note DATA is always DATA, which is why I said DATA is constant in my search. Another thing that will be the same is the grandparent folder. When i say "same" i mean "shared" between the two applications. It does not mean it will always be named "program" as in my example below.
Googling this and using things I know has got me nowhere.
Reason I cannot simply use
where /r d: userinfo.txt

is that that specific command will return hundreds of results as there is a userinfo.txt created for every.single.day the program was running and is stored separately.
Alternatively - if there would be a way to comb trough those hundreds of results and find the matching part that would also resolve my issue.
This however brings up another headache as there is usually more than one program with this exact file.
so in the example of
d:\users\path\program\storage\01-12-2016\userinfo.txt
d:\users\path\program\otherstorage\01-12-2016\userinfo.txt
d:\users\path\program\storage\02-12-2016\userinfo.txt
d:\users\path\program\otherstorage\02-12-2016\userinfo.txt
d:\users\path\program\storage\03-12-2016\userinfo.txt
d:\users\path\program\otherstorage\03-12-2016\userinfo.txt
d:\users\path\program\storage\04-12-2016\userinfo.txt
d:\users\path\program\otherstorage\04-12-2016\userinfo.txt
d:\users\path\program\storage\05-12-2016\userinfo.txt
d:\users\path\program\otherstorage\05-12-2016\userinfo.txt
d:\users\path\program\storage\06-12-2016\userinfo.txt
d:\users\path\program\otherstorage\06-12-2016\userinfo.txt
d:\users\path\program\storage\data\userinfo.txt
d:\users\path\program\otherstorage\data\userinfo.txt

Note: storage, otherstorage, storageother, storage2, storagegh are all arbitrary names as these folders are named accoring to end-user wishes.
I would want to export two separate variables for
d:\users\path\program\storage

and
d:\users\path\program\otherstorage

I would also need to do this for \data\userinfo.txt
So if searching for \data\userinfo.txt it would return
d:\users\path\program\storage\data\userinfo.txt
d:\users\path\program\otherstorage\data\userinfo.txt

I would also want to isolate both
d:\users\path\program\storage

and
d:\users\path\program\otherstorage

and use it as (separate) local variables.
I would need to note that installing/downloading any external scripting tools/aids would not be a suitable solution as I work on a lot of computers, most of which I do not have internet access and/or sufficient permissions for external downloads/installations so anything that is not integrated into the bat and needs to be imported separately is a bad idea.
Also, I am working on Windows XP SP3 but I would need this bat to be able to run on XP SP2, XP SP3, Windows 7, Windows 10, Windows NT, Windows 2000.
Any help would be appreciated.
Please note that
d:\users\path\program

would also be an acceptable variable. In this case I would manually amend the remainder of the path or would rely on end-user (my coworkers) input to complete the path correctly. The last has proven to be a fools errand.
The way that I've been handling it until now is to look for a .exe that I KNOW will be in both folders. This is a part of my code below edited to match the current example.
@echo off
SETLOCAL
echo Program will now look for program.exe and programgh.exe. Please input, when asked, matching part of the path for these files.
echo Example:
echo d:\users\path\program\storage\bin\program.exe
echo d:\users\path\program\otherstorage\bin\programgh.exe
echo In above example matching part is d:\users\path\program so you would enter that when prompted
echo Please do not input the last pathing mark: \ (backslash)
echo -------------searching---------------
::I am exporting errors to nul as I don't want them to be spammed by errors and other data that they would think is their fault
where /r c: program*.exe 2>nul
where /r d: program*.exe 2>nul
where /r e: program*.exe 2>nul
where /r f: program*.exe 2>nul
set /p dualpath="Please enter matching paths for program folder: "

After that I would proceed to work with %dualpath% variable.
As it usually happens (to me at least) most people would just copy the example path without taking a look at what the program has spat out and would be confused as to why the program did not work. Either that or would copy everything up to program.exe and programgh.exe - including the otherstorage\bin\ without noticing that \storage\ and \otherstorage\ do not match.
I think this now covers all the comments or additional questions and clarifies a bit better what I need.  Thank you all for help so far and I hope that this is easier to understand.

A: If a Windows cmd command allows wildcards in a (partially or fully qualified) path then wildcards must be used only in the path leaf (i.e. the last item or container in the path). However, you could apply findstr regex to narrow command output e.g. as follows:
where /r d:\ userinfo.txt | findstr /I "\\storage2*\\data\\userinfo.txt"

above command wold narrow output to paths ending with \storage\data\userinfo.txt and \storage2\data\userinfo.txt
Another example - narrow output to paths ending with \storageX\data\userinfo.txt where X is either nothing or any decimal cipher [0-9]:
dir /B /S d:\userinfo.txt | findstr /I "\\storage[0-9]*\\data\\userinfo.txt"

Put the paths to environment variables (with _var prefix for easier next identification), e.g. _varstorage, _varstorage2, …
@ECHO OFF
SETLOCAL EnableExtensions
for /F "delims=" %%F in ('
  dir /B /S "d:\userinfo.txt" ^| findstr /I "\\storage[0-9]*\\data\\userinfo.txt"') do (
    for /D %%D in ("%%~dpF..") do (
        set "_var%%~nxD=%%~fD"
        rem             %%~fD        path
        rem      %%~nxD              last item in above path
        rem  _var                    variable name prefix
    )
)
rem show result:
set _var

See also next %%~nxD and %%~D explanation:  Command Line arguments (Parameters): Parameter Extensions

A: Based on your above sample this batch
@Echo off
Set Search=\\data\\userinfo.txt
pushd "D:\Users\path\program
For /f "Delims=" %%A in (
  'Dir /B/S/A-D userinfo.txt ^|findstr "%Search%$"'
) Do Call :Sub "%%~fA" "%%~dpA.."
Popd
Goto :Eof
:Sub FullName DrivePath
Echo Found  %~nx1
Echo in     %~dp1
Echo Granny %~nx2
Set "Granny=%~nx2"
Echo in     %~dp2
Echo -------

Should give this output (only partially tested)
Found  userinfo.txt
in     D:\Users\path\program\storage\data\
Granny storage
in     D:\Users\path\program\
-------
Found  userinfo.txt
in     D:\Users\path\program\storage2\data\
Granny storage2
in     D:\Users\path\program\
-------

The backslash in Search has to be doubled as it is an escape char for findstr

A: If I got your intention right, the following script should do what you want:
@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_ROOT=D:\" & rem "D:\", "D:\users",..., or "D:\users\path\program"
set "_FILE=userinfo.txt"

rem // Initialise index:
set /A "INDEX=1"
rem // Search for the specified file in the given root directory:
for /F "delims=" %%F in ('dir /B /S "%_ROOT%\%_FILE%"') do (
    rem // Iterate once over the grandparent directory itself:
    for /D %%D in ("%%F\..\..") do (
        rem // Resolve the path of the grantparent directory;
        set "ITEM=%%~fD"
        rem // Initialise flag (non-empty means not yet stored):
        set "FLAG=#"
        rem // Toggle delayed expansion to avoid trouble with exclamation marks:
        setlocal EnableDelayedExpansion
        rem // Iterate over all currently stored grantparent paths:
        for /F "tokens=1,* delims==" %%V in ('2^> nul set $ARRAY[') do (
            rem // Clear flag in case current grandparent has already been stored:
            if /I "!%%V!"=="!ITEM!" set "FLAG="
        )
        rem // Check flag:
        if defined FLAG (
            rem // Flag is empty, so current grandparent needs to be stored:
            set "$ARRAY[!INDEX!]=!ITEM!"
            rem // Transfer stored grandparent over localisation barrier:
            for /F "delims=" %%E in ("$ARRAY[!INDEX!]=!ITEM!") do (
                endlocal
                set "%%E"
            )
            rem // Increment index
            set /A "INDEX+=1"
        ) else endlocal
    )
)
rem // Retrieving final count of grandparent directories:
set /A "INDEX-=1"

rem // Return stored grandparent paths:
set $ARRAY[

endlocal
exit /B

This should return D:\users\path\programs\otherstorage and D:\users\path\programs\storage in your situation, which are stored in the variables $ARRAY[1] and $ARRAY[2], respectively. Due to the array-style variables, this approach is flexible enough to cover also cases where more than two grandparent directories are present.


text:
Q: dovecot+roundcube (different IP) How to set dovecot to allow plain auth for some IP? I have lxc-containers - one with roundcube, and one with dovecot. Because the ip are different disable_plaintext_auth = yes disallows plain connection from roundcube. I can't use ssl || tls because internal IP doesn't match ssl cert CommonName (external IP).
So, do yoy have idea how to enable plain for one ip?

A: I found the workaround - i'm not happy with this, but - works. I add external domain to /etc/hosts (external domain points to internal dovecot ip). So now ssl cert matches the request - so it works . It of course works worse than plain - but works. If someone will find better solution - i'd be happy.


text:
Q: Access variable set by Volley's onResponse I have two global variables currentTemp and currentHum that are set when Volley's onResponse method is called. My code looks like this:
// Request a string response from the provided URL.
    private JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, WEATHER_URL, null, new Response.Listener<JSONObject>() {
        public void onResponse(JSONObject response) {
            try {
                JSONObject main = new JSONObject(response.getString("main"));
                currentTemp = main.getString("temp");
                currentHum = main.getString("humidity");
                Log.i("RES", "Temp: " + main.getString("temp") + " Hum: " + main.getString("humidity"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }}, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(appContext, "An error occurred while retrieving weather info", Toast.LENGTH_LONG).show();
            Log.e("ERR", "ERROR RET WEATHER DATA");
        }
    });

    // Call the OpenWeatherMap API and get data such as temperature and humidity
    private String getWeatherInfo(String key) {
        // Add the request to the RequestQueue to invoke the API
        queue.add(jsonObjectRequest);
        // Access variables set by Volley's onResponse here.
        switch (key) {
            case "temp":
                return String.valueOf(Float.parseFloat(currentTemp) - 273.15);
            case "hum":
                return currentHum;
            default:
                return " ";
        }
    }

I want to be able to access the values of the global variables set by the onResponse method in the getWeatherInfo method that invoked it. Then pass the values to a switch statement for processing. How do I do it without getting empty values for currentTemp and currentHum?

A: This work is meant to be done with use of an interface. If you don't know about an interface callbacks then please go through this answer. Which will help you understand interface, and plus point that this will guide you for handling volley response.
Also this is not recommended to take global variables to set any response, rather you can pass your whole JsonObject from volley class. and parse it where you make a call. You can use Gson for parsing the response to your Model or ArrayList.


text:
Q: What causes the "Are you sure you want to do this?" error with plugins? This is an odd case I've run into.  A site I've had for years started throwing
this "error"  when i try to make certain backend changes.  It seems pervasive -
If i try to install, update, activate or deactivate any plugin.  I can still look at the list of plugins and view their settings, generally.
Any thoughts on where to start looking?

A: This particular message happens when a nonce check fails.
I'd say the likely cause is a conflict with the referer (as part of nonce security, WP checks to see if the referer was an admin page on the same domain & path).
You can rule this out by defining a custom function in wp-config.php:
function check_admin_referer($action = -1, $query_arg = '_wpnonce') {
    if ( -1 == $action )
        _doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' );

    $adminurl = strtolower(admin_url());
    $referer = strtolower(wp_get_referer());
    $result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
    if ( !$result && !(-1 == $action /* skip this: && strpos($referer, $adminurl) === 0 */) ) {
        wp_nonce_ays($action);
        die();
    }
    do_action('check_admin_referer', $action, $result);
    return $result;
}

This implements the standard nonce check, but skips the referer part. If it cures the error message, we've isolated the problem and can work towards a permanent fix.
Further reading on the two primary types of errors (this, and insufficient permissions).

A: I ran into this problem when implementing 'on_activation' code and needed to see my output mid-development.  Well, this is a big no-no and even with an 'exit' statement, wordpress (4) was showing "Are you sure you want to do this?" instead of my dump.  @TheDeadMedic's suggestion got pointed in the right direction, but didn't work in my particular case.  I put the following into my wp-config.php
 // =============== FOR DEVELOPMENT ONLY -BEGIN- ================
/* Stop Checking NONCE
Motivation: when trying to see the output in _deactivation, it would show.
*/
function check_admin_referer($action = -1, $query_arg = '_wpnonce') { //https://wordpress.stackexchange.com/a/60977/8972
    return true;  // honey badger don't care (if I'm in development)
}
// =============== FOR DEVELOPMENT ONLY -END- ================

This will basically kill a bunch of otherwise useful security stuff.
BTW - I was following this sample (https://wordpress.stackexchange.com/a/25979/8972) by @kaiser for activating a plugin.

A: I've discovered this can also happen if a check_admin_referer() function is being called with invalid arguments somewhere in your site. If you're getting this error and cant find the problem, check your use of check_admin_referer() throughout your theme and plugins.
I started getting this error right after I created a new admin options page for my theme. I had added a check_admin_referer() inside a new class, and accidentally swapped the 1st and 2nd parameters. I didn't get any error messages from the class itself, but it mysteriously started affecting the saving of options and profiles in pages that didn't even load or call the class I had created. Fixing my call to check_admin_referer() immediately solved the problem.

A: I have fix this issue in my site for set bellow value in php.ini file
memory_limit = 128M
upload_max_filesize = 80M
post_max_size = 80M

may be this useful.


text:
Q: encryption and decryption using certificates in C# I have a big XML that needs to be encrypted on one server (by one c# application), and needs to be decrypted on another server (by another c# application). The XML contains the critical  information for which this encryption needs to be done.
My real need is that my server that does the encryption should only know the public key and the private key is known only to the server which is doing the decryption. Also, this private key should be stored in a safe area on the server such as certificates.
What should be the steps that can help me achieve so?

*

*Can I generate my private key and store that in certificates or the certificates will generate the private key on their own?

*Also, if certificates generate the public and private key, can the public key be separated from the certificate and exported to the server where the encryption has to be done?

A: Asymmetric encryption is very processor intensive and, consequently very slow. For that reason, it is not normally used to encrypt large amounts of data.
What is normally done is symmetric encryption is used to encrypt the bulk of the data and asymmetric encryption (public key) is used to encrypt the keys used in the symmetric encryption.
The encrypted keys are transmitted with the encrypted data. The keys are decrypted (private key), then using the symmetric keys the bulk data is decrypted.

A: *

*How the key-pair and certificate are generated depends on the software used.

*The private key can be obtained from a certificate.
The general method is to encrypt data with a symmetric encryption algorithm such as AES and encrypting the symmetric key with asymmetric encryption algorithm such as RSA or EC and the public key. This is done for two reasons: 1. Asymmetric encryption is very slow compared to symmetric encryption. 2. The data length for Asymmetric encryption is limited by the key size: a typical key size is 2048-bits and that limits the data length to 245-bytes.
There is in general no way to securely store a private key (or anything) on the server other than the server being secure short of the server having an HSM or access to a TPM. The main step on making the server secure is 2-factor authentication. But if it is on a shared computer beware of root escalation exploits by other users of the server.
HSM - Hardware Encryption Module
TPM - Trusted Platform Module

A: This is how I have achieved it.
On my server 2, I am generating a certificate(.cer) and a private key(.pvk) using the 'makecert.exe' command. Then, using the 'pvk2pfx.exe',  I am generating a .pfx file. This is the file which will now house the certificate and private key.
Now I export the certificate with just the public key to the server 1, where I encrypt the data, and on Server 2 using the certificate's private key I decrypt the data.


text:
Q: My select option changes to null in AngularJS I don't know how to change this, but whenever I use my select option, it always goes to null.
This is my HTML code,
<select type="number" class="footer" id="chooser"
        ng-change="selectchange(selectedPage)"
        ng-model="selectedPage" min="1"
        ng-options="x for x in pages">
    <option value="" selected="false" hidden>
</select>

Is there any reason it changes to null. Because when it changes it sends another request to angular.
What is the problem here, and how to solve it?

A: Use this in html
<select class="footer" id="chooser" ng-change ="selectchange()" ng-model="selectedPage" ng-options="x in pages"></select>

And in your controller:
$scope.selectedPage = "1";
$scope.pages = [1, 2, 3, 4];
$scope.selectchange = function() {
  console.log("selectedPage changed to : ", $scope.selectedPage);
}

For more information read https://docs.angularjs.org/api/ng/directive/select

A: You have set the option value to null and it always selected by selected tag. So it select null value every time, remove that option value and use ng-options to set the options in your selected box. No need to use option tag.
<select type="number" class="footer" id="chooser"
    ng-change="selectchange(selectedPage)"
    ng-model="selectedPage" min="1"
    ng-options="x for x in pages">
<-- <option value="" selected="false" hidden> -->   // remove this line
</select>


text:
Q: Ayuda con Moodle 3.5 y sus extensiones estoy con un trabajo que me pidieron para una plataforma en moodle.. Tengo que hacer un plugin de envio masivo de correos automaticos a todos los alumnos que reprobaron el curso...
Lo que si, nunca en mi vida toque moodle pero igual acepte el trabajo... Lo primero que hice fue descargar moodle en mi maquina para trabajar... despues empece a descargar algunos plugins como por ejemplo Quick mail para ver su funcionamiento. Pero ya no puedo avanzar desde aqui.. cuando instalo el plugin no encuentro donde utilizarlo, en todos los tutoriales y docuemntacion que vi me deberia aparecer como un bloque en la derecha de mi maquina.. alguna ayuda o consejo??
Estoy usando moodle 3.5


text:
Q: Windows Media Creation Tool is requiring 8GB PenDrive for 32 bit version of Windows 10 Windows Media Creation tool is not allowing to create Windows 32 bit media on 4GB PenDrive.
On Creators update I could do this normally on 4GB Pen Drive. Now on Fall Creators Update, the Media Creation Tool is requiring 8GB PenDrive for 32bit only image!
I need to reinstall Windows on my 32 bit tablet using a 4GB pendrive;
See https://social.technet.microsoft.com/Forums/en-US/dac269a9-168e-476a-84a5-415d75b09cba/windows-media-creation-tool-is-not-allowing-to-create-windows-32-bit-media-on-4gb-pendrive?forum=win10itprosetup
Ps:
I tried using Rufus 2.18p to Write the 32 Bits ISO on the PenDrive, using options GPT UEFI FAT32, but the Tablet does not boot from it.
If I use MBR UEFI-CSM, the tablet boots to the Windows installer, but after copy finishes, the Tablet boots to UEFI Shell. Only can enter Windows manually typing commands, see: After a clean installation of Windows 10 Fall Creators Update - 32 bits, only boots in EFI Shell, cannot boot automatically


text:
Q: Is it correct the approach of fractions in finding the weight of an object in another planet? The problem is as follows:

A body has a weight of $w$ in the surface of the Earth. If the object
  is transported to a planet whose mass and radius is two times that of
  the Earth. Find its weight.

$\begin{array}{ll}
1.&4w\\
2.&2w\\
3.&\frac{w}{2}\\
4.&\frac{w}{4}\\
5.&w\\
\end{array}$
How should I calculate the weight of this object?.
On earth the only force acting in the object is given by the weight:
$F=mg=w$
And the gravitational force between two masses is given by:
$F=G\frac{m_1m_2}{r^2}$
Since it mentions that this object is moved to a planet which it has a radius which is two times that of the Earth and a mass double that of Earth then this becomes as:
$F_{2}=G\frac{m_1\cdot 2 m_2}{(2r)^2}=\frac{1}{2}G\frac{m_1m_2}{r^2}$
Therefore:
$w_{Planet}=\frac{1}{2}w_{Earth}$
But this doesn't make sense. What could I be doing wrong?. Shouldn't be the opposite. I mean two times that of the weight from Earth?. Can someone help me here?.

A: If density were constant, (it isn't, but lets start there.)
Mass is proportional to volume.  Volume increases with the cube of radius.
If we call this alien planet, planet $X,$ we can say about its mass: $m_X = 8m_E$
As for gravity.
$g = G\frac {m_X w}{d^2}$
$d$ is $2\times$, $d^2$ is $4\times$, and $\frac{m_X}{d^2}$ is double earth gravity.
But density is not constant.  $m_X = 2m_E.$  The density is $\frac 14$ earth density.
$g = G \frac{m_X w}{(2d)^2} = \frac 12 \frac{m_E w}{d^2}$
Gravity is less because the density is so much lower.

A: Wikipedia's Shell theorem article states:

Isaac Newton proved the shell theorem and stated that:

*

*A spherically symmetric body affects external objects gravitationally as though all of its mass were concentrated at a point at its centre.

Also, the density can vary, but only based on the distance from the center. Earth matches this ideal fairly closely, and I guess it's to be assumed so does this other planet. This means you can reasonably treat earth, and the other planet, to be point masses at their centers. Note this is why you're able to use the formula for the gravitational forces between $2$ masses, i.e., $F=G\frac{m_1m_2}{r^2}$, using the planets as a whole, instead of treating each bit of mass on its own.
Using this center point masses concept, the mass of the other planet being double means that, if the radius were the same, the weight on this planet would be double that of the same object on earth. However, the radius being double that of earth means, since the force of gravity is inversely proportional to the square of the distance, the gravity would be a factor of $\left(\frac{1}{2}\right)^2 = \frac{1}{4}$ that of earth. Thus, overall, any object's weight would be $2\left(\frac{1}{4}\right) = \frac{1}{2}$ that of earth, as you correctly determined, i.e., that $w_{\text{Planet}}=\frac{1}{2}w_{\text{Earth}}$.

A: The new $g'$ would change by a factor of $M/R^2=2/2^2=1/2$, so $g'=g/2$ and $w'=w/2$.


text:
Q: Neo4j Python Driver Using Unwind with a list of dictionaries I'm trying to batch merge to create multiple nodes. Using the below code,
def test_batches(tx,user_batch):
            result= tx.run(f"Unwind {user_batch} as user\
                           MERGE (n:User {{id: user.id, name: user.name, username: user.username }})")

However I am getting this error.
Note I'm passing in a list of dictionaries.
CypherSyntaxError: {code: Neo.ClientError.Statement.SyntaxError} {message: Invalid input '[': expected "+" or "-" (line 1, column 8 (offset: 7))
"Unwind [{'id': 1596859520977969156, 'name': 'Bigspuds', 'username': 'bigspuds777'}, {'id': 1596860505662144513, 'name': 'JOHN VIEIRA', 'username': 'JOHNVIE67080352'}, {'id': 1596860610905448449, 'name': 'biru nkumat', 'username': 'NkumatB'}, {'id': 1513497734711738374, 'name': 'elfiranda Hakim', 'username': 'Kidonk182'}, {'id': 1596836234860859392, 'name': 'Ecat Miao', 'username': 'sylvanasMa'}] as user                           MERGE (n:User {id: user.id, name: user.name, username: user.username })"
        ^}

I have no idea why this is happening any help is greatly appreciated.

A: Below is a working code on using UNWIND for a list of dictionaries.  Please note that is it recommended to pass the value as a parameter rather than working on the value string in query.
from neo4j import GraphDatabase

uri = "neo4j://localhost:7687"
driver = GraphDatabase.driver(uri, auth=("neo4j", "awesomepassword"))

def test_batches(tx, user_batch):
    tx.run("UNWIND $user_batch as user \
            MERGE (n:User {id: user.id, name: user.name, username: user.username})", user_batch=user_batch)

with driver.session() as session:
    user_batch = [
                 {'id': 1596859520977969156, 'name': 'Bigspuds', 'username': 'bigspuds777'},
                 {'id': 1596860505662144513, 'name': 'JOHN VIEIRA', 'username': 'JOHNVIE67080352'},
                 {'id': 1596860610905448449, 'name': 'biru nkumat', 'username': 'NkumatB'},
                 {'id': 1513497734711738374, 'name': 'elfiranda Hakim', 'username': 'Kidonk182'},
                 {'id': 1596836234860859392, 'name': 'Ecat Miao', 'username': 'sylvanasMa'}]
    session.write_transaction(test_batches, user_batch)

driver.close()

sample result:

A: You may need to adjust the syntax of the Cypher query to conform to the Neo4j Cypher query language specification. For example, the MERGE clause should use the ON CREATE and ON MATCH syntax to specify the actions that should be taken if the node already exists or not.
Here is an example of how the Cypher query can be rewritten to use the ON CREATE and ON MATCH syntax:
def test_batches(tx,user_batch):
    result = tx.run(f"UNWIND {user_batch} as user
    MERGE (n:User {{id: user.id, name: user.name, username: user.username }})
    ON CREATE SET n = user
    ON MATCH SET n += user")


text:
Q: How to distinguish UITextFields in delegate methods? I have the following code:
class ViewController: UIViewController, UITextFieldDelegate {

    // MARK: Properties
    @IBOutlet weak var layersTextField: UITextField!
    @IBOutlet weak var innerShapeTextField: UITextField!
    @IBOutlet weak var outerShapeTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        layersTextField.delegate = self
        innerShapeTextField.delegate = self
        outerShapeTextField.delegate = self
    }

    // MARK: UITextFieldDelegate
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

    func textFieldDidEndEditing(textField: UITextField) {
        // do something
    }

}

Now in textFieldDidEndEditing(_:) I would like to do something, dependent on which UITextField called this method.
Is there any way to distinguish, which UITextField did this? Is there some kind of ID or identifier I can set on the UITextFields?

A: You can make this determination using one of two approaches: outlets or tags. For the outlet approach, declare an outlet instance variable (using the IBOutlet keyword) and then make an outlet connection. In your delegation method, test whether the passed-in text object is the same object referenced by the outlet, using pointer comparison.
For example, say you declare and connect an outlet named SSN. Your code might look something like Listing 3-1:
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if (textField == SSN) {
        // ...
        return NO;
    }
    return YES;
}

// Translated to Swift:

func textFieldShouldEndEditing(textField: UITextField) -> Bool {
    if textField === SSN {
        // ...
        return false
    }
    return true
}

A: You can check by the name of the next filed. if textField == layersTextField { //do what you want } and you can do that for any text field you need a specific action for.

A: You can create an IBAction instead:


text:
Q: Operator '<=' is not defined for type 'Date' and type 'DBNull' I have been trying to figure this out. I keep getting an error on DateRcvReal if the cell is empty. I am comparing two fields by using <= and some of the DateRcvReal are empty cells which throws an error of Operator '<=' is not defined for type 'Date' and type 'DBNull' how do I get around this. Still new at VB.net
If e.VisibleIndex > -1 And e.DataColumn.FieldName.StartsWith("DateProm") Then
                If IsDate(CType(sender, ASPxGridView).GetRowValues(e.VisibleIndex, New String() {"DatePromReal"})) Then
            If (CType(sender, ASPxGridView).GetRowValues(e.VisibleIndex, New String() {"DatePromReal"}) <= CType(sender, ASPxGridView).GetRowValues(e.VisibleIndex, New String() {"DateRcvReal"})) Then

                e.Cell.BackColor = Drawing.ColorTranslator.FromHtml("#F42121")
                e.Cell.ForeColor = Drawing.Color.White

            End If

A: Try this is not isDBNULL function
IF NOT IsDbNull((CType(sender, ASPxGridView).GetRowValues(e.VisibleIndex, New String() {"DatePromReal"})) AndAlso
(CType(sender, ASPxGridView).GetRowValues(e.VisibleIndex, New String() {"DatePromReal"}) <= CType(sender, ASPxGridView).GetRowValues(e.VisibleIndex, New String() {"DateRcvReal"})) Then

A: The easiest way is to put your code inside a try/catch block, let it throw the error on the bad comparison, then do whatever is appropriate in the catch block (ignore the error, log it, complain, etc.)
A better way is to test the cell contents for null before using them, and use the catch block to trap truly unexpected conditions.
Also, be careful of comparing booleans with null fields. VB makes assumptions about booleans and nulls so it considers null and false to be equal.
In short, make sure there's a sane value in the cell (not null, not an empty string, not nothing) before trying to compare it to something.


text:
Q: $S, T$ be multiplicatively closed sets in the ring $R$, such that $S \subseteq T$ Show that the following are equivalent Let $S, T$ be multiplicatively closed sets in the ring $R$, such that $S\subseteq T$.
Let $\varphi : S^{−1}R \to T^{−1}R$ be the homomorphism which maps each $r/s \in S^{−1}R$ to $r/s$ viewed as an element of $T^{−1}R$. Show that the following are equivalent:

(i) $\varphi$ is a bijection;
(ii) $t/1$ is a unit in $S^{−1}R$ for all $t\in T$;
(iii) for all $t\in T$ there exists $r\in R$ such that $rt\in S$;
(iv) every prime ideal of $R$ which meets $T$ also meets $S$.

A: Hints: The equivalence of (i) and (ii) is an easy consequence of the universal property of localizations. The equivalence of (ii) and (iii) follows from the usual explicit description of $S^{-1} R$. The equivalence of (ii) and (iv) follows from the characterization of prime ideals in localizations.
I hope that - this time - no complete solution is posted here, so that this exercise will remain an exercise.


text:
Q: How to rollback and make new branch from rollback point I have git project like this below
% git --log

commit 39b6b1d894d0788fdfc09947e1a5f88bf962b142 (HEAD -> master, origin/master, origin/HEAD)
Author: whitebear man <whitebear@whitebearnoMacBook-Air.local>
Date:   Wed Nov 9 15:29:13 2022 +0900

    all

commit 2656df9fb80b5085b4e7a50032712b13e3c407c9
Author: whitebear man <whitebear@whitebearnoMacBook-Air.local>
Date:   Thu Oct 13 13:48:36 2022 +0900

    all

commit d72472d00c649fdc04805d10c856d729e114a014
Author: whitebear man <whitebear@whitebearnoMacBook-Air.local>
Date:   Wed Oct 12 18:23:28 2022 +0900

    all

commit 0878cd86de3a939e8c99e33676abcfe1cfd14daa
Author: whitebear man <whitebear@whitebearnoMacBook-Air.local>
Date:   Tue Oct 11 11:38:58 2022 +0900

    all

commit 21c78ba8cfb811e1ad7dfb035ef5236e619f5d53
Author: whitebear man <whitebear@whitebearnoMacBook-Air.local>
Date:   Mon Oct 10 15:55:48 2022 +0900

    all

commit 9568b4b53fd14febc1ed100efcc6d412d0668471
Author: whitebear man <whitebear@whitebearnoMacBook-Air.local>
Date:   Mon Oct 10 15:37:27 2022 +0900

    all

Now I want to roll back commit 21c78ba8cfb811e1ad7dfb035ef5236e619f5d53 and make new branch.
However I want to keep the latest commit 39b6b1d894d0788fdfc09947e1a5f88bf962b142 as master.
I should rollback and make new branch?
or make new branch and rollback??

A: You could just create a new branch from the 21c78ba8 commit:
git branch new_branch 21c78ba8

A: @Tim's answer is a good point if you don't really want to rollback. If, however, you really want/need to revert what was done in 39b6b1d894d0788fdfc09947e1a5f88bf962b142, this is the simplest way to do it:
git revert 39b6b1d894


text:
Q: Turn off XP Theme in VS2008 compiled MFC App We've just recently switched our C++ MFC Application from VS2005 to VS2008. Unfortunately in doing so our UI has appearance problems, with things like group boxes appearing blue rather than black, properties dialogs having a white background etc. I presume that in VS2008, MFC has been changed to respect the OS theme (in my case XP default theme). Unfortunately, changing all our controls and our custom toolbars to make the app look decent again is going to require a lot of work.
So, does anyone know if there is a way in code to put the app back in VS2005 mode? I found the following code
typedef void (WINAPI *tSetThemeAppProperties)(  DWORD );

tSetThemeAppProperties pSetThemeAppProperties=0;
HINSTANCE  handle  = ::LoadLibrary("UxTheme.dll");

if (handle)
    pSetThemeAppProperties = (tSetThemeAppProperties) ::GetProcAddress(handle,"SetThemeAppProperties");

if ( pSetThemeAppProperties)
{
    // call function
    pSetThemeAppProperties(0/*dwFlags*/);
}
::FreeLibrary(handle);

Which does stop the XP theme being picked up, but turns off ALL themes and leaves the application looking more dated than it did in VS2005.
thanks

A: It may be that VS2008 is including a Manifest file in the project that loads the version 6.0 comctl32.dll rather than the 5.82 comctl32.dll... both ship with Windows XP and newer.

A: Under "Properties->Configuration Properties->Linker->Manifest File", set the "Generate Manifest" option to "No".
Then add your own manifest file if you like, and set it under "Properties->Configuration Properties->Manifest Tool->Input and Output", "Input Resource Manifest".
Just make sure that if you add your own manifest file that it doesn't contain the reference to commctl32 v6.


text:
Q: Can an Android app auto-upgrade itself? The device my Android app is running does not have Playstore on it. The plan is to pre-install the software when shipping the device. I am now looking for a strategy to upgrade the application.
I found this useful link to install an Android app from the apk file:
Android: install .apk programmatically
I am thinking I will use this logic to auto-upgrade my app. I am wondering if it is even possible. I am thinking the upgrade will first try to uninstall existing version but will fail as the executable is still running and the file may be locked. Is there a better way? Regards.

A: Peter, we've just implemented the same thing.
Users have the software pre-installed on their device and we host update APK's on the companies servers.
From the app they can then check for updates where we have a WCF service which extracts the APK file (essentially a .zip) and returns the manifest details. From there we have the version of the APK and can compare it against the local version.
If the user decides to upgrade they can download the APK and you can automatically launch it. At which point the user will be told the application is going to be updated. There are no file locks etc, the app will just close and restart using the new version.
Note: Downgrading is not "automatic". The user would have to first uninstall the app. For upgrades, however, it's a simple case of downloading and launching the APK version (the user will be told they need to allow installations from unknown sources if this is not checked).

A: You have a couple of options, depending upon your target system.

*

*Use the link you posted. This will provide the user with a traditional install dialog, whereby the user can choose to install or not. You should avoid doing that automatically, as APKs can be large and you might irritate the user if they don't want updates.

*You can install updates magically, but you will require the firmware signing key (or possibly root, but I haven't tested that). That will not ask for consent from the user. You will need to add additional code using reflection to access the installation methods of Android. If you go this way, you should build an opt-out/in mechanism.

A: If your app is open-source, F-Droid would solve the problem for you.

F-Droid is an installable catalogue of FOSS (Free and Open Source
  Software) applications for the Android platform. The client makes it
  easy to browse, install, and keep track of updates on your device.

Mainly, it updates your app when necessary. (Or just have a look at its source code for inspiration on how to do it).

A: Yes but as far as I remember only if you had Root privileges in order to have access to the INSTALL_PACKAGES permission.


text:
Q: Google Drive API upload Fails after hosting it to IIS. showing the error as Failed to launch the Browser with I am using google external login in my application, and I need a functionality that user can upload images from the application to his google drive.
In my localhost code the google drive file uploading functionality working fine, after hosting it to IIS user unable to upload the image.
I have created an error log file. in that I found the below exception:

System.AggregateException: One or more errors occurred. ---> System.NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=347588538121-jeali0jufd389gqsi4ge22ent3939b4m.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A60931%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive" for authorization. See inner exception for details. ---> System.ComponentModel.Win32Exception: Access is denied

In the redirect_uri I found "localhost". but after hosting it should be www.abc.com, and the port number is also always varying here.
Tried in many ways from the stachoverflow and other websites. but did not find the solution.
Please help me to resolve this.
Thanks.
Tried with
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
    obj,
    Scopes,
    "user",
    CancellationToken.None,
    new FileDataStore(AppDomain.CurrentDomain.BaseDirectory + "Daimto.GoogleDrive.Auth.Store")
).Result;

and also with:
using (var stream = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "credentials.json", FileMode.Open, FileAccess.Read))
{
    // The file token.json stores the user's access and refresh tokens, and is created
    // automatically when the authorization flow completes for the first time.
    string credPath = AppDomain.CurrentDomain.BaseDirectory + "token.json";
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        Scopes,
        "user",
        CancellationToken.None,
        new FileDataStore(credPath, true)).Result;
}

A: You are using GoogleWebAuthorizationBroker.AuthorizeAsync which is designed for use with installed applications. It spanws the web browser on the machine that it runs on. This will work fine when you are working locally but it will fail when you try to run it on a server as you dont have access to spawn a browser on the server (not that it would help as the user will not see it)
what you should be using is something like this
private static readonly IAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId = "PUT_CLIENT_ID_HERE",
                    ClientSecret = "PUT_CLIENT_SECRET_HERE"
                },
                Scopes = new[] { DriveService.Scope.Drive },
                DataStore = new FileDataStore("Drive.Api.Auth.Store")
            });

A full example can be found here Web applications (ASP.NET MVC)


text:
Q: How to increase number in variable each time a button is clicked in php I am creating a shopping cart which I have created using php. I have two buttons that when clicked allow the user to increase or decrease the quantity of the item.
When the user clicks the plus button the quantity goes up by one, however if they click it again nothing happens. is there a way that I can allow the user to say click the button until the quantity goes up to 20?
Here is my code:
This first part of my code checks to see if the original add to cart button has been clicked on an item. If it is it then gets the ID of the item. Once the item ID has been revived it them checks if a cart session has been created. If no shopping cart session has been found then it will create one. Once the session has been create it will then check for the quantity that has been add to the form. Next it creates an array call item which will hold the ID and quantity for the item.
if(isset($_POST['add_to_cart']) && isset($_GET['id'])) {
    $id = $_GET['id'];

    // Check if there is a session for the cart set already, if not then set one.
    if(!isset($_SESSION['shoppingcart'])) {
        $_SESSION['shoppingcart'] = [];
    }

    $quantity = $_POST["amount"];

    $item = [
        "id"        => $id,
        "quantity"  => $quantity
    ];
    }

Next on the cart file the code checks if there is a cart session and that there is at least one item. If there is at least one item in the cart then the code will one a for each loop to get each item from the database.
if(isset($_SESSION['shoppingcart']) && count($_SESSION['shoppingcart']) != 0) {
    $list = $_SESSION['shoppingcart'];
$total = 0;
    foreach($list as $item) {
        $id = $item['id'];

        $query = "SELECT * FROM item WHERE ItemID = '$id'";

        $result = mysqli_query($mysqli, $query);

    $row = $query_result->fetch_assoc();

        if (mysqli_num_rows($result) == 1){
            $row = mysqli_fetch_array($result);

            $id = $row['ItemID'];
            $name = $row['ItemName'];
            $image = $row['ItemImage'];
            $price = $row['Price'];
            $size = $row['Size'];
            $quantity = $item['quantity'];

        $subtotal = $price*$quantity;
        $total += $subtotal;

            ?>

HTML:
<form action="#" method="post">

Quantity:

  <input type="submit" value="+" name="plus" id="plus" />
  <input type="text" class="form-control" id="quanitiy" name="quantity" value= <?php echo "$quantity"; ?>>
  <button type="submit" name="minus"></button>
</form>

PHP:

<?php
if(isset($_POST['plus']) && ($quantity < 20)){
    $_SESSION['quantity'] = $quantity++;
} ?>

I know that this code is in victim of sql injections, I will be fixing it once I get this part working.

A: $quantity doesn't seem to actually be defined anywhere in your code. It's a bit unclear how even the first increment works, based on what you've shown. Perhaps you omitted some detail from the question?
Based on the information available though, this would seem to be more logical:
<?php
session_start();

if(isset($_POST['plus'])) {
   $quantity = (isset($_SESSION['quantity']) ? $_SESSION['quantity'] : 0);

   if ($quantity < 20) {
     $quantity++;
     $_SESSION['quantity'] = $quantity;
   }
}

This will check for an existing value, and use that as the starting point to increment from. If there's no existing value it will start from 0.


text:
Q: HTML Page that talk with a Python Server I have a web server that manages the GPIO Pin of the Raspberry Pi but when I Start the server I have to click two times on the div to start the led..
What could be the problem? This is the code of the html page that I have write to manage the led


text:
Q: JQuery Swap input values in rows I am working on a table that I need to be able to move rows up and down.
The problem is that I cannot re-insert the row before the previous or next row, because my application relies on the names of the input fields to stay in the same order.
My solution is to swap the values of the input fields, which works, but my code is very ugly and repetitive.
$(document).ready(function(){
    $(".up,.down").click(function(){
        var row = $(this).parents("tr:first");
        var rowdata1 = row.find('.rowdata1').val();
        var rowdata2 = row.find('.rowdata2').val();
        var rowdata3 = row.find('.rowdata3').val();
        var rowdata4 = row.find('.rowdata4').val();
        var rowdata5 = row.find('.rowdata5').val();

        if ($(this).is(".up")) {
            var tmp1 = row.prev().find('.rowdata1').val();
            var tmp2 = row.prev().find('.rowdata2').val();
            var tmp3 = row.prev().find('.rowdata3').val();
            var tmp4 = row.prev().find('.rowdata4').val();
            var tmp5 = row.prev().find('.rowdata5').val();

            row.prev().find('.rowdata1').val(rowdata1);
            row.prev().find('.rowdata2').val(rowdata2);
            row.prev().find('.rowdata3').val(rowdata3);
            row.prev().find('.rowdata4').val(rowdata4);
            row.prev().find('.rowdata5').val(rowdata5);

            row.find('.rowdata1').val(tmp1);
            row.find('.rowdata2').val(tmp2);
            row.find('.rowdata3').val(tmp3);
            row.find('.rowdata4').val(tmp4);
            row.find('.rowdata5').val(tmp5);
            //row.insertBefore(row.prev());
        } else {
            var tmp1 = row.next().find('.rowdata1').val();
            var tmp2 = row.next().find('.rowdata2').val();
            var tmp3 = row.next().find('.rowdata3').val();
            var tmp4 = row.next().find('.rowdata4').val();
            var tmp5 = row.next().find('.rowdata5').val();

            row.next().find('.rowdata1').val(rowdata1);
            row.next().find('.rowdata2').val(rowdata2);
            row.next().find('.rowdata3').val(rowdata3);
            row.next().find('.rowdata4').val(rowdata4);
            row.next().find('.rowdata5').val(rowdata5);

            row.find('.rowdata1').val(tmp1);
            row.find('.rowdata2').val(tmp2);
            row.find('.rowdata3').val(tmp3);
            row.find('.rowdata4').val(tmp4);
            row.find('.rowdata5').val(tmp5);
            //row.insertAfter(row.next());
        }
    });
});

I created a fiddle: http://jsfiddle.net/29T7V/
I would really appreciate any suggestions on how to simplify my code.
Any ideas on how to update my code to handle x amount of inputs in the rows would be absolutly awesome! TIA!

A: Something like this maybe
$(document).ready(function () {
    $(".up, .down").on('click', function () {
        var row = $(this).closest('tr').first(),
            way = $(this).hasClass('up') ? 'prev' : 'next';

        for (var i=1; i<6; i++) {
            var sel  = '.rowdata'+i,
                tmp1 = row.find(sel).val(),
                tmp2 = row[way]().find(sel).val();

            row.find(sel).val(tmp2);
            row[way]().find(sel).val(tmp1);
        }
    });
});

FIDDLE

A: Something wich would work with any number of columns:
$(document).ready(function () {
    $(".up, .down").click(function () {

        var $row = $(this).closest("tr"),
            $swap = $row[$(this).is('.up') ? 'prev' : 'next']();

        if (!$swap) return;

        $row.find('td').each(function() {
            var $input = $(this).find('input, select'),
                $swapInput, $swapVal;
            if ($input.length) {
                $swapInput = $swap.children('td:eq(' + this.cellIndex + ')').find('input, select');
                $swapVal = $swapInput.val();
                $swapInput.val($input.val());
                $input.val($swapVal);
            }
        });
    });
});

Demo: http://jsfiddle.net/29T7V/


text:
Q: Rails + Vue.js - Using Ajax to update Vue component I have a Rails 5 app using webpacker that displays a list of users. The logic to do so is in a partial that has Vue component code in it, like
<profile_modal>

  <template slot="trigger">

      <img src="<%= person.avatar.url %>" alt="">

...

Everything works well, and the .erb changes this correctly to HTML when the page is processed. So far so good.
Now I've added a button that says "show more users" that makes an ajax call to pull in more users. I've made a js.erb that has in it:
$("#users").html("<%= escape_javascript(render partial: 'layouts/components/profile-card--modal', collection: @users.last(12), as: :person, locals: { content: @users_presenter.profile_modal }) %>");

This code is executed, but instead of converting the "profile_modal" to the right html, rails is just inserting it right in the page, which makes everything wrong.
Is there a way I can have the vue code be transpiled into the html it would become during normal, non-ajaxy processing?

A: You shouldn't call a render for a whole component, you should instead make a global component that receives an array of users as variable, something in the lines of:
window.users = [
  { id: 'this-is-an-id', name: 'Evan', age: 34 },
  { id: 'unique-id', name: 'Sarah', age: 98 },
  { id: 'another-unique-id', name: 'James', age: 45 },
];

    {{ person.name }} - {{ person.id }}

Then when you change the users variable, your Vue component will change too. So instead of overriding the whole HTML for the component, make you .js.erb append to users variable:
response_users = <%=j @users.last(12).as_json %>;
Object.assign(users, response_users);


text:
Q: Docker как подключиться к контейнеру? У меня установлена windows 10 и докер на ней. В докере создал контейнеры MariaDB и adminer.
Запустил так docker run --link mysqlserver:db -p 8080:8080 adminer
Пытаюсь зайти через браузер 127.0.0.1:8080 не получается
Пытаюсь 192.168.99.100:8080 не получается
Пытаюсь 172.17.0.3:8080 не получается
Так как я могу подключиться к adminer?

A: По умолчанию docker назначает для виртуальной машины, на которой разворачиваются контейнеры, ip адрес 10.0.75.1. Исходя из того, что вы запускаете контейнер с SQL Server, то вам необходимо открыть SSMS (или иную IDE) и подключиться к инстансу по адресу 10.0.75.1,8080 (для SSMS двоеточие заменяется на запятую!)


text:
Q: webRTC multi-peer connection (3 clients and above) i want to use a simple WebRTC for my clients like this one (https://appr.tc/).
The problem with the above link is that it can only take up to 2 users(A and B). Do you know if there are any others FREE programms that take clients A,B,C and D?
Thank you for your time.

A: Here is a simple example of multi-peer connection audio/video. With a DEMO. It uses simple-peer as wrapper of RTCPeerconnection.
https://github.com/Dirvann/webrtc-video-conference-simple-peer

A: The problem with this concept is that the peer connections use too much computing power.
Isn't there a possibility to get a peer connection to multiply peers.
Ps. I try to point out, there are a dict within a lot of peer connections.


text:
Q: Does the IS operator unbox value type or not? I can't find an answer to the following question:
object o = 10; // Box
int i = (int)o; // Unbox

it's clear, but the following isn't clear
bool isInt = o is int; // Is the unbox here or not?

A: Not only does it not require unboxing, logically, it can't.
Unboxing can succeed or fail, depending on whether the object really contains a value of the type we are going to try to unbox to.
Therefore, unboxing requires a check as to whether the object is of that particular type.
Therefore, if testing the type required unboxing, then since unboxing requires testing the type, we wouldn't be able to unbox until we'd first unboxed...
Therefore testing a type can't require unboxing.

A: No, that's not unboxing - it's just checking whether the type is correct. Don't forget that there really is an object involved, with a type. Checking that type is basically the same operation regardless of whether the value is a boxed value type value or not. (There may be some optimizations feasible for value types or any sealed types, as there's no inheritance to consider, but fundamentally it's still checking the "type" part of an object header.)
One way to check that is to compile the code and look at the IL using ILASM:
// object o = 10
IL_0000:  ldc.i4.s   10
IL_0002:  box        [mscorlib]System.Int32
IL_0007:  stloc.0

// int i = (int) o;
IL_0008:  ldloc.0
IL_0009:  unbox.any  [mscorlib]System.Int32
IL_000e:  stloc.1

 // bool isInt = o is int
IL_000f:  ldloc.0
IL_0010:  isinst     [mscorlib]System.Int32

So it uses isinst - no unboxing is necessary.

A: As of C# 7, the is keyword has gained a new use case, in pattern matching as the type pattern. In this case, unboxing does occur e.g:
object o = 10;
if (o is int i) {
   // i is the unboxed value.
}

Obviously, this is a different case to the original post's where the value is purely being tested, as when using is as a pattern, you are actually assigning the value. Hence the need to unbox in this case.
To be clear - nothing has changed about the original o is int case - no unboxing will occur there, as per the old answers. The is keyword has just gained a new role.


text:
Q: TabLayout color of unselected tab underline
In this picture, in tablayout, selected tabbar underline color is purple, and text.
I search of unselected tabbar, but I couldn't find unselected tabbar underline.
I want change the color when I select some tab, change the unselected tabbar underline color.
If you know about this, would you help me?

A: Create an xml file inside your drawable folder
custom_indicator.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <!-- UNSELECTED TAB STATE -->
<item android:state_selected="false" android:state_pressed="false">
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <!-- Bottom indicator color for the UNSELECTED tab state -->
        <item android:top="-5dp" android:left="-5dp" android:right="-5dp">
            <shape android:shape="rectangle">
                <stroke android:color="#65acee" android:width="2dp"/>
            </shape>
        </item>
    </layer-list>
</item>
</selector>

And set this drawable in your tabLayout
<android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white"
            app:tabGravity="fill"
            app:tabMode="fixed"
            app:tabBackground="@drawable/custom_indicator" />

To change the unselected tab text color, simple provide a default tab text color and selected tab text color as follows:
<android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white"
            app:tabGravity="fill"
            app:tabMode="fixed"
            app:tabTextColor="@color/unselected_color"
            app:tabSelectedTextColor="@color/selected_color"
            app:tabBackground="@drawable/custom_indicator" />

A: simply you can use android:background to set color for all unselected tabs once.
    <style name="tab_text_style">
        <item name="android:textSize">16sp</item>
        <item name="android:fontFamily">sans-serif</item>
        <item name="android:textStyle">bold</item>
    </style>

    <style name="tab_style">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="tabIndicatorColor">@android:color/white</item>
        <item name="tabIndicatorHeight">3dp</item>
        <item name="tabTextAppearance">@style/tab_text_style</item>
        <item name="tabSelectedTextColor">@android:color/white</item>
        <item name="tabTextColor">@color/inactive_gray</item>
        <item name="android:background">@drawable/custom_inactive_tab_indicator</item>
        <item name="tabGravity">fill</item>
        <item name="tabMode">fixed</item>
    </style>

custom_inactive_tab_indicator.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:left="-4dp"
        android:right="-4dp"
        android:top="-4dp">
        <shape android:shape="rectangle">
            <stroke
                android:width="3dp"
                android:color="#57595f" />
        </shape>
    </item>
</layer-list>

activity.xml
        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            style="@style/tab_style" />


text:
Q: OSX: how to localize the name appearing when the mouse flies over the app icon in the dock? When the user's mouse flies over the app icon in the dock, the name of the app appears on the app icon.
According to the tests I just performed, it seams that the name which appears corresponds to the "Product Name" defined in the project target (in "Build Settings" menu).
The question is: how can I localize this target product name in order to have my app name in the correct language when the user puts its mouse over my app icon ?
Or is there any other method to localize the app name which appears when the user puts its mouse over my app icon ?
Thanks !

A: After so many years this problem still troubled me (and likely thousands of other programmers) for more than an hour.
Given that the link in the accepted answer above by Daij-Djan is already dead (Updated link is now at https://kb.applingua.com/2015/10/how-to-localize-app-names/), I'm writing yet another answer with my added cases.
Make sure you have done the following:

*

*Info.plist is not ticked for your target

*Info.plist has "Application has localized display name" set to YES

*Info.plist has "Bundle name" (CFBundleName) and its value is "$(PRODUCT_NAME)" (Don't ask me why. If I set this to some other value, it doesn't work.)

*Info.plist has no entry of "Bundle display name" (CFBundleDisplayName)

*InfoPlist.strings is ticked for your target

*InfoPlist.strings is ticked for all languages (in my case, Base and English only.) at least the Base language.

*InfoPlist.strings has both "CFBundleDisplayName" and "CFBundleName" entries

The above worked for me. I was primarily missing the "$(PRODUCT_NAME)" value part for the past hour.
If that still doesn't work, you should try creating a brand new XCode project and try to name the app into something else by following the above guides. Then, compare the Info.plist and your real project's Info.plist and see what's the difference. That's exactly how I find out about the "$(PRODUCT_NAME)" requirement.

A: have an info InfoPlist.strings file in which you have localized CFBundleDisplayName, you can also localize the NSHumanReadableCopyrigh et al.
It is indeed required to follow strictly the steps mentioned in this article: http://kb.applingua.com/2011/10/how-to-localize-app-names/

A: With a new project created by Xcode 14 I needed to do two things explained below. Note that this is the only way I have found to have special characters (non ascii, accents, utf-8, äåö, è etc) in the app name as well. Also note that this name is also shown in other places in the app such as when asking for location permission.

*

*Set Application has localized display name to YES in the target Info settings (this will automatically create an Info.plist file if one does not exist and set the LSHasLocalizedDisplayName key to true).

*Add a new InfoPlist.strings file to the target with a CFBundleDisplayName key with the wanted app name. You would then create a InfoPlist.strings file for each language supported and change the CFBundleDisplayName appropriately.
/* InfoPlist.strings */
CFBundleDisplayName = "Localized App Name";

Result