Q: Как реализовать такую css анимацию?      <div class="image">

</div>

    .image{
  width:100%;
  height: 200px;
    background-color: #000;
    position:relative;
}
.image:before {
    content: '';
    right: 0;
    bottom: 0;
    position: absolute;
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 0 0 8vw 50vw;
    border-color: transparent transparent #fff transparent;
    z-index: 5;
}
.image:after {
    content: '';
    left: 0;
    bottom: 0;
    position: absolute;
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 8vw 0 0 50vw;
    border-color: transparent transparent transparent #fff;
    z-index: 2;
}
.image:before {
    -webkit-animation: flipOutRight 7s both ease-in;
    animation: flipOutRight 7s both ease-in;
    z-index: 1000;

}
.image:after {
    -webkit-animation: flipOutLeft 7s both ease-in;
    animation: flipOutLeft 7s both ease-in;
    z-index: 1000;

}
@-webkit-keyframes flipOutRight {
    0% {
        border-width: 0 0 8vw 50vw;

    }
    100% {
        border-width: 0 0 1000008vw 50vw;

    }
}
@keyframes flipOutRight {
    0% {
        border-width: 0 0 8vw 50vw;

    }
    100% {
        border-width: 0 0 1000008vw 50vw;

    }

}
@-webkit-keyframes flipOutLeft {
    0% {
        border-width: 8vw 0 0 50vw;

    }
    100% {
        border-width: 1000008vw 0 0 50vw;

    }
}
@keyframes flipOutLeft{
    0% {
        border-width: 8vw 0 0 50vw;

    }
    100% {
        border-width: 1000008vw 0 0 50vw;

    }

}

.image:before {
    -webkit-animation: e-flipOutRight 7s both ease-in;
    animation: e-flipOutRight 7s both ease-in;
    z-index: 1000;

}
.image:after {
    -webkit-animation: e-flipOutLeft 7s both ease-in;
    animation: e-flipOutLeft 7s both ease-in;
    z-index: 1000;

}
@-webkit-keyframes e-flipOutRight {
    0% {
        border-width: 0 0 1000vw 50vw;

    }
    100% {
        border-width: 0 0 8vw 50vw;

    }
}
@keyframes e-flipOutRight {
    0% {
        border-width: 0 0 1000vw 50vw;

    }
    100% {

        border-width: 0 0 8vw 50vw;
    }

}
@-webkit-keyframes e-flipOutLeft {
    0% {
        border-width: 1000vw 0 0 50vw;

    }
    100% {

        border-width: 8vw 0 0 50vw;

    }
}
@keyframes e-flipOutLeft{
    0% {

        border-width: 1000vw 0 0 50vw;

    }
    100% {
        border-width: 8vw 0 0 50vw;

    }

}

Есть набросок кода: https://jsfiddle.net/JohDak/k27hh1jm/1/
Анимация в примере проходит сначала медленно, затем все быстрее за счет того, что бордер задан в VH(это необходимо для адаптивности, в пикселях на мобильном не подстраивается) и он чем больше к краю, тем большее значение VH требует. Помогите реализовать эту анимацию плавно и равномерно

A: Вместо ease-in тебе нужно использовать другую animation-timing-function https://www.w3schools.com/cssref/css3_pr_animation-timing-function.asp
Попробуй cubic-bezier(0,1,0,1). А точнее подобрать параметры можно на этом сервисе: http://cubic-bezier.com

.image:before {
    -webkit-animation: e-flipOutRight 7s both cubic-bezier(0,1,0,1);
    animation: e-flipOutRight 7s both cubic-bezier(0,1,0,1);
    z-index: 1000;
}
.image:after {
    -webkit-animation: e-flipOutLeft 7s both cubic-bezier(0,1,0,1);
    animation: e-flipOutLeft 7s both cubic-bezier(0,1,0,1);
    z-index: 1000;
}


Q: Set button and textView weight programmatically I'm creating a basic to-do app, when the event addRow is called, I want to programmatically add the XML layout below (a new row containing a text and button)
How can I create the following layout programmatically?
    <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/main_table"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintHorizontal_bias="0.466"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/ll_component_container">

        <TableRow
                android:layout_width="match_parent"
                android:layout_marginTop="30dp"
                android:id="@+id/tab1"
                android:weightSum="5"
                android:layout_height="84dp">
            <TextView
                    android:id="@+id/textView1"
                    android:layout_width="fill_parent"
                    android:layout_weight="4"
                    android:paddingLeft="20dp"
                    android:textColor="#FFFFFF"
                    android:layout_height="wrap_content"
                    android:text="Value1"
                    android:textAppearance="?android:attr/textAppearanceSmall"/>
            <Button
                    android:text="Remove"
                    android:background="#fc032c"
                    android:layout_marginRight="20dp"
                    android:layout_weight="1"
                    android:layout_height="40dp" android:id="@+id/button1"/>
        </TableRow>
    </TableLayout>

I've tried this, but I can't find how to change neither the weight nor the button marginRight.
   private fun addRow(content: Editable) {
        val tl = findViewById<TableLayout>(R.id.main_table)
        val _id = View.generateViewId()
        val tr_head = TableRow(this)
        tr_head.id = _id
        tr_head.layoutParams = TableRow.LayoutParams(
            TableRow.LayoutParams.MATCH_PARENT,
            84,
            5f
        )

        val label = TextView(this)
        label.id = View.generateViewId()
        label.text = content
        label.setTextColor(Color.WHITE)
        label.setPadding(20, 0,0,0)
        tr_head.addView(label)

        val btn = Button(this)
        btn.id = _id + 1
        btn.setBackgroundColor(Color.RED)
        btn.setText("Remove")

        tr_head.addView(label)
        tr_head.addView(btn)

        tl.addView(
            tr_head, TableLayout.LayoutParams(
                TableRow.LayoutParams.MATCH_PARENT,
                TableRow.LayoutParams.WRAP_CONTENT
            )
        )
    }

A: I found another way around to accomplish what I wanted, so instead of using weight I used the screen width in order to get a relative width. and to add margin, I just added an empty row before the row that contains the button and text. Here is the full code for the interested.
private fun addRow(content: Editable) {
    val tl = findViewById<TableLayout>(R.id.main_table)
    val margin = TableRow(this)
    val tr_head = TableRow(this)
    margin.id = View.generateViewId()

    tr_head.id = View.generateViewId()
    val tabParams = TableRow.LayoutParams(
        TableRow.LayoutParams.MATCH_PARENT,
        84
    )
    tr_head.setLayoutParams(tabParams)

    val label = TextView(this)
    label.id = View.generateViewId()
    label.text = content
    label.setTextColor(Color.WHITE)
    val displayMetrics = DisplayMetrics()
    windowManager.defaultDisplay.getMetrics(displayMetrics)
    label.width = (displayMetrics.widthPixels / 3)*2
    label.setPadding(50, 0,0,0)
    tr_head.addView(label)

    val btn = Button(this)
    btn.id = View.generateViewId()
    btn.width = (displayMetrics.widthPixels / 3) - 50

    btn.setBackgroundColor(Color.RED)
    btn.setText("Remove")
    btn.setOnClickListener {
        tl.removeView(tr_head)
        tl.removeView(margin)
    }
    label.id = View.generateViewId()

    val filler = TextView(this)
    filler.id = View.generateViewId()

    margin.addView(filler)
    tr_head.addView(btn)
    tl.addView(
        margin,  TableLayout.LayoutParams(
            TableRow.LayoutParams.MATCH_PARENT,
            20
        )
    )
    tl.addView(
        tr_head, tabParams
    )
}


Q: Which Thread will a Service run in? I have an Activity A that starts a service S via startService method.
 Now as per the documentation Service S will run on main thread or the UI thread
 Now my question is when activity A is destroyed will the UI thread still exist?  What will happen if I reopen the Activity A through its launcher icon will there be two UI threads spawned in total?
Thanks in Advance.

A: On Android platform: MainThread == UiThread == "ApplicationThread" (it doesn't really exists), so in your case the new Activity will NOT start a new Service but Service's OnStartCommand() method will be raised. The Service will continue to run in the "ApplicationThread".

A: According to the Android Developer Doc,

A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise.

A: When you start an app by clicking on app's icon on launcher or home screen, Android will create a process for the app with a single thread (aka main or UI thread) of execution. This thread will exist even though there is no component started, such as Activity, Service, BroadcastReceiver, ContentProvider.
Then, it will find and start the default or entry activity for the app (which defined in AndroidManifest.xml file).

I have an Activity A that starts a service S via startService method.
  Now as per the documentation Service S will run on main thread or the
  UI thread  Now my question is when activity A is destroyed will the UI
  thread still exist?

Yes, UI thread still exist.

What will happen if I reopen the Activity A through its launcher icon
  will there be two UI threads spawned in total?

When you finish Activity A, Android does not destroy the process for the application at that time. It will keep the application in the memory for faster loading if you start the app later.
So when you reopen the Activity A, if there is a process for that application exists already, then the Activity A is started within that process and uses the same thread of execution. Otherwise, Android will create a new process for the application.

Which Thread will a Service run in?

By default, all components (including Service) of the same application run in the same process and thread (called the main or UI thread).
You can find more details in this link:
https://developer.android.com/guide/components/processes-and-threads


Q: CMake subdirectory install/uninstall targets I've got a project with two subdirectory projects (added with add_subdirectory), each with their own libraries, binaries and install/uninstall targets.  So:
main_project
|
|--CMakeLists.txt
|--src/
   |--CMakeLists.txt (with binary target, install()
|
|--project_a
   |--CMakeLists.txt
   |--src/
      |--CMakeLists.txt (with library, install())
|
|--project_b
   |--CMakeLists.txt
   |--src/
      |--CMakeLists.txt (with library, install())

I'd like for the top-level project (main_project) to automatically install the libraries a and b (included in main_project from target_link_libraries()).  So, I'd like to be able to go:
cd main_project/build
cmake ..
make
sudo make install

and have the main_project binary and project_a/b libraries installed automatically.  I've tried this:
main_project/src/CMakeLists.txt
...
install(FILES main project_a project_b DESTINATION bin
        LIBRARY DESTINATION lib)

but a cmake .. results in
install TARGETS given target "project_a" which does not exist in this directory.

as expected.
I've also tried specifying a path:
main_project/src/CMakeLists.txt
...
install(FILES main ${CMAKE_SOURCE_DIR}/project_a/ ${CMAKE_SOURCE_DIR}/project_b DESTINATION bin
        LIBRARY DESTINATION lib)

which also complains that project_a/b are not in this directory (also expected, I guess?)
I've also tried installing the libraries "manually" with the FILES option in install(), and that works just fine, but that seems very kludgy considering there are perfectly good install()s in the subprojects.
One additional issue: since project_a and project_b also have uninstall() custom targets, I can't add an uninstall target to the main_project without CMake complaining about the custom target already existing.  When I try adding an uninstall directive to the top dir CMakeLists:
add_custom_target(uninstall
    COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake)

But, since my project_a has an uninstall directive, I get:
CMake Error at CMakeLists.txt:37 (add_custom_target):
  add_custom_target cannot create target "uninstall" because another
  target with the same name already exists.  The existing target is a
  custom target created in source directory "/main_project/project_a".
  See documentation for policy CMP0002 for more details.

So, how do I install and uninstall the necessary library files from my subproject alongside my main_project?

A: I found the problem. I am adding the subdirectory I want to install with EXCLUDE_FROM_ALL such that it doesn't build everything in the subdirectory, only the library I need. That flag seems to prevent the subdirectory install() from happening. Perhaps ExternalProject_Add is indeed the best way to go here...
Also, RE overriding custom targets, this worked for me: http://public.kitware.com/pipermail/cmake/2011-July/045269.html


Q: Problemas al alinear elementos en linea Tengo el siguiente código:

div{
    width: 420px;
    height: 120px;
    margin: 20px 50px 30px 10px;
    padding: 30px;
    border: 10px solid #000;
    background-color: #ff8000;
    display: inline-block;
}

Titulo de nuestro sitio

    Enlace 1
    Enlace 2

Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto.
    Lorem Ipsum ha sido el texto de relleno estándar de las industrias desde el año 1500, cuando
    un impresor (N. del T. persona que se dedica a la imprenta) desconocido usó una galería de
    textos y los mezcló de tal manera que logró hacer un libro de textos especimen.

No sólo sobrevivió 500 años, sino que tambien ingresó como texto de relleno en documentos
    electrónicos, quedando esencialmente igual al original. Fue popularizado en los 60s con la
    creación de las hojas "Letraset", las cuales contenian pasajes de Lorem Ipsum,
    y más recientemente con software de autoedición, como por ejemplo Aldus PageMaker.

Como pueden ver en la imagen, los enlaces no se alinean verticalmente a la mitad con relación a los divs
La pregunta es porque pasa esto? Como es que podría solucionarlo??

A: Basta con agregar vertical-align: middle; para que todo el contenido se centre verticalmente.
Ejecuta el snippet en pantalla completa para que veas el resultado.

div{
    width: 420px;
    height: 120px;
    margin: 20px 50px 30px 10px;
    padding: 30px;
    border: 10px solid #000;
    background-color: #ff8000;
    display: inline-block;
    vertical-align: middle;
}

Titulo de nuestro sitio

    Enlace 1
    Enlace 2

Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto.
    Lorem Ipsum ha sido el texto de relleno estándar de las industrias desde el año 1500, cuando
    un impresor (N. del T. persona que se dedica a la imprenta) desconocido usó una galería de
    textos y los mezcló de tal manera que logró hacer un libro de textos especimen.

No sólo sobrevivió 500 años, sino que tambien ingresó como texto de relleno en documentos
    electrónicos, quedando esencialmente igual al original. Fue popularizado en los 60s con la
    creación de las hojas "Letraset", las cuales contenian pasajes de Lorem Ipsum,
    y más recientemente con software de autoedición, como por ejemplo Aldus PageMaker.


Q: Getting distance from Google Direction API in Android http://maps.googleapis.com/maps/api/directions/json?origin=-20.291825,57.448668&destination=-20.179724,57.613463&sensor=false&mode=%22DRIVING%22
For example this link generate the following:
"routes" : [
      {
         "bounds" : {
            "northeast" : {
               "lat" : -20.1765204,
               "lng" : 57.6137001
            },
           "southwest" : {
               "lat" : -20.2921672,
               "lng" : 57.4472155
            }
         },
         "copyrights" : "Map data ©2014 Google",
         "legs" : [
            {
               "distance" : {
                  "text" : "24.6 km",
                  "value" : 24628
               },

i want to extract only the distance and display it in android

A: To get a distance from a Google Maps you can use Google Directions API and JSON parser to retrieve the distance value.
Sample Method
private double getDistanceInfo(double lat1, double lng1, String destinationAddress) {
            StringBuilder stringBuilder = new StringBuilder();
            Double dist = 0.0;
            try {

            destinationAddress = destinationAddress.replaceAll(" ","%20");
            String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + latFrom + "," + lngFrom + "&destination=" + latTo + "," + lngTo + "&mode=driving&sensor=false";

            HttpPost httppost = new HttpPost(url);

            HttpClient client = new DefaultHttpClient();
            HttpResponse response;
            stringBuilder = new StringBuilder();

                response = client.execute(httppost);
                HttpEntity entity = response.getEntity();
                InputStream stream = entity.getContent();
                int b;
                while ((b = stream.read()) != -1) {
                    stringBuilder.append((char) b);
                }
            } catch (ClientProtocolException e) {
            } catch (IOException e) {
            }

            JSONObject jsonObject = new JSONObject();
            try {

                jsonObject = new JSONObject(stringBuilder.toString());

                JSONArray array = jsonObject.getJSONArray("routes");

                JSONObject routes = array.getJSONObject(0);

                JSONArray legs = routes.getJSONArray("legs");

                JSONObject steps = legs.getJSONObject(0);

                JSONObject distance = steps.getJSONObject("distance");

                Log.i("Distance", distance.toString());
                dist = Double.parseDouble(distance.getString("text").replaceAll("[^\\.0123456789]","") );

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return dist;
        }

For details on parameters and more details on what are the different options available, please refer this.
https://developers.google.com/maps/documentation/directions/

A: public class ApiDirectionsAsyncTask extends AsyncTask<URL, Integer, StringBuilder> {

    private static final String TAG = makeLogTag(ApiDirectionsAsyncTask.class);

    private static final String DIRECTIONS_API_BASE = "https://maps.googleapis.com/maps/api/directions";
    private static final String OUT_JSON = "/json";

    // API KEY of the project Google Map Api For work
    private static final String API_KEY = "YOUR_API_KEY";

    @Override
    protected StringBuilder doInBackground(URL... params) {
        Log.i(TAG, "doInBackground of ApiDirectionsAsyncTask");

        HttpURLConnection mUrlConnection = null;
        StringBuilder mJsonResults = new StringBuilder();
        try {
            StringBuilder sb = new StringBuilder(DIRECTIONS_API_BASE + OUT_JSON);
            sb.append("?origin=" + URLEncoder.encode("Your origin address", "utf8"));
            sb.append("&destination=" + URLEncoder.encode("Your destination address", "utf8"));
            sb.append("&key=" + API_KEY);

            URL url = new URL(sb.toString());
            mUrlConnection = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(mUrlConnection.getInputStream());

            // Load the results into a StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1){
                mJsonResults.append(buff, 0, read);
            }

        } catch (MalformedURLException e) {
            Log.e(TAG, "Error processing Distance Matrix API URL");
            return null;

        } catch (IOException e) {
            System.out.println("Error connecting to Distance Matrix");
            return null;
        } finally {
            if (mUrlConnection != null) {
                mUrlConnection.disconnect();
            }
        }

        return mJsonResults;
    }
}

I hope that help you!

A: Just check below link. You will probably get idea of it and try it on your own.
http://about-android.blogspot.in/2010/03/sample-google-map-driving-direction.html
Also you can use Google Distance Matrix API
https://developers.google.com/maps/documentation/distancematrix/

A: String url = getDirectionsUrl(pickupLatLng, dropLatLng);
new GetDisDur().execute(url);

Create URL using latlng
private String getDirectionsUrl(LatLng origin, LatLng dest) {

        String str_origin = "origin=" + origin.latitude + "," + origin.longitude;

        String str_dest = "destination=" + dest.latitude + "," + dest.longitude;

        String sensor = "sensor=false";

        String mode = "mode=driving";

        String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;

        String output = "json";

        return "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
    }

Class GetDisDur
private class GetDisDur extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... url) {

            String data = "";

            try {
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            try {
                JSONObject jsonObject = new JSONObject(result);

                JSONArray routes = jsonObject.getJSONArray("routes");

                JSONObject routes1 = routes.getJSONObject(0);

                JSONArray legs = routes1.getJSONArray("legs");

                JSONObject legs1 = legs.getJSONObject(0);

                JSONObject distance = legs1.getJSONObject("distance");

                JSONObject duration = legs1.getJSONObject("duration");

                distanceText = distance.getString("text");

                durationText = duration.getString("text");

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

        }
    }


Q: what is difference between TDF and PCEF? In the PCC architecture there is  is TDF and PCEF that they are same. What is difference between TDF and PCEF?
HowTDF and PCEF work with together?

A: Firstly it is worth also mentioning the PCRF, the Policy and Charging Rules Function, which is the entity that defines and manages the policies. It will often group sets of rules into profiles.
The TDF, Traffic Detection Function, is 'is a functional entity that performs application detection and reporting of detected application and its service data flow description to the PCRF'.
The PCEF 'encompasses service data flow detection, policy enforcement and flow based charging functionalities.'
From the above descriptions, all from the 3GPP spec the distinction seem quite clear - the PCRF is the brains, the TDF detects application flow and the PCEF enforces policy. However, the TDF definition goes on to say that a TDF:

For solicited application reporting, the PCRF can request the TDF to also perform enforcement actions and usage monitoring.
  For those cases where service data flow description is not possible to be provided by the TDF to the PCRF, the TDF performs:

*

*Gating;

*Redirection;

*Bandwidth limitation.
  for the detected applications.

and to also note that a PCEF can be extended to include TDF functionality:

NOTE: The PCEF can be enhanced with application detection and control feature as specified in clause 6.2.2.5

So, your question is a good one, there is clearly some potential for overlap, and it is quite common for vendors to actually offer a single combined TDF/PCEF product.

A: TDF was introduced as a functional entity from Release 11 and the related information are present in the specification. Let met touch upon few key points w.r.t TDF, PCEF and PCRF for setting the context for the differences between them.
TDF :

The TDF is a functional entity that performs application detection and
  reporting of detected application and its service data flow
  description to the PCRF. The TDF supports solicited application
  reporting and/or unsolicited application reporting.

PCEF :

The PCEF encompasses service data flow detection, policy enforcement
  and flow based charging functionalities. It also provides user plane traffic
  handling, triggering control plane
  session management (where the IP-CAN permits), QoS handling, and
  service data flow measurement as well as online and offline charging
  interactions.
  Policy Control is enforced by PCEF as indicated by the PCRF
  in two different ways: a.Gate enforcement and b.QoS enforcement.
  Charging control is enforced by PCEF in the following way:
  - For a service data flow (defined by an active PCC rule) that is subject to charging control, the PCEF shall allow the service data
  flow to pass through the PCEF if and only if there is a corresponding
  active PCC rule with and, for online charging the OCS has authorized credit for the charging key.

PCRF :

The PCRF that uses usage monitoring for making dynamic policy
  decisions shall set and send the applicable thresholds to the PCEF or
  TDF for monitoring.  The usage monitoring thresholds shall be based on
  volume. The PCEF or TDF shall notify the PCRF when a threshold is
  reached and report the accumulated usage since the last report for
  usage monitoring.

Other points to note :

*

*PCEF interacts with PCRF and OCS.  The TDF interacts only with PCRF and not with charging system (Online or Offline CS).

*PCEF resides with-in the PDN GW. The TDF resides as a separate entity outside PGW.

*Interfaces :  The Sd reference point enables a PCRF to have dynamic control over the ADC (Application Detection and Control) behaviour at a TDF. The Gx reference point enables a PCRF to have dynamic control over the PCC(Policy Charging and Control)/ADC (Application Detection and Control) behaviour at a PCEF.

ADC - This is present in TDF or in some scenario along with PCEF in which case, the PCEF is termed as PCEF enhanced with ADC.

In Application Detection and Control(ADC), two models may be applied,
  depending on operator requirements: solicited and unsolicited
  application reporting
Solicited application reporting: The PCRF shall instruct the TDF, or the PCEF enhanced with ADC, on which applications to detect and
  whether to report start or stop event to the PCRF by activating the
  appropriate ADC rules.
Unsolicited application reporting: The TDF is pre-configured on which applications to detect and report. The enforcement is done in
  the PCEF

The report to the PCRF shall include the same information for solicited and unsolicited application reporting that is whether the report is for start or stop, the detected Application Identifier and, if deducible, the service data flow descriptions for the application user plane traffic.

The PCRF shall accept input for PCC decision-making from the PCEF, the
  TDF if present and other entities.

High level Information obtained from the PCEF via the Gx reference point, e.g. IP-CAN bearer attributes, request type, subscriber related information, IP flow mobility routing rules (if IP flow mobility is supported) and detected application’s traffic information, if the PCEF supports Application Detection and Control feature (Detected Application Identifier, Allocated Application Instance Identifier, Detected service data flow descriptions.)
PCC procedures over Gx reference point

Request for PCC rules
  Provisioning of PCC rules
  Provisioning of Event Triggers
  Provisioning of charging related information for the IP-CAN session
  Provisioning and Policy Enforcement of Authorized QoS
  Requesting Usage Monitoring Control
  Reporting Accumulated Usage

ADC procedures over Gx reference point :

Request for ADC rules
  Provisioning of ADC rules
  Requesting Usage Monitoring Control for applications
  Reporting applications' Accumulated Usage
  Application Detection Information

High level Information obtained from the TDF via the Sd reference point, e.g. report on application’s traffic detection start/stop, Detected Application Identifier, Allocated Application Instance Identifier, Detected service data flow descriptions.
ADC procedures over Sd reference point for solicited application reporting :

Provisioning of ADC rules
  Request for ADC rules
  Provisioning of Event Triggers
  Requesting Usage Monitoring Control
  Reporting Accumulated Usage
  Application Detection Information

ADC procedures over Sd reference point for unsolicited application reporting :

Provisioning of ADC rules
  Application Detection Information
  TDF session to Gx session linking


Q: Limited Amount of Lords in a Castle? Whenever I host a feast and all of my lords attend it, there's always a limit to how many of them are actually visible in the castle. Instead of other lords, some random wives show up, which is pretty useless to me. I'd like to know how to bypass that limit or at least let everyone in and keep the ladies outside, so I can improve my relation with each one of them.
Thanks in advance.

A: Circumventing this limit is rather tedious and requires you to manually add more spots for the lords to stand in in the castle/city halls' configuration files. The lords stand at pre-determined spots, and when there aren't enough spots left, the rest of the lords are omitted from showing up. Exiting and re-entering the town shuffles which lords show up on visually on the feast, though it would take quite some exiting/reentering to greet every single lord in attendance.
Some castles and cities do have larger halls, allowing more lords to visibly attend. Which ones are the larger ones I am unsure, but the Nord have the largest I can recall at least.


Q: SonarQube giving unused private method issue for lambda usage I have the following logic;
..
if(list.stream()
       .filter(MyClass::isEnabled)
       .filter(this::isActive)
       .count() > 0) {
    //do smth
}
..
private boolean isActive(MyClass obj) {
    return bool;
}

As you see, isActive method is being used in the stream structure, but when I build this class on Jenkins, I get the unused private method issue from SonarQube, it says you should delete this redundant private method. Is this a bug? If not, why haven't they still included lambda logic in their analyze structure?
Only solution is, obviously, to do this;
.filter(obj -> isActive(obj)), but it destroys the uniformity, and even the readability (imo).

A: This is a known issue of SonarQube java analyzer : https://jira.sonarsource.com/browse/SONARJAVA-583
This is due to a lack of semantic analysis to resolve properly method reference (thus identify to which method this::isActive refers to).


Q: Material UI Typography & Media Queries in below in the typography component, i wanted to make the variant prop dynamic in accordance to the different screen widths , how it can be done??  appreciate your feedback
import { useTheme, useMediaQuery } from "@material-ui/core";

const Home = () => {
  const classes = useStyles();
  const theme = useTheme();
  const MQlg = useMediaQuery(theme.breakpoints.down("lg"));
  const MQmd = useMediaQuery(theme.breakpoints.down("md"));
  const MQsm = useMediaQuery(theme.breakpoints.down("sm"));

<Typography
          variant={`${MQsm && "h4"}   ${MQmd && "h3"}  $ {MQlg && "h2"} `}
          className={classes.text}
          gutterBottom
        >
          pioneering
</Typography>

A: Following the example on this MUI page for useMediaQuery, please see what I have created to assist you:
import * as React from "react";
import { createTheme, ThemeProvider, useTheme } from "@mui/material/styles";
import useMediaQuery from "@mui/material/useMediaQuery";
import { Typography } from "@material-ui/core";
function MyComponent() {
  const theme = useTheme();
  const large = useMediaQuery(theme.breakpoints.up("lg"));
  const medium = useMediaQuery(theme.breakpoints.up("md"));
  const small = useMediaQuery(theme.breakpoints.up("sm"));

  return (
    <>

{`large: ${large}`}

{`medium: ${medium}`}

{`small: ${small}`}

      <Typography
        variant={large ? "h1" : medium ? "h2" : small ? "h3" : "body1"}
      >
        Font Size Change
      </Typography>
    </>
  );
}

const theme = createTheme();

export default function ThemeHelper() {
  return (
    <ThemeProvider theme={theme}>
      <MyComponent />
    </ThemeProvider>
  );
}

Inspect the page, and change the sizes for the screen. Some will appear true, whilst other's false.


Q: AttributeError: 'module' object has no attribute 'point' When I try to run this code:
import arcpy, os
arcpy.env.overwriteOutput = True
def polylineArea(x, y): # this is your function definition
   count=len(xlist)
   area=0
   j=count-1
   for i in range (0, count):
       area+=((x[j]+x[i])*(y[j]-y[i]))
       j=i
   return area*.5

infile=open("C:/KateFiles/Courses/SIE510/ParcelStuff/parcel15.txt", "r")
outputname = "C:/KateFiles/Courses/SIE510/ParcelStuff/P_12/ParcelPolys2.shp"

sr=arcpy.SpatialReference(102683)
arcpy.CreateFeatureclass_management(os.path.dirname(outputname),os.path.basename(outputname),"POLYLINE", spatial_reference=sr)

arcpy.AddField_management(outputname, "ParcelID", "LONG", field_precision=8)
arcpy.AddField_management(outputname, "Map", "TEXT", field_length=4)
arcpy.AddField_management(outputname, "Lot", "TEXT", field_length=4)
arcpy.AddField_management(outputname, "point", "Float", field_precision=10, field_scale=2)
cursor1 = arcpy.da.InsertCursor(outputname,("ParcelID","SHAPE@", "Map","Lot", "point"))

header1 = infile.readline()
print header1 # print this out so you can see what this contains
header2 =header1.split()# split the header parts by white space
parcelID=header2[1]#assign parcel ID
Mapno=header2[2]# assign the Mapno
Lotno=header2[3]# assign the Lotno
xlist=[]
ylist=[]

#poly =[] # A list that will hold each of the Polygon objects
#point=arcpy.point
parray=arcpy.Array()
# Loop over lines and extract variables of interest
for line in infile:
   segments=line.split()
   x=float(segments[0]) # gets x
   y=float(segments[1]) # gets y
   print x, y
   pt=arcpy.point(x, y)
   parray.add(pt)

   xlist.append(x)
   ylist.append(y)

area=polylineArea(x, y) # this is your function call
print area
point=arcpy.polyline(parray)

row=(parcelID, poly, Mapno, Lotno, point) # these match the fields in your insert cursor specification
cursor1.insertRow(row)
infile.close()

I got this Error:
 Traceback (most recent call last):
  File "C:/Users/Ahmed A. Jasim/Desktop/Q3_Lb8.py", line 45, in <module>
    pt=arcpy.point(xlist, ylist)
AttributeError: 'module' object has no attribute 'point'

A: The ArcPy module is case sensitive, so you need to capitalize those objects, e.g.
pt=arcpy.Point(x, y)
point=arcpy.Polyline(parray)


Q: Exceeding the 256 serial COM PORT limit? Can I use more than 256 COM PORTS on a single host?
From this answer, it looks like it's a software/OS limit only: How many serial ports can be configured in Windows 7?
I'm unable to figure out how to actually increase the limit so that Windows can see more than 256 devices. Is this possible for linux/debian?


Q: CBCharacteristic value in swift3 I am beginner in swift development. I was working on BLE based application.
Today I updated Xcode 8, iOS 10 and convert my code to swift3. Then some of my syntax are need to convert. After fixing this , I found one issue on CBCharacteristic.
Issue
Inside didUpdateValueforCharacteristic , I can get updated CBCharacteristic object.
If I print out whole object, it show correctly. -> value = <3a02>
When I retrieved value from CBCharacteristic , characteristic.value -> 2bytes (size of this value)
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic:     CBCharacteristic, error: Error?)
{
if (characteristic.uuid.description == LED_WAVELENGTH_CHARACTERISTIC_UUID)
{
            print("Characteristic - \(characteristic)")
            print("Data for characteristic  Wavelength - \  (characteristic.value)")
        }
 }

Log Result :

Characteristic - <CBCharacteristic: 0x1742a50a0, UUID = 2C14, properties = 0xE, value = <3a02>, notifying = NO>
Data for characteristic  Wavelength - Optional(2 bytes)

PS : This code is completely working fine on previous version.
Thanks for attention and hope someone can help me to fix this issue.

A: It seems that you have been relying on the description of NSData returning a string of the form <xxxx> in order to retrieve the value of your data. This is fragile, as you have found, since the description function is only meant for debugging and can change without warning.
The correct approach is to access the byte array that is wrapped in the Data object.  This has been made a little bit more tricky, since Swift 2 would let you copy UInt8 values into a single element UInt16 array.   Swift 3 won't let you do this, so you need to do the math yourself.
var wavelength: UInt16?
if let data = characteristic.value {
    var bytes = Array(repeating: 0 as UInt8, count:someData.count/MemoryLayout<UInt8>.size)

    data.copyBytes(to: &bytes, count:data.count)
    let data16 = bytes.map { UInt16($0) }
    wavelength = 256 * data16[1] + data16[0]
}

print(wavelength)

A: Now, you can use String(bytes: characteristic.value!, encoding: String.Encoding.utf8), to get the string value of the characteristic.


Q: Construct .htaccess file to cover set of cases This is what I need to do: I need to write an .htaccess file that:

*

*Redirect all http requests to https

*Redirect all https://example.com to https://www.example.com

*Block bad bots

*Prevent access to .htaccess

*Add compression to ALL file types on the site

This is all I need to do, yet no matter how many thousands of different ways I try, it doesn't work. Do I need the rewrite engine 'on' with every rule?
I have read 100's of sites telling me how, however everyone seems to have a different solution, yet whatever I try, it DOESN'T work. When I use the redirect tool in Godaddy it does redirect my site from http to https, but that is all. When I try to add more to the htaccess file, it stops working. Even the original redirect no long works.
Can anyone tell me how to put together all these codes so they work? I started a small business website, but no one told me there would be so  little technical help or examples of all the 'other' things you need to do to get your website ready for all the search engine requirements.
Please, please, can someone help me? The site name is billionairemailinglist.com, can anyone give me or help me create these codes to use in my htaccess file? I would be forever grateful and would be glad to offer you the products we sell for free for helping me.

A: The blocking of bad bots is a non discrete, nebulous task so I'll deal with that at the end of this answer.
After each itemized question I'll adjust the .htaccess to cover the solution along with all previous questions.  The final solution will address all questions.
1. Switches my site from http to https
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.example.com [R=301,L]

2. Switches my site from https://with no www to https://with www.
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) https://www.example.com [R=301,L]

4. Prevent viewing of .htaccess file
Taken from How to deny access to a file in .htaccess
<Files ~ "^.*\.([Hh][Tt][Aa])">
    order allow,deny
    deny from all
    satisfy all
</Files>

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) https://www.example.com [R=301,L]

5. Add compression to ALL file types on the site*
<Files ~ "^.*\.([Hh][Tt][Aa])">
    order allow,deny
    deny from all
    satisfy all
</Files>

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) https://www.example.com [R=301,L]

<ifmodule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
</ifmodule>

*Note that not all file types should/could be compressed.  I've added the boilerplate that we used to use above which seemed to work well.  If you're interested in truly maximizing compression opportunities without the complexities of browser compatibility, look into ModPagespeed
3. block bad bots
I wish it was easy as BlockBadBots yes.  If you'd prefer to not analyze bandwidth usage and blocking of bots based on consumption etc., I would recommend that you put your site behind CloudFlare.  This service has a good reputation for dealing with high profile DDOS attacks, limiting harmful bots, and keeping sites alive even as demand increases.
Good luck!


Q: LEFT JOIN doesn't work with count I have a problem with my query:
SELECT table1.Name,
       COUNT(*)
FROM table1
LEFT JOIN table2 ON table2.Name_all = table1.Name
GROUP BY table1.Name

It shows and counts a names from table1. I want to join all names from table2 which do not exist in table1.
Maybe someone knows what I am doing wrong?
Thanks in advance

A: From your description you seem to mean this, which is a list of name_all that does not match table1 name.
SELECT table2.Name_all
FROM table2
LEFT JOIN table1 ON table2.Name_all = table1.Name
WHERE table1.Name Is Null

If you need a count as well, you can say:
SELECT table2.Name_all, Count(table2.Name_all) AS CountOf
FROM table2
LEFT JOIN table1 ON table2.Name_all= table1.Name
WHERE table1.Name Is Null
GROUP BY table2.Name_all;

A: Try this
This query will fetch common names from table 1 and table 2. It will also fetch names from table 2 which are not there in table 1.
SELECT table1.Name,
       table2.Name,
       COUNT(*)
FROM table2
LEFT JOIN table1
    ON table2.Name_all = table1.Name
GROUP BY table1.Name, table2.Name

Let me if this works.

A: I would do a simple in check then
SELECT table1.Name,
FROM table1
WHERE table1.Name In (SELECT table2.Name_all FROM table2)
GROUP BY table1.Name

There are other ways, but without more information this is a simple way t


Q: when i call str.replace() in javascript it goes to error ir is not defined See my code
for (var i = 0; i < allTextLines.length; i++) {
            var row_data = allTextLines[i];
            console.log(row_data);
            row_data = row_data.replace(/ /g,'');
            try {

                ir(row_data == "")
                {
                    continue;
                }
                if (document.getElementById("devicesList").value.length > 0) {
                    document.getElementById("devicesList").value += ",";
                }
                document.getElementById("devicesList").value += row_data;
            }
            catch (oErr) {
                not_read += 1;
                console.log(oErr.message);
                str_error_detail_rows += "
Error :" + oErr.message + " could not read line# " + i + " while reading from file.
";
            }

        }

when i run the code, in the console i got "ir is not defind" please someone help me. the code goes smooth when i remove str.replace. thanks.

A: ir(row_data == "")

should be
if(row_data == "")

A: The ir should be an if, I reckon - it's a typo.
To be perfectly frank, you really could have read through and practically immediately noticed the problem while paying attention.


Q: ASP.NET MVC3 Using Areas I'm having some troubles setting up two Areas in my project, I created both Areas by right clicking my project -> Add -> Area using VS 2010 Professional,
The code it generated in the *AreaRegistration.cs files is exactly as I'd expect it.
Both my areas have multiple controllers.
I've checked my global.asax.cs file and it contains what I'd expect, the following is at the bottom:

// Generated code
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);

When I change the default generated routing info I can get it to work for a Single controller:
context.MapRoute(
    "CommunityCourses_default",
    "CommunityCourses/{controller}/{action}/{id}",
    new {controller="NameOfController", action = "Index", id = UrlParameter.Optional }
);

The controller="NameOfController" is what I've tried adding to the generated code, but it only works for a single controller.
Edit: I renamed the namespace of my files to use PROJECTNAME.AREANAME within an area, is this causing issues? I thought it'd simplify my imports in a non-convention-breaking way.
What am I missing? I've noticed a lot of problems about areas on SO and tried to follow the answers without success. This issue has bothered eluded me for the majority of the day, any help would be greatly appreciated!

A: If you moved files from the Controllers folder or the VIews folder in the root of the project into Controllers or View folders contained in the {AreaName} folder, then all of those files moved need their namespaces changed from {ProjectName}.{*etCetera} to:
{ProjectName}.Areas.{AreaName}.{*etCetera}

A:
Turns out what was wrong was that the order or routing was incorrect, it was processing {controller}/{action}/{id} first which was breaking my areas. Moving the
AreaRegistration.RegisterAllAreas();

to the top of my application_start fixed my problem.
http://haacked.com/archive/2011/04/13/routedebugger-2.aspx Link to the tool I used to find the problem, unfortunately the current version of the tool doesn't work on the default 404 pages, so I also had to create a custom 404 page for it to work.


Q: Using sed (or other command line programs) to delete every other X lines I have a huge text file that has several iterations of the same thing at different times, with a basic structure of:
Header (5 lines)
Data (thousands of lines)
Header (5 lines)
Data (thousands of lines)
Header (5 lines)
Data (thousands of lines)

This repeats and goes on for a while.
I want to cull this file, by removing every other set of Header + Data. I was thinking I'd use sed, but I can't figure out how.
It might be of help that each "cycle" starts with the same line (for the purpose of this example, imagine it says Program X output) and that exact line only appears once, at the beginning of each "cycle".
Thanks

A: Sounds like all you need is:
awk '/Program X output/ && c++{exit} 1' file

e.g.
$ seq 50 | awk '/2/ && c++{exit} 1'
1
2
3
4
5
6
7
8
9
10
11

If that's not all you need then edit your question to clarify your requirements and show us concise, testable sample input and expected output.

A: Keep track of how often you see the keywords, and print only when this count is an odd number:
awk '/Program X output/ {n++} n%2 == 1' <<END
Program X output
a
b
c
Program X output
d
e
Program X output
f
g
h
i
j
Program X output
m
n
o
END

Program X output
a
b
c
Program X output
f
g
h
i
j

A: This might work for you (GNU sed):
sed -r '/Program X output/{x;s/^/x/;x};G;/\n(x{2})*$/!P;d' file

When encountering a header line, add 1 to a counter in the hold space (HS). Append the HS to every line and only print the first line in the pattern space (PS) if the counter is a multiple of the required amount.


Q: How do I merge the multiple If Else using decode in PL/SQL? The code goes like-
If X=x1
then
  select a,b
  from tab
  where zz=yy;

elsif X=x2 or X=x3
then
  select a,b
  from tab
  where zz=yy
  and yy= 123;

elsif X=x4
then
  select a,b
  from tab
  where zz=yy
  and yy= 456;

end if;

The code in select is being repeated. How should i merge it?

A: At first I thought that a CASE statement would be appropriate, but then I noticed that your logic always conditionally selects the same two columns a and b.  So I think that what you need here is a WHERE clause to handle all the cases.
SELECT a, b
FROM tab
WHERE (x = 'x1' OR
      ((x = 'x2' OR x = 'x3') AND yy = 123) OR
      (x = 'x4' AND yy = 456)) AND
      zz = yy

A: You can use dynamic SQL and compose your query from different parts.
For example:
-- common part of query
common_query := 'SELECT a, b FROM tab WHERE zz= yy';

-- set additional condition
IF X=x1 THEN add_where := '';
ELSIF X=x2 OR X=x3 THEN add_where := ' AND yy= 123';
ELSIF X=x4 THEN add_where := ' AND yy= 456';
END IF;

-- compose final query
final_query:=  common_query||add_where;

EXECUTE IMMEDIATE final_query;

Of couse when you use dynamic SQL you can use bind variables and you need to remember about return values.


Q: Extracting last occurrence of a certain string from each row in a pandas series from each row i want to extract the last occurrence of the word "user" + the number that follow right after it from a pandas series. everything else can be discarded.
how would you perform this action?
thanks!!!
here's an example of the series :
0                         1 - Unassigned, 2 - User 397335
1         1 - Unassigned, 2 - User 525767, 3 - Unassigned
2                                          1 - Unassigned
3                                          1 - Unassigned
4                                          1 - Unassigned
                               ...
163678                                     1 - Unassigned
163679    1 - Unassigned, 2 - User 347991, 3 - Unassigned
163680                                     1 - Unassigned
163681                                     1 - Unassigned
163682    1 - Unassigned, 2 - User 663455, 3 - Unassigned

A: Use str.findall:
>>> df['A'].str.findall(r'User \d+').str[-1]

0         User 397335
1         User 525767
2                 NaN
3                 NaN
4                 NaN
163678            NaN
163679    User 347991
163680            NaN
163681            NaN
163682    User 663455
Name: A, dtype: object


Q: Read from named piped I have to write a program which monitors two named pipes and prints the information sent through either.
When the write end of one of the pipes is closed, the program will detect this and close and open the pipe again.
This is what I have written so far:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#define BUF_SIZE 200

int
main(void)
{
   fd_set rfds;
   struct timeval tv;
   int retval;
   ssize_t n_read;
   char buf[BUF_SIZE];

   /* Open pipes */
   int tuberia1_fd = open("tuberia1",O_RDONLY);
   int tuberia2_fd = open("tuberia2",O_RDONLY);

   while(1){
       /* Watch stdin (fd 0) to see when it has input. */
       FD_ZERO(&rfds);
       FD_SET(0, &rfds);

       /* Wait for an indefinite amount of time. */
       tv.tv_sec = 0;
       tv.tv_usec = 0;

       retval = select(2, &rfds, NULL, NULL, &tv);
       /* Don't rely on the value of tv now! */

       if (retval == -1)
           perror("select()");
           exit(EXIT_FAILURE);

       if(FD_ISSET(tuberia1_fd, &rfds)){
           n_read = read(tuberia1_fd, &buf, BUF_SIZE);
           if (n_read == 0){
               close(tuberia1_fd);
               tuberia1_fd = open("tuberia1", O_RDONLY);
           }else{
               buf[n_read] = '\0';
               printf("tuberia1: %s", buf);
           }
       } else if (FD_ISSET(tuberia2_fd, &rfds)){
           n_read = read(tuberia2_fd, &buf, BUF_SIZE);
           if (n_read == 0){
               close(tuberia2_fd);
               tuberia2_fd = open("tuberia2", O_RDONLY);
           }else{
               buf[n_read] = '\0';
               printf("tuberia2: %s", buf);
           }
       }
   }
}

When I run it, the program locks, which is the expected behavior. But when I echo hello_world > tuberia1 there is no response from the program.
What is going on?
EDIT: As observed by GM below, I was incorrectly passing arguments to select. After fixing that my program looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#define BUF_SIZE 200

int
main(void)
{
   fd_set rfds;
   struct timeval tv;
   int retval;
   ssize_t n_read;
   char buf[BUF_SIZE];

   /* Open pipes */
   printf("Opening tuberia1");
   int tuberia1_fd = open("tuberia1",O_RDONLY);
   printf("Opening tuberia2");
   int tuberia2_fd = open("tuberia2",O_RDONLY);

   while(1){
       printf("Enter the loop");
       /* Watch stdin (fd 0) to see when it has input. */
       FD_ZERO(&rfds);
       FD_SET(tuberia1_fd, &rfds);
       FD_SET(tuberia2_fd, &rfds);

       /* Wait for an indefinite amount of time. */
       tv.tv_sec = 5;
       tv.tv_usec = 0;

       int fd_max = (tuberia1_fd > tuberia2_fd) ? tuberia1_fd : tuberia2_fd;

       retval = select(fd_max, &rfds, NULL, NULL, &tv);
       /* Don't rely on the value of tv now! */

       if (retval == -1)
           perror("select()");
           exit(EXIT_FAILURE);

       if(FD_ISSET(tuberia1_fd, &rfds)){
           n_read = read(tuberia1_fd, &buf, BUF_SIZE);
           if (n_read == 0){
               close(tuberia1_fd);
               tuberia1_fd = open("tuberia1", O_RDONLY);
           }else{
               buf[n_read] = '\0';
               printf("tuberia1: %s", buf);
           }
       } else if (FD_ISSET(tuberia2_fd, &rfds)){
           n_read = read(tuberia2_fd, &buf, BUF_SIZE);
           if (n_read == 0){
               close(tuberia2_fd);
               tuberia2_fd = open("tuberia2", O_RDONLY);
           }else{
               buf[n_read] = '\0';
               printf("tuberia2: %s", buf);
           }
       }
   }
}

It still does not work. Running it under GDB shows that the program never progresses past the first open.

A: You need to use FD_SET on the file descriptors you're actually interested in -- namely tuberia1_fd and tuberia2_fd.
So something like...
while (1) {
  FD_ZERO(&rfds);
  FD_SET(tuberia1_fd, &rfds);
  FD_SET(tuberia2_fd, &rfds);
  int max;
  if (tuberia1_fd > tuberia2_fd) {
    max = tuberia1_fd;
  } else {
    max = tuberia2_fd;
  }
  tv.tv_sec = 0;
  tv.tv_usec = 0;
  retval = select(max + 1, &rfds, NULL, NULL, &tv);


Q: How to convert String to its resource ID (Android Studio) I have an xml string in my values/strings.xml file
    <string name="pokemon_d">150</string>

And I have the String "150" in my controller MainActivity.java. In my MainActivity, how can I convert that String to the resource ID of the pokemon_d String in the xml file? Is this even possible?

A: You can not get identifier by value, but you can make your identifier name look like a value and get it by string name,
So what I suggest,
use your String resource name something like, resource_150
<string name="resource_150">150</string>
Now here resource_ is common for your string entries in string.xml file, so
in your code,
String value = "150";
int resourceId = this.getResources().
             getIdentifier("resource_"+value, "string", this.getPackageName());

Now resourceId value is as equivalent to R.string.resource_150
Just make sure here this represent your application context. In your case MainActivity.this will work.

A: EDIT
You can't search for a resource Id by the string value. You could make your own Map of the values and resourceIds and use that as a look up table, but I believe just choosing an intelligent naming convention like in the accepted answer is the best solution.

A: I have found some tips here:    Android, getting resource ID from string?
Below an example how to get strings and their values defined in strings.xml. The only thing you have to do is making a loop and test which string is holding your value. If you need to repeat this many times it might be better to build an array.
//---------
    String strField = "";
    int resourceId = -1;
    String sClassName = getPackageName() + ".R$string";
    try {
        Class classToInvestigate = Class.forName(sClassName);

        Field fields[] = classToInvestigate.getDeclaredFields();

        strField = fields[0].getName();
        resourceId = getResourceId(strField,"string",getPackageName());

        String test = getResources().getString(resourceId);

        Toast.makeText(this,
                       "Field: " + strField + " value: " + test ,
                       Toast.LENGTH_SHORT).show();

    } catch (ClassNotFoundException e) {
            Toast.makeText(this,
                       "Class not found" ,
                       Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(this,
                       "Error: " + e.getMessage() ,
                       Toast.LENGTH_SHORT).show();
    }

}
public int getResourceId(String pVariableName, String pResourcename, String pPackageName)
{
    try {
        return getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}

A: In addition to user370305, you could make an extension and use it the same was as with int ids.
import android.app.Activity

fun Activity.getString(id: String): String {
    val resourceId = this.resources.getIdentifier(id, "string", this.packageName)
    return getString(resourceId)
}


Q: Print narrow strings using swprintf in C++Builder The following lines both "work as intended":
wchar_t u[50], v[50];

swprintf(u, 50, L"%s", L"hello");
swprintf(v, 50, L"%ls", L"goodbye");

MessageBoxW(NULL, u, v, MB_OK);   // output: MessageBox showing "hello" and "goodbye"

Is there any way to print a narrow string, and where is the documentation for this? E.g.
swprintf(u, 50, L"%?", "hello");

The C++ Standard specifies (by reference to the C standard) that in the wprintf family of functions, %s specifies a string of char (in multibyte encoding, e.g. UTF-8), and %ls specifies a string of wchar_t.
So the RTL (run-time library implementation supplied with C++Builder) is apparently not standards-compliant here.
Background: I'm actually trying to use UnicodeString::sprintf, however that delegates the heavy lifting to vswprintf.

A: This is not really an answer, but more of a compilation of elements.
Reference :
The site http://www.cplusplus.com/ is clear: for the wprintf family : ... all format specifiers have the same meaning as in printf; therefore, %lc shall be used to write a wide character (and not %c), as well as %ls shall be used for wide strings (and not %s)
Implementations :
gcc and clang both conform to above specification
MSVC and according to OP Borland C++ do not conform and accept %s for a wide string.

A: I managed to find this in the vprinter.c file in the RTL source code (C++Builder comes with its own RTL, it doesn't reference MS):
            /* The 's' conversion takes a string (char *) as
             * argument and copies the string to the output
             * buffer.
             *
             * Note: We must handle both narrow and wide versions
             * depending on the flags specified and the version called:
             *
             * Format           printf          wprintf
             * ----------------------------------------
             * %s               narrow          wide
             * %S               wide            narrow
             * %hs              narrow          narrow
             * %hS              narrow          narrow
             * %ls              wide            wide
             * %lS              wide            wide
             *
             */

so the code:
swprintf(v, 50, L"%hs", "hello");

generates the correct output.
However, this doesn't do any UTF-8 conversion; narrow characters are "widened" by attaching a null byte. (Confirmed by inspecting the resut of the source).


Q: Why does there are three equations and two unknowns have solutions if determinant is zero? how to prove the equation system:
$a_1$$x$ + $b_1$$y$  = $p$
$a_2$$x$ + $b_2$$y$  = $q$
$a_3$$x$ + $b_3$$y$  = $r$
has unique solution for $x$ and $y$ if the determinant of the matrix
${$a_1, b_1, p$; $a_2, b_2, q$; $a_3, b_3, r$}$ is zero
ps: I just red a topic of two lines intersecting in 3d


Q: Can we derive $N=aa^{\dagger}$ from these conditions? Let $[a,b]:=ab-ba$ for all $a,b\in X$ a non commutative ring. Suppose that $a,a^{\dagger},N$ are operators satisfying
$$\begin{align}
[a,a^{\dagger}]&=1 \\
[N,a]&=-a \\
[N,a^{\dagger}] &= a^{\dagger}
\end{align}$$
where $1$ is simply the identity operator and $a^{\dagger}$ is the physicist's adjoint of $a$.

Does it follow that
  $$
N=aa^{\dagger}
$$
  just from these $3$ conditions?

Motivation: My friend ask me a related question, which can be easily solve if the above is true. The $3$ conditions are simply given at the very beginning of the exercise. If we interpret $N$ as the number operator, $a$ as the annihilation operator and $a^{\dagger}$ as the creation operator then it is generally known that $N=aa^{\dagger}$. So I wonder if his professor simply forgot to write that in the exercise sheet or if the fact can be derived.

A: If we assume that  $N$ is positive, the second condition is just a restatement of the second one. If you multiply the first condition by $-a$ on the left you get the second condition for $N=a^{\vphantom\dagger} a^\dagger$. So $N=a^{\vphantom\dagger} a^\dagger$ is certainly a solution. The question is whether it is unique.
This boils down to the question of whether $Xa-aX=0$ implies $X=0$. Such condition certainly doesn't follow from the given conditions. Actually, $X=\lambda I$ will always commute with $a$, so $N=a^{\vphantom\dagger} a^\dagger+\lambda I$ will satisfy the equations for all $\lambda\in\mathbb R$.


Q: Imagemagick transparency not working in 6.9 but works in 7.0 I'm running this command to crop an image and retain (alpha?) transparency:
convert bigger.png -crop 2048x2048 -gravity northwest \
-extent 2048x2048 -transparent white \
-set 'filename:tile' '%[fx:page.x/2048]_%[fx:page.y/2048]' 'tile_%[filename:tile].png'

I'm using the exact same command, but on three different versions.

*

*6.7.2-7 2017-03-23 Q16 (Linux, not sure which dist)

*6.9.7-4 Q16 x86_64 20170114 (Linux/Ubuntu)

*7.0.8-42 Q16 x86_64 (Mac Os Mojave)

On 7.0 it works perfectly, but on 6.x, the background is black after conversion.
Is there some option that was changed in 7.0 that I can try in the old versions?
Thanks!
EDIT:
I tried different combination of these parameters and adding PNG32 to force an alpha channel:
-alpha on -background none -transparent white PNG32:bigger.png


Q: UnknownHostException with HTTPConnection in Android An UnknownHostException arises when I attempt to execute the following code...
String line;
String url = "http://mywebsite.com";
URL theURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) theURL.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
line = rd.readLine();
conn.disconnect();

I have followed suggestions from former posts to ensure that the Internet Permission Tag appears properly in the manifest. I also made sure that my Android has WIFI access, and that the website I am attempting to use is correct. This usually appeared to be a popular resource on StackOverflow: http://guerrarj.hubpages.com/hub/Tips-to-solve-the-UnknownHostException-on-Android
The stack trace is...
java.net.UnknownHostException: the_website.com
    at java.net.InetAddress.lookupHostByName(InetAddress.java:512)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:300)
at java.net.InetAddress.getAllByName(InetAddress.java:259)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1018)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:512)
at com.example.privacyapp.MainActivity.scrapWeb(MainActivity.java:127)
at com.example.privacyapp.MainActivity.checkLocation(MainActivity.java:148)
at com.example.privacyapp.MainActivity$1.onLocationChanged(MainActivity.java:93)
at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:227)
at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:160)
at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:176)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:4263)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)

Update: It appeared that my WIFI connection was faulty. Without a connection, the UnknownHostException arises.

A: Somtimes we have to write ip address instead of "http://mywebsite.com"; so try onece using Ip address.
check also The INTERNET permission tag is a child of the manifest tag, not the application tag.!
and check this once hope this helpful to you


Q: how to calculate sum of dynamically named model names in a ng-repeat I have a dynamic table with dynamic inputs. Each input has an unique number added to the end of the model name. There are 10 inputs per table with the last being the total. I need to watch the first 9 inputs and calculate the sum. Here is what the json looks like after dynamically assigning unique model names.
[
 {
"section_id": 3155,
"subdivision_id": 3500,
"section_name": "Ph 1(P)-Mercedes",
"sectionInputs": [
  {
    "model": "price_min-3155"
  },
  {
    "model": "price_max-3155"
  },
  {
    "model": "units_occ-3155"
  },
  {
    "model": "inv_mod-3155"
  },
  {
    "model": "inv_fin-3155"
  },
  {
    "model": "inv_vdl-3155"
  },
  {
    "model": "inv_uc-3155"
  },
  {
    "model": "inv_fut-3155"
  },
  {
    "model": "inv_con-3155"
  },
  {
    "model": "units_total-3155"
     }
  ]
},
{
"section_id": 12863,
"subdivision_id": 3500,
"section_name": "Ph 1(P)-Adams",
"sectionInputs": [
  {
    "model": "price_min-12863"
  },
  {
    "model": "price_max-12863"
  },
  {
    "model": "units_occ-12863"
  },
  {
    "model": "inv_mod-12863"
  },
  {
    "model": "inv_fin-12863"
  },
  {
    "model": "inv_vdl-12863"
  },
  {
    "model": "inv_uc-12863"
  },
  {
    "model": "inv_fut-12863"
  },
  {
    "model": "inv_con-12863"
  },
  {
    "model": "units_total-12863"
  }
]
},
{
"section_id": 16152,
"subdivision_id": 3500,
"section_name": "Ph 1(P)-Unassigned",
"sectionInputs": [
  {
    "model": "price_min-16152"
  },
  {
    "model": "price_max-16152"
  },
  {
    "model": "units_occ-16152"
  },
  {
    "model": "inv_mod-16152"
  },
  {
    "model": "inv_fin-16152"
  },
  {
    "model": "inv_vdl-16152"
  },
  {
    "model": "inv_uc-16152"
  },
  {
    "model": "inv_fut-16152"
  },
  {
    "model": "inv_con-16152"
  },
  {
    "model": "units_total-16152"
  }
  ]
 }
]

The units_total needs to hold the sum value for each array.  I was looking at using a watchgroup function but not sure how I could do this with possibly needing a for loop? I'm open to suggestions on the best way to handle this. javascript, jquery, lodash, linq.js are what is currently being used in project.
Here is
working plunker
 $scope.model = {};

   function prepareDataForView() {
    for (var i = 0; i < sections.length; i++) {
        sections[i].sectionInputs = sectionInputSvc.sectionInputs(sections[i]);
        sections[i].sectionInputLabels = sectionInputLabels;
    }

    $scope.sections = sections;
}
prepareDataForView();

A: One way to implement this is to calculate the total whenever input ng-changes:
var sum = function(acc,cur){ return acc+cur; }
$scope.modelChanged = function(section, input){
  var inputsCount = section.sectionInputs.length;
  var totalInput = section.sectionInputs[inputsCount-1];
  if(input === totalInput){
    return;
  }
  var total = section.sectionInputs.slice(0, inputsCount - 1).map(function(input){
    return $scope.model[input.model];
  }).filter(angular.isDefined).reduce(sum, 0);

  $scope.model[totalInput.model] = total;
};

Which can then be invoked on each input:
<input ng-model="model[input.model]"  ng-change="modelChanged(section, input)" type="number" />

Here's an updated plunker.

A: Well, I have solved it with jQuery, maybe this answer doesn't fit you because it's inconsistent with your angular app, but I hope it can be helpful to someone else.
$(document).on("change", "input", function()
{
    $tr = $(this).parent().parent();
    $tds = $tr.find("td");
    var sum = 0;
    $.each($tds, function(index, td){
        var valueInput = $(td).find("input").val();
        if(index < 9 ){
            sum += parseFloat((valueInput != "") ? valueInput : 0 );
        }
    });

    $tds.eq(9).find("input").val(sum);
});

Here is the updated plunker


Q: Xpages get a handle on next rowData or Doc in a repeat In my repeat control I want to be able to get a handle on data in the next row in order to modify what data is displayed in my current row (I have move up and down actions, and I don't want to display them if the move is not possible).
It seems I should be able to do this. Probably I cannot from within in the repeat itself, as when it is writing the repeat it will not know the data for the next repeat. But shouldn't there be a fairly easy way to get the next document?
Here is a reduced version of my repeat control:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">

<xp:repeat
                id="repeat1"
                var="rowData"
                indexVar="repeatIndex"
                value="#{view1}"><xp:this.facets>
                    <xp:text
                        disableTheme="true"
                        xp:key="header"
                        escape="false"
                    >
                        <xp:this.value><![CDATA[

Category
Move
Task

]]></xp:this.value>

                    </xp:text>
                    <xp:text
                        disableTheme="true"
                        xp:key="footer"
                        escape="false"
                    >
                        <xp:this.value><![CDATA[
]]></xp:this.value>

                    </xp:text>
                </xp:this.facets>
                <xp:this.rows><![CDATA[#{javascript:var rows:Integer = viewScope.get("rows");
if (rows == null)
{return 5}
else
{return rows}}]]></xp:this.rows>
                <xp:tr id="rowDataContainer">

                    <xp:td
                        style="width:55px;min-width:55px;max-width: 55px;">
                        <xp:text
                            escape="true"
                            id="computedField2">
                            <xp:this.value><![CDATA[#{javascript:rowData.getColumnValue("category");}]]>
                            </xp:this.value>
                        </xp:text>
                    </xp:td>

                </xp:tr>
            </xp:repeat>
</xp:view>

A: You can get view's next row within the repeat with
var nextRow = view1.getAllEntries().getNthEntry(repeatIndex + 2);

"view1" is the xp:dominoView assigned to repeat control and "repeatIndex" is the indexVar of xp:repeat.
You can get next row document's UniqueID then with
nextRow ? nextRow.getUniversalID() : ""

and the e.g. Form field with
nextRow ? nextRow.getDocument().getItemValueString("Form") : ""

Accordingly, you get the previous row with
var prevRow = view1.getAllEntries().getNthEntry(repeatIndex);


Q: Why does my program loop without receiving any new input? I am trying to make is so that my program will start over once the answer is given.  It just won't function again once I run it once.  I want to make it functional to where the user doesn't have to start the program up again.  Thanks!
#include <stdio.h>
#include <math.h>

int main()
{
    float firstnum, secondnum, answer;
    char function;

    printf("\nHello and welcome to my calculator!\n");                                             //Intro

    start:                                                                                //Area to loop to when program completes

    printf("\nPlease input the function you would like to use.  These include +, -, *, /.\n");     //Asking for function input

    scanf("%c", &function);                                                                        //Receiving Function Input

    printf("\nNow please input the two variables.\n");                                             //Asking for variables

    scanf("%f", &firstnum);

    scanf("%f", &secondnum);                                                                       //Receiving Input for Variables

    if (function == '+')                                                                           //Doing calculation
    {
            answer = firstnum+secondnum;
    }
    else if (function == '-')
    {
    answer = firstnum-secondnum;
    }
    else if (function == '*')
    {
    answer = firstnum*secondnum;
    }
    else if (function == '/')
    {
    answer = firstnum/secondnum;
    }
    else
    {
            printf("Sorry that was an incorrect function.  The correct inputs are +, -, *, /.");       //If they don't follow the directions
    }

    printf("Your answer is %f \n", answer);                                                        //Answer

    goto start;                                                                                //Loop

return 0;

}

A: It's the [enter] key. Your first scanf is reading the enter key you pressed to terminate the previous iteration.
So you need to add another scanf("%c", &function); or getchar(); just before the goto to eat the newline.
When reading in numbers, scanf will eat any initial whitespace; but when reading characters, it won't. It gives you the very next byte in the stream.

A better way, perhaps, would be to tell `scanf` where to expect all the newlines. This way you don't need that *weird* mystery line that doesn't appear to do anything but isn't commented (!); because that's gonna cause problems when you play with this code again months from now.

//scanf("%c\n", &function); /* read a character followed by newline DOESN'T WORK */
...
//scanf("%f\n", &secondnum); /* read a number followed by newline DOESN'T WORK */

This way, trailing newlines are consumed. Which is, I think, the more intuitive behavior (from the User side).
 Nope. Doesn't work. Wish it did, cause I'd look less foolish.

I'm not upset by the goto. It's nice to see an old friend. This is an appropriate use of it if ever there was one. It is exactly equivalent to the while form. So you should certainly be aware that most people will prefer to see while(1) because it tells you more about what's going on than label:. But for an infinite loop in a function smaller than a screen, why not? Have fun. No baby seals will be harmed. :)

A: This is why you use loops. (And try not to use goto for this).
#include <stdio.h>
#include <math.h>

int main() {

    float firstnum, secondnum, answer;
    char function, buffer[2];

    while(1) {

        printf("\nHello and welcome to my calculator!\n");

        printf("\nPlease input the function you would like to use.  These include +, -, *, /.\n");
        scanf("%s", &buffer);
        function = buffer[0];
        printf("\nNow please input the two variables.\n");
        scanf("%f", &firstnum);
        scanf("%f", &secondnum);
        if (function == '+') answer = firstnum+secondnum;
        else if (function == '-') answer = firstnum-secondnum;
        else if (function == '*') answer = firstnum*secondnum;
        else if (function == '/') answer = firstnum/secondnum;
        else printf("Sorry that was an incorrect function.  The correct inputs are +, -, *, /.");

        printf("Your answer is %f \n", answer);
        }

     return 0;
     }

This should go in an infinite loop, so use an input from the user to break; the loop to exit the program

Note : I have replaced the scanf %c with %s indicating an input of a string & used a buffer.
 scanf("%s",&buffer); function = buffer[0];

(Updated as per discussion in comments)

A: One "best practise" regarding scanf is to check it's return value. In regards to the return value of scanf, I suggest reading this scanf manual carefully and answering the following questions:

*

*int x = scanf("%d", &foo); What do you suppose x will be if I enter "fubar\n" as input?

*Where do you suppose the 'f' from "fubar\n" will go?

*If it remains in stdin, would you expect a second scanf("%d", &foo); to be successful?

*int x = scanf("%d", &foo); What do you suppose x will be if I run this code on Windows and press CTRL+Z to send EOF to stdin?

*Would it be safe to use foo if x is less than 1? Why not?

*int x = scanf("%d %d", &foo, &bar); What would you expect x to be if I enter "123 456\n" as input?

*Do you suppose the '\n' will still be on stdin? What value would char_variable hold following scanf("%c", &char_variable);?

EOF can be sent through stdin in Windows by CTRL+Z, and in Linux and friends by CTRL+D, in addition to using pipes and redirection to redirect input from other programs and files.
By using code like int function; for (function = getchar(); function >= 0 && isspace(function); function = getchar()); assert(function >= 0); or char function; assert(scanf("%*[ \n]%c", &function) == 1); you can discard leading whitespace before assigning to function.


Q: Why is there an error about headers and authorization in a Stripe dependency? Stripe HTTP request dependency returns an error about headers, but these are not configurable.
Using a GET request seems fine, but a post route fails with the error:
error [err_invalid_char]: invalid character in header content ["authorization"]
app.post('/charge',function(req,res){

  stripe.charges.create({
      amount: 10,
      description: 'Charge',
      currency: 'gbp',
      customer: 'cus_EXgisfTr7LuiO9'
  },function(err,result){
    if(err){
      res.status(400);
      res.send(err);
    }
    else{
      res.status(201);
      res.send(result);
    }
  });
});

Hitting the endpoint https://myapp.herokuapp.com/charge with an HTTP POST request returns this to the console:
error [err_invalid_char]: invalid character in header content ["authorization"]
This is a Stripe dependency however and not configured by the developer.

A: The above error occurs when the Stripe Secret API key is passed incorrectly.
Just for the help,
const Stripe = require('stripe');
const stripe = Stripe(env.STRIPE_TEST_SECRET_KEY);

make sure you change the key as per the production/development environment.
Cheers.


Q: Server.MapPath behaves differently with IIS Server and ASP.Net Development Server? Why does Server.MapPath("~") return different results with IIS Express and ASP.Net Development server?
When I run my application with ASP.Net Development Server, my path returns like "D:\\MyProject\\Web\\WWWRoot\\ISuite5" but when i run using IIS Express , path comes as "D:\\MyProject\\Web\\WWWRoot\\ISuite5\\". There is a difference of "\\" between both. I am not able to figure out the reason behind it or how to resolve it so that IIS Server also returns the same result as ASP.Net Development Server.


Q: Orbits / phase space for ODE. I'm quite confuse with several definition. Let consider the ODE $$\dot x=f(x).$$
As I understand, orbits are the sets $$\mathcal O(x_0)=\{x(t)\mid t\in I, x(0)=x_0\}.$$
Now, I'm a bit confuse with the Phases space. I always thought that it was $$\bigcup_{x\in \mathbb R}\mathcal O(x),$$
(we suppose that $\mathcal O(x)$ is well defined for all $x$), but in some example it works, but in some it doesn't. Suppose that I have the ODE $$\begin{cases}\dot x=y\\ \dot y=-k^2x \end{cases}.$$
So it's a pendulum. And indeed, here, the phase space is $\bigcup_{x\in\mathbb R}\mathcal O(x)$ and near to equilibrium points, these are circle.

But for example, if I consider the ODE $y'(x)=\sin(y(x))$, in my course they say that the phase space is  $$\bigcup_{x_0\in\mathbb R}\{(x(t),\dot x(t))\mid t\in I, x(0)=x_0\}\tag{D}.$$ But these are not orbits... So according to my definition, the phase space should be $\bigcup_{x_0\in\mathbb R}\mid \{x(t)\mid t\in I,\exists s: x(s)=x_0\}$, but according to $(D)$ the phase space of the pendulum should be $$\bigcup_{}\{(x(t),\dot x(t),y(t),\dot y(t))\mid...\}$$
so I'm quite confuse. What do you think ?

A: You are confused because your notation is overloaded. Consider the linearized pendulum, given by the equation
$$
\ddot{y}(t) = -ky(t).
$$
Here $y$ is the physical position of the pendulum in some system of units.
Notice that this equation is NOT in the form $\dot{x} = f(x)$, but can be written in this form by defining two state variables $x_1(t) := x(t)$ and $x_2(t) := \dot{x}(t)$. We define the state vector $x$ to be the vector of all the state variables, that is, $x(t) := [x_1(t) \ x_2(t)]^T$. In terms of the state variables, the system has the form
$$
\begin{bmatrix}
\dot{x}_1(t)\\ \dot{x}_2(t)\\
\end{bmatrix}
=
\begin{bmatrix}
x_2(t)\\ -kx_1(t)\\
\end{bmatrix}
$$
which IS in the form $\dot{x} = f(x)$, where $x$, again, is the state vector. Hence, the orbits are of the form
$$
O(x_0) := \{x(t) \ | \ t\in I, x(0) = x_0\} = \{[x_1(t) \ x_2(t)]^T \ | \ t\in I, [x_1(0) \ x_2(0)]^T = [x_{1,0} \ x_{2,0}]^T\}
$$
where I have defined initial conditions in the obvious way.
The phase space is defined to be
$$
\bigcup_{x\in \mathbb{R}^2}O(x) = \bigcup_{[x_{1,0} \ x_{2,0}]^T\in \mathbb{R}^2}\{[x_1(t) \ x_2(t)]^T \ | \ t\in I, [x_1(0) \ x_2(0)]^T = [x_{1,0} \ x_{2,0}]^T\}
$$
but in your notation $x_1 = x$ and $x_2 = y$. Note that $\dot{x} = y$ so it doesn't make sense to include both of them.


Q: Arrays inside of Object JavaScript I want to create an array inside of an object with values that refer to properties of the same object containing the array.
The only problem I am having is that the results inside of the array are undefined instead of what they are supposed to be.
Am I even referring to the properties correctly? Here is my JavaScript for the object.
var cc_cd = {
    name: "CC Waterbound",
    date: "Summer 1995",
    t1name: "Intro",
    t1url: "https://www.youtube.com/embed/Rsh5oQ6JCTI",
    t1length: "0:40",
    t2name: "Bout 2 Go Down",
    t2url: "https://www.youtube.com/embed/XgJ6DdIaXd0",
    t2length: "4:44",
    t3name: "Dope and money",
    t3url: "https://www.youtube.com/embed/cruY77l99_M",
    t3length: "3:51",
    t4name: "Looking Down the Barrel",
    t4url: "https://www.youtube.com/embed/jmLgcnUlgfk",
    t4length: "4:33",
    t5name: "Playa Hatas",
    t5url: "https://www.youtube.com/embed/ZY8eCUuuqJY",
    t5length: "5:18",
    t6name: "4 Real Nigga Possie",
    t6url: "https://www.youtube.com/embed/A-syQCa3iN0",
    t6length: "6:14",
    t7name: "CC Waaterbound",
    t7url: "https://www.youtube.com/embed/eIAOcKg8xfk",
    t7length: "5:25",
    t8name: "Creepin",
    t9url: "https://www.youtube.com/embed/MpBB7rnaw_Q",
    t9length: "3:56",
    t10name: "Hood Cord",
    t10url: "https://www.youtube.com/embed/PNMiP67NhcM",
    t10length: "4:11",
    t11name: "All This Dick",
    t11url: "https://www.youtube.com/embed/a5zWyURBIjE",
    t11length: "5:25",
    array:[this.t1name,this.t1date,this.t1url,this.t2name,this.t2date,this.t2url,this.t3name,this.t3date,this.t3url,this.t4name,this.t4date,this.t4url,this.t5name,this.t5date,this.t5url,this.t6name,this.t6date,this.t6url,this.t7name,this.t7date,this.t7url,this.t8name,this.t8date,this.t8url,this.t9name,this.t9date,this.t9url,this.t10name,this.t10date,this.t10url,this.t11name,this.t11date,this.t11url]
}

A: I wouldn't know what could be going wrong, but I do know an easy solution could be creating a global array and then setting the property to the global array.
Code:

    var array = [ your array] ;
    var cc_cd = {
    List : array,
    Other properties
    };

Please mark answered or vote to let me know if this helped!


Q: How to use Oraclize in solidity to pass arguments to the data source? My aim is to pass some string to the data source and then process there and get back the result.
Below given code works in solidity
oraclize_query("URL", "json(https://clever-ape-38.localtunnel.me).a","sfdg");

But when i try to fetch some value from blockchain and use it, if fails
string memory st = arr[msg.sender];
oraclize_query("URL", "json(https://clever-ape-38.localtunnel.me).a",st);

everything compiles properly. Even truffle migrate --reset works fine.
I feel that the fetching from blockchain takes some time and oraclize_query() is called before the fetch.
Below there is mentioned the error.
    [2019-05-28T08:54:50.206Z] INFO new HTTP query created, id: 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19
[2019-05-28T08:54:50.215Z] INFO checking HTTP query 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19 status in 0 seconds
[2019-05-28T08:54:50.215Z] INFO checking HTTP query 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19 status every 5 seconds...
[2019-05-28T08:54:56.634Z] INFO 72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19 HTTP query result:
    {
    "result": {
        "_timestamp": 1559033691,
        "id": "72e3a263387ed365d97bc97a64c601380a5b4e8bbd1b3740bcc2af1e2bc97b19",
        "daterange": [
            1559033689,
            1559035489
        ],
        "_lock": false,
        "id2": "72fdf59adf3ecc92244e3b173ce1657252ab5eb877c3569a393599d34dd2c848",
        "actions": [],
        "interval": 3600,
        "checks": [
            {
                "errors": [
                    "TypeError",
                    "parsing_helper.wrong_path"
                ],
                "success": true,
                "timestamp": 1559033691,
                "results": [
                    ""
                ],
                "proofs": [
                    null
                ],
                "match": true
            }
        ],
        "version": 3,
        "_timestamp_creation": 1559033689,
        "context": {
            "protocol": "eth",
            "relative_timestamp": 1559033687,
            "type": "blockchain",
            "name": "eth_AB65E563DB"
        },
        "active": false,
        "hidden": false,
        "payload": {
            "conditions": [
                {
                    "query": [
                        "json(https://purple-squid-54.localtunnel.me).a",
                        "28189689"
                    ],
                    "proof_type": 0,
                    "check_op": "tautology",
                    "datasource": "URL",
                    "value": null
                }
            ]
        }
    },
    "success": true
}
[2019-05-28T08:54:56.637Z] ERROR HTTP query error
    [
    "TypeError",
    "parsing_helper.wrong_path"
]
[2019-05-28T08:54:56.639Z] INFO sending __callback tx...
    {
    "contract_myid": "0x72fdf59adf3ecc92244e3b173ce1657252ab5eb877c3569a393599d34dd2c848",
    "contract_address": "0x481a276d14a6a74e1ec1f74b64c2af226ba7033c"
}
[2019-05-28T08:55:01.853Z] INFO contract 0x481a276d14a6a74e1ec1f74b64c2af226ba7033c __callback tx sent, transaction hash: 0xfada229b6f9860e0717b3a098dd93aaef280852dbf75109c830b555c488e6c81
    {
    "myid": "0x72fdf59adf3ecc92244e3b173ce1657252ab5eb877c3569a393599d34dd2c848",
    "result": "",
    "proof": null,
    "proof_type": "0x00",
    "contract_address": "0x481a276d14a6a74e1ec1f74b64c2af226ba7033c",
    "gas_limit": 200000,
    "gas_price": null
}

Please help to solve this.

A: Thank you for adding the error logs.
Actual answer:
If you're adding POST data as a string but that's in a valid JSON format, it will be parsed as such. In order to preserve it as a string, you need to add a newline char or whitespace so the beginning of the string:
"\n<post-data-here"
Original answer re the parsing-error which proved not to be the main issue in the end...
You're hitting a parsing error in the ethereum-bridge due to it trying but failing to parse the returned json from your query.
However at the time of writing, your local tunnel is returning a 404 error rather than the data it originally returned.
Then, as the ethereum-bridgeattempts to parse thejsonto pluck the value from thea` key, per your query:
json(https://purple-squid-54.localtunnel.me).a
...it can't because there is not json and so no a field and so you get a parsing error.
To fix it, ensure your local tunnel is working and that the data returned is in correct json format, and that there is an a key present for the parser to work with.


Q: Trying to write Java program to play mp3 file I am trying to write a program that plays an mp3 file. For some reason, I am getting the error "package.javafx.scene.media does not exist." How can I fix this?

A: You need e(fx)clipse or you need to add the jfxrt.jar to your classpath. It comes with your JDK.
How do I work with JavaFX in Eclipse Juno? should sort it out for you. NetBeans and IntelliJ come with built-in support for JavaFX.

A: You could also work with Java 8 as JavaFX is already included there. It also provides a lot of improvements on JavaFX components.


Q: JAX-RS @Path() custom format I'm Regex newbie. What I trying to do here is, I have 2 @PathParam so the user can either type in "/session" or "/requester" or anything but these two.
If the user type "/session" or "/requester" this input will go to pathparam 1 else the pathparam 2.
Here is my regex.
@Path("/generateotp{session:(/session[^\\w&&[^\\W]]|/requester[^\\w&&
[^\\W]])?}{senderid:(/[^/&&\\w]|(?:(?!requester|session).))?}")

I know I'm kind of redundant the [^\w&&[^\W]] part but the [^.+] just don works.
Extra things here. How can I cut the "/" when the input will go to the senderid pathparam. I need the user to input it in because of the generateotp there but when it process and throw to the pathparam, that is where i don't need it. I can use substring after that to cut it but is there anyway i can do it in the regex?


Q: What service can be used to limit the number of IoT device connections to a database? I have an IoT system with about 2000 devices. I would like each of the devices to upload data to a MongoDB instance.
Each device connects every 8-12 seconds and makes a single entry. The actual entry writing takes about 50ms.
My MongoDB has a maximum connection count of 100. Even though it's unlikely, there's always the chance that all 2000 devices will simultaneously connect and be rejected by the db due to max connection count.
Is there a pre-existing queuing service that all my devices can send data to? I don't want to have to write a middle-man server to collect all the data from IoT devices and forward it onto the db.
So basically instead of:
|device| --------> Database
I need:
|device|-------> service ------> Database
I'm just not sure what this 'service' is. Does such a thing exist? What should i be looking for? I tried using AWS SQS but I couldn't quite figure out how to make entries to the mongo db from the AWS SQS. Is this the right tool or is there another service out there?

A: You can try using Message Queues.
Rabbit MQ is a good option as it supports MQTT (which is great for device to cloud communication) as well as AMQP (0.9.1) (which is great for cloud to cloud communication)
You can also use any standard MQTT broker (EMQTT, Mosquito, Hive etc) and implement an MQTT to MongoDB client in between. Setting the MQTT clean_session flag to false will make the broker act as a cache.


Q: Resize an image before uploading it to firebase Firebase storage looks very cool and easy to use, but I'm wondering if there's a way to resize an image before uploading it to Firebase Storage, e.g., run a proccess using ImageMagick in a server and then run the uploading process using Firebase SDK but I notice there aren't storage functions for Firebase SDK Server.

A: Resize using JavaScript Client-Side-Processing
We're using JavaScript resizing, which uses clients device processing power to resize the image, and works GREAT, saving us space and money, saving the netwrok unnecesary bandwidth, and saving the client a bunch of time and also money in most mobile cases.
The original script we are using came from here, and the procedure to use it is as simple as this:
<input type="file" id="select">
<img id="preview">
<script>
document.getElementById('select').onchange = function(evt) {
    ImageTools.resize(this.files[0], {
        width: 320, // maximum width
        height: 240 // maximum height
    }, function(blob, didItResize) {
        // didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
        document.getElementById('preview').src = window.URL.createObjectURL(blob);
        // you can also now upload this blob using an XHR.
    });
};
</script>

I believe that guy (dcollien) deserves a LOT of merit, so I would recommend you to vote his answer up.

A: You can also use Firebase Storage + Google Cloud Functions to upload an image, resize the image (using ImageMagick or similar), and write it back to Firebase Storage.
I have an example using these together here (though I trigger the Cloud Vision API, rather than an image resizer).
A quick side note: Firebase Storage doesn't have a Node.js client, instead we recommend using the GCloud-Node library.

A: You could also use Firebase Storage + the official Firebase Resize Image extension:
https://firebase.google.com/products/extensions/firebase-storage-resize-images. The downside here is that "To install an extension, your project must be on the Blaze (pay as you go) plan". Bc basically what it will do is spin up a Firebase Function App for you, and it'll get triggered every time you upload a file to the path you specify. You can configure things like the desired size as well as the format or if you want to keep a copy of the original file or not.  Good thing you won't need to worry about the underlying implementation.


Q: XPath - выбрать промежуток данных до и после определенных элементов <!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

H2

P

Python code

JS code

Example

Вот есть такой HTML код.
Хочу написать XPath для выборки всех данных в тегах code, т.е. мне нужен список в конце с элементами Python code и JS code.
Проблема заключается в том, что нужен такой XPath, который бы собирал все теги code, которые вложены в дивы перед тегом p в котором text()='Example'.
Играюсь с following-sibling и preceding-sibling и не могу подобрать нужный икспас.
Спасибо.

A: Ищем code, который вложен в div, относительно которого первой следующей нодой, не содержащей дочерний code, является p с текстом Example :
//code[ancestor::div/following-sibling::*[not(.//code)][1][self::p][text()='Example']]

const xpath = "//code[ancestor::div/following-sibling::*[not(.//code)][1][self::p][text()='Example']]";

function getElementByXpath(xpathToExecute){
  var result = [];
  var nodesSnapshot = document.evaluate(xpathToExecute, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
  for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ ){
    result.push( nodesSnapshot.snapshotItem(i) );
  }
  return result;
}

console.log( getElementByXpath(xpath) );

      <meta charset="UTF-8">
      <title>Title</title>

    dont touch me 1

H2

P

      dont touch me 2

      dont touch me 3

    dont touch me 4

Example

    dont touch me 5

      dont touch me 6

      dont touch me 7

Invalid Example

      Python code

      JS code

Example

A: Ищем div'ы, за которыми сразу следует параграф с текстом Example, и берем дочерние code
//div[following-sibling::p[1][text()='Example']]/code


Q: varnish - regexp to edit x-forward-for header inbound / outbound I am curious if anyone knows, is it possible to build a varnish config which

*

*looks at inbound headers from clients

*and does regexp match, to build a certain header - that is passed on to backed web server?

Context:
-- Varnish server deployed in front of 3-(apache)-webserver pool, acting as cache and LB
-- 3rd party service DDOS proxy was dropped in front of varnish recently
-- now all inbound requests to varnish have an X-Forwarded-For: header already present, indicating what the 'real' client IP address is.
-- the back-end PHP web app running on the apache hosts - wants to see only one IP address, not a 'proper' X-F-F header which shows a comma-delimited list IP1, IP2, IP3 (for external proxy; varnish as proxy, original client IP - for example)
-- ideally what I would like to do: is get Varnish to do regexp pattern match:rebuild on the existing inbound X-F-F headers; and strip away the external DDOS proxy IP address
I had tried something like this in the 'default.vcl' file,
set req.http.X-Forwarded-For = regsub(req.http.X-Forwarded-For, "123.123.123.123"," ");
where 123.123.123.123 is the IP address of the external DDOS / proxy
but this most certainly is not working / is not the correct syntax.  I'm having trouble finding good resources online that explain regexp in varnish / or good clear examples that people use.
If anyone can provide a kick in the right direction, certainly it would be greatly appreciated.

Thanks for comment below - I have adjusted my config now as follows,

if (req.http.x-forwarded-for) {
set    req.http.X-Forwarded-For =
regsub(req.http.X-Forwarded-For, "\, 123\.123\.123\.123","");
           } else {
               set req.http.X-Forwarded-For = client.ip;
           }

and now I find in my apache logs, for example,
    client.ip.real.here, 123.123.123.123 - - [22/Dec/2013:07:45:17 -0800] "GET /PATH/TO/STUFF" "Mozilla/5.0.... like Gecko"

which suggests to me the regexp is not actually doing what I thought I wanted.  Is there any way to 'test' varnish interactively, ie, feed a given VCL rule set some defined input, and then get varnish to feed out specific output; kind of a 'dry run' processing as a way to facilitate debug ?
Thanks!


Q: How to restrict user to use 1 email id or phone number in only 1 device I'm developing an Android app with Android studio and firebase authentication and I want to restrict user to use 1 email id or 1 phone number in only 1 device .any suggestion how can I archive this functionality.

A: Firebase Authentication was not designed to support this case. It's intended for users to be able to use a Firebase app on multiple devices.  It's also expected that a user could create multiple accounts.  There is no way of limiting the number of accounts a person can create.