text:
Q: Finding the stationary point on the curve: $e^x+ye^{-x}=2e^2$ So I'm trying to find the stationary point of this equation: $e^x+ye^{-x}=2e^2$. This is my attempt at doing so:
$$\dfrac{d}{dx}(e^x+ye^{-x})=\dfrac{d}{dx}(2e^2)$$
$$e^x+(-ye^{-x}+\frac{dy}{dx}\times e^{-x})=0$$
$$\dfrac{dy}{dx}=\dfrac{-e^x+ye^{-x}}{e^{-x}}$$ Setting $\dfrac{dy}{dx}=0$
$$-e^x+ye^{-x}=0$$
$$y=\dfrac{e^x}{e^{-x}}=e^{2x}$$
I can't seem to draw a conclusion, and I don't know how to proceed, could anyone help?
Thanks in advance.

A: Now you have two relations between abscissa and ordinate of stationary point .
$1.)$ The curve itself.
$2.)$ $y=e^{2x}$
Substitute $y=e^{2x}$ in the equation of the curve, you will get $x$-coordinate of stationary point and you know how to calc. $y$-coordinate then.

A: First find $y$:
$$y = 2e^{2+x}-e^{2x}$$
So that:
$$y' = 2e^{2+x}-2e^{2x}=0$$
$$e^2=e^x \to x=2$$


text:
Q: How to execute multiple-line selection in do-file editor of Stata? Does anyone know how to use the "execute selection" function in the do-file editor of Stata for code that spans multiple lines?
Currently I can't find a way to do this without using the #delimit ; system which requires repeating "delimit ;" at the beginning of every block I want to run.
Any suggestions appreciated!

A: I believe that you might be understanding the #delimit ; command wrongly: this is useful when you are coding a do-file to execute it in its entirety afterwards. I also assume that you are using Stata 11, since previous versions behave differently (if I recall well, Stata 10 SE for Mac does not support // comments and delimiting, for example).
If you are executing only a fraction of the code, use /// at the end of a line to continue its command on the next one.
Basic example (that will clear any open data, so beware):
sysuse lifeexp, clear
sc lexp safewater, ///
mlab(country);

This should run flawlessly even if you execute the sysuse command and the sc (scatter) commands separately. The sc command has the mlab option (to add labels to the data points) on a different line, but both lines will be interpreted as only one command due to the /// indication.
Hope this helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Support for Fonts in Zebra Android SDK I am printing a receipt using Zebra printer ( Android SDK).
I have checked the documentation of the SDk but could not find any utility class that can help in setting of font size/name/height.
Currently i am hard-coding the parameters and creating a .lbl file but i think that is not a good approach.
So, is their any utility class that would generate the script for .lbl file depending on set of parameters i provided to it.

A: The Zebra SDK does not provide extensive label design support.  It is designed to help with discovery, communication, configuration, and printing to Zebra printers.  To my knowledge there is no real element of the SDK that will help you change font sizes dynamically.
Your approach is correct: defined a .LBL template file, and populate the data at print-time. Often, an end-user wil want to use a nearly identical label (in terms of font size, graphics, positioning) and will simply change the printed data.  Dynamically changing those elements (font size, for example) doesn't seem to be a common need.  That is just my impression.


text:
Q: How to set Api response message like {Success or Not - message} in UI / Screen in flutter? I want to display message on screen or a snackbar or AlertDialog which get from api response.
So how to get API response message?
Here is my Function for Validate OTP as below in api_manager.dart file.
Now how can i pass the snackbar to my screen?
Future validateOtp(BuildContext context, String otp, LogedinUser? userData,
      UserPlan? userPlan) async {
    final String otpUrl = "$baseUrl/otp/validate";
    var formData = FormData.fromMap({
      'user_id': userData!.userId,
      'otp': otp,
      'device_id': userData.deviceId,
    });
    var response = await dio.post(otpUrl, data: formData);

    final validateOtpData = validateOtpFromJson(response.data);
    final status = validateOtpData.success;

    print(response.data);

    if (response.statusCode == 200) {
      var res = response.data;
      print(userData.userId);
      print(userData.deviceId);
      print(otp);
      print(res);
      if (status == 1) {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => DashBoard(
              user: userData,
              userPlan: userPlan,
            ),
          ),
        );
        return status;
      } else if (status == 0) {
        final apiMsg = validateOtpData.msg;
        final snackBar =
            SnackBar(content: Text(apiMsg!), backgroundColor: Colors.grey);
        ScaffoldMessenger.of(context).showSnackBar(snackBar);
      }
    }
  }

Here is my OTP verifivation screen.
@override
  void initState() {
    super.initState();

    ApiManager().validateOtp(context, otp, userData, userPlan).then((apiMsg) {
      setState(() {
        //msg = apiMsg;
      });
    });
  }

 @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        OtpTextField(
          numberOfFields: 6,
          fieldWidth: 43,
          focusedBorderColor: Colors.black,
          onSubmit: (String otpValue) {
            setState(() {
              otp = otpValue;
            });
          },
        ),
        ElevatedButton(
          onPressed: () {
            ApiManager().validateOtp(context, otp, userData, userPlan);
          },
          child: Text("Verify"),
        )
      ],
    );
  }

Here is the response for invalid or expired OTP .

And this is valid OTP response.

Below is Validate OTP Model Class in validate_otp.dart file.
// To parse this JSON data, do
//
//     final validateOtp = validateOtpFromJson(jsonString);

import 'dart:convert';

ValidateOtp validateOtpFromJson(String str) =>
    ValidateOtp.fromJson(json.decode(str));

String validateOtpToJson(ValidateOtp data) => json.encode(data.toJson());

class ValidateOtp {
  ValidateOtp({
    required this.success,
    required this.msg,
  });

  int success;
  String? msg;

  factory ValidateOtp.fromJson(Map<String, dynamic> json) => ValidateOtp(
        success: json["success"] == null ? null : json["success"],
        msg: json["msg"] == null ? null : json["msg"],
      );

  Map<String, dynamic> toJson() => {
        // ignore: unnecessary_null_comparison
        "success": success == null ? null : success,
        "msg": msg == null ? null : msg,
      };
}

So when OTP is incorrect or expired i want to display OTP is either expired or not valid. response from api on Validate OTP Screen.
Thank you.

A: Your model ValidateOtp exposes the data member msg which you can use to access the "msg" field from the received JSON.
Just do
var response = await dio.post(otpUrl, data: formData);
final validateOtpData = validateOtpFromJson(response.data);
final apiMsg = validateOtpData.msg;
final status = validateOtpData.success;

print(apiMsg!);

Just remember that validateOtpData.msg would be null in case of successful verification so you'd have to handle that case appropriately.
Now to show a snackbar on success or failure, you could do something like this
if(response.statusCode != 200){
    final snackbar = SnackBar(content: Text(apiMsg!), backgroundColor: Colors.red);
    ScaffoldMessenger.of(context).showSnackBar(snackbar);
}

For the context variable, you'd have to pass an additional BuildContext from the widget from which you are trying to show the snackbar. So change your function arguments to look something like
validateOtp(
      context, String otp, LogedinUser? userData, UserPlan? userPlan, BuildContext context)

And now pass the context as well when you try to call the function.

A: The below snippet should help. It gives you a very basic idea of how to achieve your purpose.
N.B: Example is just an abstract explanation
   import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: OTP(),));
}

class OTP extends StatefulWidget {
  @override
  _OTPState createState() => _OTPState();
}

class _OTPState extends State<OTP> {
  String error = "";

  Future OtpValidation() async{
    error= "Error occured";
  }

  Future validateOtp() async {
   await OtpValidation(); //Do your Networking & logic
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: !error.isEmpty
          ? Text(error)
          : Column(
        children: [
          ElevatedButton(
            onPressed: () {validateOtp();},
            child: Text("Validate OTP"),
          ),
        ],
      ),
    );
  }
}


text:
Q: add color info into checkbox folder dat.gui Is it possible to add color information into checkbox folder? Like on the picture.
I know there exists color controller, but I just need checkbox with information about color, which it represents (TCP is red, UDP is purple,...).
I tried to google it, but unsuccessfully.

A: You can modify the DOM elements for each gui option however you want.
var checkbox = gui.add( obj, 'showTCP' )
checkbox.domElement.classList.add('blue')


text:
Q: Not able to LEFT OUTER JOIN three tables I've got a problem.
Currently I have three tables, the first table is the main table and if there is no record in the second table, write it too. But if a record exists in the second table, so from the third table display "dispo" information..
I want to use three SAP table - lagp, lqua and marc.
Me goal is write all stock positions from lagp.
2x LEFT JOIN doesnt work: "Unable to compare with"B~MATNR". A table can be joined with a maximum of one other table usign LEFT OUTER JOIN.
Structure:
TYPES:
  BEGIN OF t_work,
    lgnum TYPE lgnum,
    lgtyp TYPE lgtyp,
    lgpla TYPE lgpla,
    bdatu TYPE lagp_bdatu,
    matnr TYPE matnr,
    verme TYPE lqua_verme,
    meins TYPE meins,
    dispo TYPE dispo,
  END OF t_work.
DATA:
  lt_work TYPE TABLE OF t_work INITIAL SIZE 0,
  ls_work LIKE LINE OF lt_work.

And SQL command:
SELECT a~lgnum a~lgtyp a~lgpla a~bdatu b~matnr b~verme b~meins c~dispo FROM lagp AS a
   LEFT JOIN lqua AS b ON a~lgnum = b~lgnum AND a~lgtyp = b~lgtyp AND a~lgpla = b~lgpla
  INNER JOIN marc AS c ON b~matnr = c~matnr AND b~werks = c~werks
  INTO TABLE lt_work
   WHERE a~lgnum IN so_lgnum
     AND a~lgtyp IN so_lgtyp
     AND a~skzua EQ space
     AND a~skzue EQ space.

But as result is only one stock position - http://i.stack.imgur.com/1sEEo.png
Can you tell me, how the SQL code has look?
Thank you

A: Try:
SELECT a~lgnum, a~lgtyp, a~lgpla, a~bdatu, b~matnr, b~verme, b~meins, c~dispo
   FROM lagp AS a
   LEFT JOIN ( lqua AS b
               JOIN marc AS c ON b~matnr = c~matnr AND b~werks = c~werks )
          ON a~lgnum = b~lgnum AND a~lgtyp = b~lgtyp AND a~lgpla = b~lgpla
  INTO TABLE @lt_work
   WHERE a~lgnum IN @so_lgnum
     AND a~lgtyp IN @so_lgtyp
     AND a~skzua EQ @space
     AND a~skzue EQ @space.

Other option would be to put the join between LQUA and MARC in a view and do an outer join with the view. Or split out the select on MARC and do that while looping at the data found with a select on LAGP and LQUA.

A: I got that fine working code:
  SELECT ma~matnr ma~mtart ma~ernam ma~ersda ma~laeda
  de~maktx as maktx_de fr~maktx as maktx_fr it~maktx as maktx_it
  FROM mara as ma
  LEFT JOIN MAKT as de ON de~matnr = ma~matnr AND de~spras = 'DE'
  LEFT JOIN MAKT as fr ON fr~matnr = ma~matnr AND fr~spras = 'FR'
  LEFT JOIN MAKT as it ON it~matnr = ma~matnr AND it~spras = 'IT'
  INTO CORRESPONDING FIELDS OF TABLE g_it_material
  WHERE ma~ernam IN so_ERNAM
  AND ma~laeda IN so_LAEDA
  AND ma~matnr IN so_MATNR.

and it works fine. What did you say about multi-leftjoins?


text:
Q: How to write insert trigger in sql server 2005? Hello I want create one insert trigger in that i have to table that
Table hardwaremaster
 hardwareid     hardwarename      quantity
     1             HDD              5          and second table
     2             RAM              2

Table transdetails
  transid        hardwareid
     1               1
     2               1
     3               1
     4               1
     5               1
     6               2
     7               2

Here i want to create trigger in that once value come in hardwaremaster then it will update table transdetails . then how to write trigger in to it

A: This can help you :
 CREATE TRIGGER TR_INS_WhatYouWant
    ON hardwaremaster
    AFTER INSERT
    AS
    DECLARE @hardwareid  INT
    SELECT @hardwareid  = hardwareid  FROM inserted
    GO

    INSERT INTO dbo.transdetails (hardwareid) VALUES (@hardwareid)

But I suggest to read this before make trigger work :
CREATE TRIGGER


text:
Q: How to bend a mesh along a circle in three.js? I want to bend or curve a text mesh along a circle. I'm working on it from 4 days but still can't get any solution.
I use Bend-modifier library to bed the text. It helps but it bends the object from center only. So if i want to make a circle it cant help me. i.e. If I bend the text 90 degree's it'll be a 'U' shape text.
I just want to make it complete circle or even a half circle. It bends in a way that no shape will lost. It's width remain same.
    textMesh = new THREE.Mesh(geometry, materials);

    var bendModifier = new THREE.BendModifier();
    var direction = new THREE.Vector3(0, 0, -1);
    var axis = new THREE.Vector3(0, 1, 0);
    var angle = Math.PI/2.6
    bendModifier.set(direction, axis, angle).modify(textMesh.geometry);
    scene.add(textMesh);

But I want this to make a perfect half circle of text in the scene
Anyone knows how to do it?


text:
Q: App sin errores de compilación no responde Estoy desarrollando una app que, pese a no tener errores de compilación, al intentar emularla no responde. He probado a comentar partes del código pero el resultado no ha variado. Por ello, no sé dónde puede estar el problema ¿A qué se puede deber esto?
Añado el manifest y el Gradle por si acaso:
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="xxx.xxxx.xxx">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:debuggable="false"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
           <receiver
               android:name="xxx.xxx.xxx.Monitor"
               android:enabled="true"
               android:permission="android.permission.RECIEVE_BOOT_COMPLETED" >
                  <intent-filter>
                      <action android:name="android.intent.action.BOOT_COMPLETED" />
                      <category android:name="android.intent.category.DEFAULT" />
                  </intent-filter>
            </receiver>
        <activity android:name="com.xxx.xxx.MainActivity"
                android:configChanges= "orientation|screenSize"
                android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
        </activity>
        <activity android:name="com.xxx.xxx.Ajustes"
            android:configChanges= "orientation|screenSize"
            android:label="@string/app_name">
        </activity>
    </application>
</manifest>

Gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "xxx.xxxx.xxx"
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'org.jetbrains:annotations-java5:15.0'
    compile 'com.android.support:design:26.+'
}

logcat:
07-18 12:36:05.414 3649-3649/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: xxx.xxx.xxx, PID: 3649
                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{xxx.xxx.xxx/com.xxx.xxx.MainActivity}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                     at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:154)
                                                     at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
                                                  Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
                                                     at com.android.internal.policy.PhoneWindow.requestFeature(PhoneWindow.java:338)
                                                     at android.app.Activity.requestWindowFeature(Activity.java:3946)
                                                     at com.xxx.xxx.MainActivity.onCreate(MainActivity.java:52)
                                                     at android.app.Activity.performCreate(Activity.java:6662)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                     at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:154)
                                                     at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

la línea del main activity al que hace referencia ahí es
 requestWindowFeature(Window.FEATURE_NO_TITLE);

pero he probado a comentarla y no ha funcionado.
MainActivity:
public class MainActivity extends Activity
{
    static WebView web;
    static String etiqueta;
    static String mensaje;
    static String si;
    Context context=this;
    static SharedPreferences datos;
    ImageButton boton;
    static boolean paisES;

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

       // BotonAjustes();
        //Identificar la WebView con la variabe "web" que hemos creado
        web = (WebView) findViewById(R.id.webV);

        //identificar el país y el idioma para distintos diomas
        paisES =("ES".equals(Locale.getDefault().getCountry())|| "es".equals(Locale.getDefault().getLanguage()));

        //Para poner pantalla completa
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        //Verificar conexión

        if (Conectividad.conectado(this))
        {
            if(paisES)
            {
                etiqueta="https://www.xxx.xx/launcher/xxx-xx/?language=es_ES";
            }
            else
            {
                etiqueta="https://www.xxx.xx/launcher/xxx-xx/?language=en_US";
            }
        }
        else
        {
            if(paisES)
            {
                etiqueta="https://www.xxx.xx/launcher/xxx-xx/?language=es_ES";
                mensaje="No tienes conexión ¿Deseas configurar tu conexión a Wi-fi ahora?";
                si="Sí";
            }
            else
            {
                etiqueta="https://www.xxx.xx/launcher/xxx-xx/?language=en_US";
                mensaje="You have no connection. Do you want to configure your Wi-Fi connection?";
                si="Yes";
            }
            dialogWifi(web);
        }
        //si hay un ID metido, entra directamente al mismo. Si no, va al launcher
        if (Leer("ID").equals("vacío")==false)
        {
            //SEGUIDA DE LA EJECUCIÓN PREVIA
            if ("ES".equals(Locale.getDefault().getCountry()))
            {
                //mensaje = "¿Quieres seguir la ejecución desde el punto en el que lo dejaste?";
                //si = "Sí";
                //leemos el fichero para saber si hay datos de ejecuciones previas
                etiqueta="https://www.xxx.xx/xxx/"+Leer("ID")+"/?mode=autoplay&language=es_ES";

            }
            else
            {
                // mensaje = "Do you want to continue the execution from the point you left it?";
                //si = "Yes";
                etiqueta="https://www.xxx.xx/player/"+Leer("ID")+"/?mode=autoplay&language=en_US";
            }
            // dialReanudar(web);
        }

        web=(WebView)findViewById(R.id.webV);
        GestionWeb.CrearWeb(etiqueta, web);
        GestionWeb.Seguirweb(web);

        //Para acelerar el webView
        web.getSettings().setCacheMode(web.getSettings().LOAD_NO_CACHE);
        web.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    }
    public void BotonAjustes()
    {
        View.OnClickListener aj= new  View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Intent intent= new Intent(MainActivity.this, Ajustes.class);
                startActivity(intent);
            }
        };
        boton= (ImageButton) findViewById(R.id.imageButton7);
        boton.setOnClickListener(aj);
    }
    /**
     * Método para preguntarle al usuario si desea configurar el wi-fi o no. en caso afirmativo, se le redirecciona a ajustes
     * @param view se necesitará para usar web
    */
    public void dialogWifi(View view)
    {
        AlertDialog.Builder dial= new AlertDialog.Builder(this);
        dial.setMessage(mensaje);
        dial.setPositiveButton(si, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i)
            {
                //Abre la configuración de Wi-fi
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                dialogInterface.cancel();
                web.reload();
            }
        });
        dial.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i)
            {
                dialogInterface.cancel();
            }
        });
        dial.create().show();
    }

    public void dialReanudar(View view)
    {
        AlertDialog.Builder dial= new AlertDialog.Builder(this);
        dial.setMessage(mensaje);
        dial.setPositiveButton(si, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i)
            {
                //En este caso, etiqueta tendrá la web leída
                etiqueta=Leer("enelace");
                GestionWeb.CrearWeb(etiqueta,web);
                dialogInterface.cancel();
            }
        });
        dial.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i)
            {
                dialogInterface.cancel();
            }
        });
        dial.create().show();
    }

    public static void Guardar(String guardado, String fichero)
    {
        SharedPreferences.Editor editor=datos.edit();
        editor.putString(fichero, guardado);
        editor.commit();
    }

    public static String Leer(String fichero)
    {
        String e=datos.getString(fichero, "vacío" ); //(valor que queremos recoger, valor por defecto si no encuentra nada)
        return e;
    }
}

Cabe destacar que la app empezó a dar problemas al añadir una nueva actividad.

A: El error

Caused by: android.util.AndroidRuntimeException: requestFeature() must
  be called before adding content

Indica que requestFeature() debe ser llamado antes de agregar el contenido mediante setContentView(), en este caso sería:
@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        //Para poner pantalla completa
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.activity_main);

       // BotonAjustes();
        //Identificar la WebView con la variabe "web" que hemos creado
        web = (WebView) findViewById(R.id.webV);

        //identificar el país y el idioma para distintos diomas
        paisES =("ES".equals(Locale.getDefault().getCountry())|| "es".equals(Locale.getDefault().getLanguage()));

        //Verificar conexión
...
...

A: El problema que estás teniendo es que estás haciendo el requestWindowFeature()
después del  setContentView(); esto es lo que te está provocando el error que aparece en el Logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{xxx.xxx.xxx/com.xxx.xxx.MainActivity}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content

Como dice la documentación de Android para la función requestWindowFeature()

Enable extended screen features. This must be called before
  setContentView(). May be called as many times as desired as long as it
  is before setContentView(). If not called, no extended features will
  be available. You can not turn off a feature once it is requested. You
  canot use other title features with FEATURE_CUSTOM_TITLE.

Traducción:

Habilitar funciones de pantalla extendida. Esto debe llamarse antes de
  setContentView(). Se puede llamar tantas veces como se desee, siempre
  y cuando sea antes de setContentView(). Si no se llama, no habrá
  funciones extendidas. No se puede desactivar una función una vez que
  se solicita. No puede utilizar otras funciones de título con
  FEATURE_CUSTOM_TITLE.

Por lo que tu código debería cambiarse para cumplir esto de la siguiente forma:
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.activity_main);

    .....
}

EDIT:
Prueba a poner el getWindow().setFlags(); antes del setContentView() también
ya que según la documentación de setFlags() indica que:

Note that some flags must be set before the window decoration is
  created (by the first call to setContentView(View,
  android.view.ViewGroup.LayoutParams)

Traducción:

Tenga en cuenta que algunos indicadores deben establecerse antes de
  que se cree la decoración de la ventana (por la primera llamada a
  setContentView(View,  android.view.ViewGroup.LayoutParams)

Quedando tu código de la siguiente forma:
 @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_main);

        .....
    }


text:
Q: Adding module to sys.modules to deal with non-relative submodule imports I have a submodule I'm vendoring in which is poorly written (it does not use relative imports but has two packages. To be clear, I'm not installing these packages (because they don't have well maintained packages on pypi, just including the source code.)
So the layout looks like the following:
root
  |
  |-code
  |   |-file.py
  |
  |-vendor
      |-submodule
           |-package_1
           |    |-alpha.py
           |-package_2
                |-beta.py

Unfortunately, beta.py tries to import package_1 which doesn't work because there's no __init__.py. Because I'm pulling all submodules fresh during CI/CD, this lack of relative imports breaks my tests.
This would work if everything is at the root directory, but I can't control the submodules. I also don't want to change alpha.py or beta.py because I don't want to deal with forks.
Is there any way to have a universal __init__.py or some equivalent so that when beta.py imports, it sees package_1 and alpha.py?

A: __init__.py or lack thereof is irrelevant for whether something counts as a package on modern (3.3+) Python due to PEP 420's Implicit Namespace Packages.
Something tells me the vendor packages expects the directory containing both of their packages (root/vendor/submodule in this case) to be added to sys.path by some mechanism (possibly just be being installed at top level in site-packages, not in some nested directory as you have it set up); if your repackaging fails to put them in the root of some entry in sys.path, nor updates sys.path to include wherever you did put them, then their packages won't work.
The solution is to install their packages to a sys.path location or update sys.path to include their location, so package_1 is a top-level package as package_2 expects.
Assuming these vendor modules are only used in file.py, you could have the import of file.py manually update sys.path with code like this:
import pathlib
import sys

# Get the path to file.py, go up to the parent directory, then down to
# vendor/submodule
vendor_dir = pathlib.Path(__file__).parent.parent / 'vendor' / 'submodule'
sys.path.append(str(vendor_dir))

# import package_1.alpha or package_2.beta will now work


text:
Q: data limit on chrome.storage.local It is my understanding that there is no hard limit imposed on saving to
chrome.storage.local

so long as the unlimited storage permission is set.  Is this true?  Doesn't that endanger the sandbox, by allowing a malicious developer to flood someones hard drive merely by asking for an innocent sounding permission?

A: By default, it is limited to 5 MB in Chrome, but it is true that the limit can be disabled by the unlimitedStorage permission.
To quote the documentation of chrome.storage.local:

QUOTA_BYTES

5242880
The maximum amount (in bytes) of data that can be stored in local storage, as measured by the JSON stringification of every value plus every key's length. This value will be ignored if the extension has the unlimitedStorage permission. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError.

It is correct that the WebExtension API in combination with unlimitedStorage allows to fill up the disk.
That is why it is recommended to install only trusted extensions. Yet for malicious extensions, I would be more concerned about the data that they could send out (e.g. stealing credentials). Or that they can redirect users to phishing sites. Like malware, which is capable of filling up the disk, but typically chooses other - more harmful - attacks.


text:
Q: how to start each function from index 1 to post json objects in different div in html I have this json data
somehow i displayed this part of data in html
and want to display this part of data

into div in html but i am unable to display it using for loop and don't to how to start each function from index 1 as index 0 in personal details data.
here is my code
var url = "http://localhost/ReadExchange/api.php";
$.getJSON(url, function(data) {
      if (data) {
        alert("hey got the data" + JSON.stringify(data));
        var arr = data.length;

        //$.each(data, function(i,element) {
        var element = data[0];
        $("#postjson").append(
          '
' + '
' + 'FirstName:' + element.FirstName + '
'

          + 'MiddleName:' + element.MiddleName + '
' + 'LastName:' + element.LastName + '
' + 'Gender:' + element.Gender + '
' + 'Location:' + element.Location + '
' + 'Email:' + element.Email + '
' + 'Mobile:' + element.Mobile + '
' + '
' + '
'
        );

        for (var i = 1; i < arr; i++) {
          $("#postjson").append(
            '
' + '
' + 'BookTitle:' + data[i].data.BookTitle + '
' + 'BookGenre:' + data[i].data.BookGenre + '
' + 'BookWriter:' + data[i].data.BookWriter + '
' + 'Gender:' + data[i].data.BookDescription + '
'

            + '
' + '
'
          );
        }

      } else {
        return;
      }

A: You can use Array.prototype.splice()
data.splice(0, 1);

then iterate data array at for loop, with i set to 0

var data = [{abc:123}, {def:456}];

data.splice(0, 1);

for (var i = 0; i < data.length; i++) {
  alert(JSON.stringify(data))
}


text:
Q: Preventing Reset during ESD I would like to design a RC filter to prevent reset to a SoC during a ESD strike. Assuming the reset net is by default low.
And the reset comes from a separate board which connects to the main board (where SoC resides) using a Board to Board connector.
In case there is air discharge on the daughter board. I want to avoid changing the state of reset line during the ESD strike and avoid trigger of reset to the SoC.

A: Assuming the reset pin is pulled up, putting a 100nF cap to ground at the pin generally won't hurt you. The bigger issue here is ESD protection. Where is the ESD getting into the circuit? Cable shields, connectors, the enclosure, any user interface buttons or knobs, , etc. all need to be considered. The energy from the event needs to be safely dissipated, with the how depending on the source. I strongly recommend read through John Barnes' articles on ESD protection.


text:
Q: How to mock an object into the Application class of android in a test-case? I am testing [Using UI Automator] a particular task, where a thread is started when the application class is created. [onCreate()].
Now, I have mocked the entire thread which makes a http call to series of tasks that happen inside the app. [mockedThread]
Now, I use a variable to access this object when TEST=true and run in the normal mode where a http call is made when TEST=false. I make TEST=true only inside the test methods.
Right now the code works in this way -
onCreate() {

  if TEST == true {
    use mock object and update it manually.
    -- mockedObject
  } else if TEST == false {
    use real object and update it using http calls.
    -- real Object
  }
}

Now I'm trying to use the mocked object without this if -- else loop of testing = TRUE or FALSE. Is there any was we can do this with mockito or any other way... like dagger2 or something ?
[PS: Please don't advise on Powermock as these are not static object]
I am trying to mock it like this but doesn't work :
testMock() {
 try {
   AndroidApplication application = Mockito.mock(AndroidApplication.class);
   context.startActivity(intent);
   mDevice.wait(Until.hasObject(By.pkg(TARGET_PACKAGE).depth(0)), Constants.LAUNCH_TIMEOUT);
            Mockito.when(application.getThreadObject()).thenReturn(mockObject);
 } catch(MockException m){
    m.printStackTracke();
 }
}

Error I get it - Actually, there were zero interactions with this mock.


text:
Q: How to stop default action of tab key in HTML page In my HTML page multiple components exist and on pressing tab button, focus is set to some components (not in sequence). How do I stop tab from putting focus on any component on entire page ? Using outermost div id of html page can we block tab from putting focus on any component and on location bar as well ?
I have added jsfiddle (demo) as well where even I am not using tabindex but still focus is coming so kindly tell me how to disable tab  click.
$(document).on('keydown', function(event) {
   if (event.keyCode == 9) {   //tab pressed
      event.preventDefault(); // stops its action
   }
});

A: I tried below code and its working fine in my scenario :
$(document).keydown(function (e)
{
    var keycode1 = (e.keyCode ? e.keyCode : e.which);
    if (keycode1 == 0 || keycode1 == 9) {
        e.preventDefault();
        e.stopPropagation();
    }
});

A: Here is some jQuery you can use to disable the tab key on the whole page.
$(document).on('keydown', function(event) {
    if (event.keyCode == 9) {   //tab pressed
        event.preventDefault(); // stops its action
    }
});

There may be some other ramifications of completely disabling the tab key that you may want to consider.

A: A little change try keypress instead of keydown and return false instead of event.preventDefault();
Something like this
$(document).on("keypress", function(event) {
    if (event.keyCode == 9) {   //tab pressed
        return false; // stops its action
    }
});

A: I am new to this place so dont know How to answer in comments. I tried but it looks like a line not code
its worked fine with this code Actually .on shud be removed from it
$(document).keydown(function(event) {
    if (event.keyCode == 9) {  //tab pressed
        event.preventDefault(); // stops its action
    }
})

Updated the fiddle as well


text:
Q: Underscore.js - How to identify javascript dependencies? I'm using backbone.js and underscore.js for my mobile app project. My question is how to identify javascript dependencies for each files? I try using my code below but still not working in my browser.
require.config({
    waitSeconds: 0,
    //path mappings for module names not found directly under baseUrl
    paths: {
        jquery: 'vendor/jqm/jquery_1.7_min',
        jqm: 'vendor/jqm/jquery.mobile-1.4.0-rc.1',
        underscore: 'vendor/underscore/underscore_amd',
        backbone: 'vendor/backbone/backbone_amd',
        jqueryflexslider: 'vendor/lib/jquery.flexslider',
        shCore: 'vendor/lib/shCore',
        shBrushXml: 'vendor/lib/shBrushXml',
        shBrushJScript: 'vendor/lib/shBrushJScript',
        jqueryeasing: 'vendor/lib/jquery.easing',
        jquerymousewheel: 'vendor/lib/jquery.mousewheel',
        demo: 'vendor/lib/demo',
        text: 'vendor/require/text',
        plugin: 'plugin',
        main: 'main',
        messages: 'messages',
        templates: '../templates',
        modules: '../modules',
        model: '../model'
    },
    shim: {
        'backbone': {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        },
        'jquery': {
            exports: '$'
        },
        'jqm': {
            deps: ['jquery'],
            exports: '$'
        },
        'jqueryflexslider': {
            deps: ['jquery'],
            exports: '$'
        },
        'jqueryeasing': {
            deps: ['jquery'],
            exports: 'jQuery'
        },
        'jquerymousewheel': {
            deps: ['jquery'],
            exports: '$'
        },
        'demo': {
            deps: ['jquery'],
            exports: '$'
        },
        'main': {
            deps: ['jquery'],
            exports: '$'
        },
        'messages': {
            deps: ['jquery'],
            exports: '$'
        },
        'underscore': {
            exports: '_'
        },
    }
});
//1. load app.js,
//2. configure jquery mobile to prevent default JQM ajax navigation
//3. bootstrapping application
define(['app', 'jqm-config'], function(app) {
    $(document).ready(function() {
        console.log("DOM IS READY"); // Handler for .ready() called.
    });
    app.initialize();
});

Reference: https://github.com/woothemes/FlexSlider/blob/master/demo/index.html
Please advice me.

A: It really depends. I am new to JavaScript as well.  I use Visual studio as my IDE. To install packages I use NuGet Package Manager in visual studio. It basically installs all dependency packages for you.
In other hand, you have two good websites where if you search for packages/libraries, it will give you the most up-to-date information about the package and its dependencies.
NPM - Search for the package you need
ex:backbone

NuGet - Search for the package you need
ex:DataTables

This way you can find the dependencies of the package to configure amd.
Hope this helps somebody if not you!
Happy Javascripting!!


text:
Q: (Visual Basic) How to split a string value into an array of strings? I have an array of strings:
array()
and
string = "('one','two','three', ...)"
The values one two three are examples. The string may have more than three words.
How can I fill the array() with:
"one"
"two"
"three"
...

A: Dim s = "('one','two','three', ...)"
Dim tokens = From token In s.Trim("(", ")").Split(","c)
             Select token.Trim("'"c)
Dim array() As String = tokens.ToArray()

Remember to add Imports System.Linq
Demo: https://dotnetfiddle.net/Ayy0y1
Note that it's not necessary to use LINQ, i just found it more readable than:
Dim array As String() = s.Trim("(", ")").Split(","c)
For i As Int32 = 0 To array.Length - 1
    array(i) = array(i).Trim("'"c)
Next

A: Use String.Split to break up the starting string into an array populated with the split items.
Dim items = "one two three four five"
Dim array = items.Split(" ")
' Outputs array = [ "one", "two", "three", "four", "five" ]

A: Another solution is with the use of Regex:
Dim str As String = "('one','two','three')"
str = RegularExpressions.Regex.Replace(str, "\('|'\)", "")
Dim array() As String = RegularExpressions.Regex.Split(str, "','")

If there are spaces to remove then:
Dim str As String = "( 'one','two' , 'three ')"
str = RegularExpressions.Regex.Replace(str, "\s+|\(\s*'|'\s*\)", "")
Dim array() As String = RegularExpressions.Regex.Split(str, "','")

A: Start with the string as you presented it:
Dim myString As String = "('one','two','three')"
Debug.WriteLine(myString)

Output:
('one','two','three')

Next get rid of the unwanted characters by replacing them with empty quotes (nothingness).  The Chr(39) function represents the single quote:
myString = myString.Replace("(", "").Replace(")", "").Replace(Chr(39), "")
Debug.WriteLine(myString)

output:
one,two,three

Next convert it to an array with the .Split() method:
Dim myStringArray() As String = myString.Split(",")
For i As Integer = 0 To myStringArray.Length - 1
    Debug.WriteLine(myStringArray(i))
Next i

Output:
one
two
three

This works without any "Imports" statements


text:
Q: Preserve order by after updating data in Material UI in React When I select a column, the order is not preserved when the data is automatically reloaded and returns to the original order.
  const [data, setData] = useState([]);

  const [order, setOrder] = useState("asc");
  const [orderBy, setOrderBy] = useState("category");

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        `https://example.com/api/v1/news?orderBy=${orderBy}&order=${order}`
      );

      setData(result.data);
    };

    const interval = setInterval(() => {
      fetchData();
    }, 120000);
    return () => clearInterval(interval);
  }, []);

  const handleRequestSort = (event, property) => {
    const isAsc = orderBy === property && order === "asc";
    setOrder(isAsc ? "desc" : "asc");
    setOrderBy(property);
  };

The handleRequestSort does not seem to work.
<MaterialTable
          data={data}
          onRequestSort={handleRequestSort}
          columns={[
            {
              title: "Category",
              field: "category",
              render: (rowData) => {
                return {rowData.category};
              },
            },
            {
              title: "Type",
              field: "type",
              render: (rowData) => {
                return {rowData.type};
              },
            },
          ]}
        ></MaterialTable>

How can I make sure it is preserved?


text:
Q: How can I remove the associated image when an image map area is clicked in JavaScript (jQuery)? I created a simple 'whack-a-mole' game where the same image appears in the gamespace in random positions and at random times and if you click the image it disappears, no problem. To make the game more difficult I added an image map so that you have to click a certain part of the image and now I can't figure out how to remove the associated image after a click. I have read lots of related questions on this site and the closest that I found was the answer by FiLeVeR10 that used hover but it was too slow and only worked for about 20% of the clicks playing the game at speed.
The closest other way that worked is adding an .on click to the image map area. This method is running my IncrementScore() function just fine, but what can I use on the next line to remove the associated image? I have tried at least a hundred different things and none of them work. Adding an onclick attribute to the area behaved the same and would increment the score, but I still had the same problem removing the underlying image.
The only place that I can even see the image is in offsetParent, but all of the images in the gamespace were in there as well and not just the one that I want to remove, so I couldn't figure out how to select the right one. The relevant code is below.

$(document).ready(function() {
  $('#molemap').on('click', function(e) {
    incrementScore(); //This works perfectly
    $(this).I.have.tried.hundreds.of.things.here; //And I can't figure it out
  });
});

function addMole() {
  $('#gamespace').append('');
}

  <map name="molemap">
          <area id="molemap" coords="25,163,56,139,48,125,44,108,45,92,8,82,4,100,5,118,9,133,15,146" shape="poly"/>
      </map>

A: You'll need to create a different map for each image, otherwise you won't be able to tell which image was clicked.
This markup assigns a data-mole attribute to the area, so you'll be able to associate it with the matching image upon click:

<map name="mm1">
  <area shape="rect" data-mole="1" coords="20, 20, 60, 60" href="#" />
</map>

A working example with 3 images.

const gameSpace = document.getElementById('gamespace');

// listen for clicks within the gamespace
gamespace.addEventListener('click', evt => {
  const area = evt.target;
  const map = area.parentElement;

  // determine if click was within a mole's area
  const iMole = area.dataset.mole;
  if (iMole) {
    let moleImg = document.getElementById(`mole${iMole}`);
    // remove image, area, map
    moleImg.remove();
    area.remove();
    map.remove();
  } else {
    alert('you missed!');
  }
});
#gamespace {
  background-color: green;
  width: 400px;
  height: 180px;
}

img {
  height: 80px;
  width: 80px;
  position: absolute;
}

  <map name="mm1">
     <area shape="rect" data-mole="1"
       coords="20, 20, 60, 60" href="#" />
    </map>

  <map name="mm2">
     <area shape="rect" data-mole="2"
       coords="20, 20, 60, 60" href="#" />
    </map>

  <map name="mm3">
     <area shape="rect" data-mole="3"
       coords="20, 20, 60, 60" href="#" />
    </map>


text:
Q: How to find all nodes in a subtree in a recursive SQL query? I have a table which defines a child-parent relationship between nodes:
CREATE TABLE node (                           ' pseudo code alert
  id        INTEGER PRIMARY KEY,
  parentID  INTEGER, ' should be a valid id.
)

If parentID always points to a valid existing node, then this will naturally define a tree structure.
If the parentID is NULL then we may assume that the node is a root node.
How would I:

*

*Find all the nodes which are decendents of a given node?

*Find all the nodes under a given node to a specific depth?

I would like to do each of these as a single SQL (I expect it would necessarily be recursive) or two mutually recursive queries.
I'm doing this in an ODBC context, so I can't rely on any vendor specific features.
Edit

*

*No tables are written yet, so adding extra columns/tables is perfectly acceptable.

*The tree will potentially be updated and added to quite often; auxillary data structures/tables/columns would be possible, though need to be kept up-to-date.
If you have any magic books you reach for for this kind of query, I'd like to know.

Many thanks.

A: This link provides a tutorial on both the Adjacency List Model (as described in the question), and the Nested Set Model. It is written as part of the documentation for MySQL.
What is not discussed in that article is insertion/delection time, and maintenance cost of the two approaches. For example:

*

*a dynamically grown tree using the Nested Set Model would seem to need some maintenance to maintain the nesting (e.g. renumbering all left and right set numbers)

*removal of a node in the adjacency list model would require updates in at least one other row.

A:
If you have any magic books you reach for for this kind of query, I'd like to know.

Celko's Trees and Hierarchies in SQL For Smarties

A: Store the entire "path" from the root node's ID in a separate column, being sure to use a separator at the beginning and end as well. E.g. let's say 1 is the parent of 5, which is the parent of 17, and your separator character is dash, you would store the value -1-5-17- in your path column.
Now to find all children of 5 you can simply select records where the path includes -5-
The separators at the ends are necessary so you don't need to worry about ID's that are at the leftmost or rightmost end of the field when you use LIKE.
As for your depth issue, if you add a depth column to your table indicating the current nesting depth, this becomes easy as well. You look up your starting node's depth and then you add x to it where x is the number of levels deep you want to search, and you filter out records with greater depth than that.


text:
Q: When is $R \, A^{-1} \, R^t$ invertible? In the context of a Gaussian model, I came across a matrix product $R \, A^{-1} \, R^t$ where $R$ is a $m \times n$ rectangular matrix and as implied $A$ is $n \times n$ and invertible.
On which properties of $R$ does the existence of $(R \, A^{-1} \, R^t)^{-1}$ depend?

A: First, if $m=n$ and $R$ is invertible, then $RA^{-1}R^T$ is invertible as well.
Second, if $A$ is in addition symmetric and positive definite on the range of $R$, then $RA^{-1}R^T$ is invertible if $R$ has rank $m$. Actually, in this case $RA^{-1}R^T$ is symmetric and positive definite as well.
This does not work without definiteness of $A$:
$$
R=\begin{pmatrix}0&1\end{pmatrix}, \quad
A^{-1}=\begin{pmatrix}1 & 1 \\  1 &0\end{pmatrix}, \quad
RA^{-1}R^T = 0,
$$
which provides an example, where $R$ has full rank, but $RA^{-1}R^T$ is not
invertible.


text:
Q: contentDocument возвращает null Мне надо изменить расположение куба при нажатии на кнопку. Я должен получить координаты куба(в примере используется только прямоугольник) и изменить их. Но contentDocument возвращает null, из за чего getElementById вызывает ошибку.
html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru" lang="ru">
<head>
<title></title>
</head>
<body>

    <object data="kub.svg" width="500" height="600" type="image/svg+xml" id="kub">
    </object>

    <input type=button value="Смещение по оси OX" onClick="test1()">

    <script type="text/javascript">

        var temp, xx, yy, zz;
        temp = document.getElementById("kub");

        function test1() {
            var svgDoc = temp.contentDocument;

            *var r1 = svgDoc.getElementById("r1");*

            xx = r1.getAttribute("x");
            xx = IntParse(xx);
            r1.setAttribute("x", xx);
        }

    </script>

</body>
</html>

SVG:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" width="100%" height="100%" fill="none"
xmlns="http://www.w3.org/2000/svg">

    <g>
        <line x1 = "300" y1 = "300" x2 = "500" y2 = "300" stroke = "black" fill = "none"
        stroke-width = "1">
        </line>
        <line x1 = "500" y1 = "300" x2 = "490" y2 = "300" stroke = "black" fill = "none"
        stroke-width = "1" transform = "rotate(45, 500, 300)">
        </line>
        <line x1 = "500" y1 = "300" x2 = "490" y2 = "300" stroke = "black" fill = "none"
        stroke-width = "1" transform = "rotate(-45, 500, 300)">
        </line>
        <text x = "510" y = "303" stroke = "black" fill = "none">
            y
        </text>
    </g>

    <g>
        <line x1 = "300" y1 = "300" x2 = "300" y2 = "100" stroke = "black" fill = "none"
        stroke-width = "1">
        </line>
        <line x1 = "300" y1 = "100" x2 = "300" y2 = "110" stroke = "black" fill = "none"
        stroke-width = "1" transform = "rotate(45, 300, 100)">
        </line>
        <line x1 = "300" y1 = "100" x2 = "300" y2 = "110" stroke = "black" fill = "none"
        stroke-width = "1" transform = "rotate(-45, 300, 100)">
        </line>
        <text x = "297" y = "95" stroke = "black" fill = "none">
            z
        </text>
    </g>

    <g>
        <line x1 = "300" y1 = "300" x2 = "150" y2 = "450" stroke = "black" fill = "none"
        stroke-width = "1">
        </line>
        <line x1 = "150" y1 = "450" x2 = "157" y2 = "443" stroke = "black" fill = "none"
        stroke-width = "1" transform = "rotate(45, 150, 450)">
        </line>
        <line x1 = "150" y1 = "450" x2 = "157" y2 = "443" stroke = "black" fill = "none"
        stroke-width = "1" transform = "rotate(-45, 150, 450)">
        </line>
        <text x = "143" y = "463" stroke = "black" fill = "none">
            x
        </text>
    </g>

    <line x1="350" y1="400" x2="300" y2="450" stroke="red" stroke-width="2"></line>
    <line x1="450" y1="400" x2="400" y2="450" stroke="red" stroke-width="2"></line>
    <rect id="r1" x="300" y="350" height="100" width="100" stroke="red" stroke-width="2"</rect>
    <rect x="350" y="300" height="100" width="100" stroke="red" stroke-width="2"></rect>
    <line x1="350" y1="300" x2="300" y2="350" stroke="red" stroke-width="2"></line>
    <line x1="450" y1="300" x2="400" y2="350" stroke="red" stroke-width="2"></line>

</svg>

Ошибка:

Uncaught TypeError: Cannot read properties of null (reading 'getElementById')


text:
Q: Handling multiple top level elements with jq I'm trying to modify the deluge web.conf file with jq and I'm having some issues. The deluge web config seems to be invalid json
{
  "file": 1,
  "format": 1
}
{
  "sidebar_show_zero": false,
  "show_session_speed": false,
  "pwd_sha1": "CHANGEME",
  "show_sidebar": true,
  "sessions": {},
  "enabled_plugins": [],
  "base": "/",
  "first_login": true,
  "theme": "gray",
  "pkey": "ssl/daemon.pkey",
  "default_daemon": "",
  "cert": "test",
  "session_timeout": 3600,
  "https": false,
  "interface": "0.0.0.0",
  "sidebar_multiple_filters": true,
  "pwd_salt": "salt",
  "port": 8112
}

It has multiple top level elements which aren't separated by a comma so if I try to edit the file with jq using something like this jq '.pwd_sha1 = "NEW HASH"' web.conf I get the following
{
  "file": 1,
  "format": 1,
  "pwd_sha1": "NEW HASH"
}
{
  "sidebar_show_zero": false,
  "show_session_speed": false,
  "pwd_sha1": "NEW HASH",
  "show_sidebar": true,
  "sessions": {},
  "enabled_plugins": [],
  "base": "/",
  "first_login": true,
  "theme": "gray",
  "pkey": "ssl/daemon.pkey",
  "default_daemon": "",
  "cert": "test",
  "session_timeout": 3600,
  "https": false,
  "interface": "0.0.0.0",
  "sidebar_multiple_filters": true,
  "pwd_salt": "salt",
  "port": 8112
}

jq is adding a new element to the first top level object and changing the second top level element's value. How can I get this to only change the existing item in the second top level element?

A: The web.conf you show is a stream of JSON entities. Fortunately for you, jq is stream-oriented, and it appears from your example that you could simply write:
jq 'if .pwd_sha1 then .pwd_sha1 = "NEW HASH" else . end' web.conf

In general, though, it might be more appropriate to write something with a more stringent test, e.g.
jq 'if type == "object" and has("pwd_sha1")
  then .pwd_sha1 = "NEW HASH" else . end' web.conf

"changing the second top level element's value"
To edit the second top-level item only, you could use foreach inputs with the -n command-line option:
foreach inputs as $in (0; .+1;
  if . == 2 then $in | .pwd_sha1 = "NEW_HASH"
  else $in end)


text:
Q: How to retrieve data from firebase v9 to display it on the frontend? Hi I have a contact form that I connected to firebase. Now I want to be able to use that data and display in the browser. I tried so many approaches but to no avail. So now I'm seeking your help.
the collection is called messages
Here's the code of how I connected the contact form to firebase:
import {addDoc, collection} from '@firebase/firestore'
import {db} from '../firebase'

    const [fullName, setFullName] = useState("")
    const [email, setEmail] = useState("")
    const [phone, setPhone] = useState("")
    const [company, setCompany] = useState("")
    const [service, setService] = useState("")
    const [msg, setMsg] = useState("")

        const docRef = await addDoc(collection(db, 'messages'), {
            Email: email,
            Nom: fullName,
            Message: msg,
            Service: service,
            Téléphone: phone,
            Société: company
        })

Here is my attempt at retrieving the data from firebase:
import { db } from "../firebase"
import { useState, useEffect } from "react"
import {
    onSnapshot,
    collection,
} from "@firebase/firestore"

const messages = () => {
    const [messages, setMessages] = useState([])

    useEffect(() =>
        onSnapshot(collection(db, "messages"),
            (snapshot) => {
        setMessages(snapshot.docs)
            }
        ),
            [db]
      )

    return (

            {messages.map((message) => {

{message.Email}

            })}

    )
}

export default messages

A: I think mostly you're not unwrapping the data() from the DocumentSnapshot in your onSnapshot handler. If that's indeed the only problem (it's hard to be certain with some more details, such as seeing what your documents look like), it'd be fixed with:
(snapshot) => {
  setMessages(
    snapshot.docs.map(doc => {
      return { id: doc.id, ...doc.data() }
    })
  )
}


text:
Q: What is a good way in Mercurial to untrack all files and start fresh? Related question: https://softwareengineering.stackexchange.com/questions/275310/why-isnt-the-addremove-recommended-by-default-in-mercurial
I am working on a LaTeX project and was new to Hg when I started on it about a week ago. Basically I tracked all the files in the folder using the command hg addremove *. After realizing my error, I have been tracking only the files which I think I will repeatedly edit. However, I haven't yet untracked all the files I asked Hg to track at the start of the repo.
The result is that Hg not only tracks the source files with .tex extensions but is also tracking the resulting .pdf files — something that I think is resulting in an unnecessary bloat in my repo. How can I start fresh?
On a related but separate note: is it a bad idea to track MS Word files (say ending in .docx) using Hg?  My method of using LaTeX is somewhat like this:  https://tex.stackexchange.com/questions/61967/how-to-run-latex-from-word
If add a string Rome was not built in a day. to a text file and save it, the new version of the text file is just 28 characters larger than the old version. I am not sure if .docx works in a similar way. Hence the question.

A: Regarding your first question
hg convert is what you're looking for -- ConvertExtension.
You want to use the --filemap option to exclude all your PDF files.
Because the filemap doesn't support wildcards/globs (*.pdf), you'll need to build a list of all the PDF files in your repository in order to exclude them. If you're on a unix like platform you can do that with find.


text:
Q: Getting vertical gridlines to appear in line plot in matplotlib I want to get both horizontal and vertical grid lines on my plot but only the horizontal grid lines are appearing by default. I am using a pandas.DataFrame from an sql query in python to generate a line plot with dates on the x-axis. I'm not sure why they do not appear on the dates and I have tried to search for an answer to this but couldn't find one.
All I have used to plot the graph is the simple code below.
data.plot()
grid('on')

data is the DataFrame which contains the dates and the data from the sql query.
I have also tried adding the code below but I still get the same output with no vertical grid lines.
ax = plt.axes()
ax.yaxis.grid() # horizontal lines
ax.xaxis.grid() # vertical lines

Any suggestions?

A: maybe this can solve the problem:
matplotlib, define size of a grid on a plot
ax.grid(True, which='both')

The truth is that the grid is working, but there's only one v-grid in 00:00 and no grid in others. I meet the same problem that there's only one grid in Nov 1 among many days.

A: plt.gca().xaxis.grid(True) proved to be the solution for me

A: For only horizontal lines
ax = plt.axes()
ax.yaxis.grid() # horizontal lines

This worked

A: According to matplotlib documentation, The signature of the Axes class grid() method is as follows:

Axes.grid(b=None, which='major', axis='both', **kwargs)
  Turn the axes grids on or off.
which can be 'major' (default), 'minor', or 'both' to control whether
  major tick grids, minor tick grids, or both are affected.
axis can be 'both' (default), 'x', or 'y' to control which set of
  gridlines are drawn.

So in order to show grid lines for both the x axis and y axis, we can use the the following code:
ax = plt.gca()
ax.grid(which='major', axis='both', linestyle='--')

This method gives us finer control over what to show for grid lines.

A: Short answer (read below for more info):
ax.grid(axis='both', which='both')

What you do is correct and it should work.
However, since the X axis in your example is a DateTime axis the Major tick-marks (most probably) are appearing only at the both ends of the X axis. The other visible tick-marks are Minor tick-marks.
The ax.grid() method, by default, draws grid lines on Major tick-marks.
Therefore, nothing appears in your plot.
Use the code below to highlight the tick-marks. Majors will be Blue while Minors are Red.
ax.tick_params(which='both', width=3)
ax.tick_params(which='major', length=20, color='b')
ax.tick_params(which='minor', length=10, color='r')

Now to force the grid lines to be appear also on the Minor tick-marks, pass the which='minor' to the method:
ax.grid(b=True, which='minor', axis='x', color='#000000', linestyle='--')

or simply use which='both' to draw both Major and Minor grid lines.
And this a more elegant grid line:
ax.grid(b=True, which='minor', axis='both', color='#888888', linestyle='--')
ax.grid(b=True, which='major', axis='both', color='#000000', linestyle='-')

A: You may need to give boolean arg in your calls, e.g. use ax.yaxis.grid(True) instead of ax.yaxis.grid().  Additionally, since you are using both of them you can combine into ax.grid, which works on both, rather than doing it once for each dimension.
ax = plt.gca()
ax.grid(True)

That should sort you out.

A: Try:
plt.grid(True)

This turns on both horizontal and vertical grids for date series with major tick marks in the right place.
Using Python3 / MatPlotLib 3.4.3


text:
Q: Why would seed method work properly, but queries not work? I'm using EF to manage my database and I've successfully set up the database, ran my migration, updated the database, and checked in MSSQL Studio to confirm that the records are there.
However, when I try and run a query against the DB, the debug window prints

Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll

until it seems like the call eventually times out nothing gets returned.
Here is my query.
public async Task<Feature> GetFeatureById(int id){
   try {return await _dbcontext.Features.FirstAsync(m => m.Id == id); }
   catch (Exception e) {return null;}
}

I've also tried this variation:
return await (await _dbcontext.Features.AnyAsync(m => m.Id == id) ?
        _dbcontext.Features.FirstAsync(m => m.Id == id) :
        Task.Run(() => new Feature()));

And this variation:
_dbcontext.Features.SqlQuery(
    String.Format("SELECT * FROM [Features] WHERE {0} = Id", id))
    .FirstAsync();

Edit:
This is the message from the debug console when i print out the exception message:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.

Which adds to my confusion, since, like I said, the project connects to the DB just fine when I run "Update-Database -StartupProject [projectName]"
Edit:
This is my connection string in app.config
<add name="Context" connectionString="Data Source=localhost\mssqlserver2008;Initial Catalog=HA_Madmin;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

But when I print out
_dbcontext.Database.Connection.ConnectionString

I see the following:
Data Source=.\SQLEXPRESS;Initial Catalog=Context;Integrated Security=True;MultipleActiveResultSets=True

A: Turns out the problem was there because my application was running in an app pool with a different identity than what my database's connection was set to.


text:
Q: Shuffle a small list in Redis DB i need to shuffle a small list (100 elements) in my Redis DB with Python.
Or is it easier to do the shuffling locally and then save it to the DB?
Is it possible?

A: There is no Redis list command to shuffle the order, so you'll need to shuffle it using Python (likely you can use the random.shuffle method) and then store that shuffled list in Redis.


text:
Q: Can't connect to EC2 instance I am trying to run EC2 instance on AWS but after creating when I do ssh from gibash or any thing else it says time out.
First I think it was some error through my end but it wasn't I disable the firewall etc.
But when I open the public ip address after giving the permission to 80 port from all ip address the webpage open and says it took too much time to respond.
So I clicked on my created instance and pressed Connect from the header and tried to connect direct from AWS (to open console) but the error is still displaying.
I tried with different Operating Systems:

*

*Amazon  Linux

*Ubuntu

*Centos 7

A: Typical things to check when trying to connect to an EC2 instance:
Security Groups
Check that at least one of the Security Groups associated with the instance has port 22 (SSH) or port 3389 (RDP) open to your source IP range (eg a specific IP address 54.87.23.11/32, or the whole world 0.0.0.0/0 -- the latter is very poor security practice but worth trying to see if it helps). Security Groups are stateful, so you only need to open Inbound access and the return path will automatically work.
Public IP Address
Confirm that you are using a Public IP address associated with the instance. This can either be assigned at instance launch (which will allocate a random IP address from a pool) or can be assigned as an Elastic IP Address (which is a static IP address that you can assign assign to any instance and you keep it until you release it back to AWS).
Public Subnet / Routing
Confirm that your instance is in a "Public" VPC Subnet. This means that the Route Table associated with the Subnet has a route through an Internet Gateway.
Your Network
If you are connecting via a corporate network, be aware that some companies block SSH access via their network. Try to connect via a different network (eg home, office, tethered via your phone).


text:
Q: login from webservice using web service Hi i am new person in asp.net webservice. I want to give user name and password in my web application the authentication performed by comparing username and password from webservice instead of comparing to database. Can anyone able to help me it will really appreciated.
Thank you,

A: Are you developing the webservice or it is done by someone else.
What is the functionality that you would be doing in Webservice.
I think you are trying to compare the username and password submitted with the
values stored in the database through webservie isn't it?
If you want to compare only in webservie or any page without using the database then I think you have to hard code the useername and password and simply do string comparison.

A: You should use Forms Authentication - on click of login button on Login Form, you need to validate user supplied credentials by making the web service call. In case the credentials are correct then you can use FormsAuthentication.RedirectFromLoginPage to indicate authentication success to ASP.NET runtime.
Yet another variation (along with Forms Authentication) will be to use custom membership provider. See this MSDN link to understand how membership works. Then you have to write a custom membership provider that will use the web service to validate user.


text:
Q: Confusion related to the definition of NP problems I have this confusion related to the definition of NP problems. According to wikipedia
Intuitively, NP is the set of all decision problems for which the instances where the answer is "yes" have efficiently verifiable proofs of the fact that the answer is indeed "yes". More precisely, these proofs have to be verifiable in polynomial time by a deterministic Turing machine. In an equivalent formal definition, NP is the set of decision problems where the "yes"-instances can be accepted in polynomial time by a non-deterministic Turing machine.
However, as far as I know NP is the set of problems which cannot be solved in polynomial time, but given a solution it can be verified in polynomial time. Now from the definition of wikipedia, I think the part where it says that they have verifiable proofs means the part that the solution can be verified in polynomial time. But I didn't get the first part where it says NP is the set of decision problems where the "yes"-instances can be accepted in polynomial time by a non-deterministic Turing machine. (Does this mean that the problem cannot be solved in polynomial time, even if it could it is by non deterministic turing machine rather than the deterministic one?).
Further I was referring to a book where it says
The input to a computational problem will be encoded as a finite binary string s. We denote the length of a string s by |s|. We will identify a decision problem X with the set of strings on which the answer is "yes." An algorithm A for a decision problem receives an input string s and returns the value "yes" or "no"—we will denote this returned value by A(s). We say that A solves the problem X if for all strings s, we have A(s)=yesif and only if s∈X.
Now, how should we formalize the idea that a solution to a problem can be checked efficiently, independently of whether it can be solved efficiently? A "checking algorithm" for a problem X has a different structure from an algorithm that actually seeks to solve the problem; in order to "check" a solution, we need the input string s, as well as a separate "certificate" string t that contains the evidence that s is a "yes" instance of X.
The above definition from the book are hard to grasp. Can any provide some intuition?

A: This is a frequent source of confusion among people seeing NP for the first time. Let's see what the two definitions mean in the context of the Hamiltonian Circuit problem.
HAMILTONIAN CIRCUIT: Given a description of a graph $G$ (perhaps by an adjacency matrix), is there a simple circuit in $G$ that contains all vertices of $G$?
Definition 1 (verifying a solution by a deterministic computation in polynomial time). If someone claimed to have found a solution for a particular graph $G$), what would it take for us to determine whether it was indeed a solution? We could require that they present us with a certificate we could check, which in this example might be the adjacency matrix, $A$, of $G$ along with the proposed cycle, namely
$$
(A, \langle\;v_1, v_2, \dots, v_n, v_1\;\rangle)
$$
We'd then write a program for our (Model I, deterministic) computer take this certificate as input and verify (1) that the edges $\{v_1, v_2\}, \{v_2, v_3\}, \dots, \{v_n, v_1\}$ were edges of $G$, (2) that none of the edges were listed twice, (3) that each vertex of $G$ was contained in the cycle and (4) that no vertex appeared more than once in the cycle. It is clear that we could write such a program and that the time required by this program would be polynomial in the size, in bits, of the certificate, so HAMILTONIAN CIRCUIT is an NP problem by this definition.
Definition 2 (generating a solution using non-determinism) Suppose we just purchased a Model II nondeterministic computer which has the ability to select at each step a finite collection of statements to execute. Think of such a machine as executing all of the statements in the collection at the same time in parallel universes. Notice that in each universe our machine appears to be just a Model I deterministic machine. Trying our new computer on HAMILTON CIRCUIT, we'll instruct it to generate possible solutions by starting at a vertex $v$ and simultaneously adding all vertices adjacent to $v$ (in parallel universes). Repeating this process $n$ times, we'll end this phase with lots of parallel universes, perhaps as many as $n^n$, and in each we'll have generated a possible solution. However, in each of the universes, we'll have done just $n$ steps.
Now in each universe, we'll test whether the path we generated was a solution (answer "yes") or not (answer "no"), using the poly-time verifier we made for Definition 1. Finally our Model II computer enters God Mode: it looks at the results in all of the parallel universes and answers "yes" if and only if there was a "yes" answer in any of the parallel universes. In summary, our Model II computer can solve any instance of HAMILTON CIRCUIT in polynomial time.
This is at the heart of essentially all problems in NP: in simple terms, we nondeterministically guess a solution and then verify our guess in poly time.

Remarks

*

*Note that any problem that can be solved in deterministic poly time (i.e., problems in P) can be solved in nondeterministic poly time (just don't use the universe-creation feature of the Model II machine), so P $\subseteq$ NP.

*In our example, we used nondeterminism to find a poly-time solution to HAMILTONIAN CIRCUIT. That doesn't imply that there isn't a poly-time deterministic solution. Perhaps we just weren't clever enough to find one.

*At present there are no known problems in NP that have been proven not to be in P. In other words, we don't know if NP $\setminus$ P is empty or not. Equivalently, we just don't know whether P=NP or not. The consensus among many theorists is the current machinery just isn't powerful enough to settle this question so we'll have to wait until someone creates some new mathematics.

A: As others already mentioned, NP does not mean the problem is not solvable in polynomial time (if that were true we would have P$\neq$NP, which is unproven). As you yourself said, NP just means solvable in polynomial time by a non-deterministic Turing machine, or equivalently that the solutions are verifiable in polynomial time.
For intuition consider bin packing, which is in NP. I give you a list of $n$ numbers between $0$ and $1$ and $k$ bins, each with capacity $1$. The question is, if I can pack the elements into the bins, such that no bin overflows. Now it appears to be very hard to determine if this is possible for such an instance, as the number of possibilities of distributing $n$ elements onto $k$ beens grows exponentially. An algorithm solving this decision problem in polynomial time, would proof P=NP.
On the other side, it is very easy to verify a solution. If I give you a mapping $f:\{1,\dotsc, n\} \to \{1,\dotsc, k\}$ you can check whether or not the bin packing works, simply by applying the function to your values and check if any bin overflows at the end.
The point is that it is very easy to verify whether a map and a list of numbers and bins is an acceptable bin packing, but it seems to be very hard to for a list of numbers and bins to decide, whether or not such an accepting map $f$ exists.
To make a really simple analogy, if I give you a height, it is very hard to check if there exists a building which is taller. If I give you a height and a building, it is very easy to verify, whether or not that building is taller or shorter.


text:
Q: Shell-script to decrypt file I have to create a shell-script that can decrypt a RSA key file  that is encrypted with a specific .pem file. And then to decrypt zip file with the AES key which I get from the RSA file once it is decrypted in a file named keyaes (or whatever you want).
Here are the two commands I have to use
openssl rsautl -decrypt -in AES_KEY -inkey CERTIFICATE.pem -out keyaes
openssl enc -d -aes-256-cbc -in zipfile.zip -out extraction.zip -nosalt -p -K RSA_KEY_from_key_aes_output -iv 0

The commands work perfectly, the problem is in my script I don't know how to make it automatically and to get the key from the keyaes output and put it into the next command properly.
How can I do it ?

A: you could just use bash command substitution in the second command, using backticks
openssl enc -d -aes-256-cbc -in zipfile.zip -out extraction.zip -nosalt -p -K `cat output_filename_with_aes_key` -iv 0


text:
Q: Exact positioning of items on packed ice water conveyors? I'm building a triple-Minerva villager breeder. I've got the packed ice going like so up-top.
████▒▒████
█▒▒█▒▒█▒▒█
█▒▒█▒▒█▒▒█
█▒▒█▒▒█▒▒█
█▒▒█▒▒█▒▒█
█▒▒█▒▒█▒▒█
█▒▒█▒▒█▒▒█
█▒▒█▒▒█▒▒█
█▒▒████▒▒█

Obviously, this is top-down. █/full block is packed ice, ▒/medium shade is the slabs over the villagers.
Problem is, no matter how I lay down water, the bread won't travel the full squiggle. It keeps getting dumped off to the side, trying to take off under the slabs. How do I arrange water/waterlogged whatever/gates to keep bread moving down the center of the ice chute so it gets to everyone? Can I do that?
In sum: how do I create a water/ice conveyor, defined by top-slabs, such that the stuff on the conveyor won't "understeer" and skate off under them?

A: The arrangement you want is this one:

Explanation: The water either has to flow around the corner, meaning that it goes at least one block further after the turn, or it has to start in the corner and the previous water has to point towards it. If any water stream ends in a corner, the items will only be pushed against the wall and not swim on towards the next water stream.


text:
Q: cURL GET-params? i can't download the source code from the site. It displays 'error - please fill in all form data'
the url w/ GET-parameters:
http://bahn.ltur.com/index/search/?mnd=de&lang=de_DE&searchin=DE-SB-VI&trip_mode=trip_simple&from_spar=Hamburg+Dammtor&to_spar=Stuttgart+Hbf&start_datum=01.07.2012&start_time=23%3A49&end_datum=02.07.2012&end_time=23%3A51&SEA_adults=1&SEA_kids1=0&SEA_kids2=0&SEA_adult1=&SEA_adult2=&SEA_adult3=&SEA_adult4=&SEA_adult5=&SEA_kid11=&SEA_kid12=&SEA_kid13=&SEA_kid14=&SEA_kid15=&trainclass_spar=2&x=56&y=5
i tried this via OSX bash: curl -O get_ticket_list.html
also w/ -L (you get redirected to blah.com/details)
No errors when I open the URL in my Browser.
What is going wrong?

A: If you click the url you have mentioned in your question then it redirects you to http://bahn.ltur.com/details.
If it asking you to fill the form data, you should be sending in a "POST" request and not "GET" request.
The POST request should have the form data as payload in the request.
See the following to be able to make a POST request:

*

*https://superuser.com/questions/149329/what-is-the-curl-command-line-syntax-to-do-a-post-request

*https://superuser.com/questions/361504/how-to-send-post-with-body-data-headers-andhttp-params-over-the-curl-command


text:
Q: Merge multiple sources into a single destination I want to combine 2 Domain Objects into a single data transfer object using AutoMapper.
Domain Model:
public class Service  {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public ICollection<DownloadService> DownloadServices { get; set; } = new HashSet<DownloadService>();
}

public class DownloadService {
    public int Id { get; set; }
    public int PageLimit { get; set; }
    public virtual int ServiceId { get; set; }
    public virtual Service Service { get; set; }
}

public class Volume {
    public override int Id { get; set; }
    public bool IsActive { get; set; }
    public string Path { get; set; }
    public string Description { get; set; }
}

DTO:
 public class PreferenceVM {
        public ICollection<VolumeVM> Volumes { get; set; }
        public ICollection<ServiceVM> Services { get; set; }
 }

 public class ServiceVM {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public ICollection<DownloadServiceVM> DownloadServices { get; set; } = new HashSet<DownloadServiceVM>();
 }

public class DownloadServiceVM {
        public int Id { get; set; }
        public int PageLimit { get; set; }
        public int CleaningInterval { get; set; }
}

 public class VolumeVM {
        public int Id { get; set; }
        public bool IsActive { get; set; }
        public string Path { get; set; }
        public string Description { get; set; }
}

Mapping:
 cfg.CreateMap<Volume, VolumeVM>().ReverseMap();
 cfg.CreateMap<DownloadService, DownloadServiceVM>().ReverseMap();
 cfg.CreateMap<Service, ServiceVM>()
     .ForMember(d => d.DownloadServices, opt => opt.MapFrom(s => s.DownloadServices))
     .ReverseMap();

 cfg.CreateMap<ICollection<Volume>, PreferenceVM>()
            .ForMember(x => x.Volumes, y => y.MapFrom(src => src)).ReverseMap();
 cfg.CreateMap<ICollection<Service>, PreferenceVM>()
            .ForMember(x => x.Services, y => y.MapFrom(src => src)).ReverseMap();

when I try the mapping above:
 var services = serviceRepository.GetAll();
 var volumes = volumeRepository.GetAll();

 var entities = mapper.Map<PreferenceVM>(services);
 entities = mapper.Map(volumes, entities);

I get the following errors:

Missing type map configuration or unsupported mapping.
Mapping types: EntityQueryable1 -> PreferenceVM
  Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable1[[Fwims.Core.Data.Model.Setting.Service,
  Fwims.Core.Data.Model, Version=1.0.1.10, Culture=neutral,
  PublicKeyToken=null]] -> Fwims.Core.ViewModel.Setting.PreferenceVM

It looks like my mapping is wrong, nothing I have tried has worked. How do I properly map the Domain objects to the Data transfer objects?

A: Here
cfg.CreateMap<ICollection<Volume>, PreferenceVM>()
    .ForMember(x => x.Volumes, y => y.MapFrom(src => src)).ReverseMap();

and
cfg.CreateMap<ICollection<Service>, PreferenceVM>()
    .ForMember(x => x.Services, y => y.MapFrom(src => src)).ReverseMap();

you create mappings from ICollection<TSource>.
However later on you are trying to map IQeryable<TSource>. While AutoMapper can use a base mapping to map a derived class, IQueryable<T> does not derive from ICollection<T>, hence the missing type map exception.
The solution is to create a mapping from some common base interface of IQueryable<T> and ICollection<T>, which is IEnumerable<T>.
So replace the above with:
cfg.CreateMap<IEnumerable<Volume>, PreferenceVM>()
    .ForMember(x => x.Volumes, y => y.MapFrom(src => src));
cfg.CreateMap<IEnumerable<Service>, PreferenceVM>()
    .ForMember(x => x.Services, y => y.MapFrom(src => src));

and the current issue will be solved.
Note that ReverseMap does not work in such scenarios, so I've just removed it. If you need such functionality, you have to create that mappings manually (eventually using ConvertUsing because there is no destination member).


text:
Q: Javascript in adobe form field - converting a "Trade In Value" To Be Multiplied if falls within specified range Im attempting to create a Javascript range calculator for a "trade in value of a car" this is a small part of a huge project im working on, i have the finished version in an excel file but decided to remake in adobe acrobat pro using Javascript, the purpose is to adjust the value of a number if it falls between the ranges below, if someone can point me in the right direction to get this code to work, id really appreciate it!
In plain text below,

Trade Value X 2.00 If Less Than 5999.00;
Trade Value X 1.75 If Greater Than 5999.00 But Less Then 9000.00;
Trade Value X 1.50 if Greater Than 9000.00 But less Than 11,000.00;
Trade Value X 1.40 if Greater Than 11,000.00 But less Than 12,000.00;
Trade Value X 1.35 if Greater Than 12,000.00 But less Than 13,000.00;
Trade Value X 1.30 if Greater Than 13,000.00 But less Than 14,000.00;
Trade Value X 1.25 if Greater Than 14,000.00 But less Than 17,000.00;
Trade Value X 1.20 if Greater Than 17,000.00 But less Than 20,000.00;
Trade Value X 1.15 if Greater Than 20,000.00 But less Than 24,000.00;
Trade Value X 1.10 if Greater Than 24,000.00;

Should = "Amount Financed" Field In Adobe
The code im attempting to implement:
var VTV = Number(this.getField("VehicleTradeValue").valueAsString);
var AMF = Number(this.getField("AmountFinanced").valueAsString);
((VehicleTradeValue)*2.00) If (VehicleTradeValue) < 5999.00;
elif:
((VehicleTradeValue)*1.75) If (VehicleTradeValue) < 5999.00 < 9000.00;
elif:
((VehicleTradeValue)*1.50) if (VehicleTradeValue) > 9000.00 < 11,000.00;
elif:
((VehicleTradeValue)*1.40) if (VehicleTradeValue) > 11,000.00 < 12,000.00;
elif:
((VehicleTradeValue)*1.35) if (VehicleTradeValue) > 12,000.00 < 13,000.00;
elif:
((VehicleTradeValue)*1.30) if (VehicleTradeValue) > 13,000.00 < 14,000.00;
elif:
((VehicleTradeValue)*1.25) if (VehicleTradeValue) > 14,000.00 < 17,000.00;
elif:
((VehicleTradeValue)*1.20) if (VehicleTradeValue) > 17,000.00 < 20,000.00;
elif:
((VehicleTradeValue)*1.15) if (VehicleTradeValue) > 20,000.00 < 24,000.00;
else:
((VehicleTradeValue)*1.10) if (VehicleTradeValue) > 24,000.00;
    event.value = self;

A: Code would be like:

function adjustVTV(val, separator = ',', every = 3){
  let vtv = +val.replace(/,/g, ''), n;
  if(vtv < 5999){
    vtv *= 2;
  }
  else if(vtv < 9000){
    vtv *= 1.75;
  }
  else if(vtv < 11000){
    vtv *= 1.5;
  }
  else if(vtv < 12000){
    vtv *= 1.4;
  }
  else if(vtv < 13000){
    vtv *= 1.35;
  }
  else if(vtv < 14000){
    vtv *= 1.3;
  }
  else if(vtv < 17000){
    vtv *= 1.25;
  }
  else if(vtv < 20000){
    vtv *= 1.2;
  }
  else if(vtv < 24000){
    vtv *= 1.15;
  }
  else{
    vtv *= 1.1;
  }
  vtv = vtv.toFixed(2).split('.'); n = vtv[0].split('');
  for(let i=n.length-every,z=0; i>z; i-=every){
    n.splice(i, 0, separator);
  }
  return n.join('')+'.'+vtv[1];
}
/* your use
let vtv = +this.getField('VehicleTradeValue').valueAsString), amf = +this.getField('AmountFinanced').valueAsString;
console.log(adjustVTV(vtv));
*/
// example
console.log(adjustVTV('5998.99'));
console.log(adjustVTV('8999.99'));
console.log(adjustVTV('10999.99'));
console.log(adjustVTV('11999.99'));
console.log(adjustVTV('12999.99'));
console.log(adjustVTV('13999.99'));
console.log(adjustVTV('16999.99'));
console.log(adjustVTV('19999.99'));
console.log(adjustVTV('23999.99'));
console.log(adjustVTV('24,000.00'));

A: Here Is the Answer Finally!!!
var vtv = this.getField("VehicleTradeValue").value;
if( vtv <= 6000) event.value = (vtv * 2.0);
else if ( vtv <= 9000) event.value = (vtv * 1.75);
else if( vtv <= 11000) event.value = (vtv * 1.50);
else if( vtv <= 12000) event.value = (vtv * 1.40);
else if( vtv <= 13000) event.value = (vtv * 1.35);
else if( vtv <= 14000) event.value = (vtv * 1.30);
else if( vtv <= 17000) event.value = (vtv * 1.25);
else if( vtv <= 20000) event.value = (vtv * 1.20);
else if( vtv <= 24000) event.value = (vtv * 1.15);
else ( vtv <= 200000) event.value = (vtv * 1.10);