text:
Q: Local Storage properties export const addNabuaItem = (item = [], count = 0, next = f => f) => {
let nabua = [];
if (typeof window !== 'undefined') {
    if (localStorage.getItem('nabua')) {  //If it has cart in local storage then ...
        //NOTE to convert json to object
        // get product from local storage
        nabua = JSON.parse(localStorage.getItem('nabua'));
    }
    //NOTE store it as an Array of Object
    nabua.push({
        ...item,
        count: 1 // NOTE intitial count after item was added by a user is one
    });
    // remove duplicates
    // build an Array from new Set and turn it back into array using Array.from
    // so that later we can re-map it
    // new set will only allow unique values in it
    // so pass the ids of each object/product
    // If the loop tries to add the same value again, it'll get ignored
    // ...with the array of ids we got on when first map() was used
    // run map() on it again and return the actual product from the cart

    nabua = Array.from(new Set(nabua.map(p => p._id))).map(id => {
        return nabua.find(p => p._id === id);
    });

    localStorage.setItem('nabua', JSON.stringify(nabua));
    next();
}
};

This is my code for adding products to cart (store in Local Storage). I would like to add only a specific property of the product such as only name, price, and description because I don't want to store unnecessary properties in Local storage. How can I do that ?
Below is my console of local storage that contain product Object,
enter image description here

A: Just add another map when you are assigning to nabua so it looks like this:
nabua = Array.from(new Set(nabua.map(p => p._id))).map(id => {
    return nabua.find(p => p._id === id);
})
.map(item => ({
  field1: item.field1,
  field2: item.field2
}));

And make field1/field2 whatever field you like. So if you want name, description and price, it can look something like this
.map(item => ({
      name: item.name,
      description: item.description,
      price: item.price
}));


text:
Q: How to override default(T) in C#?
Possible Duplicate:
Howto change what Default(T) returns in C#

print(default(int) == 0) //true

Similarly if I have a custom object, its default value will be null.
print(default(Foo) == null) //true

Can I have a custom value for default(Foo) and not null?
For example, something like this:
public static override Foo default()
{
    return new Foo();
}

This wont compile. Thanks..

A: Frankly, it's not a real answer but a simple mention. If Foo was a struct so you can have something like this:
public struct Foo
{

    public static readonly Foo Default = new Foo("Default text...");

    public Foo(string text)
    {
        mText = text;
        mInitialized = true;
    }

    public string Text
    {
        get
        {
            if (mInitialized)
            {
                return mText;
            }
            return Default.mText;
        }
        set { mText = value; }
    }

    private string mText;
    private bool mInitialized;

}

[TestClass]
public class FooTest
{

    [TestMethod]
    public void TestDefault()
    {
        var o = default(Foo);

        Assert.AreEqual("Default text...", o.Text);
    }

}

A: You can't override the default(T) keyword. It is always null for reference types and zero for value types.
More Information

*

*MSDN - default Keyword in Generic Code (C# Programming Guide)

A: Doesn't seem like it. From the documentation:

default ... will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to resolve jquery custom Timer issue? I have created a custom Jquery Timer. but i am facing little problem i dont know that is not working for me. below is my code.
  function show(Hos, mins, secds) {

        var hours = Hos;
        var minutes = mins;
        var seconds = secds;
        var dn = "AM";
        if (hours > 12) {
            dn = "PM"
            hours = hours - 12
        }
                    if (hours == 0)
                        hours = 12

        document.getElementById('<%= Label1.ClientID %>').innerHTML = hours + ":" + minutes + ":" + seconds + " " + dn
        if (parseInt(seconds) == 59) {
            seconds = 0;
            if (parseInt(minutes) == 59) {
                if (parseInt(hours) == 12) {
                    hours = 0;
                } else {
                    hours = parseInt(hours) + 1;
                }
            } else {

                minutes = parseInt(minutes) + 1;
            }
        } else {
            seconds = parseInt(seconds) + 1;

        }

        setTimeout("show('" + hours + "','" + minutes + "','" + seconds + "'" + " )", 1000)
    }

This code is working fine i am passing the hours,mins,seconds first time from the code behind using c#.Now my problem is i want to add "0" if the seconds is less than 9 and minutes less than 9 and hours less than 9. i have tried the following trick but i dont know why its not working for me..
if (seconds <= 9) {
                seconds = '0' + parseInt(seconds);
            }

Please help me..Actually what happens when i tried this . its concatenate 0 with seconds upto 9 but as 9 comes it restarts from 1. That is the problem.

A: seconds = '0' + parseInt(seconds) will do string addition, since '0', is a string.
When you add a string to a number in javascript, the number will be appended to the string.
Remove the quotes for 0, then it will be treated like number.
P.S. I guess this is the problem you are trying to crack

A: i have resolve this problem using some trick that is as follow:
function show(Hos, mins, secds) {

        var hours = Hos;
        var minutes = mins;
        var seconds = parseInt(secds, 10);

        if (hours == 0)
            hours = 12

        if (parseInt(seconds, 10) < 10) {
            seconds = "0" + parseInt(seconds, 10);
        }
        if (parseInt(hours, 10) < 10) {
            hours= "0" + parseInt(hours, 10);
        }
        if (parseInt(minutes, 10) < 10) {
            minutes= "0" + parseInt(minutes, 10);
        }
        document.getElementById('<%= Label1.ClientID %>').innerHTML = hours + ":" + minutes + ":" + seconds + " "
        if (parseInt(seconds) == 59) {
            seconds = 0;
            if (parseInt(minutes, 10) == 59) {
                if (parseInt(hours, 10) == 24) {
                    hours = 0;
                } else {
                    hours = parseInt(hours, 10) + 1;
                }
            } else {

                minutes = parseInt(minutes, 10) + 1;
            }
        } else {
               seconds = parseInt(seconds, 10) + 1;
       }
        setTimeout("show('" + hours + "','" + minutes + "','" + seconds + "'" + " )", 1000)
    }


text:
Q: Apostrophe doesn't get translated properly when placed in a resource bundle Apostrophe doesn't get translated properly when placed in a resource bundle.
key = {0}'s brush is {1} centimeters tall

(e.g. Sam's brush is 4 centimeters tall)

The apostrophe gets missed if I format the above key from a java.util.ResourceBundle What could be the problem here?

A: Adding to @Ralph's answer:
You will realize that this is a MessageFormat thing when you have a text like
text1=It's too late

versus
text2={0}''s too late

text1 would probably not run through a MessageFormater (e.g. spring has different code paths if arguments are passed or not), whereas text2 would.
So if you used two single quotes in text1, they may / will display as such. So you'll need to check if any arguments get formatted in or not and use one or two single quotes accordingly.

A: Look at the javadoc here

Within a String, "''" represents a
  single quote. A QuotedString can
  contain arbitrary characters except
  single quotes; the surrounding single
  quotes are removed. An UnquotedString
  can contain arbitrary characters
  except single quotes and left curly
  brackets. Thus, a string that should
  result in the formatted message
  "'{0}'" can be written as "'''{'0}''"
  or "'''{0}'''".

A: You need to double single quote i.e. {0}''s brush is {1} centimeters tall

A: If you are completely stuck, as I was (none of the above worked), you can replace the apostrophe sign with its Unicode: \u0027. Remember you are always allowed to use UTF symbol in your properties file.

A: I strongly belive that the problem is not the ressource bundle but the MessageFormater you use to print the message:
From MessageFormater java doc:

Within a String, '' (two single quotes ) represents a
  single quote. A QuotedString can
  contain arbitrary characters except
  single quotes; the surrounding single
  quotes are removed. An UnquotedString
  can contain arbitrary characters
  except single quotes and left curly
  brackets. Thus, a string that should
  result in the formatted message
  '{0}' can be written as '''{'0}''
  or '''{0}'''.

So you need to write:
{0}''s brush is {1} centimeters tall

A: Consider using Properties Editor plugin (for Eclipse)
http://propedit.sourceforge.jp/index_en.html

A: You should escape the single quote as
key = {0}''s brush is {1} centimeters tall

A: For everyone that has Android problems in the string.xml, use \'\' instead of single quote.


text:
Q: Why does this code always produces a "Internal System Error: 1731640370-112053 (-1981348559)"? To add Ids to a Set without looping over a list of SObjects I tried to do the following.
In every org I tried it leads to this error:
Set<Opportunity> myset = new Set<Opportunity>([SELECT Id FROM Opportunity]);
Map<Id, Opportunity> mymap = new Map<Id, Opportunity>(mySet);
System.debug(mymap.keySet());

when I try to save. When I just change
Set<Opportunity> myset = new Set<Opportunity>([SELECT Id FROM Opportunity]);
Map<Id, Opportunity> mymap = new Map<Id, Opportunity>(new List<Opportunity>(mySet));
System.debug(mymap.keySet());

it works. Why?!

A: http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_collections_maps_from_SObjects.htm
Map<Id, sObject> can be initialized with a List<sObject> or a [query].
Or - without the () - with {comma, separated, list, of, items, in, curly braces}.
There's no method to initialize it with a set. Similarly putAll method accepts a compatible map or a list, but not a set. Why did you think you can use a set?
Just Use PJC's suggested code :)
Map<Id, Opportunity> mymap = new Map<Id, Opportunity>([SELECT Id FROM Opportunity]);
Set<Id> mySet = mymap.keyset();


text:
Q: Axios React cors issue on product my third party axios requests works properly on local mode properly thanks to "http-proxy-middleware", but after i build and deploy it, axios requests gives homepage html as response.
setupProxy.js file
const { createProxyMiddleware } = require("http-proxy-middleware")
const cors=require("cors")
const express = require('express');
const app = express();
module.exports=app=>{

    app.use(
        createProxyMiddleware("/api",
        {
            target:"third-party-api-url",
            secure:false,
            changeOrigin:true
        })
    )

ApiFrontend.jsx file
const [apiData,setApiData]=useState("")
  var data = JSON.stringify({
    "MERCHANT": "****",
    "MERCHANT_KEY": "*******************************"
  });
var config = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    data : data
  };

  useEffect(()=>{
    axios("/api",config)
    .then(function (response) {
      setApiData(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
  },[])

i tried node server with express and use;
app.use(cors({
  origin: API_URL,
  credentials: true
 }));

but it gives the same response


text:
Q: F# how to append/join array2D and combine 1D arrays to array2D in F#, array.append can join two arrays; is there a way to append 2 array2D objects into one  or column-wise join several 1-D arrays into one array2D object?

A: The array2D function will turn any seq<#seq<'T>> into a 'T [,] so it should work for turning a bunch of 1D arrays into a 2D array.
let arr1 = [| 1; 2; 3 |]
let arr2 = [| 4; 5; 6 |]

let combined = array2D [| arr1; arr2 |]

A: As far as I can see, there is no F# library function that would turn several 1D arrays into a single 2D array, but you can write your own function using Array2D.init:
let joinInto2D (arrays:_[][]) =
  Array2D.init arrays.Length (arrays.[0].Length) (fun i j ->
    arrays.[i].[j])

It takes an array of arrays, so when you call it, you'll give it an array containing all the arrays you want to join (e.g. [| arr1; arr2 |] to join two arrays). The function concatenates multiple 1D arrays into a single 2D array that contains one row for each input array. It assumes that the length of all the given arrays is the same (it may be a good idea to add a check to verify that, for example using Array.forall). The init function creates an array of the specified dimensions and then calls our lambda function to calculate a value for each element - in the lambda function, we use the row as an index in the array of arrays and the column as an index into the individual array.
Here is an example showing how to use the function:
> let arr1 = [| 1; 2; 3 |]
  let arr2 = [| 4; 5; 6 |];;

> joinInto2D [| arr1; arr2 |];;
val it : int [,] = [[1; 2; 3]
                    [4; 5; 6]]

EDIT: There is already a function to do that - nice! I'll leave the answer here, because it may still be useful, for example if you wanted to join 1D arrays as columns (instead of rows, which is the behavior implemented by array2D.

A: I don't think there's anything built-in to handle this.  You can define your own reusable method based on either Array2D.init or Array2D.blit, though.  If you need to combine several columns into one logical whole, I think it would frequently be more convenient to use an array of arrays rather than a 2D array (and in general, the 1D array operations in .NET are significantly faster than the multi-dimensional array operations).


text:
Q: androidx.constraintlayout.widget.ConstraintLayout cannot be cast to android.widget.TextView I'm trying to learn Android development, but the problem is that my app crash every time I tried to run it and I get these errors in logcat:
2019-06-30 16:17:18.198 5317-5317/? E/e.myapplicatio: Unknown bits set in runtime_flags: 0x8000
2019-06-30 16:17:20.551 5317-5317/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 5317
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
        at android.view.View.performClick(View.java:7125)
        at android.view.View.performClickInternal(View.java:7102)
        at android.view.View.access$3400(View.java:801)
        at android.view.View$PerformClick.run(View.java:27301)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7319)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:7125)
        at android.view.View.performClickInternal(View.java:7102)
        at android.view.View.access$3400(View.java:801)
        at android.view.View$PerformClick.run(View.java:27301)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7319)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
     Caused by: java.lang.ClassCastException: androidx.constraintlayout.widget.ConstraintLayout cannot be cast to android.widget.TextView
        at com.example.myapplication.MainActivity.onButtonClick(MainActivity.java:23)
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:7125)
        at android.view.View.performClickInternal(View.java:7102)
        at android.view.View.access$3400(View.java:801)
        at android.view.View$PerformClick.run(View.java:27301)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7319)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)

this is my xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.32" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"

    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"

    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:onClick="onButtonClick"
    android:text="click me"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/text" />

<EditText
    android:id="@+id/nameEditText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:ems="10"
    android:inputType="textPersonName"
    android:text="Name"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>

and here the java code:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

public void onButtonClick (View view){

    TextView t1 = findViewById(R.id.text);

    t1.setText("Hello ss");

    EditText  e1 = findViewById(R.id.nameEditText);

    t1.setText(e1.getText().toString());
}

A: This is because both your ConstraintLayout and TextView is sharing the same id text in your layout XML file. As a result, when you try to refer the TextView in your Java code via R.id.text, it links to your ConstraintLayout instead which causes the crash.
Change the id of your ConstraintLayout to something else (like mainlayout).
Like this (copy and replace your XML code with the below) :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mainlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.32" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"

    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"

    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:onClick="onButtonClick"
    android:text="click me"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/text" />

<EditText
    android:id="@+id/nameEditText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:ems="10"
    android:inputType="textPersonName"
    android:text="Name"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button" />

A: The ConstraintLayout and the TextView use the same ID. Rename the ID of the ConstraintLayout to something different and use @+id/text instead of @id/text in your TextView, so the ID is generated.

A: In my case I was using the id of text_view but the layout practically contains constraintlayout
so just alter the layout to have a text view instead of constraintlayout

A: <androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.32" />

Your ConstraintLayout and Textviw have the same id Check it.

android:id="@id/text"

A: this is happening because in Your XML file you are using the same id  "text"
for layout and Textview.
your XML file should be like this.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/text"                      ///////////////// here
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@id/text"                        ///////////////// here
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.32" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"

    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"

    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:onClick="onButtonClick"
    android:text="click me"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/text" />

<EditText
    android:id="@+id/nameEditText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:ems="10"
    android:inputType="textPersonName"
    android:text="Name"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: in my case I`v got :
 java.lang.ClassCastException: androidx.constraintlayout.widget.ConstraintLayout cannot be cast to androidx.appcompat.widget.LinearLayoutCompat

So, I have the constriantLayout and LinearLayout with the same id, Just change the id and your problem is fixed.

A: This is because you have give the same id to your TextView or the ConstraintLayout.
You can simply solve this issue by removing the android:id="@id/text" which you have given to the ConstraintLayout or name it something else like android:id="@id/parentLayout"
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.32" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:onClick="onButtonClick"
    android:text="click me"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/text" />

<EditText
    android:id="@+id/nameEditText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:ems="10"
    android:inputType="textPersonName"
    android:text="Name"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: BrowserID without Javascript (preferably in Python) - is it possible? BrowserID currently uses a Javascript shim, while browsers are still (hopefully) developing support for it. Is it possible to use BrowserID for clients that don't run javascript?
I could read the 600 line JS shim, and figure out what navigator.id.getVerifiedEmail is meant to do, then replicate it on a server, but I was hoping there's an easier way. And even then, I don't think it would really work.
OK, digging a bit deeper, this seems to be peripheral to what BrowserID is meant to do, and might require some kind custom BrowserID validator, but I'm hoping there's an easier way.

A: "Server-side" BrowserID in python or whatever is impossible by its design. Read carefully the How BrowserID works page, especially pay attention to section 'Certificate Provisioning' and step 3 in the flow description. It does require support for BrowserID and javascript from the client's browser, because BrowserID technology requires some code to be run in the client browser during Certificate Provisioning step.

A: The Javascript shim exists to work around missing native support in browsers, so it will be required for the foreseeable future:
https://developer.mozilla.org/en-US/docs/Persona/FAQ#Why_does_Persona_require_JavaScript.3F

A: One solution, use OpenID or hand-rolled email verification, but then I have 2 problems. :(


text:
Q: MSTEST/VSTS Reflection Tool Does anyone know of a tool that will spit out a list of all methods with the [TestMethod] attribute within a solution?
What we're trying to accomplish is a review, with the customer, of our Unit Tests (names, not pass/fail status) against the Requirements.  We are using VSTS 2008 and Scrum for Team Systems, so I wasn't sure if this was something that was built in somewhere, or if it's a tool I just need to toss together for our purposes.  Any help would be great.  Thanks.

A: VS essentially offers this ability for free by generating the TRX file to summarize the results of a test run. There are a number of different ways to run all tests in a project but pick one and off mstest will go running each method with the [TestMethod] attribute and producing a UnitTestResult in the results file.
What you're asking for is essentially what the Test Results window shows you after a completed Test Run. If you're looking for something external to VS, you could always run a simple XSLT transform against the Test Results (.trx) file giving you a customized summary. Here's a very rough sample which proofs the concept, generating an HTML document containing an unordered list with a list item (test name and result) for each unit test:
<?xml version='1.0'?>
<xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:vs="http://microsoft.com/schemas/VisualStudio/TeamTest/2006">

    <xsl:template match="/">

Test Results

            <xsl:apply-templates select="//vs:Results//vs:UnitTestResult" />

    </xsl:template>
    <xsl:template match="vs:UnitTestResult" >

            <xsl:value-of select="@testName" />

            <xsl:variable name="Result">
                <xsl:choose>
                    <xsl:when test="@outcome='Passed'">pass</xsl:when>
                    <xsl:otherwise>nopass</xsl:otherwise>
                </xsl:choose>
            </xsl:variable>

                <xsl:value-of select="@outcome" />

    </xsl:template>
</xsl:stylesheet>


text:
Q: Getting UnsupportedClassVersionError while running Scala jar file using spark2-submit in Cloudera VM I'm trying to run a Scala project from here involving Azure Event hub in a Cloudera VM installed locally with a single node. I'm using CDH 5.10. I built the jar file using sbt 0.13.15 which uses Openjdk 1.8.0. Also Oracle Jdk 1.8 is installed in my VM which is being used by spark2 while running jar file I think. The VM didn't have spark2 initially. I upgraded it using Cloudera Manager 5.11.
I'm getting the following error after the project is run:
java.lang.UnsupportedClassVersionError: com/microsoft/azure/eventhubs/EventData : Unsupported major.minor version 52.0

The error displayed in the console after the jobs are submitted I think and then the code kind of hangs.
I enforced the jvm version to be 1.8 while building the jar. My complete build.sbt-
name := "AzureGeoLogProject"

version := "1.0"

scalaVersion := "2.11.8"

libraryDependencies += "org.scala-lang" % "scala-library" % "2.11.8"

libraryDependencies += "com.microsoft.azure" % "spark-streaming-eventhubs_2.11" % "2.0.3"

libraryDependencies += "org.apache.spark" % "spark-core_2.11" % "2.0.2"

libraryDependencies += "org.apache.spark" % "spark-sql_2.11" % "2.0.2"

libraryDependencies +=  "org.apache.spark" % "spark-streaming_2.11" % "2.0.2"

libraryDependencies += "org.apache.httpcomponents" % "httpclient" % "4.2.5"

libraryDependencies += "com.typesafe" % "config" % "1.3.1"

scalacOptions += "-target:jvm-1.8"

I googled the error but got nothing. Don't know how to proceed from here. Any suggestion would be greatly appreciated.

A: sudo alternatives --config java

When prompted, choose java(jre) 1.8 and try again


text: Q: How to remove unused CSS on pingendo? I am currently using pingendo to make responsive landing pages. But I am wondering if there is a way to remove unused CSS codes on the output of the project? I can't remove it manually, because I get thousand result of unused CSS property. My landing page is very simple and I don't think the css output of the project are all needed. What to do?


text:
Q: App not showing in TestFlight as App Store Connect User I've submitted a build for my app on App Store Connect.
Under iOS Builds in the Testflight tab, the builds shows as "testing" for App Store Connect users, but App Store Connect Users page under "Testers & Groups", my info is there, but it says "No Builds Available"
Why the mismatch between the Builds page and the App Store Connect Users page? How do I get an invite/how do I get this build on my phone?
(the build is waiting for review for external testers)


text:
Q: shallow Button in React Enzyme throws error "Cannot read property 'addEventListener' of null" I want to simulate a click on Button and check if onClick was called or not.
Here I am not using JEST or SINON to mock or spy instead using my own spy.
const DeselectAll = (props: Props) => (
  <div className="deselectall">
    <Button
      className="deselectall--button"
      icon="minus"
      onClick={props.clearItems}
      text={translate("deselectall")}
    />
  </div>
);

test
function MySpy() {
  this.calls = 0;
}
  MySpy.prototype.fn = function () {
    return () => this.calls++;
  }
When(/^Deselect button is clicked$/, function () {
    const mySpy = new MySpy();
    const mockCallBack = mySpy.fn();

    const wrapper = mount(DeselectAll);
    const button = enzyme.shallow(React.createElement(Button, { onClick: mockCallBack }));
                                                          //error: seems button is not yet
                                                          // available
    button.find('.deselectall--button').simulate('click');
    expect(mySpy.calls).to.be.equal(1);
});

ERROR: Cannot read property 'addEventListener' of null
Any help appreciated!


text:
Q: Unable to display image from web on blackberry device I developed simple code to display an image and title on blackberry screen, but I am not able to display anything (but if I tested for title only it is working).
My requirement is to display image with title in a list.
I have followed this link for fetching image from image url
and here my code in drawlistrow method:
public void drawListRow(ListField list, Graphics g, int index, int y, int w)
        {
            String text = (String)listElements.elementAt(index);
            Bitmap image =GetImage.connectServerForImage("http://toucheradio.com/toneradio/iphone/toriLite/toriLive.png");
            g.drawLine(0, y, w, y);

            g.drawText(text, 150, y, 60, w);
            g.drawBitmap(0,y,image.getWidth(),image.getHeight(),image,0,0);
        }

What could be  the problem?

A: And please check the image height and width if its big than your screen resolution, then you have to crop or enlarge the image you are getting. Give some x axis to the drawBitmapMethod i have just giving you the idea like below you can implement.
g.drawBitmap(340, y, image.getWidth(), image.getHeight(), image, 0, 0);


text:
Q: Can I use host network for docker stack deployment in a Docker Swarm cluster Can I use host network for docker stack deployment in a Docker Swarm cluster. Basically I want to assign host IP address to all the containers in Docker Swarm.

A: Even though you can create a Swarm-aware macvlan (see: collabnix blog post) in an ip-range within your subnet, which will allow services to get ips from this range, Swarm does not support to set fixed ip's for swarm services or it's tasks (=containers).
Either you run Swarm with macvlan and live with random ip's in the declared ip-range, or you live without Swarm and use plain containers with macvlan, which allow fixed ip's in the declared ip-range.
I am working in containerized environments since roughly 6 years now and neither macvlan, nor fixed container ip's where ever necessary.
... usualy people trying to enforce old patterns from the vm world to the container world end up thinking they need this as a solution, though high likely there is a better and more docker-like solution for the problem domain.


text:
Q: Haskell: anonymous function with two arguments I have the following anonymous function:
(\x y -> y+y) (5*(7+20))

As far as I understand anonymous functions, x should be (5*(7+20)) and y is not given (which is where it gets fishy). When I try to execute that function, GHCI tells me the return value is
Integer -> Integer

So obviously my interpretation is wrong here and I just can't see why. Can anyone explain to me what is happening here?

A: Giving a function of two arguments only one is resulting in a partial application of that function, whose result is a function of one (the remaining) argument. While in your case the signature of the returned function is Integer -> Integer.

A: Note that
\x y -> y+y

is syntactic sugar for
\x -> (\y -> y+y)

i.e. rather than saying "a lambda function of two arguments" you might say it's a function of only one argument. The return type just happens to be again a function.
This currying technique is really crucial for good Haskell code; partial application makes many things very concise without sacrificing readability. For example,
GHCi> map (logBase 2) [1,2,4,8,16]
[0.0, 1.0, 2.0, 3.0, 4.0]

Here I've used logBase as a function of a single argument (2), which gives me a simple number→number function that can be mapped over a list. Without currying, I would have needed to write map (\x -> logBase(2,x)) [1,2,4,8,16].

A: Look at it this way: if you had provided a value for y, you'd get an integer.  If you don't provide a value, you'll get an expression which takes an integer (which you call y) and returns an integer, i.e. a function
Integer -> Integer

This works for named functions too.  E.g.
plus :: Int -> Int -> Int
plus x y = x + y

You can check in ghci that the type of plus 1 is Int -> Int.  In fact, this process works for any function in Haskell.  You read more at the HaskellWiki.


text:
Q: insert node field into sidebar I'm trying to figure out how to have sidebar content for a 'page' content type. I've created a fied in page called sidebar. Now how do I insert that content if it exists into the right sidebar? Would I use  hook_page_alter().

A: CCK Blocks module will do it for you:
Don't be confused with "CCK" in name, Drupal 7 has fields in core so you don't have to install it.


text:
Q: many to many unidirectional I have a many to many relationship between User and Survey, the relationship is bi-directional, so when adding a new survey for a list of users, I need to do this:
foreach(User user in users)
{
    survey.Users.Add(user);
    user.Survey.Add(survey);
}

Iterating through all of the users looks overkill to me as there can be many users.
Isn't there a better way?
Is it possible to have a unidirectional many to many?

A: Ah, your problem is your database design. Many-to-many relationships will cause you major headaches like this if they aren't decomposed :).
Solution: Create a new table called UserSurvey, with a Primary Key and then a UserID field and a SurveyID field, like so:
----------------------------------------
| UserSurveyID | PrimaryKey            |
| UserID       | Foreign Key to User   |
| SurveyID     | Foreign key to Survey |
----------------------------------------

Then all you need to do is query that table for what you need.
What I would also do is maybe in the nHibernate UserSurvey class, put the actual User property and the Survey property to save you additional querying once you have your UserSurvey objects.

A: Yes, you can have a unidirectional many-to-many. There's nothing special you need to do to achieve this, just do not map the other side of the relationship.
If you need to maintain an in-memory representation of the relationship, then you need to add the references to both sides of the relationship as you're doing. This isn't overkill, you have to associate a set of users with a survey so at some point you have to loop through the set of users and make that association.
If you want to avoid loading the survey's user collection, you can check if the collection is initialized before accessing it:
foreach(User user in users)
{
    user.Survey.Add(survey);
    if (NHibernateUtil.IsInitialized(survey.Users)
    {
        survey.Users.Add(user);
    }
}


text:
Q: Prevent Twitter Bootstrap .span2 from resizing in responsive layout I want to prevent a .span2 from resizing, while keeping a responsive layout.
My code looks like this

   Toolbar

   Code input

   Code preview

Basically what I want is while resizing other elements(.span5) I want for #toobar to have a fixed widht. Is that possible?

A: Why don't you just assign a fixed width to #toolbar?
#toolbar {
  width: 200px;
}


text:
Q: I want to make a grid and a rectangle shape inside the grid Hi everyone I am trying to draw in latex but it is hard. I want to make a grid and a rectangle shape inside the grid with few labels. I would really appreciate some help!!

A: For example, the points of the grid can be set as empty circle nodes. Then the connecting lines will connect to the circle leaving the inner of the circle intact. The grid can be drawn via nested \foreach loop for the two dimensions:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
  \foreach \x in {0, ..., 5} {
    \foreach \y in {0, ..., 3} {
      \node[
        circle,
        minimum size=3pt,
        draw,
        inner sep=0pt,
      ] (n\x_\y) at (\x, \y) {};
    }
  }
  \draw
    (n0_0) -- (n1_0) -- (n2_0) -- (n3_0) -- (n4_0) -- (n5_0)
    (n0_0) -- (n3_1)
    (n1_0) -- (n3_1)
    (n2_0) -- (n3_1)
    (n3_0) -- (n3_1)
    (n4_0) -- (n3_1)
    (n4_0) -- (n4_1)
    (n5_0) -- (n4_1)
    (n5_0) -- (n5_1)
    (n3_1) -- (n4_1) -- (n5_1)
  ;
  \node[below] at (n0_0) {$(0, 0)$};
  \node[above] at (n3_1) {$(a, 1)$};
  \node[above right] at (n5_1) {$(a + b, 1)$};
  \node[left=1ex] at (n0_3) {$v$};
  \node[below=1ex] at (n5_0) {$t$};
\end{tikzpicture}
\end{document}

A: Her is a short code with pstricks. You can compile with pdflatex if the switch --enable-write18 (MiKTeX) or -shell-escape (TeX Live, MacTeX) is set:
\documentclass[a4paper,11pt,x11names]{article}
\usepackage{pst-node, multido}
\usepackage{auto-pst-pdf}

\begin{document}%

\psset{xunit =1.5, nodesep=2pt, linecolor=IndianRed3}
\footnotesize
\begin{pspicture}
    \multido{\Ix=0 + 1}{6}{\multido{\Iy=0 + 1}{4}{\dotnode(\Ix, \Iy){A\Ix\Iy}}}
    \multido{\Ix=0 + 1}{5}{\ncline{A\Ix0}{A31}}
    \multido{\I=0 + 1, \In=1 + 1}{5} {\ncline{A\I0}{A\In0}}
    \ncline{A31}{A40}
    \ncline{A41}{A31}\ncline{A41}{A51}\ncline{A41}{A40}\ncline{A41}{A50}\ncline{A50}{A51}
    \uput[dl](A00){$ (0,0) $}\uput[dr](A50){$ t $}\uput[l](A03){$ V $}
    \uput[ur](A31){$ (a, 1) $}\uput[ur](A51){$ (a + b, 1) $}
\end{pspicture}

\end{document}


text:
Q: Why Apache beam can't infer the default coder when using KV? I'm implementing the CombinePerKeyExample using a subclass of CombineFn  instead of using an implementation of SerializableFunction.
package me.examples;

import org.apache.beam.sdk.coders.AvroCoder;
import org.apache.beam.sdk.coders.DefaultCoder;
import org.apache.beam.sdk.transforms.Combine.CombineFn;

import java.util.HashSet;
import java.util.Set;

public class ConcatWordsCombineFn extends CombineFn<String, ConcatWordsCombineFn.Accumulator, String> {
    @DefaultCoder(AvroCoder.class)
    public static class Accumulator{
        HashSet<String> plays;
    }

    @Override
    public Accumulator createAccumulator(){
        Accumulator accumulator = new Accumulator();
        accumulator.plays = new HashSet<>();
        return accumulator;
    }

    @Override
    public Accumulator addInput(Accumulator accumulator, String input){
        accumulator.plays.add(input);
        return accumulator;
    }

    @Override
    public Accumulator mergeAccumulators(Iterable<Accumulator> accumulators){
        Accumulator mergeAccumulator = new Accumulator();
        mergeAccumulator.plays = new HashSet<>();

        for(Accumulator accumulator: accumulators){
            mergeAccumulator.plays.addAll(accumulator.plays);
        }

        return mergeAccumulator;
    }

    @Override
    public String extractOutput(Accumulator accumulator){
        return String.join(",", accumulator.plays);
    }
}

The pipeline is composed of a ReadFromBigQuery, ExtractAllPlaysOfWords (code below) and WriteToBigQuery
package me.examples;

import com.google.api.services.bigquery.model.TableRow;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.transforms.Combine;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;

public class PlaysForWord extends PTransform<PCollection<TableRow>, PCollection<TableRow>> {

    @Override
    public PCollection<TableRow> expand(PCollection<TableRow> input) {

            PCollection<KV<String, String>> largeWords = input.apply("ExtractLargeWords", ParDo.of(new ExtractLargeWordsFn()));

            //PCollection<KV<String, String>> wordNPlays = largeWords.apply("CombinePlays", Combine.perKey(new ConcatWordsCombineFunction()));
            //using CombineFn instead
            PCollection<KV<String, String>> wordNPlays = largeWords.apply("CombinePlays",Combine.perKey(new ConcatWordsCombineFn()));
            wordNPlays.setCoder(KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of()));
            PCollection<TableRow> rows = wordNPlays.apply("FormatToRow", ParDo.of(new FormatShakespeareOutputFn()));
            return rows;
    }
}

If I'm not adding this line in the code above
 wordNPlays.setCoder(KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of()));

I'm having an exception
Exception in thread "main" java.lang.IllegalStateException: Unable to return a default Coder for ExtractAllPlaysOfWords/CombinePlays/Combine.GroupedValues/ParDo(Anonymous)/ParMultiDo(Anonymous).output [PCollection]. Correct one of the following root causes:
          No Coder has been manually specified;  you may do so using .setCoder().
          Inferring a Coder from the CoderRegistry failed: Cannot provide coder for parameterized type org.apache.beam.sdk.values.KV<K, OutputT>: Unable to provide a Coder for K.
          Building a Coder using a registered CoderProvider failed.
          See suppressed exceptions for detailed failures.
          Using the default output Coder from the producing PTransform failed: PTransform.getOutputCoder called.
                at org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkState(Preconditions.java:444)
                at org.apache.beam.sdk.values.PCollection.getCoder(PCollection.java:278)
                at org.apache.beam.sdk.values.PCollection.finishSpecifying(PCollection.java:115)
                at org.apache.beam.sdk.runners.TransformHierarchy.finishSpecifyingInput(TransformHierarchy.java:191)
                at org.apache.beam.sdk.Pipeline.applyInternal(Pipeline.java:536)
                at org.apache.beam.sdk.Pipeline.applyTransform(Pipeline.java:488)
                at org.apache.beam.sdk.values.PCollection.apply(PCollection.java:370)
                at me.examples.PlaysForWord.expand(PlaysForWord.java:21)
                at me.examples.PlaysForWord.expand(PlaysForWord.java:10)
                at org.apache.beam.sdk.Pipeline.applyInternal(Pipeline.java:537)
                at org.apache.beam.sdk.Pipeline.applyTransform(Pipeline.java:488)
                at org.apache.beam.sdk.values.PCollection.apply(PCollection.java:370)
                at me.examples.Main.main(Main.java:41)

From the stacktrace, I think the pipeline is not able to get a coder for the String type of the KV obejct. Why is that ? Isn't supposed to be a "known" type for Apache Beam. Why is it working without specifying the coder when using the subclass of SerializableFunction in the Combine.perKey?
In addition to that, when I tried to get the default coder for String from the coder registry I get StringUTF8Coder
Coder coder = null;
       try {
           coder = pipeline.getCoderRegistry().getCoder(String.class);
           logger.info("coder is " + coder);
       } catch (Exception e){
           logger.info("exception "+ e.getMessage() +"\n coder is " + coder );
       }
/*result
INFO: coder is StringUtf8Coder
*/

I used Apache Beam 2.12.0 and run it on Google Dataflow


text: Q: SQL Server and empty partitions scan Does the amount of partitions influence the cost of scan in anyway? Let's say, in case the table is daily partitioned, but most of partitions are empty, shall these be dropped of may remain in the table without any performance effect?


text:
Q: How to avoid using the dummy lines? I'm fairly new to programming so I'm currently stuck on figuring out how to make my code work cleaner. As of right now there are some random dummy lines in my code to make sure i dont skip part certain part of the loops. I was wondering if there are any ways to avoid it.
public static void main(String arg[]) {

        String CandidateID;
        String Name;
        String Option1;
        int Test1;
        int Test2;
        String dummy;
        Scanner sc = new Scanner(System.in);
        ArrayList<TestResult> StudentResults = new ArrayList<TestResult>();
        do {
            dummy = sc.nextLine();
            System.out.println("Enter student data? y/n");
            Option1 = sc.nextLine();
            if (Option1.equals("y")) {
                System.out.println("Enter Candidate ID:");
                CandidateID = sc.nextLine();
                System.out.println("Enter Name:");
                Name = sc.nextLine();
                System.out.println("Enter Test 1:");
                Test1 = sc.nextInt();
                System.out.println("Enter Test 2:");
                Test2 = sc.nextInt();
                TestResult TestResult = new TestResult(CandidateID, Name, Test1, Test2);
                StudentResults.add(TestResult);
            }
        }
        while (!Option1.equals("n"));

A: If you don't use the value inside the dummy variable, you can just execute sc.nextLine(); without assigning its return value to a variable.
It'll have the same effect, because the function is still being called.


text:
Q: How to solve error java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 This code used to work but I added some things just to get the contentprovider name[s].  No matter how much I check that there wont be any null or empty arraylists, it still does the same error.
LogCat
05-25 08:57:40.429: E/AndroidRuntime(11600): FATAL EXCEPTION: main
05-25 08:57:40.429: E/AndroidRuntime(11600): Process: com.example.sillimaninquirer, PID: 11600
05-25 08:57:40.429: E/AndroidRuntime(11600): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
05-25 08:57:40.429: E/AndroidRuntime(11600):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at java.util.ArrayList.get(ArrayList.java:308)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at com.example.sillimaninquirer.Adapter.getView(NewsFeed.java:402)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.widget.AbsListView.obtainView(AbsListView.java:2467)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.widget.ListView.measureHeightOfChildren(ListView.java:1286)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.widget.ListView.onMeasure(ListView.java:1194)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.View.measure(View.java:17915)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5698)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1692)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:760)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:629)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.View.measure(View.java:17915)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:846)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:512)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.View.measure(View.java:17915)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5698)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:465)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.View.measure(View.java:17915)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5698)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:447)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.View.measure(View.java:17915)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5698)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:465)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2728)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.View.measure(View.java:17915)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2412)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1414)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1638)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1292)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6598)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:800)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.Choreographer.doCallbacks(Choreographer.java:603)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.Choreographer.doFrame(Choreographer.java:572)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:786)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.os.Handler.handleCallback(Handler.java:815)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.os.Handler.dispatchMessage(Handler.java:104)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.os.Looper.loop(Looper.java:194)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at android.app.ActivityThread.main(ActivityThread.java:5631)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at java.lang.reflect.Method.invoke(Native Method)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at java.lang.reflect.Method.invoke(Method.java:372)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
05-25 08:57:40.429: E/AndroidRuntime(11600):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)

NewsFeed.java
import java.util.ArrayList;
import java.util.Arrays;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class NewsFeed extends Activity {
    ListView feed_listView;
    EditText search;
    //Button t, a, d, c, k;
    Spinner spinner;

    AQuery aq;
    ProgressDialog pd;
    Adapter artadapter;
    JSONArray articles          = new JSONArray();
    ArrayList<String> artID     = new ArrayList<String>();
    ArrayList<String> title     = new ArrayList<String>();
    ArrayList<String> content   = new ArrayList<String>();
    ArrayList<String> date      = new ArrayList<String>();
    ArrayList<String> cpid      = new ArrayList<String>();
    ArrayList<String> publisher         = new ArrayList<String>();

    JSONArray contentprovider           = new JSONArray();
    ArrayList<String> cpID  = new ArrayList<String>();

    @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_feed);
        spinner = (Spinner)findViewById(R.id.spinner1);

        aq = new AQuery(this);
        pd = new ProgressDialog(this);
        pd.setMessage("Loading articles. . .");
        pd.setCancelable(false);

        getSIData();
        getContentProvider();
        search = (EditText) findViewById(R.id.search);

        feed_listView = (ListView) findViewById(R.id.listView_NewsFeed);

        artadapter = new Adapter(this,artID, title, content, date, publisher,cpid);
        feed_listView.setAdapter(artadapter);

        feed_listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                String t = title.get(position);
                String c = content.get(position);
                String d = date.get(position);
                String p = publisher.get(position);
                String cp = cpid.get(position);

                Intent i = new Intent(getApplicationContext(), Article.class);
                i.putExtra("t", t);
                i.putExtra("c", c);
                i.putExtra("d", d);
                i.putExtra("p", p);
                i.putExtra("cp", cp);
                startActivity(i);

                Toast.makeText(getApplicationContext(), "Clicked "+position,Toast.LENGTH_LONG).show();
            }
        });
        search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                    searchTitle(s.toString());
                    if(s.toString().equals("")){
                        clearVar();
                        addArticlesToVar();
                    }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {

            }

            @Override
            public void afterTextChanged(Editable arg0) {

            }
        });

    }
    public void AddPref(View v){
        Intent i = new Intent(v.getContext(), AddPreference.class);
        startActivity(i);
    }
    public void News(View v){
        Intent i = new Intent(v.getContext(), NewsFeed.class);
        startActivity(i);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.news_feed, menu);
        return true;
    }
    public void getSIData(){
        aq.progress(pd).ajax("http://sillimaninquirer.esy.es/TWS/sidata.php?key=none", JSONObject.class, new AjaxCallback<JSONObject>(){
            @Override
            public void callback(String url, JSONObject jo, AjaxStatus as){
                try {
                    if(jo!=null){
                        articles = jo.getJSONArray("articles");
                        //Toast.makeText(getBaseContext(), "Articles: "+articles, Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getBaseContext(), "Error: No internet connection", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                addArticlesToVar();
            }
        });
    }
    public void getContentProvider(){
        aq.progress(pd).ajax("http://sillimaninquirer.esy.es/TWS/sidata.php?key=contentprovider", JSONObject.class, new AjaxCallback<JSONObject>(){
            @Override
            public void callback(String url, JSONObject jo, AjaxStatus as){
                try {
                    if(jo!=null){
                        contentprovider = jo.getJSONArray("contentprovider");
                        //Toast.makeText(getBaseContext(), "Articles: "+articles, Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getBaseContext(), "Error: No internet connection", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public void addArticlesToVar(){
        // articles = Manage.getArticles();
         for(int x=0; x<articles.length(); x++){
             try {
                JSONObject article = articles.getJSONObject(x);
                artID.add(article.getString("id"));
                title.add(article.getString("title"));
                content.add(article.getString("content"));
                date.add(article.getString("pdate"));
                String pub = article.getString("pubid");
                if(pub=="1"){
                    publisher.add("Stones and Pebbles");
                }
                if(pub=="1"){
                    publisher.add("Junior Sillimanians");
                }
                if(pub=="1"){
                    publisher.add("the Weekly Sillimanian");
                }
                String a = article.getString("cpid");
                for(int y=0; y<contentprovider.length(); y++){
                     try {
                        JSONObject cp = contentprovider.getJSONObject(y);
                        String con = article.getString("id");
                        if(a==con){
                            String fname = cp.getString("firstname");
                            String lname = cp.getString("lastname");
                            String mi = cp.getString("mi");
                            cpid.add(fname+" "+mi+". "+lname);
                        }

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

            } catch (JSONException e) {
                e.printStackTrace();
            }
         }
         artadapter.notifyDataSetChanged();
         Log.d("XX"," has art? "+articles);
     }
    public void searchTitle(String key){
        clearVar();
        for(int x=0; x<articles.length(); x++){
             try {

                JSONObject article = articles.getJSONObject(x);
                    String[] splited   = article.getString("title").split(" "); //split on word boundries
                    if(Arrays.asList(splited).contains(key)){
                        artID.add(article.getString("id"));
                        title.add(article.getString("title"));
                        content.add(article.getString("content"));
                        date.add(article.getString("pdate"));
                        String pub = article.getString("pubid");
                        if(pub=="1"){
                            publisher.add("Stones and Pebbles");
                        }
                        if(pub=="1"){
                            publisher.add("Junior Sillimanians");
                        }
                        if(pub=="1"){
                            publisher.add("the Weekly Sillimanian");
                        }
                        String a = article.getString("cpid");
                        for(int y=0; y<contentprovider.length(); y++){
                             try {
                                JSONObject cp = contentprovider.getJSONObject(y);
                                String con = article.getString("id");
                                if(a==con){
                                    String fname = cp.getString("firstname");
                                    String lname = cp.getString("lastname");
                                    String mi = cp.getString("mi");
                                    cpid.add(fname+" "+mi+". "+lname);
                                }

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

            } catch (JSONException e) {
                e.printStackTrace();
            }
         }
        artadapter.notifyDataSetChanged();
    }
    public void searchDate(String key){
        clearVar();
        for(int x=0; x<articles.length(); x++){
             try {

                JSONObject article = articles.getJSONObject(x);
                String[] splited   = article.getString("pdtae").split(" "); //split on word boundries
                if(Arrays.asList(splited).contains(key)){
                    artID.add(article.getString("id"));
                    title.add(article.getString("title"));
                    content.add(article.getString("content"));
                    date.add(article.getString("pdate"));
                    String pub = article.getString("pubid");
                    if(pub=="1"){
                        publisher.add("Stones and Pebbles");
                    }
                    if(pub=="1"){
                        publisher.add("Junior Sillimanians");
                    }
                    if(pub=="1"){
                        publisher.add("the Weekly Sillimanian");
                    }
                    String a = article.getString("cpid");
                    for(int y=0; y<contentprovider.length(); y++){
                         try {
                            JSONObject cp = contentprovider.getJSONObject(y);
                            String con = article.getString("id");
                            if(a==con){
                                String fname = cp.getString("firstname");
                                String lname = cp.getString("lastname");
                                String mi = cp.getString("mi");
                                cpid.add(fname+" "+mi+". "+lname);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                     }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
         }
        artadapter.notifyDataSetChanged();
    }
    public void clearVar(){
        title.clear();
        content.clear();
        date.clear();
        cpid.clear();
    }
}
class Adapter extends ArrayAdapter<String>{
    Context context;
    ArrayList<String> artID, title, content, date, apubid, cpid;
    //ArrayList<Articles> art1, art2;

    Adapter (Context context, ArrayList<String> artID,ArrayList<String> title,ArrayList<String> content, ArrayList<String> date, ArrayList<String> apubid, ArrayList<String>cpid){

        super(context, R.layout.row,R.id.newsfeed_Title, title);
        this.context = context;
        this.artID  = artID;
        this.content  = content;
        this.date     = date;
        this.title    = title;
        this.apubid = apubid;
        this.cpid     = cpid;

    }
    public View getView(int position, View convertView, ViewGroup parent){
        String c="", con="";
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = layoutInflater.inflate(R.layout.row, parent, false);

        TextView tv_title   = (TextView) row.findViewById(R.id.newsfeed_Title);
        TextView tv_content = (TextView) row.findViewById(R.id.newsfeed_Contentext);
        TextView tv_date    = (TextView) row.findViewById(R.id.newsfeed_date);

        c = content.get(position);
        for(int cc=0; cc<50; cc++){
            con+=c.charAt(cc);
        }

        tv_title.setText(title.get(position));
        tv_content.setText(apubid.get(position)+"\n"+con);
        tv_date.setText("By "+cpid.get(position)+"   "+date.get(position));

        return row;

    }

}

A: when you call
 artadapter = new Adapter(this,artID, title, content, date, publisher,cpid);

the content array is empty. This is why you get the problem


text:
Q: Using OutputDebugString in the code is making the compilation fail when built in release mode.(VC++) I have used OutputDebugString @ many placed in my VC++ code. Its building fine in debug mode. But using the same code with OutputDebugString is making the compilation to fail.
How to avoid this build failure in RELEASE mode even while using "OutputDebugString" in the code. Thanks in advance.


text:
Q: Dictionary of two different type and convert as JSON I have a Json file write as follow :
{
    "KeyString1": "ValueString1",
    "KeyListOfDict": [
        {
            "KeyString2": "ValueString2",
            "KeyDict2": {
                "KeyString3": "ValueString3"
            }
        },
        {
            "KeyString4": "ValueString4",
            "KeyDict2": {
                "KeyString5": "ValueString5"
            }
        }
    ]
}

I need to access "ValueString3" and "ValueString5" but I can't manage to Deserialize in a Dictionary.
dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
Because of the several value type in the dictinary I don't know to make the thing work.
Can you help to find a way to use this Json file ?

A: JavaScriptSerializer jss = new JavaScriptSerializer();
jss.Deserialize<dynamic>(json);

the result you can able access with the property name.

A: You can try with JObject
string json = File.ReadAllText(path);
var resultToDict = JObject.Parse(json)["KeyListOfDict"]
                   .Select(p => (((JProperty)p["KeyDict2"].Children().First()).Name, ((JProperty)p["KeyDict2"].Children().First()).Value))
                   .ToDictionary(x => x.Name, x => x.Value.ToString());


text:
Q: Combinational division in HDL I am trying to come up with a way to estimate the gate count if I were to implement a purely combinational 64-bit division.
I can't get my synthesis tool to generate a combinational 64-bit/64-bit integer division.

A: a 64bit/64bit divider fully combinational is leading to a huge design. this will use a lot of resources and lead to poor speed achievements. I'd suggest to implement the division with several register stages instead of fully combinational.
however, if you'd like to try, the following code would be synthesisable (as "/" operation is given by numeric_std library). check with a synthesis tool the recources needed for it (for synthesis the use of std_logic_vector in entities is suggested):
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.ALL;

entity divideComb is
Port ( a : in  STD_LOGIC_VECTOR (63 downto 0);
       b : in  STD_LOGIC_VECTOR (63 downto 0);
       c : out  STD_LOGIC_VECTOR (63 downto 0));
end divideComb;

architecture Behavioral of divideComb is

begin

    c<=std_logic_vector(signed(a)/signed(b));

end Behavioral;

the above code leads to the following synthesis results with Xilinx ISE 13.4:

*

*inferred 131 Adder/Subtractor(s)

*inferred  65 Comparator(s)

*inferred 4036 Multiplexer(s)

when using Spartan 6 architecture, this leads to 6982 Slice LUTs (and 0 FlipFlops, of course!)


text:
Q: How to print multiple jobs to multiple raw files (using FILE: port in printer properties)? In any printer properties I can choose a port named "FILE:" to have the driver save the printout to a raw file. That works well, however, when printing multiple jobs over the windows print spooler, the file is immediately overwritten, so at the end I have only the last print job.
Unfortunately, the file name doesn't support any placeholder variables..
I was thinking about writing a tool/script quickly moving the file away when it's closed. But isn't there a better solution?

A: This free tool installs a new port with the capability to save to a generated file name with placeholder variables:
http://mfilemon.sourceforge.net/
Tested with Windows 10 x64, but should work with previous versions as well.
After installation just click "Add Port..." in the "Ports" tab and you'll see how it works.


text:
Q: Windows Batch file - Delete with Y/N prompt and not allow wild cards I don't think this is a duplicate question (much to my surprise). I'm not a fan of using batch files and I can count on 1 hand the number of times I've had to create one.
I'm trying to create a batch file for deleting 1 file at a time, without wild cards. If the file name doesn't exist, then the batch file should terminate.
My errant batch file:
 @echo off
set /p image="Enter file name (e.g. car.jpg):"
set fullFileName=C:\testimages\%image%

IF EXIST "%fullFileName%" (
    ECHO[
    del /P /F "%fullFileName%"
) ELSE (
    ECHO File %fullFileName% doesn't exist
)

pause

Correct:
Enter file name (e.g. car.jpg):car.jpg

C:\testimages\car.jpg, Delete (Y/N)?

Correct:
Enter file name (e.g. car.jpg):plane.jpg
File C:\testimages\plane.jpg doesn't exist
Press any key to continue . . .

I want to disallow any wild cards. Such as the following:
Enter file name (e.g. car.jpg):*

C:\testimages\bus.jpg, Delete (Y/N)? n
C:\testimages\car.jpg, Delete (Y/N)? n
C:\testimages\truck.jpg, Delete (Y/N)? n
Press any key to continue . . .

A: I am assuming you want to disallow the user entering in * or ?.  There are other undocumented wildcards as well though.
@echo on

:loop
cls
set /p "image=Enter file name (e.g. car.jpg):"

(echo "%image%"|findstr /L "* ? < > ^" >nul 2>&1) && GOTO :EOF

set "fullFileName=C:\testimages\%image%"

IF EXIST "%fullFileName%" (
    ECHO[
    ECHO del /P /F "%fullFileName%"
) ELSE (
    ECHO File "%fullFileName%" doesn't exist
)
endlocal
pause

There are probably more robust ways to check for input validation.  I am sure this could be broken in some form.

A: Here is an option using the for /F command:
set "image=" & set /P image="Enter file name: "
for /F tokens^=1*^ delims^=?*^<^>^" %%A in ("_%image%_") do set "TEST=%%B"
if defined TEST echo There are wild-cards!

If at least one wild-card is present in %image%, %%B and hence TEST are not empty. The _ characters are prepended and appended for the approach not to fail in case wild-cards are only present at the beginning and/or at the end of %image%.

This is another option using a standard for loop:
set "image=" & set /P image="Enter file name: " & set "FLAG=#"
for %%A in ("%image%") do if /I "%image%"=="%%~nxA" (set "FLAG=") else goto :QUIT
:QUIT
if defined FLAG echo There are wild-cards!

If at least one wild-card is present in %image%, the for loop resolves it by accessing the file system and returning the matching items (zero or more); this means that the original string %image% does not equal any of the iterated items, so the if query fails; the goto is there to avoid any more iterations, hence to break the loop; if no items match, the loop does not iterate at all. If no wild-cards are present in %image%, the for loop iterates once only over the original string, hence the if condition is fulfilled and variable FLAG is cleared.


text:
Q: Link to an external file in XML Hi all I want to link an external file/link in my XML code, but it does not work. Would you please let me know the correct way?
Sample xml:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="xml2html.xslt"?>

   <test name="test_2_4_4">
      <test name="tst_start_app">
        <result state="OK">
            <description
                    href="test_45.xml">
                    <description >
                        <![CDATA[test_45.xml]]>
                    </description>
            </description>
        </result>
      </test>
   </test>

Edit:
and here is the xslt file:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" version="5.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="Summary/test">

 Squish Test Results Overview

Details

                        Testname
                        Testsuits

                    <xsl:for-each select="test">
                        <xsl:variable name="LinkName" select="attribute::name"/>
                        <xsl:variable name="LinkFile" select="descendant::node()/attribute::href"/>

                            <xsl:value-of select="$LinkName"/>
                            <xsl:for-each select="descendant::node()">
                                <xsl:choose>
                                    <xsl:when test="attribute::state='NotOK'">

                                            <xsl:value-of select="description"/>

                                    </xsl:when>
                                    <xsl:when test="attribute::state='OK'">

                                            <xsl:value-of select="description"/>

                                    </xsl:when>
                                </xsl:choose>
                            </xsl:for-each>

                    </xsl:for-each>

                TO TOP

                         Not OK

                         OK

Summary

                        Test cases
                        More Info

                    <xsl:for-each select="test">
                        <xsl:variable name="LinkIt" select="@name"/>
                        <xsl:choose>
                            <xsl:when test="descendant::node()/@state='NotOK'">

                                    <xsl:value-of select="$LinkIt"/>

                                        <xsl:value-of select="count(descendant::node()[@state='NotOK'])"/> of <xsl:value-of select="count(descendant::node()[@state='OK']) + count(descendant::node()[@state='NotOK'])"/> Not OK

                            </xsl:when>
                            <xsl:when test="descendant::node()/attribute::state='OK'">

                                    <xsl:value-of select="$LinkIt"/>

                                        OK

                            </xsl:when>
                        </xsl:choose>
                    </xsl:for-each>

</xsl:template>

What I want to do is just read the xml file and show it in normal browser as a html file.

A: Seems you are looking for XInclude
In your case it would look ilke
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="xml2html.xslt"?>

   <test name="test_2_4_4">
      <test name="tst_start_app">
        <result state="OK">
            <xi:include href="test_45.xml" />
        </result>
      </test>
   </test>

The test_45.xml content
<description>

</description>


text:
Q: Inherit volumes with extension fields
I would like to share host `/etc/timezone` file with all docker services from single `docker-compose.yml` file.
I thought, that using extension fields would be good idea.
I've found similar topic where extension fields are used to inherit environment variables.
So, I've tried it with docker-compose.yml like below:
x-timezone-volumes:
  &timezone-volumes
  volumes:
    - "/etc/localtime:/etc/localtime:ro"
    - "/etc/timezone:/etc/timezone:ro"

services:
  postgres-database:
    image: "postgres:12-alpine"
    hostname: PostgresContainer
    networks:
      backend-network:
    env_file:
      - backups/.env.db
    volumes:
      <<: *timezone-volumes
      - ./postgres-data:/var/lib/postgresql/data

and I've this error:
ERROR: The Compose file './docker-compose.yml' is invalid because:
services.postgres-database.volumes contains an invalid type, it should be an array

As i understood from this topic, it is because merge key is outdated.
Does it mean that I can't use it anymore?
Is there any other solution to inherit volumes?

A: Yaml merge <<: is only supported for mappings. Which is also somewhat indicted by its syntax as its contains a colon.
If you have such an object:
x-timezone-volumes:
  &timezone-volumes
  volumes:
    - "/etc/localtime:/etc/localtime:ro"
    - "/etc/timezone:/etc/timezone:ro"

You can reference it like this:
services:
  app:
    <<: *timezone-volumes

In your case you want to append another item to the volumes array though. So it is not helpful. At max you can reference the individual strings.
x-timezone-volumes:
  &timezone-volumes
  volumes:
    - &tz1 "/etc/localtime:/etc/localtime:ro"
    - &tz2 "/etc/timezone:/etc/timezone:ro"

And then use it like this:
services:
  app:
    volumes:
      - ./foo:/bar
      - *tz1
      - *tz2

You can also mix and match those. Use the first version where there is no additional volume and the second version where you need to add more volumes. For that you could set an anchor name of the entire object and on the array elements.

That said, there is the environment variable TZ which you also can use to control the time zone of containers.
services:
  app:
    environment:
      TZ: UTC


text:
Q: How to print in reverse in assembly language using DOSBox Debug? This is one of the examples my instructor gave me but I need to find a way to reverse the order of what I input.
Here's the code:
e200 "Name: $"
e300 "Hello, $"
a100
mov ah, 09
mov dx, 200
int 21
mov bx, 400
mov ah, 01
int 21
mov [bx], al
inc bx
cmp bx, 405
jne 10a
mov cl, 24
mov [bx], cl
mov ah, 02
mov dl, 0a
int 21
mov dl, 0d
int 21
mov ah, 09
mov dx, 300
int 21
mov ah, 09
mov dx, 400
int 21
int 20

Output is:
Name: Maria
Hello, Maria

Expected Output (reverse):
Name: Maria
Hello, ariaM

A: Tested on current lDebug and (creating the executable only) on Microsoft's Debug from MS-DOS version 2 (available under MIT license). This should solve your task.
f 100 4FF 90
a 100
 mov ah, 09
 mov dx, 500
 int 21
 mov ah, 0A
 mov dx, 800
 int 21
 mov ah, 09
 mov dx, 600
 int 21
 xor cx, cx
 mov cl, [801]
 mov bx, cx
 add bx, 801
 jcxz 190

a 130
 mov ah, 02
 mov dl, [bx]
 int 21
 dec bx
 loop 130

a 190
 mov ah, 09
 mov dx, 700
 int 21
 mov ax, 4C00
 int 21

e 800 FF 0 0D
e 500 "Name: $"
e 600 0D 0A "Hello, $"
e 700 0D 0A "$"
g
q

*

*800 up to below 901 holds a maximum size buffer for interrupt 21h service 0Ah, which we initialise to FF (buffer size 255), 0 (nothing to recall), 0D (indicate end of recallable input).

*500, 600, and 700 contain dollar-terminated messages to be used with interrupt 21h service 09h.

*The output loop counter is initialised to CX = CL = length in bytes of input line, as returned by service 0Ah, excluding the final Carriage Return.

*The offset to output is initialised to BX = 801 + CX, which is the same as 802 + CX - 1. 802 is the address of the first byte of the returned input. 802 + CX is the address behind the last byte of the returned input. The minus one serves as an adjustment to point at the last byte instead of behind it.

*jcxz skips the loop for empty names.

*mov dl, [bx] loads a byte into the low half of DX.

*Interrupt 21h service 02h is used to output a byte.

*dec bx decrements the offset stored in BX.

*The loop 130 instruction decrements CX and jumps back if the resulting CX is non-zero.

*The f command is to fill a part of the code segment with all nop instructions. Along with the different a commands this allows us to place and use fixed offsets for jump targets in the code, without having to know exactly how long each instruction will be.

*Enter the name input, then indicate its end using the Enter key.
To generate an executable, prepend the command f 100 9FF 0, then instead of the g command run this:
r bx
 0
r cx
 900
n test.com
w 100
q


text:
Q: Is the property of being a connected component local? More precisely, my question is as follows: Let $X$ be a qcqs scheme, $Z \subset X$ a closed subscheme and assume that there exists an open affine subscheme $U \subset X$ containing $Z$ such that $Z$ is a connected component of $U$. Does this imply that $Z$ is a connected component of $X$ ?
I do not know whether we need the algebro-geometric setup since this question only regards the underlying topological space of the scheme. Note that since $X$ is qcqs, every connected component is the intersection of its clopen supersets in $X$.


text:
Q: Efficient mapping between first element of each tuple in a list and the alphabet characters I have a list of tuples of strings:
lst = [('first', 'one'), ('second', 'two'), ('third', 'three'), ('fourth', 'four')]

I want to create a mapping between the first element of each tuple and the English alphabet lowercase characters:

*

*'first' mapped to 'a'

*'second' mapped to 'b'

*'third' mapped to 'c'

*'fourth' mapped to 'd'
I have tried the dictionary
dct = {'first': 'a', 'second': 'b', 'third': 'c', 'fourth': 'd'}

but I was wondering if there was a more efficient approach which would create the list containing the first element of the tuples and the alphabet list and then iterate them to create the dictionary.
Also, for the alphabet characters, I have tried using string.ascii_lowercase but it gives the string not as a list of each character.
I am new with Python so excuse if the question above is basic. I would appreciate any example code for me to understand and learn.

A: You can use zip() and a dictionary comprehension:
>>> from string import ascii_lowercase
>>> lst = [('first', 'one'), ('second', 'two'), ('third', 'three'), ('fourth', 'four')]
>>> {x[0]: y for x, y in zip(lst, ascii_lowercase)}
{'first': 'a', 'second': 'b', 'third': 'c', 'fourth': 'd'}

or if you want to do it in a more 'functional' way:
>>> from operator import itemgetter
>>> {x: y for x, y in zip(map(itemgetter(0), lst), ascii_lowercase)}
{'first': 'a', 'second': 'b', 'third': 'c', 'fourth': 'd'}

A: import string
lst = [('first', 'one'), ('second', 'two'), ('third', 'three'), ('fourth', 'four')]
alphabetList = [i for i in string.ascii_lowercase ]
dic = {lst[i] : alphabetList[i] for i in range(len(lst))}
print(dic)

A: Sure, you can achieve that using dictionary comprehension and using string library:
from string import ascii_lowercase

{lst[i][0]: c for i, c in enumerate(ascii_lowercase)}

A: You may create your desired dict using zip as:
from string import ascii_lowercase
lst = [('first', 'one'), ('second', 'two'), ('third', 'three'), ('fourth', 'four')]

my_dict =  dict(zip(list(zip(*lst))[0], ascii_lowercase)) # in python 3
# In python 2, you may just do:
#     my_dict = dict(zip(zip(*lst)[0], ascii_lowercase))

OR, even better to use it with operator.itemgetter as:
my_dict = dict(zip(map(itemgetter(0), lst), ascii_lowercase))

Value hold by my_dict will be:
{'first': 'a', 'second': 'b', 'third': 'c', 'fourth': 'd'}

Explanation:
You were almost there. string.ascii_lowercase returns a string but you may iterate the string and access the item based on index (same as you do with list). For example:
my_alphas = string.ascii_lowercase

# Iterate the string, valid
for alpha in my_alphas:
    print alpha

# access based on index, valid
my_alphas[13]

As an additional piece of information even though you don't need this: If you want to convert the string into list, you may type-cast it as:
my_alpha_list = list(string.ascii_lowercase)
#  ^  will hold all the alphabets in the form of list


text:
Q: save expect buffer outside scope? In my expect script I am using exp_continue to send the spacebar until I get a different prompt, however it appears the way I'm doing it might be putting the $expect_out(buffer) outside of the scope of my script.
The script is
#!/usr/bin/expect -f

# Set variables
set timeout 300
set SWITCH [lindex $argv 0]

# Its busy time
spawn ssh -o "StrictHostKeyChecking no" $SWITCH -luser
match_max 100000000
expect {
    "*assword:"
}
send "password\r"
expect "*>"
send "show run\r"
expect {
    "*More*" {send -- " ";exp_continue}
    "*>" {send -- "exit\r"}
}
set fid [open $SWITCH.conf w+]
set out $expect_out(buffer)
puts $fid $out

and the output to my shell shows the complete output (what i would expect to be written to file, below is snipped)
    no telnet server
    username admin password .....
    username user privilege 5 password .....
    !
    !
    hitless-failover enable
    !
    end

    SSH@TELCO-STACK>

however the file that gets written from the puts line only contains the following
^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H
!^M
!^M
!^M
end^M
^M
SSH@TELCO-STACK>

why are only the ^H and the last few lines of output being written to file, when I see the entire (correct) output to stdout?

A: The expect man page says:

Upon matching a pattern (or eof or full_buffer), any matching and previously unmatched output is saved  in
               the  variable  expect_out(buffer).

This means that you'll only get the characters since the last "More".
I suspect you may want the log_file command instead:
#!/usr/bin/expect -f
set timeout 300
set SWITCH [lindex $argv 0]
spawn ssh -o "StrictHostKeyChecking no" $SWITCH -luser
match_max 100000000
expect "*assword:"
send "password\r"
expect "*>"

log_file /some/log/file

send "show run\r"
expect {
    "*More*" {send -- " ";exp_continue}
    "*>" {send -- "exit\r"}
}


text:
Q: How to have files extracted from archive inherit permission from parent folder I'm using a Centos 8 Linux with multiple user belonging to the same group accessing a number ff folder/subfolder and files in the same FS (xfs). I want all files and folders have write permission for the group setting umask to 0002 allow new file created from user to have the right permission, but I have tar and other compressed files being extracted by users the extracted files maintain the permission they had in origin and are not changing resulting with some files being with permission only for the owner and not the group I'm trying to find a way to set the permission automatically without need of user to run a chmod to allow write for group I tried assign g+s on themain folder but I can only get the new folder inherit the group permission not the single files. I tried enabling ACL but again I don't get files to inherit parent folder permission. This how it look my main folder
drwxrwsr-x+ 4 owner group 4.0K Mar 6 10:26 test

And the content after extracting a tgz file in it
drwxrwsr-x+ 8 owner group 202 Mar 6 09:56 folder1
drwxrwsr-x+ 8 owner group 202 Mar 6 10:12 folder2

but then when i reach the first folder with files, files permission are just for owner
ll test/folder1
-rwx------. 1 owner group 195K Jun 6 2018 file1
-rwx------. 1 owner group 225K Aug 4 2018 file2
-rwx------. 1 owner group 211K Aug 20 2018 file3
-rwx------. 1 owner group 100K Sep 9 2018 file4
-rwx------. 1 owner group 200K Oct 24 2018 file5
-rwx------. 1 owner group 199K Nov 9 2018 file6

even after executing
setfacl -R -m d:o:rwx test

files are not changing their permission
Is there a way to force all files created or extracted from a compressed archive to inherit the permission from the main folder?

A: I'm still looking for a better solution, but for now I created a a script that pipe tar output to chmod command
#!/bin/bash -
set -o pipefail
tar xvf "$@" | xargs -rd '\n' chmod 770 --

I don't like it so much because instruct 100 and more user to use a different command will be tricky  but if won't find better solution I'll keep this.
just for info from man page tar seems to have an option which should ignore the file permission
--no-same-permissions
but seems working only if umask permission are more restrictive than the one on the extracted files, wonder if it's a bug

A: You could use the star implementation of tar and its -chmod option to set the permissions of files upon extraction:
star -x -o -f file.tar -find -chmod ug+rwX


text:
Q: Azure Powershell Error - The Resource Group Was Not Found Trying to run a powershell to change the DTUs for an Azure Elastic Pool. Problem is that it cannot find the resource group. Any ideas what is going wrong. My steps are:

*

*Sign in and run Azure Cloud shell

*Paste code below:

Set-AzureRmSqlElasticPool –ResourceGroupName "MyResourceGroup"–ServerName "MyServer.database.windows.net" –ElasticPoolName "My_ElasticPool" –Dtu 200 –DatabaseDtuMax 100 –DatabaseDtuMin 50

Full error is:

Set-AzureRmSqlElasticPool : The Resource
  'Microsoft.Sql/servers/MyServer.database.windows.net/elasticpools/My_ElasticPool'
  underresource group 'MyResourceGroup' was not found. At line:1 char:1
  + Set-AzureRmSqlElasticPool –ResourceGroupName "FluResourceGroup"–Serve ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  + CategoryInfo          : CloseError: (:) [Set-AzSqlElasticPool], CloudException
  + FullyQualifiedErrorId : Microsoft.Azure.Commands.Sql.ElasticPool.Cmdlet.SetAzureSqlElasticPool

Completely new to powershell so apologies if this is a donut question?

A: the error clearly says: this resource doesnt exist under that resource group. I would assume that the resource group exists. this means that there is a typo in the resource name and\or resource was moved, etc.
Another option is the resource group doesnt exist at all and the error is misleading. I'd say in that case you need to select proper subscription with Select-AzSubscription %subscription_name%. Because Azure PowerShell operates under specific subscription context. It won't search across all subscriptions.

A: Basic Error. Didn't reference the Azure server correctly. It should read:
Set-AzureRmSqlElasticPool –ResourceGroupName "MyResourceGroup"–ServerName "MyServer" –ElasticPoolName "My_ElasticPool" –Dtu 200 –DatabaseDtuMax 100 –DatabaseDtuMin 50


text:
Q: Isolating PWM From H-Bridge I have a H-bridge based on FAN7392 drivers. This bridge works at 350VDC to output a approximately 240V 50Hz waveform. This circuit is isolated from rest of the board and I would like to maintain the isolation. The bridge is fed by two complementary PWM signals from a microcontroller. The signals can be isolated easily with opto-couplers - however I'm worried that the timing difference between the opto-isolators might cause one side of the bridge to turn on both it's transistors simultaneously, for a short time. For instance, if one opto-coupler takes 2us to go high while the other takes 3us to go low there will be a 1us interval where one half of the bridge will be short-circuiting the power supply.
So my main question is, what is the best way to isolated timing critical signals?

A:
So my main question is, what is the best way to isolated timing
  critical signals?

For an application like this I'd consider sending only one PWM signal through one opto and, at the H-bridge side, recover that signal and apply the inversion and necessary timing differences to prevent shoot-through.
Here's a circuit that can avoid shoot thru by introducing a dead-band i.e. no overlap: -

Using a small time constant RC low pass filter and schmitt trigger OR and AND gates you can manufacture two PWM signals from one - all you should need to do is invert the output from the OR gate and you have dual, complementary PWM signals with shoot-thru protection.

A: You should adjust your timings to compensate for any possible delays. Many off-the-shelf gate drivers will have matched propogation delays.
Check a few of the irf gate driver ics. They often take care of many of these details for you, and simply design. IRF is ofcourse not the only manufacturer of such devices.
https://www.infineon.com/cms/en/product/power/gate-driver-ics/
Another advantage, is that these companies want you to use their chips, the app notes on that page are a great resource; Even if you don't use the ic.
Note that these delays, and switching losses will affect your maximum frequency and efficiency at said frequency. Switching too fast will result in more switching losses, and possible "ringing". Designing/choosing your driver circuit should balance all of this dependent on desired operating parameters.