问:
Unable to implement readmore feature to TextView in Android
I am developing an Android application. In my app, I need to implement, readmore feature to TextView like in Facebook post. My app also has newfeeds feature like Facebook. I am implementing for each TextView in the RecyclerView Adapter. But it is giving me error.

In the RecyclerAdapter I am setting the Readmore feature with Custom Event Listener like this. This is happening in onBindViewHolder of Adapter.

```<code>   viewHolder.tvTitle.setText(post.getTitle());
    listener.ReadMoreListener(viewHolder.tvTitle, 3, "Read more", true);
</code>```

This is the event listener interface

```<code>public interface AdapterListener{

        public void ReadMoreListener(TextView textView, int maxLine, String expandText, boolean viewMore);
    }
</code>```

This is how I implement event and readmore feature to each TextView in Fragment.

In onCreateView of Activity, I set up event like this.

```<code>adapter.setAdapterListener(new MemeListAdapter.AdapterListener() {

            @Override
            public void ReadMoreListener(TextView textView, int maxLine, String expandText, boolean viewMore) {
                makeTextViewResizable(textView, maxLine, expandText, viewMore);
            }
        });
</code>```

These are the required methods to implement readmore feature in Fragment.

```<code>public static void makeTextViewResizable(final TextView tv, final int maxLine, final String expandText, final boolean viewMore) {

        if (tv.getTag() == null) {
            tv.setTag(tv.getText());
        }
        ViewTreeObserver vto = tv.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout() {

                ViewTreeObserver obs = tv.getViewTreeObserver();
                obs.removeGlobalOnLayoutListener(this);
                if (maxLine == 0) {
                    int lineEndIndex = tv.getLayout().getLineEnd(0);
                    String text = tv.getText().subSequence(0, lineEndIndex - expandText.length() + 1) + " " + expandText;//This line is throwing error.
                    tv.setText(text);
                    tv.setMovementMethod(LinkMovementMethod.getInstance());
                    tv.setText(
                            addClickablePartTextViewResizable(Html.fromHtml(tv.getText().toString()), tv, maxLine, expandText,
                                    viewMore), TextView.BufferType.SPANNABLE);
                } else if (maxLine > 0 && tv.getLineCount() >= maxLine) {
                    int lineEndIndex = tv.getLayout().getLineEnd(maxLine - 1);
                    String text = tv.getText().subSequence(0, lineEndIndex - expandText.length() + 1) + " " + expandText;
                    tv.setText(text);
                    tv.setMovementMethod(LinkMovementMethod.getInstance());
                    tv.setText(
                            addClickablePartTextViewResizable(Html.fromHtml(tv.getText().toString()), tv, maxLine, expandText,
                                    viewMore), TextView.BufferType.SPANNABLE);
                } else {
                    int lineEndIndex = tv.getLayout().getLineEnd(tv.getLayout().getLineCount() - 1);
                    String text = tv.getText().subSequence(0, lineEndIndex) + " " + expandText;
                    tv.setText(text);
                    tv.setMovementMethod(LinkMovementMethod.getInstance());
                    tv.setText(
                            addClickablePartTextViewResizable(Html.fromHtml(tv.getText().toString()), tv, lineEndIndex, expandText,
                                    viewMore), TextView.BufferType.SPANNABLE);
                }
            }
        });

    }

    private static SpannableStringBuilder addClickablePartTextViewResizable(final Spanned strSpanned, final TextView tv,
                                                                            final int maxLine, final String spanableText, final boolean viewMore) {
        String str = strSpanned.toString();
        SpannableStringBuilder ssb = new SpannableStringBuilder(strSpanned);

        if (str.contains(spanableText)) {
            ssb.setSpan(new ClickableSpan() {

                @Override
                public void onClick(View widget) {

                    if (viewMore) {
                        tv.setLayoutParams(tv.getLayoutParams());
                        tv.setText(tv.getTag().toString(), TextView.BufferType.SPANNABLE);
                        tv.invalidate();
                        makeTextViewResizable(tv, -1, "View Less", false);
                    } else {
                        tv.setLayoutParams(tv.getLayoutParams());
                        tv.setText(tv.getTag().toString(), TextView.BufferType.SPANNABLE);
                        tv.invalidate();
                        makeTextViewResizable(tv, 3, "View More", true);
                    }

                }
            }, str.indexOf(spanableText), str.indexOf(spanableText) + spanableText.length(), 0);

        }
        return ssb;

    }
</code>```

When I run my code, it is giving me this error:

I commented "this line is throwing error" in the code to where the error is thrown. I referenced on this link - Add "View More" at the end of TextView after 3 lines. What is the cause of the error? I know it is null exception error. How can I fix it?

I found out that tv.getLayout() always return null. How can I set Layout to TextView not to return null?

答:
The easiest answer for this is to set the maximum line of the textview programmatically. For example, assume you have a tvReadMore textview below your tvTitle textview. First check if the text for your tvTitle textview is more enough to display the tvReadMore. if so, set the maxLine to Integer.MAX_VALUE. Take a look at the following sample code

```<code>if(post.getTitle.length() > 50) { //assuming you want to show the [Read more] for more than 50 characters
   if(ViewHolder.tvReadMore.getText().toString().equalsIgnoreCase("Read More")) { //you should set the text of tvReadMore textview to [Read more] in the beginning
       viewHoler.tvTitle.setMaxLines(Integer.MAX_VALUE); //set the maximum line to Maximum integer
       viewHolder.tvReadMore.setText("Show Less")
   } else {
        viewHoler.tvTitle.setMaxLines(3); //set the maximum line to 3
        viewHolder.tvReadMore.setText("Read more")
   }
} else { //if there are no enough characters to show the read more text
   viewHolder.tvTitle.setVisibility(View.GONE); //hide the read more textview
}
</code>```

I have seen a lot of work arounds to implement the read more feature for textview but, in my opinion, this is the easiest and simplest way so far. The nice thing about this is, it works for both simple textview and a textview in a recyclerview.
if you want to add three dots at the end of your text, when there are more lines hidden, you can add

```<code> android::ellipsize(end)
</code>```

to your tvTitle textview.

Body:
I am developing an Android application. In my app, I need to implement, readmore feature to TextView like in Facebook post. My app also has newfeeds feature like Facebook. I am implementing for each TextView in the RecyclerView Adapter. But it is giving me error.

In the RecyclerAdapter I am setting the Readmore feature with Custom Event Listener like this. This is happening in onBindViewHolder of Adapter.

   viewHolder.tvTitle.setText(post.getTitle());
    listener.ReadMoreListener(viewHolder.tvTitle, 3, "Read more", true);

This is the event listener interface

public interface AdapterListener{

        public void ReadMoreListener(TextView textView, int maxLine, String expandText, boolean viewMore);
    }

This is how I implement event and readmore feature to each TextView in Fragment.

In onCreateView of Activity, I set up event like this.

adapter.setAdapterListener(new MemeListAdapter.AdapterListener() {

            @Override
            public void ReadMoreListener(TextView textView, int maxLine, String expandText, boolean viewMore) {
                makeTextViewResizable(textView, maxLine, expandText, viewMore);
            }
        });

These are the required methods to implement readmore feature in Fragment.

public static void makeTextViewResizable(final TextView tv, final int maxLine, final String expandText, final boolean viewMore) {

        if (tv.getTag() == null) {
            tv.setTag(tv.getText());
        }
        ViewTreeObserver vto = tv.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout() {

                ViewTreeObserver obs = tv.getViewTreeObserver();
                obs.removeGlobalOnLayoutListener(this);
                if (maxLine == 0) {
                    int lineEndIndex = tv.getLayout().getLineEnd(0);
                    String text = tv.getText().subSequence(0, lineEndIndex - expandText.length() + 1) + " " + expandText;//This line is throwing error.
                    tv.setText(text);
                    tv.setMovementMethod(LinkMovementMethod.getInstance());
                    tv.setText(
                            addClickablePartTextViewResizable(Html.fromHtml(tv.getText().toString()), tv, maxLine, expandText,
                                    viewMore), TextView.BufferType.SPANNABLE);
                } else if (maxLine > 0 && tv.getLineCount() >= maxLine) {
                    int lineEndIndex = tv.getLayout().getLineEnd(maxLine - 1);
                    String text = tv.getText().subSequence(0, lineEndIndex - expandText.length() + 1) + " " + expandText;
                    tv.setText(text);
                    tv.setMovementMethod(LinkMovementMethod.getInstance());
                    tv.setText(
                            addClickablePartTextViewResizable(Html.fromHtml(tv.getText().toString()), tv, maxLine, expandText,
                                    viewMore), TextView.BufferType.SPANNABLE);
                } else {
                    int lineEndIndex = tv.getLayout().getLineEnd(tv.getLayout().getLineCount() - 1);
                    String text = tv.getText().subSequence(0, lineEndIndex) + " " + expandText;
                    tv.setText(text);
                    tv.setMovementMethod(LinkMovementMethod.getInstance());
                    tv.setText(
                            addClickablePartTextViewResizable(Html.fromHtml(tv.getText().toString()), tv, lineEndIndex, expandText,
                                    viewMore), TextView.BufferType.SPANNABLE);
                }
            }
        });

    }

    private static SpannableStringBuilder addClickablePartTextViewResizable(final Spanned strSpanned, final TextView tv,
                                                                            final int maxLine, final String spanableText, final boolean viewMore) {
        String str = strSpanned.toString();
        SpannableStringBuilder ssb = new SpannableStringBuilder(strSpanned);

        if (str.contains(spanableText)) {
            ssb.setSpan(new ClickableSpan() {

                @Override
                public void onClick(View widget) {

                    if (viewMore) {
                        tv.setLayoutParams(tv.getLayoutParams());
                        tv.setText(tv.getTag().toString(), TextView.BufferType.SPANNABLE);
                        tv.invalidate();
                        makeTextViewResizable(tv, -1, "View Less", false);
                    } else {
                        tv.setLayoutParams(tv.getLayoutParams());
                        tv.setText(tv.getTag().toString(), TextView.BufferType.SPANNABLE);
                        tv.invalidate();
                        makeTextViewResizable(tv, 3, "View More", true);
                    }

                }
            }, str.indexOf(spanableText), str.indexOf(spanableText) + spanableText.length(), 0);

        }
        return ssb;

    }

When I run my code, it is giving me this error:

I commented "this line is throwing error" in the code to where the error is thrown. I referenced on this link - Add "View More" at the end of TextView after 3 lines. What is the cause of the error? I know it is null exception error. How can I fix it?

I found out that tv.getLayout() always return null. How can I set Layout to TextView not to return null?

Body:
The easiest answer for this is to set the maximum line of the textview programmatically. For example, assume you have a tvReadMore textview below your tvTitle textview. First check if the text for your tvTitle textview is more enough to display the tvReadMore. if so, set the maxLine to Integer.MAX_VALUE. Take a look at the following sample code

if(post.getTitle.length() > 50) { //assuming you want to show the [Read more] for more than 50 characters
   if(ViewHolder.tvReadMore.getText().toString().equalsIgnoreCase("Read More")) { //you should set the text of tvReadMore textview to [Read more] in the beginning
       viewHoler.tvTitle.setMaxLines(Integer.MAX_VALUE); //set the maximum line to Maximum integer
       viewHolder.tvReadMore.setText("Show Less")
   } else {
        viewHoler.tvTitle.setMaxLines(3); //set the maximum line to 3
        viewHolder.tvReadMore.setText("Read more")
   }
} else { //if there are no enough characters to show the read more text
   viewHolder.tvTitle.setVisibility(View.GONE); //hide the read more textview
}

I have seen a lot of work arounds to implement the read more feature for textview but, in my opinion, this is the easiest and simplest way so far. The nice thing about this is, it works for both simple textview and a textview in a recyclerview.
if you want to add three dots at the end of your text, when there are more lines hidden, you can add

 android::ellipsize(end)

to your tvTitle textview.


来源: stackexchange

问:
How to iterate over columns of "spark" dataframe?
I have the following Spark dataframe that is created dynamically

| name|  number |

+--------+---------+

| Andy | (20,10,30)|

|Berta | (30,40,20)|

| Joe  | (40,90,60)|

+-------+---------+

Now, I need to iterate each row and column in Spark to print the following output, How to do this?

Andy    20

Andy    10

Andy    30

Berta   30

Berta   40

Berta   20

Joe     40

Joe     90

Joe     60

答:
Assuming the number column is of string Data Type, you can achieve the desired results by following below steps.

Original Data Frame:

```<code>         val df = Seq(("Andy", "20,10,30"), ("Berta", "30,40,20"), ("Joe", "40,90,60"))
         .toDF("name", "number")
</code>```

Then Create an intermediate Data Frame having 3 number columns by splitting the number column with comma.

```<code>  val Interim_Df = df.withColumn("n1", split(col("number"), ",").getItem(0))
  .withColumn("n2", split(col("number"), ",").getItem(1))
  .withColumn("n3", split(col("number"), ",").getItem(2))
  .drop("number")
</code>```

Then generate the final result data frame by doing union with oneIndexDfs.

```<code>val columnIndexes = Seq(1, 2, 3)

val onlyOneIndexDfs = columnIndexes.map(x =>
  Interim_Df.select(
    $"name",
    col(s"n$x").alias("number")))

val resultDF = onlyOneIndexDfs.reduce(_ union _)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Assuming the number column is of string Data Type, you can achieve the desired results by following below steps.

Original Data Frame:

         val df = Seq(("Andy", "20,10,30"), ("Berta", "30,40,20"), ("Joe", "40,90,60"))
         .toDF("name", "number")

Then Create an intermediate Data Frame having 3 number columns by splitting the number column with comma.

  val Interim_Df = df.withColumn("n1", split(col("number"), ",").getItem(0))
  .withColumn("n2", split(col("number"), ",").getItem(1))
  .withColumn("n3", split(col("number"), ",").getItem(2))
  .drop("number")

Then generate the final result data frame by doing union with oneIndexDfs.

val columnIndexes = Seq(1, 2, 3)

val onlyOneIndexDfs = columnIndexes.map(x =>
  Interim_Df.select(
    $"name",
    col(s"n$x").alias("number")))

val resultDF = onlyOneIndexDfs.reduce(_ union _)


问:
"Automatically set exception at clean up" exception showing in Control Room
When reviewing in cases in a work queue the message:

Automatically set exception at clean up

appears as the exception reason.

Why has Blue Prism set the case as an exception?

答: "Automatically set exception at cleanup" appears when you have picked up a case and not declared it as completed or exception WHILE THE PROCESS FINISHES WITHOUT ANY FURTHER ACTION ON THE QUEUE ITEM. In other words, if you leave the queue item to be in the locked state and your process execution finishes, it will still go in the said reason.</p>

ContentLicense: CC BY-SA 3.0


问:
Excluding elements from an old array and creating a new array
I have an array that has 3 different values, I want to create a new array that has only the values that are smaller that 12 (for example).

```<code>import array as arr

numbers = arr.array([10,12, 12, 13])

numbers.remove(12)
numbers.remove(13)
print(numbers)
</code>```

I don't know how to add them in a new array

答:
You can do the below if you want to stick with array only (I don't know why you want to do that). array and list in python are different things.

```<code>import array as arr

numbers = arr.array('i', [10,11, 12, 13])

print(arr.array('i', filter(lambda x : x < 12, numbers)))
</code>```

Body:
I have an array that has 3 different values, I want to create a new array that has only the values that are smaller that 12 (for example).

import array as arr

numbers = arr.array([10,12, 12, 13])

numbers.remove(12)
numbers.remove(13)
print(numbers)

I don't know how to add them in a new array

Body:
You can do the below if you want to stick with array only (I don't know why you want to do that). array and list in python are different things.

import array as arr

numbers = arr.array('i', [10,11, 12, 13])

print(arr.array('i', filter(lambda x : x < 12, numbers)))


问:
How Can we load data into hive using URL
I have created a table in hive and I need to load csv data into hive table,
but the data is in github (I have downloaded and tested it is working fine) I need to load data directly from URL is it possible to load data into hive from URL

something like this can work

```<code>LOAD DATA  INPATH 'https://github.com/xx/stock-prices.csv' INTO TABLE
stocks;
</code>```

答:
Loading data from flat files into Hive can be done using below command.

From Apache Hive Wiki:

```<code>LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)]

LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)] [INPUTFORMAT 'inputformat' SERDE 'serde'] (3.0 or later)
</code>```

If the keyword LOCAL is specified, Hive looks for file path in local filesystem and loads from there. If the keyword LOCAL is not specified, Hive looks for file path in HDFS filesystem and loads data there.

You can specify full URI for HDFS files as well as local files.

Example:

```<code>file:///user/data/project/datafolder (Local Path)

hdfs://namenode:10001/user/data/project/datafolder (HDFS path)
</code>```

This means it is not possible to load data directly into hive from https. So you have to download the data first and load into hive.

This is not the solution but the correct answer.

Body:
I have created a table in hive and I need to load csv data into hive table,
but the data is in github (I have downloaded and tested it is working fine) I need to load data directly from URL is it possible to load data into hive from URL

something like this can work

LOAD DATA  INPATH 'https://github.com/xx/stock-prices.csv' INTO TABLE
stocks;

Body:
Loading data from flat files into Hive can be done using below command.

From Apache Hive Wiki:

LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)]

LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)] [INPUTFORMAT 'inputformat' SERDE 'serde'] (3.0 or later)

If the keyword LOCAL is specified, Hive looks for file path in local filesystem and loads from there. If the keyword LOCAL is not specified, Hive looks for file path in HDFS filesystem and loads data there.

You can specify full URI for HDFS files as well as local files.

Example:

file:///user/data/project/datafolder (Local Path)

hdfs://namenode:10001/user/data/project/datafolder (HDFS path)

This means it is not possible to load data directly into hive from https. So you have to download the data first and load into hive.

This is not the solution but the correct answer.


问:
How to pass data from a master array to multiple arrays in PHP
I have an array with subarrays, each subarray has 'type' (int) and a 'datetime'. I need to loop trought the array and create new arrays (or objects) with groups of these subarrays in a special way: every 'type' could be [0-3] 0 means startdate and 3 means enddate (1 and 2 are in between for other purposes). Every new array with these subarrays should start with 0 and end with 3.

Im not using any framework, only PHP5 and jQuery. The master array comes from a loop I made from a SQL query with GROUP_CONCAT. I just passed the concat fields to a master array but I need to regroup the subarrays to create some type of registries.

Here is the array I got with subarrays. They are already sorted by datetime, every type '0' means "start date / start new registry" and '3' means "end date / end registry".

```<code>$array = [
["tipo"=>0,"fechahora"=>"2019-05-26 09:35:30"],
["tipo"=>1,"fechahora"=>"2019-05-26 10:30:15"],
["tipo"=>2,"fechahora"=>"2019-05-26 10:43:12"],
["tipo"=>3,"fechahora"=>"2019-05-26 14:30:26"],
["tipo"=>0,"fechahora"=>"2019-05-26 15:35:22"],
["tipo"=>3,"fechahora"=>"2019-05-26 16:35:31"],
["tipo"=>0,"fechahora"=>"2019-05-27 08:31:57"],
["tipo"=>1,"fechahora"=>"2019-05-27 10:27:22"],
["tipo"=>2,"fechahora"=>"2019-05-27 10:38:31"],
["tipo"=>3,"fechahora"=>"2019-05-27 14:20:38"],
["tipo"=>0,"fechahora"=>"2019-05-28 09:39:42"],
["tipo"=>1,"fechahora"=>"2019-05-28 11:43:08"],
["tipo"=>2,"fechahora"=>"2019-05-28 11:53:19"],
["tipo"=>3,"fechahora"=>"2019-05-28 14:43:31"],
["tipo"=>0,"fechahora"=>"2019-05-29 10:30:22"],
["tipo"=>3,"fechahora"=>"2019-05-29 14:38:46"]
];
</code>```

I need to create a new array with subarrays or objects by registry, a registry is an element who have startdate (type 0), somedates in between (type 1,2) and a enddate (type 3). Its important The next subarray have the startdate more current than the older subarray enddate. Every "tipo"+"fechahora" array have more fields (signature, address, etc) so I need to keep these as subarrays:

```<code>$newarray = [
    'registry0' => [
            "startdate"=> ["tipo"=>0,"fechahora"=>"2019-05-26 09:35:30"],
            "pauses"=> [
                ["tipo"=>1,"fechahora"=>"2019-05-26 10:30:15"],
                ["tipo"=>2,"fechahora"=>"2019-05-26 10:43:12"]
            ],
            "enddate" => ["tipo"=>3,"fechahora"=>"2019-05-26 14:30:26"]
        ],
    'registry1' => [
            "startdate"=> ["tipo"=>0,"fechahora"=>"2019-05-26 15:35:22"],
            "pauses"=> [],
            "enddate" => ["tipo"=>3,"fechahora"=>"2019-05-26 16:35:31"]
        ],
    'registry2' => [
            "startdate"=> ["tipo"=>0,"fechahora"=>"2019-05-27 08:31:57"],
            "pauses"=> [
                ["tipo"=>1,"fechahora"=>"2019-05-27 10:27:22"],
                ["tipo"=>2,"fechahora"=>"2019-05-27 10:38:31"]
            ],
            "enddate" => ["tipo"=>3,"fechahora"=>"2019-05-27 14:20:38"]
    ]
];
</code>```

I could use arrays or objects, I dont know hot to develop a loop to regroup arrays like this (starting at one field value and ending with another and so on). I dont even know if there is a simpler way. Any help would be appreciated.

If this could help: I need the registries this way to put into an HTML table, each registry in a row.

EDIT:

Iknow I have to use a loop but I dont know how to "get first element with type 0, create an array, include element, include all other element until type 3, close array, create new array and so on..."

In some code:

```<code>$newarray = [];
foreach($array as $element) {
if ($element["tipo"]==0) {
  //new subarray
  //include this in subarray
}
// include all "tipos" 1,2 in subarray
if ($element["tipo"]==3) {
  //include this in subarray
  //finish subarray
}
//incude subarray in $newarray
}
return $newarray;
</code>```

I dont know how to continue.

答:
For this case a simple foreach followed by switch case will do,

```<code>$result = [];
$i      = 0;
$var = 3; // you can manage this at your will
foreach ($array as $key => $value) {
    switch ($value['tipo']) { // passing tipo value here
        case 0:
            // it will capture for same record for current value of $i
            $result['registry' . $i]['startdate'] = $value;
            break;
        case $var:
            // detects last entry and will increment
            $result['registry' . $i++]['enddate'] = $value;
            break;
        default:
            // if not 0 and $var then push it in pauses
            $result['registry' . $i]['pauses'][] = $value;
            break;
    }
}
</code>```

Demo Link.

Body:
I have an array with subarrays, each subarray has 'type' (int) and a 'datetime'. I need to loop trought the array and create new arrays (or objects) with groups of these subarrays in a special way: every 'type' could be [0-3] 0 means startdate and 3 means enddate (1 and 2 are in between for other purposes). Every new array with these subarrays should start with 0 and end with 3.

Im not using any framework, only PHP5 and jQuery. The master array comes from a loop I made from a SQL query with GROUP_CONCAT. I just passed the concat fields to a master array but I need to regroup the subarrays to create some type of registries.

Here is the array I got with subarrays. They are already sorted by datetime, every type '0' means "start date / start new registry" and '3' means "end date / end registry".

$array = [
["tipo"=>0,"fechahora"=>"2019-05-26 09:35:30"],
["tipo"=>1,"fechahora"=>"2019-05-26 10:30:15"],
["tipo"=>2,"fechahora"=>"2019-05-26 10:43:12"],
["tipo"=>3,"fechahora"=>"2019-05-26 14:30:26"],
["tipo"=>0,"fechahora"=>"2019-05-26 15:35:22"],
["tipo"=>3,"fechahora"=>"2019-05-26 16:35:31"],
["tipo"=>0,"fechahora"=>"2019-05-27 08:31:57"],
["tipo"=>1,"fechahora"=>"2019-05-27 10:27:22"],
["tipo"=>2,"fechahora"=>"2019-05-27 10:38:31"],
["tipo"=>3,"fechahora"=>"2019-05-27 14:20:38"],
["tipo"=>0,"fechahora"=>"2019-05-28 09:39:42"],
["tipo"=>1,"fechahora"=>"2019-05-28 11:43:08"],
["tipo"=>2,"fechahora"=>"2019-05-28 11:53:19"],
["tipo"=>3,"fechahora"=>"2019-05-28 14:43:31"],
["tipo"=>0,"fechahora"=>"2019-05-29 10:30:22"],
["tipo"=>3,"fechahora"=>"2019-05-29 14:38:46"]
];

I need to create a new array with subarrays or objects by registry, a registry is an element who have startdate (type 0), somedates in between (type 1,2) and a enddate (type 3). Its important The next subarray have the startdate more current than the older subarray enddate. Every "tipo"+"fechahora" array have more fields (signature, address, etc) so I need to keep these as subarrays:

$newarray = [
    'registry0' => [
            "startdate"=> ["tipo"=>0,"fechahora"=>"2019-05-26 09:35:30"],
            "pauses"=> [
                ["tipo"=>1,"fechahora"=>"2019-05-26 10:30:15"],
                ["tipo"=>2,"fechahora"=>"2019-05-26 10:43:12"]
            ],
            "enddate" => ["tipo"=>3,"fechahora"=>"2019-05-26 14:30:26"]
        ],
    'registry1' => [
            "startdate"=> ["tipo"=>0,"fechahora"=>"2019-05-26 15:35:22"],
            "pauses"=> [],
            "enddate" => ["tipo"=>3,"fechahora"=>"2019-05-26 16:35:31"]
        ],
    'registry2' => [
            "startdate"=> ["tipo"=>0,"fechahora"=>"2019-05-27 08:31:57"],
            "pauses"=> [
                ["tipo"=>1,"fechahora"=>"2019-05-27 10:27:22"],
                ["tipo"=>2,"fechahora"=>"2019-05-27 10:38:31"]
            ],
            "enddate" => ["tipo"=>3,"fechahora"=>"2019-05-27 14:20:38"]
    ]
];

I could use arrays or objects, I dont know hot to develop a loop to regroup arrays like this (starting at one field value and ending with another and so on). I dont even know if there is a simpler way. Any help would be appreciated.

If this could help: I need the registries this way to put into an HTML table, each registry in a row.

EDIT:

Iknow I have to use a loop but I dont know how to "get first element with type 0, create an array, include element, include all other element until type 3, close array, create new array and so on..."

In some code:

$newarray = [];
foreach($array as $element) {
if ($element["tipo"]==0) {
  //new subarray
  //include this in subarray
}
// include all "tipos" 1,2 in subarray
if ($element["tipo"]==3) {
  //include this in subarray
  //finish subarray
}
//incude subarray in $newarray
}
return $newarray;

I dont know how to continue.

Body:
For this case a simple foreach followed by switch case will do,

$result = [];
$i      = 0;
$var = 3; // you can manage this at your will
foreach ($array as $key => $value) {
    switch ($value['tipo']) { // passing tipo value here
        case 0:
            // it will capture for same record for current value of $i
            $result['registry' . $i]['startdate'] = $value;
            break;
        case $var:
            // detects last entry and will increment
            $result['registry' . $i++]['enddate'] = $value;
            break;
        default:
            // if not 0 and $var then push it in pauses
            $result['registry' . $i]['pauses'][] = $value;
            break;
    }
}

Demo Link.


问:
UITableView dynamic cell heights only correct after some scrolling when resizing cell according to uiimage view

As you can see in the 1st Image . No text visible in UITableviewCell.
After I scroll it appears and resize the cell. I want to resize cell according to UIImage. I am fetching image  from API using SDWebImage.
I am putting code I have done in UITableView Cell for row method .

```<code>cell.imgViewSlide.sd_setImage(with: URL(string:
  self.arrSliderImage[indexPath.row]), placeholderImage: UIImage(named: "HomeSliderImage"), options: .continueInBackground) { (image, error, type, url) in

let screenBounds = UIScreen.main.bounds

let pixelWidth = Int((image?.size.width)!)

let pixelHeight = Int((image?.size.height)!)

let height = ((pixelHeight  * Int(screenBounds.width)) / pixelWidth)
cell.heightImage.constant = CGFloat(integerLiteral: height)
                                }
</code>```

I have applied plenty of solution but not working correctly.

答:
First of all, as you are fetching the Images from dynamic URL using SDWebImage, Initially you need to set a static height for the image of your tableView Cell in the storyboard.

Define a constraint Outlet for this image height in your cell, and then you should define the height of the image according to the aspect Ratio.

```<code>cell.imgViewSlideHeight.constant = CGFloat((aspectRatio) * Double(self.frame.width))
</code>```

Here self is the UITableViewCell reference and imgViewSlideHeight is the cell Image Height Constraint.

Body:
As you can see in the 1st Image . No text visible in UITableviewCell.
After I scroll it appears and resize the cell. I want to resize cell according to UIImage. I am fetching image  from API using SDWebImage.
I am putting code I have done in UITableView Cell for row method .

cell.imgViewSlide.sd_setImage(with: URL(string:
  self.arrSliderImage[indexPath.row]), placeholderImage: UIImage(named: "HomeSliderImage"), options: .continueInBackground) { (image, error, type, url) in

let screenBounds = UIScreen.main.bounds

let pixelWidth = Int((image?.size.width)!)

let pixelHeight = Int((image?.size.height)!)

let height = ((pixelHeight  * Int(screenBounds.width)) / pixelWidth)
cell.heightImage.constant = CGFloat(integerLiteral: height)
                                }

I have applied plenty of solution but not working correctly.

Body:
First of all, as you are fetching the Images from dynamic URL using SDWebImage, Initially you need to set a static height for the image of your tableView Cell in the storyboard.

Define a constraint Outlet for this image height in your cell, and then you should define the height of the image according to the aspect Ratio.

cell.imgViewSlideHeight.constant = CGFloat((aspectRatio) * Double(self.frame.width))

Here self is the UITableViewCell reference and imgViewSlideHeight is the cell Image Height Constraint.


问:
How to convert 16bit hexadecimal and binary representations to decimal float (and vice versa) in python?
I am working on a problem which requires me to convert hexadecimal and binary FP16 representation of float numbers to decimal float. I also need to convert decimal float numbers to FP16 hexadecimal and binary representations.

There are a lot of solutions for conversion of FP32 numbers. But I specifically require FP16 representations.

I already found a solution for FP16 binary to decimal float:

```<code>a = struct.pack("H",int("0010100011110101",2))

float = np.frombuffer(a, dtype =np.float16)[0]
</code>```

Basically what I want is:

FP16 binary -> decimal float    (0010100011110101 -> 0.0387268066)

FP16 hex -> decimal float       (28f5 -> 0.0387268066)

decimal float -> FP16 binary    (0.0387268066 -> 0010100011110101)

decimal float -> FP16 hex       (0.0387268066 -> 28f5)

答:
So, I found the solution after a bit of research and I'm posting it here for anyone who might need the same.

```<code>import struct
import numpy as np
bin = "0010100011110101"
hex = "28f5"
dec_float = 0.03872680
</code>```

FP16 binary to decimal float

```<code>y = struct.pack("H",int(bin,2))
float = np.frombuffer(y, dtype =np.float16)[0]
</code>```

FP16 hex to decimal float

```<code>y = struct.pack("H",int(hex,16))
float = np.frombuffer(y, dtype =np.float16)[0]
</code>```

Decimal float to FP16 binary

```<code>binary = struct.unpack('H',struct.pack('e',dec_float))[0]
binary = bin(binary)
binary = binary[2:]
binary = "0"*2 + binary
</code>```

Decimal float to FP16 hex

```<code>hexa = struct.unpack('H',struct.pack('e',dec_float))[0]
hexa = hex(hexa)
hexa = hexa[2:]
</code>```

Body:
I am working on a problem which requires me to convert hexadecimal and binary FP16 representation of float numbers to decimal float. I also need to convert decimal float numbers to FP16 hexadecimal and binary representations.

There are a lot of solutions for conversion of FP32 numbers. But I specifically require FP16 representations.

I already found a solution for FP16 binary to decimal float:

a = struct.pack("H",int("0010100011110101",2))

float = np.frombuffer(a, dtype =np.float16)[0]

Basically what I want is:

FP16 binary -> decimal float    (0010100011110101 -> 0.0387268066)

FP16 hex -> decimal float       (28f5 -> 0.0387268066)

decimal float -> FP16 binary    (0.0387268066 -> 0010100011110101)

decimal float -> FP16 hex       (0.0387268066 -> 28f5)

Body:
So, I found the solution after a bit of research and I'm posting it here for anyone who might need the same.

import struct
import numpy as np
bin = "0010100011110101"
hex = "28f5"
dec_float = 0.03872680

FP16 binary to decimal float

y = struct.pack("H",int(bin,2))
float = np.frombuffer(y, dtype =np.float16)[0]

FP16 hex to decimal float

y = struct.pack("H",int(hex,16))
float = np.frombuffer(y, dtype =np.float16)[0]

Decimal float to FP16 binary

binary = struct.unpack('H',struct.pack('e',dec_float))[0]
binary = bin(binary)
binary = binary[2:]
binary = "0"*2 + binary

Decimal float to FP16 hex

hexa = struct.unpack('H',struct.pack('e',dec_float))[0]
hexa = hex(hexa)
hexa = hexa[2:]


问:
Delay Action in Javascript without stopping the rest of the code
Trying to delay shooting in a game, the action is done by clicking but currently, it shots every frame while holding click.

SetTimeInterval does not work in my case since it just loops the function
SetTimeout does not work as well because it stops the function the second it's played and after the interval.
Tried a sleep function but it freezes up the code while running

```<code>//sleepcode
var sleep = function(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}
//called by:
if(self.pressingAttack){
    self.shootBullet(self.mouseAngle);
    sleep(3000);
}
</code>```

I want a function that shots the second its clicked but delays the second bullets, similar to every shooting game ever.

答:
You cannot do what you want the way you want it. JavaScript is designed not to have "a sleep function".

From what you said it seems you have a check inside an animation frame handler that tests whether a button is pressed, and to trigger an action if it is. In order to prevent this action from triggering for the next three seconds, simply check if it has been three seconds since the action last triggered:

```<code>let lastAttack = null;

// ...

if (self.pressingAttack) {
    let now = new Date();
    if (!lastAttack || now - lastAttack > 3000) {
      self.shootBullet(self.mouseAngle);
      lastAttack = now;
    }
}
</code>```

Body:
Trying to delay shooting in a game, the action is done by clicking but currently, it shots every frame while holding click.

SetTimeInterval does not work in my case since it just loops the function
SetTimeout does not work as well because it stops the function the second it's played and after the interval.
Tried a sleep function but it freezes up the code while running

//sleepcode
var sleep = function(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}
//called by:
if(self.pressingAttack){
    self.shootBullet(self.mouseAngle);
    sleep(3000);
}

I want a function that shots the second its clicked but delays the second bullets, similar to every shooting game ever.

Body:
You cannot do what you want the way you want it. JavaScript is designed not to have "a sleep function".

From what you said it seems you have a check inside an animation frame handler that tests whether a button is pressed, and to trigger an action if it is. In order to prevent this action from triggering for the next three seconds, simply check if it has been three seconds since the action last triggered:

let lastAttack = null;

// ...

if (self.pressingAttack) {
    let now = new Date();
    if (!lastAttack || now - lastAttack > 3000) {
      self.shootBullet(self.mouseAngle);
      lastAttack = now;
    }
}


问:
Angular Router Resolve not working when task kill and reopen Android Google Chrome
I use Angular Resolve Function to get dynamic data before drawing components.
However, when I open Android Chrome again after having task-killed Android Chrome, the page reload process will be performed but data can not be acquired.

Angular 7.2.7

My Resolver

```<code>import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { ApiService } from './api.service';
import { Observable } from 'rxjs';

...

@Injectable({
  providedIn: 'root'
})
export class CalenderByDateResolverService implements Resolve<any> {
  constructor(private api: ApiService) {}

  resolve(route: ActivatedRouteSnapshot): Observable<any> {
    const date = route.data.date;
    return this.api.getCalenderByDate(date);
  }
}
</code>```

My Routing Definition

```<code>{
    path: 'operation/real-time',
    component: RealTimeComponent,
    data: {
      title: 'Test Title',
      date: moment()
        .subtract(Number(moment().format('H')) < 4 ? 1 : 0, 'days')
        .format('YYYYMMDD')
    },
    resolve: {
      calender: CalenderByDateResolverService,
      stations: StationsResolverService
      // trips: TripsGroupByOperationsResolverService
    }
},
</code>```

答:
I understand.
It's a Service Worker Probrem.

All GET messages are sent to the same Backend URL through the intercepter.

Service Worker caches the result of GET communication to Backend URL.

Therefore, for communication to API URL A, Service Worker returned cache obtained from API URL B.

It solved by giving API URL to the query of Backend URL.

Body:
I use Angular Resolve Function to get dynamic data before drawing components.
However, when I open Android Chrome again after having task-killed Android Chrome, the page reload process will be performed but data can not be acquired.

Angular 7.2.7

My Resolver

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { ApiService } from './api.service';
import { Observable } from 'rxjs';

...

@Injectable({
  providedIn: 'root'
})
export class CalenderByDateResolverService implements Resolve<any> {
  constructor(private api: ApiService) {}

  resolve(route: ActivatedRouteSnapshot): Observable<any> {
    const date = route.data.date;
    return this.api.getCalenderByDate(date);
  }
}

My Routing Definition

{
    path: 'operation/real-time',
    component: RealTimeComponent,
    data: {
      title: 'Test Title',
      date: moment()
        .subtract(Number(moment().format('H')) < 4 ? 1 : 0, 'days')
        .format('YYYYMMDD')
    },
    resolve: {
      calender: CalenderByDateResolverService,
      stations: StationsResolverService
      // trips: TripsGroupByOperationsResolverService
    }
},


问:
How to optimally divide an array into two subarrays so that sum of elements in both are same, otherwise give an error?
How to optimally divide an array into two subarrays so that sum of elements in both subarrays is same, otherwise give an error?

Example 1

Given the array

```<code>10,  20 , 30 , 5 , 40 , 50 , 40 , 15
</code>```

It can be divided as

```<code>10, 20, 30, 5, 40
</code>```

and

```<code>50, 40, 15
</code>```

Each subarray sums up to 105.

Example 2

```<code>10,  20,  30,  5,  40,  50,  40,  10
</code>```

The array cannot be divided into 2 arrays of an equal sum.

答:
This Python3 function will split and balance a list of numbers to two separate lists equal in sum, if the sum is even.

```<code>Python3 solution:

def can_partition(a):
    mylist1 = []
    mylist2 = []
    sum1 = 0
    sum2 = 0

    for items in a:
        # Take total and divide by 2.
        total = sum(a)
        if total % 2 == 0:
            half = total//2
        else:
            return("Exiting, sum has fractions, total %s half %s" % (total, total/2))
        mylist1.append(items)
    print('Total is %s and half is %s' %(total, total/2))

    for i in a:
        sum1 = sum(mylist1)
        sum2 = sum(mylist2)
        if sum2 < half:
            mypop = mylist1.pop(0)
            mylist2.append(mypop)

    # Function to swtich numbers between the lists if sums are uneven.
    def switchNumbers(list1, list2,switch_diff):
        for val in list1:
            if val == switch_diff:
                val_index = list1.index(val)
                new_pop = list1.pop(val_index)
                list2.append(new_pop)

    #Count so while do not get out of hand
    count = len(a)
    while count != 0:
        sum1 = sum(mylist1)
        sum2 = sum(mylist2)
        if sum1 > sum2:
            diff = sum1 -half
            switchNumbers(mylist1, mylist2, diff)
            count -= 1
        elif sum2 > sum1:
            diff = sum2 - half
            switchNumbers(mylist2, mylist1, diff)
            count -= 1
        else:
            if sum1 == sum2:
                print('Values of half, sum1, sum2 are:',half, sum1,sum2)
                break
        count -= 1

    return (mylist1, mylist2)

b = [ 2, 3, 4, 2, 3, 1, 2, 5, 4, 4, 2, 2, 3, 3, 2 ]
can_partition(b)

Output:
Total is 42 total, half is 21.0
Values of half, sum1 & sum2 are : 21 21 21

([4, 4, 2, 2, 3, 3, 2, 1], [2, 3, 4, 2, 3, 2, 5])
</code>```

Body:
How to optimally divide an array into two subarrays so that sum of elements in both subarrays is same, otherwise give an error?

Example 1

Given the array

10,  20 , 30 , 5 , 40 , 50 , 40 , 15

It can be divided as

10, 20, 30, 5, 40

and

50, 40, 15

Each subarray sums up to 105.

Example 2

10,  20,  30,  5,  40,  50,  40,  10

The array cannot be divided into 2 arrays of an equal sum.

Body:
This Python3 function will split and balance a list of numbers to two separate lists equal in sum, if the sum is even.

Python3 solution:

def can_partition(a):
    mylist1 = []
    mylist2 = []
    sum1 = 0
    sum2 = 0

    for items in a:
        # Take total and divide by 2.
        total = sum(a)
        if total % 2 == 0:
            half = total//2
        else:
            return("Exiting, sum has fractions, total %s half %s" % (total, total/2))
        mylist1.append(items)
    print('Total is %s and half is %s' %(total, total/2))

    for i in a:
        sum1 = sum(mylist1)
        sum2 = sum(mylist2)
        if sum2 < half:
            mypop = mylist1.pop(0)
            mylist2.append(mypop)

    # Function to swtich numbers between the lists if sums are uneven.
    def switchNumbers(list1, list2,switch_diff):
        for val in list1:
            if val == switch_diff:
                val_index = list1.index(val)
                new_pop = list1.pop(val_index)
                list2.append(new_pop)

    #Count so while do not get out of hand
    count = len(a)
    while count != 0:
        sum1 = sum(mylist1)
        sum2 = sum(mylist2)
        if sum1 > sum2:
            diff = sum1 -half
            switchNumbers(mylist1, mylist2, diff)
            count -= 1
        elif sum2 > sum1:
            diff = sum2 - half
            switchNumbers(mylist2, mylist1, diff)
            count -= 1
        else:
            if sum1 == sum2:
                print('Values of half, sum1, sum2 are:',half, sum1,sum2)
                break
        count -= 1

    return (mylist1, mylist2)

b = [ 2, 3, 4, 2, 3, 1, 2, 5, 4, 4, 2, 2, 3, 3, 2 ]
can_partition(b)

Output:
Total is 42 total, half is 21.0
Values of half, sum1 & sum2 are : 21 21 21

([4, 4, 2, 2, 3, 3, 2, 1], [2, 3, 4, 2, 3, 2, 5])


问:
Django context value for home page
I have a model that takes a Boolean update from the admin. If the admin clicks it, the end user can or cannot access the a view. The problem is that the view is accessible through the home page which has a base file and it requires the id of the user to check against.
I get this error NoReverseMatch at /home/
I am unable to understand how can I pass the context value to the base file. I don't want to create another view for as it's a base file.

I tried context_processors but it gives me this error at the home.view
int() argument must be a string or a number, not builtin_function_or_method

I have two functions in context_processors, each has it's own characteristics.

Here is the code

settings.py

TEMPLATES = [{
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'projectfiles.context_processors.emp_base_context',
                'projectfiles.context_processors.lev_base_context',
            ],},},]

```

<p><strong>models.py</strong></p>

<pre class="lang-py prettyprint-override"><code>class Employee(models.Model):

    allowed = models.BooleanField(default=True)
    employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
    employee_designation = models.CharField(max_length = 5)
    employee_department = models.CharField(max_length = 5)

    Annual_leave = models.PositiveSmallIntegerField(default=5)
    Sick_leave = models.PositiveSmallIntegerField(default=5)
    Casual_leave = models.PositiveSmallIntegerField(default=5)
    Half_pay = models.PositiveSmallIntegerField(default=5)
    Emergency_leave = models.PositiveSmallIntegerField(default=5)

class Leave(models.Model):
    employee_leaves = models.ForeignKey(Employee, on_delete=models.CASCADE)
    leave_Type = models.CharField(max_length=25)
    leave_qty = models.PositiveSmallIntegerField(default=0)
    description = models.CharField(max_length=75, blank=True, null=True)
    submit_date = models.DateTimeField(auto_now_add=True)
    from_date = models.DateField(auto_now=False, auto_now_add=False)
    to_date = models.DateField(auto_now=False, auto_now_add=False)
    leave_status = models.CharField(max_length=10, default="Pending")

</code>```

context_processors.py

from .models import Employee, Leave

def emp_base_context(request):
    emp_data = Employee.objects.get(id=id)

    return {
        'emp_base_context': emp_base_context}

```

<p><strong>urls.py</strong></p>

<pre class="lang-py prettyprint-override"><code>urlpatterns = [
    url(r'^(?i)Home/$', views.home, name='Home-Page'),
    url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
        name='Leave-Page'),  # leave request
</code>```

views.py

def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(id=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.employee_leaves = request.user.employee
            abc.save()
        form = Leave_Form
        context = {'employee': employee, 'form': form}
        return render(request, 'projectfiles/reqleave.html', context)
    else:
        return render(request, "projectfiles/banned.html")
```

<p><strong>base.html</strong></p>

<pre class="lang-html prettyprint-override"><code><nav id="mynav" class="navbar navbar-expand-sm bg-dark">
                  class="glyphicon glyphicon-folder-close"></span> Leave Management System</a>
            </h4>
          </div>
          <div class="panel-collapse collapse panel-scroll" id="accordion">
            <div class="panel panel-default">
              <div class="panel-heading">
                <h4 class="panel-title">
                  <span
                      class="glyphicon glyphicon-folder-close"></span> Home
                </h4>
              </div>
              <div id="collapseOne" class="panel-collapse collapse">
                <div class="panel-body">
                  <table class="table">
                    <tbody>
                      <tr>
                        <td>

                       The request page   **<span class="glyphicon glyphicon-pencil text-primary"></span> Request Leave**
                        </td>
                      </tr>
                      <tr>
                        <td>
                        <span class="glyphicon glyphicon-pencil text-primary"></span> Notifications
                        </td>
                      </tr>
                      <td>
                        <span class="glyphicon glyphicon-file text-info"></span> About
                      </td>
                      </tr>

                    </tbody>
                  </table>
                </div>
              </div>
            </div>
            <div class="panel panel-default">
              <div class="panel-heading">
                <h4 class="panel-title">
                  <span
                      class="glyphicon glyphicon-user"></span> {{user.username}}
                </h4>
              </div>
              <div id="collapseThree" class="panel-collapse collapse ">
                <div class="panel-body">

                </div>
              </div>
            </div>
            <div class="panel panel-default">
              <div class="panel-heading">
                <h4 class="panel-title">
                  <span
                      class="glyphicon glyphicon-th"></span>Remaining Leaves
                </h4>
              </div>
              <div id="collapseTwo" class="panel-collapse collapse ">
                <div class="panel-body">
                  <table class="table">
                    <tbody>
                      <tr>
                        <td>
                          Annual<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
                        </td>
                      </tr>
                      <tr>
                        <td>
                          Emergency<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
                        </td>
                      </tr>
                      <tr>
                        <td>
                          Sick<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
                        </td>
                      </tr>
                      <tr>
                        <td>
                          Casual<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
              </div>
            </div>
          </div>
        </div>

      </div>

    </div>
  </div>
</div>
<div id="push"></div>
</code>```

errors

```<code>Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/home/

Django Version: 1.11.20
Python Version: 2.7.16
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'projectfiles',
 'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\views.py" in home
  25.     return render(request, "projectfiles/HomePage.html")

File "C:\Python27\lib\site-packages\django\shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string
  68.     return template.render(context, request)

File "C:\Python27\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  205.                 with context.bind_template(self):

File "C:\Python27\lib\contextlib.py" in __enter__
  17.             return self.gen.next()

File "C:\Python27\lib\site-packages\django\template\context.py" in bind_template
  263.             updates.update(processor(self.request))

File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\context_processors.py" in emp_base_context
  7.     emp_data = Employee.objects.get(id=id)

File "C:\Python27\lib\site-packages\django\db\models\manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in get
  371.         clone = self.filter(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in filter
  787.         return self._filter_or_exclude(False, *args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
  805.             clone.query.add_q(Q(*args, **kwargs))

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
  1250.         clause, _ = self._add_q(q_object, self.used_aliases)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in _add_q
  1276.                     allow_joins=allow_joins, split_subq=split_subq,

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_filter
  1210.             condition = self.build_lookup(lookups, col, value)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_lookup
  1104.                 return final_lookup(lhs, rhs)

File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in __init__
  24.         self.rhs = self.get_prep_lookup()

File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in get_prep_lookup
  74.             return self.lhs.output_field.get_prep_value(self.rhs)

File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
  966.         return int(value)

Exception Type: TypeError at /home/
Exception Value: int() argument must be a string or a number, not 'builtin_function_or_method'

</code>```

error 2.0

```<code>Request Method: GET
Request URL: http://127.0.0.1:8000/home/

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

Exception Type: TypeError at /home/
Exception Value: home() takes exactly 2 arguments (1 given)

</code>```

UPDATED

```<code>url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
        name='Leave-Page'),

<a href="{% url "Leave-Page" request.user.id %}"><span class="glyphicon glyphicon-pencil text-primary"></span> Request Leave</>

def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(employee_name=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.employee_leaves = request.user.employee
            abc.save()
        form = Leave_Form
        context = {'employee': employee, 'form': form}
        # context = {'form': form}
        return render(request, 'projectfiles/reqleave.html', context)
    else:
        return render(request, "projectfiles/banned.html")

using context_processor was passing the id to the entire view, I just needed to use it for request and by comparing the user id with the employee name worked for me.

</code>```

I expect, when the user is allowed by the admin from the back end then the user is able to access the request page and apply, otherwise the view redirects the user to a different page.

答:
From error

int() argument must be a string or a number, not builtin_function_or_method

it's obvious that context processor does not like a function or method to be returned.

so don't do

```<code>return {'emp_base_context': emp_base_context}
</code>```

return a proper value instead like

```<code>return {'emp_base_context': emp_data}
</code>```

Also I could not understand why you've declared emp_data and lev_data when you're not using it. So, I feel your context processors should look like.

```<code>from .models import Employee, Leave

def emp_base_context(request):
    emp_data = Employee.objects.get(id=id)
    return {
        'emp_base_context': emp_data}

def lev_base_context(request):
    lev_data = Leave.objects.get(id=id)
    return {
        'lev_base_context': lev_data}
</code>```

Title: Django context value for home page

Body:
I have a model that takes a Boolean update from the admin. If the admin clicks it, the end user can or cannot access the a view. The problem is that the view is accessible through the home page which has a base file and it requires the id of the user to check against.
I get this error NoReverseMatch at /home/
I am unable to understand how can I pass the context value to the base file. I don't want to create another view for as it's a base file.

I tried context_processors but it gives me this error at the home.view
int() argument must be a string or a number, not builtin_function_or_method

I have two functions in context_processors, each has it's own characteristics.

Here is the code

settings.py

TEMPLATES = [{
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'projectfiles.context_processors.emp_base_context',
                'projectfiles.context_processors.lev_base_context',
            ],},},]

models.py

class Employee(models.Model):

    allowed = models.BooleanField(default=True)
    employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
    employee_designation = models.CharField(max_length = 5)
    employee_department = models.CharField(max_length = 5)

    Annual_leave = models.PositiveSmallIntegerField(default=5)
    Sick_leave = models.PositiveSmallIntegerField(default=5)
    Casual_leave = models.PositiveSmallIntegerField(default=5)
    Half_pay = models.PositiveSmallIntegerField(default=5)
    Emergency_leave = models.PositiveSmallIntegerField(default=5)

class Leave(models.Model):
    employee_leaves = models.ForeignKey(Employee, on_delete=models.CASCADE)
    leave_Type = models.CharField(max_length=25)
    leave_qty = models.PositiveSmallIntegerField(default=0)
    description = models.CharField(max_length=75, blank=True, null=True)
    submit_date = models.DateTimeField(auto_now_add=True)
    from_date = models.DateField(auto_now=False, auto_now_add=False)
    to_date = models.DateField(auto_now=False, auto_now_add=False)
    leave_status = models.CharField(max_length=10, default="Pending")

context_processors.py

from .models import Employee, Leave

def emp_base_context(request):
    emp_data = Employee.objects.get(id=id)

    return {
        'emp_base_context': emp_base_context}

urls.py

urlpatterns = [
    url(r'^(?i)Home/$', views.home, name='Home-Page'),
    url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
        name='Leave-Page'),  # leave request

views.py

def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(id=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.employee_leaves = request.user.employee
            abc.save()
        form = Leave_Form
        context = {'employee': employee, 'form': form}
        return render(request, 'projectfiles/reqleave.html', context)
    else:
        return render(request, "projectfiles/banned.html")

base.html

                  class="glyphicon glyphicon-folder-close"> Leave Management System

                   Home

                       The request page   ** Request Leave**

                         Notifications

                         About

                   {{user.username}}

                  Remaining Leaves

                          Annual
Remaining leaves

                          Emergency
Remaining leaves

                          Sick
Remaining leaves

                          Casual
Remaining leaves

errors

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/home/

Django Version: 1.11.20
Python Version: 2.7.16
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'projectfiles',
 'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\views.py" in home
  25.     return render(request, "projectfiles/HomePage.html")

File "C:\Python27\lib\site-packages\django\shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string
  68.     return template.render(context, request)

File "C:\Python27\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  205.                 with context.bind_template(self):

File "C:\Python27\lib\contextlib.py" in __enter__
  17.             return self.gen.next()

File "C:\Python27\lib\site-packages\django\template\context.py" in bind_template
  263.             updates.update(processor(self.request))

File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\context_processors.py" in emp_base_context
  7.     emp_data = Employee.objects.get(id=id)

File "C:\Python27\lib\site-packages\django\db\models\manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in get
  371.         clone = self.filter(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in filter
  787.         return self._filter_or_exclude(False, *args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
  805.             clone.query.add_q(Q(*args, **kwargs))

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
  1250.         clause, _ = self._add_q(q_object, self.used_aliases)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in _add_q
  1276.                     allow_joins=allow_joins, split_subq=split_subq,

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_filter
  1210.             condition = self.build_lookup(lookups, col, value)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_lookup
  1104.                 return final_lookup(lhs, rhs)

File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in __init__
  24.         self.rhs = self.get_prep_lookup()

File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in get_prep_lookup
  74.             return self.lhs.output_field.get_prep_value(self.rhs)

File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
  966.         return int(value)

Exception Type: TypeError at /home/
Exception Value: int() argument must be a string or a number, not 'builtin_function_or_method'

error 2.0

Request Method: GET
Request URL: http://127.0.0.1:8000/home/

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

Exception Type: TypeError at /home/
Exception Value: home() takes exactly 2 arguments (1 given)

UPDATED

url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
        name='Leave-Page'),

 Request Leave</>

def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(employee_name=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.employee_leaves = request.user.employee
            abc.save()
        form = Leave_Form
        context = {'employee': employee, 'form': form}
        # context = {'form': form}
        return render(request, 'projectfiles/reqleave.html', context)
    else:
        return render(request, "projectfiles/banned.html")

using context_processor was passing the id to the entire view, I just needed to use it for request and by comparing the user id with the employee name worked for me.

I expect, when the user is allowed by the admin from the back end then the user is able to access the request page and apply, otherwise the view redirects the user to a different page.

Body:
From error

int() argument must be a string or a number, not builtin_function_or_method

it's obvious that context processor does not like a function or method to be returned.

so don't do

return {'emp_base_context': emp_base_context}

return a proper value instead like

return {'emp_base_context': emp_data}

Also I could not understand why you've declared emp_data and lev_data when you're not using it. So, I feel your context processors should look like.

from .models import Employee, Leave

def emp_base_context(request):
    emp_data = Employee.objects.get(id=id)
    return {
        'emp_base_context': emp_data}

def lev_base_context(request):
    lev_data = Leave.objects.get(id=id)
    return {
        'lev_base_context': lev_data}


问:
AFNetworking was built without full bitcode
I am getting error "AFNetworking was built without full bitcode" when i enable bitcode in a project.
There is a open issue also there.

If anyone have solve the issue please help me.

AFNetworking version : 3.2.1

Detailed error : "ld: bitcode bundle could not be generated because '/Users/Library/Developer/Xcode/DerivedData/ServiceSDK-hkwcndktudaxkjebecaqimswckgp/Build/Products/Release-iphoneos/AFNetworking/AFNetworking.framework/AFNetworking' was built without full bitcode. All frameworks and dylibs for bitcode must be generated from Xcode Archive or Install build file '/Users/Library/Developer/Xcode/DerivedData/ServiceSDK-hkwcndktudaxkjebecaqimswckgp/Build/Products/Release-iphoneos/AFNetworking/AFNetworking.framework/AFNetworking' for architecture armv7"

答:
Ok, so i fixed the issue by adding following in podfile

```<code>    post_install do |installer|
         installer.pods_project.targets.each do |target|
             target.build_configurations.each do |config|
                 config.build_settings['BITCODE_GENERATION_MODE'] = 'bitcode'
                 config.build_settings['ENABLE_BITCODE'] = 'YES'
             end
         end
     end
</code>```

May be it will help others.

Thanks

Body:
Ok, so i fixed the issue by adding following in podfile

    post_install do |installer|
         installer.pods_project.targets.each do |target|
             target.build_configurations.each do |config|
                 config.build_settings['BITCODE_GENERATION_MODE'] = 'bitcode'
                 config.build_settings['ENABLE_BITCODE'] = 'YES'
             end
         end
     end

May be it will help others.

Thanks


问:
What are the %functions in JavaScript source code?
Looking through the promise code in v8 source code, I noticed a lot of functions that starts with %, what are those? do they have any special meaning?

example here https://chromium.googlesource.com/v8/v8/+/3.29.45/src/promise.js?autodive=0%2F
like %DebugPushPromise

答: They're internal built-in runtime functions. More info here: https://v8.dev/docs/builtin-functions


问:
Client Server communication opc ua
I am new to opcua and I have been trying to do communication in the following way:

Server imports xml --> client reads a value(using get_node) --> based on the value, client sends request to server --> Server responds to the request --> Client receives the response.

I have completed the part until the client reads the value. I am now trying to send a request to the server.
But I am unable to understand which method to I use?

I have seen the source code and I can see send_request() method. But I cannot get how to send the request.

Also once I send the request, how would the server respond to it? Please guide me through this or point me to an example.

My client and server look like this:

server.py

```<code>from opcua import Server
from opcua.ua.uatypes import NodeId, NumericNodeId
from opcua import ua

server = Server()
server.import_xml("Opc.Ua.Di.NodeSet2.xml");
server.import_xml("final.xml");
server.set_endpoint("opc.tcp://localhost:4840/MyServer");
server.set_server_name("MyServer");

MyServerNameSpace = server.get_namespace_index("urn:freeopcua:python:server");
server.start();
</code>```

client.py

```<code>from opcua import Client
from opcua import ua
from opcua.ua import StringNodeId

client = Client("opc.tcp://localhost:4840");

client.connect_socket();
client.create_session();
client.activate_session(username=None, password=None, certificate=None);

objects = client.get_objects_node();
xx = client.get_node(StringNodeId("i40.io/PrmInst/Temp_1",3));
tempval = xx.get_value();

if tempval < 20 :
#here i want to write the request code
</code>```

答:
can u bit more precise on request code. If its status code that you are after, then
use

```<code>tempval = xx.get_data_value()
if tempval.Value.Value < 20:
   status = tempval.StatusCode.name # eg: Good/Bad etc..
   message= tempval.StatusCode.doc
</code>```

Try to use get_data_value() which gives you much more info.From there on you can pull out the details that u are after.

Title: Client Server communication opc ua

Body:
I am new to opcua and I have been trying to do communication in the following way:

Server imports xml --> client reads a value(using get_node) --> based on the value, client sends request to server --> Server responds to the request --> Client receives the response.

I have completed the part until the client reads the value. I am now trying to send a request to the server.
But I am unable to understand which method to I use?

I have seen the source code and I can see send_request() method. But I cannot get how to send the request.

Also once I send the request, how would the server respond to it? Please guide me through this or point me to an example.

My client and server look like this:

server.py

from opcua import Server
from opcua.ua.uatypes import NodeId, NumericNodeId
from opcua import ua

server = Server()
server.import_xml("Opc.Ua.Di.NodeSet2.xml");
server.import_xml("final.xml");
server.set_endpoint("opc.tcp://localhost:4840/MyServer");
server.set_server_name("MyServer");

MyServerNameSpace = server.get_namespace_index("urn:freeopcua:python:server");
server.start();

client.py

from opcua import Client
from opcua import ua
from opcua.ua import StringNodeId

client = Client("opc.tcp://localhost:4840");

client.connect_socket();
client.create_session();
client.activate_session(username=None, password=None, certificate=None);

objects = client.get_objects_node();
xx = client.get_node(StringNodeId("i40.io/PrmInst/Temp_1",3));
tempval = xx.get_value();

if tempval < 20 :
#here i want to write the request code

Body:
can u bit more precise on request code. If its status code that you are after, then
use

tempval = xx.get_data_value()
if tempval.Value.Value < 20:
   status = tempval.StatusCode.name # eg: Good/Bad etc..
   message= tempval.StatusCode.doc

Try to use get_data_value() which gives you much more info.From there on you can pull out the details that u are after.


问:
Print Currency Number Format in PHP
I have some price values to display in my page.

I am writing a function which takes the float price and returns the formatted currency val with currency code too..

For example, fnPrice(1001.01) should print $ 1,000.01

答:
From the docs</p>

```<code><?php

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>
</code>```

Title: Print Currency Number Format in PHP

Body:
From the docs

<?php

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>


问:
How to Join Eloquent and Query Builder in one query statement in laravel
I have 2 queries that needed to join 1st is eloquent and 2nd is query builder,

1st Query

```<code>$products = Product::all();
</code>```

2nd Query

```<code>$inventory = DB::table('product_warehouse')
->where('product_id', $product_id)
->where('warehouse_id', $warehouse_id)
->first();
</code>```

How to merge this 2 queries into elouquent way ?

答:
From your usage of the query builder it seems like you have an intermediate table to store which product to which warehouse exist, but if it is a one to many relationship you should not have that table, instead in your products table you should have a warehouse_id which will reference the id on the warehouses table, as you said the relationship is one to many, not many to many.

So in your Warehouse model you can add:

```<code>public function products()
{
    return $this->hasMany(Product::class);
}
</code>```

And in your Product model:

```<code>public function warehouse()
{
    return $this->belongsTo(Warehouse::class);
}
</code>```

Based on your table name, you might need to set the $table in your warehouse model to match that:

```<code>protected $table = 'product_warehouse';
</code>```

Then you have many ways to fetch it, one of which is :

```<code>Warehouse::find($warehouse_id)->products;

// or

Warehouse::with('products')->where('id', $warehouse_id)->get();

// to get the warehouse to which the product belongs to
Product::find($product_id)->warehouse;
</code>```

Body:
I have 2 queries that needed to join 1st is eloquent and 2nd is query builder,

1st Query

$products = Product::all();

2nd Query

$inventory = DB::table('product_warehouse')
->where('product_id', $product_id)
->where('warehouse_id', $warehouse_id)
->first();

How to merge this 2 queries into elouquent way ?

Body:
From your usage of the query builder it seems like you have an intermediate table to store which product to which warehouse exist, but if it is a one to many relationship you should not have that table, instead in your products table you should have a warehouse_id which will reference the id on the warehouses table, as you said the relationship is one to many, not many to many.

So in your Warehouse model you can add:

public function products()
{
    return $this->hasMany(Product::class);
}

And in your Product model:

public function warehouse()
{
    return $this->belongsTo(Warehouse::class);
}

Based on your table name, you might need to set the $table in your warehouse model to match that:

protected $table = 'product_warehouse';

Then you have many ways to fetch it, one of which is :

Warehouse::find($warehouse_id)->products;

// or

Warehouse::with('products')->where('id', $warehouse_id)->get();

// to get the warehouse to which the product belongs to
Product::find($product_id)->warehouse;


问:
How to pick specific column from txt file with delimiters in c# Console application
Hello I've got a data(in txt file) which contains 1,4 million rows ++ and i need to separate the data based on ID. So if in the data has 10 differents ID, then the console application will create 10 different files which each files contains data who has same ID.

My problem is , the data that have been given to me , not all columns to be insert, so if the data has has 10 columns, i only need to take 8 columns

Here's the code that i use to write and separate data into files with differents id

```<code>  string appPath = AppDomain.CurrentDomain.BaseDirectory;
  string dirTxt = appPath + "VA_" + tglskrg;
  string dirZip = appPath + "VA_" + tglskrg + "\\ZIP";

 var writers = new Dictionary<string, TextWriter>();
            string header = "COMPANY CODE;CUSTOMER NUMBER;CUSTOMER NAME;INSERT DATE;TRANSACTION ID;TRANSACTION AMOUNT;ADMIN FEE;TRANSACTION REF;FLAG STATUS;TRANSACTION STATUS"; //its still 10 columns because my code still write all the columns in the old data .
            string inputFile = appPath + "va_txn_success_daily_"+tglkemarin+".txt";

            string outputPath = dirTxt;
            string outputPathh = dirZip;
            TextWriter writer;
            using (var reader = File.OpenText(inputFile))
            {
                //skip header
                reader.ReadLine();

                try
                {
                    while (!reader.EndOfStream)
                    {
                        //read one line and separate key and value
                        var line = reader.ReadLine();
                        var separatorIndex = line.IndexOf(';');
                        var id = line.Substring(0, separatorIndex);
                        var value = line.Substring(separatorIndex - 5);

                        //get a writer or create one
                        if (!writers.TryGetValue(id, out writer))
                        {
                            writer = File.CreateText(dirTxt + "\\" + "va_txn_success_" + id + "_" + tglskrg + ".txt");
                            writer.WriteLine(header);
                            writers.Add(id, writer);

                        }

                        //write the line to the correct file
                        writer.WriteLine(value);

                    }
                }
                finally
                {
                    reader.Close();
                    //dispose all the writers
                    foreach (var writerr in writers.Values)
                    {
                        writerr.Dispose();
                    }
                }
</code>```

I cant show the data , because the data its restricted

if i can give example so will be

```<code>COMPANY CODE;CUSTOMER NUMBER;CUSTOMER NAME;INSERT DATE;TRANSACTION ID;TRANSACTION AMOUNT;ADMIN FEE;TRANSACTION REF;FLAG STATUS;TRANSACTION STATUS;
A;01;Ricky;15-Jan;ABC01;1000;0;BCD123;Success;Trans success
B;02;John;15-Feb;ABC02;1500;1000;BCC122;Success;Trans success
A;02;Ricky;1-Jan;Abc03;2000;0;BCC;123;Success;Trans success
</code>```

So it will be create 2 file , for A company Code and B company Code

And i want to take the company code, cust number, cust name, insert date, trans amount, trans ref, flag status ,and trans status only

Thankyou

答:
Read the items of the line into an array. Easiest way: String.Split

```<code>string[] items = String.Split(";");
</code>```

Then you are able to acces the columns;

```<code>string company = item[0};
string customer = item[1];
....
</code>```

Body:
Hello I've got a data(in txt file) which contains 1,4 million rows ++ and i need to separate the data based on ID. So if in the data has 10 differents ID, then the console application will create 10 different files which each files contains data who has same ID.

My problem is , the data that have been given to me , not all columns to be insert, so if the data has has 10 columns, i only need to take 8 columns

Here's the code that i use to write and separate data into files with differents id

  string appPath = AppDomain.CurrentDomain.BaseDirectory;
  string dirTxt = appPath + "VA_" + tglskrg;
  string dirZip = appPath + "VA_" + tglskrg + "\\ZIP";

 var writers = new Dictionary<string, TextWriter>();
            string header = "COMPANY CODE;CUSTOMER NUMBER;CUSTOMER NAME;INSERT DATE;TRANSACTION ID;TRANSACTION AMOUNT;ADMIN FEE;TRANSACTION REF;FLAG STATUS;TRANSACTION STATUS"; //its still 10 columns because my code still write all the columns in the old data .
            string inputFile = appPath + "va_txn_success_daily_"+tglkemarin+".txt";

            string outputPath = dirTxt;
            string outputPathh = dirZip;
            TextWriter writer;
            using (var reader = File.OpenText(inputFile))
            {
                //skip header
                reader.ReadLine();

                try
                {
                    while (!reader.EndOfStream)
                    {
                        //read one line and separate key and value
                        var line = reader.ReadLine();
                        var separatorIndex = line.IndexOf(';');
                        var id = line.Substring(0, separatorIndex);
                        var value = line.Substring(separatorIndex - 5);

                        //get a writer or create one
                        if (!writers.TryGetValue(id, out writer))
                        {
                            writer = File.CreateText(dirTxt + "\\" + "va_txn_success_" + id + "_" + tglskrg + ".txt");
                            writer.WriteLine(header);
                            writers.Add(id, writer);

                        }

                        //write the line to the correct file
                        writer.WriteLine(value);

                    }
                }
                finally
                {
                    reader.Close();
                    //dispose all the writers
                    foreach (var writerr in writers.Values)
                    {
                        writerr.Dispose();
                    }
                }

I cant show the data , because the data its restricted

if i can give example so will be

COMPANY CODE;CUSTOMER NUMBER;CUSTOMER NAME;INSERT DATE;TRANSACTION ID;TRANSACTION AMOUNT;ADMIN FEE;TRANSACTION REF;FLAG STATUS;TRANSACTION STATUS;
A;01;Ricky;15-Jan;ABC01;1000;0;BCD123;Success;Trans success
B;02;John;15-Feb;ABC02;1500;1000;BCC122;Success;Trans success
A;02;Ricky;1-Jan;Abc03;2000;0;BCC;123;Success;Trans success

So it will be create 2 file , for A company Code and B company Code

And i want to take the company code, cust number, cust name, insert date, trans amount, trans ref, flag status ,and trans status only

Thankyou

Body:
Read the items of the line into an array. Easiest way: String.Split

string[] items = String.Split(";");

Then you are able to acces the columns;

string company = item[0};
string customer = item[1];
....


答:
There are a few ways to solve this problem. Here's how I would go about it.

```<code>import array as arr

numbers = arr.array('i', [10,12,12,13])

new_nums = arr.array('i', [i for i in numbers if i<12])
</code>```

You can also use the pop() method, like so:

```<code>new_nums = arr.array('i', [numbers.pop(i) for i,val in enumerate(numbers) if val<12])
</code>```

Alternatively, you can just use list comprehension on a Python list, like this:

```<code>new_nums = [i for i in numbers if i<12]
</code>```

Hope this helps!

Title: Excluding elements from an old array and creating a new array

Body:
I have an array that has 3 different values, I want to create a new array that has only the values that are smaller that 12 (for example).

import array as arr

numbers = arr.array([10,12, 12, 13])

numbers.remove(12)
numbers.remove(13)
print(numbers)

I don't know how to add them in a new array

Body:
There are a few ways to solve this problem. Here's how I would go about it.

import array as arr

numbers = arr.array('i', [10,12,12,13])

new_nums = arr.array('i', [i for i in numbers if i<12])

You can also use the pop() method, like so:

new_nums = arr.array('i', [numbers.pop(i) for i,val in enumerate(numbers) if val<12])

Alternatively, you can just use list comprehension on a Python list, like this:

new_nums = [i for i in numbers if i<12]

Hope this helps!


问:
How to destroy and spawn different GameObjects in specified seconds using coroutine?
I am working on an educational kids game. Teaching materials should horizontally scroll one by one, together with the related audio files. For example, if the cat image is on the screen, then the cat sound plays.

I am trying to use coroutines. But GameObjects aren't destroyed individually. All of the previously spawned GameObjects are waiting for the new spawning GameObjects and they are being destroyed at once after all GameObject spawns.

```<code>[SerializeField] private GameObject[] sceneObjects;
[SerializeField] private int objectSlideSpeed;
[SerializeField] private int timer;
[SerializeField] private float targetLocation;

void Update()
{
    StartCoroutine(SlideLeft());
}

IEnumerator SlideLeft()
{
    for (int i = 0; i < sceneObjects.Length; i++)
    {
        while(sceneObjects[i].transform.position.x > targetLocation)
        {
            sceneObjects[i].transform.Translate(objectSlideSpeed * Time.deltaTime * Vector3.left);
            yield return new WaitForSeconds(timer);

            if (sceneObjects[i].transform.position.x < targetLocation)
            {
                StopSlide(); // objectSlideSpeed = 0;
                Destroy(sceneObjects[i]);
            }
        }
    }
}
</code>```

Expected

Different GameObjects are supposed to be spawned in every second which is specified in int timer.

Every GameObjects must reach to the target transform position.

At this position, the GameObject must wait without any speed and then the related sound plays. (Audio.Play() function will be implemented in the StopSlide() function later)

After sound plays, the GameObject must be destroyed and the different one is supposed to be spawned.

Without destroying the previous GameObject, the new one mustn't be spawned.

Destruction and spawning methods don't require any user actions. They occur automatically depending on the timer variable.

Current Situation

The first GameObject is spawned and it reaches the target transform position which is specified in the float targetLocation variable.

At this point, the first GameObject waits for a specified second without any speed.

Meanwhile, the new and different GameObject is spawned and after it reaches the target location either, all of spawned GameObjects are destroyed altogether.

答:
```<code>[SerializeField] private GameObject[] sceneObjects;
[SerializeField] private int objectSlideSpeed;
[SerializeField] private int timer;
[SerializeField] private float targetLocation;

// When the scene loads, you dont want update or else the coroutine will be called every frame
void Start()
{
    StartCoroutine(SlideLeft());
}

IEnumerator SlideLeft()
{
    for (int i = 0; i < sceneObjects.Length; i++)
    {
        // [Here], on while we check the conidtion and if it is not true we dont step into it
        while(sceneObjects[i].transform.position.x > targetLocation)
        {
            sceneObjects[i].transform.Translate(objectSlideSpeed * Time.deltaTime * Vector3.left);
            // Why you need a timer, if your goal is to start a gameobject when the other one arrived,
            // at its destination? O.o
            // yield return new WaitForSeconds(timer);

            yield return null; // After this yield execution will continue on the [Here] Tag
        }
        StopSlide();
        Destroy(sceneObjects[i]);
    }
}
</code>```

There is some things that i do not understand, in your expected behavior, but write a comment if i misunderstood something.

And the reason why it seems like it works is because you called them in update, but you like created a million coroutines and hundred of thousands were in paused execution.

Body:
I am working on an educational kids game. Teaching materials should horizontally scroll one by one, together with the related audio files. For example, if the cat image is on the screen, then the cat sound plays.

I am trying to use coroutines. But GameObjects aren't destroyed individually. All of the previously spawned GameObjects are waiting for the new spawning GameObjects and they are being destroyed at once after all GameObject spawns.

[SerializeField] private GameObject[] sceneObjects;
[SerializeField] private int objectSlideSpeed;
[SerializeField] private int timer;
[SerializeField] private float targetLocation;

void Update()
{
    StartCoroutine(SlideLeft());
}

IEnumerator SlideLeft()
{
    for (int i = 0; i < sceneObjects.Length; i++)
    {
        while(sceneObjects[i].transform.position.x > targetLocation)
        {
            sceneObjects[i].transform.Translate(objectSlideSpeed * Time.deltaTime * Vector3.left);
            yield return new WaitForSeconds(timer);

            if (sceneObjects[i].transform.position.x < targetLocation)
            {
                StopSlide(); // objectSlideSpeed = 0;
                Destroy(sceneObjects[i]);
            }
        }
    }
}

Expected

Different GameObjects are supposed to be spawned in every second which is specified in int timer.

Every GameObjects must reach to the target transform position.

At this position, the GameObject must wait without any speed and then the related sound plays. (Audio.Play() function will be implemented in the StopSlide() function later)

After sound plays, the GameObject must be destroyed and the different one is supposed to be spawned.

Without destroying the previous GameObject, the new one mustn't be spawned.

Destruction and spawning methods don't require any user actions. They occur automatically depending on the timer variable.

Current Situation

The first GameObject is spawned and it reaches the target transform position which is specified in the float targetLocation variable.

At this point, the first GameObject waits for a specified second without any speed.

Meanwhile, the new and different GameObject is spawned and after it reaches the target location either, all of spawned GameObjects are destroyed altogether.

Body:
[SerializeField] private GameObject[] sceneObjects;
[SerializeField] private int objectSlideSpeed;
[SerializeField] private int timer;
[SerializeField] private float targetLocation;

// When the scene loads, you dont want update or else the coroutine will be called every frame
void Start()
{
    StartCoroutine(SlideLeft());
}

IEnumerator SlideLeft()
{
    for (int i = 0; i < sceneObjects.Length; i++)
    {
        // [Here], on while we check the conidtion and if it is not true we dont step into it
        while(sceneObjects[i].transform.position.x > targetLocation)
        {
            sceneObjects[i].transform.Translate(objectSlideSpeed * Time.deltaTime * Vector3.left);
            // Why you need a timer, if your goal is to start a gameobject when the other one arrived,
            // at its destination? O.o
            // yield return new WaitForSeconds(timer);

            yield return null; // After this yield execution will continue on the [Here] Tag
        }
        StopSlide();
        Destroy(sceneObjects[i]);
    }
}

There is some things that i do not understand, in your expected behavior, but write a comment if i misunderstood something.

And the reason why it seems like it works is because you called them in update, but you like created a million coroutines and hundred of thousands were in paused execution.


问:
Is it a good practice to use intents for communication inside the same application?
I'm working on application where I have several modules and logic running on several threads. Sometimes I need some communication between the different threads to achieve some functionality. I started using Intents for this purpose but I'm not sure if this is a good practice in Android in general or it's an overkill (in terms of usage, performance, etc) since the intent mechanism is designed to be used for inter-app communication.</p>

答: Between threads?  Why?  That's a bit heavyweight.  Why not just pass the threads a message with a map of the parameters?  Intents are optimized for cross process communication, they really shouldn't be used unless you're starting a new Context.  Look into MessageQueues, Handlers, and HandlerThreads for better solutions to the problem.</p>