问:
What does char*** mean in C?
I need help understanding what char*** means and how do I initialize a variable that is of type char***.

For example, if there is a function that reads the lines of a file, while keeping track of the number of lines and printing out each line with its corresponding number:

```<code>void read_lines(FILE* fp, char*** lines, int* num_lines){}
</code>```

What would char*** represent in this case and how would I initialize the variable lines?

答:
I need help understanding what char*** means ...

The char*** type is a pointer.  A pointer to a char **.  p as pointer to pointer to pointer to char

```<code>char*** p;
</code>```

... and how do I initialize a variable that is of type char***.

```<code>char*** p1 = NULL;  // Initialize p with the null pointer constant.

char *q[] = { "one", "two", "three" };
char*** p2 = &q;  // Initialize p2 with the address of q

char ***p3 = malloc(sizeof *p3);  // Allocate memory to p3.  Enough for 1 `char **`.
....
free(p3); // free memory when done.
</code>```

Title: What does char*** mean in C?

Body:
I need help understanding what char*** means and how do I initialize a variable that is of type char***.

For example, if there is a function that reads the lines of a file, while keeping track of the number of lines and printing out each line with its corresponding number:

void read_lines(FILE* fp, char*** lines, int* num_lines){}

What would char*** represent in this case and how would I initialize the variable lines?

Body:
I need help understanding what char*** means ...

The char*** type is a pointer.  A pointer to a char **.  p as pointer to pointer to pointer to char

char*** p;

... and how do I initialize a variable that is of type char***.

char*** p1 = NULL;  // Initialize p with the null pointer constant.

char *q[] = { "one", "two", "three" };
char*** p2 = &q;  // Initialize p2 with the address of q

char ***p3 = malloc(sizeof *p3);  // Allocate memory to p3.  Enough for 1 `char **`.
....
free(p3); // free memory when done.


来源: stackexchange

问:
tdlib: GetBasicGroupFullInfo returns "Group not found" error
I want to get all users (user id and username) from group in Telegram. I use the tdlib. ID of group I receive by method getChats. When I pass received ID to method GetBasicGroupFullInfo - I got a response with error:

```<code>Error {
  code = 6
  message = "Group not found"
}
</code>```

What I'm doing wrong? And how to get user id and username of all users from telegram group?

答: I had the same issue. I found out TDLIB had to "cache" the basic group before getting the full info. So what I did is: first, call getBasicGroup (even if you ignore the result) then you can call getBasicGroupFullInfo.</p>

ContentLicense: CC BY-SA 4.0

Body:
I want to get all users (user id and username) from group in Telegram. I use the tdlib. ID of group I receive by method getChats. When I pass received ID to method GetBasicGroupFullInfo - I got a response with error:

Error {
  code = 6
  message = "Group not found"
}

What I'm doing wrong? And how to get user id and username of all users from telegram group?


问:
Mouse control is not working with object movement. Fabric Js
I am trying to create a responsive canvas and while I am doing that I am facing issues related to the transform tool object movement and selection.

Can you please help me where I am doing wrong?

In this code, I am creating canvas dynamically using JSON and underscore js

Here are the steps

Launch the code

Resize te window

Check now you will see controls are not working.

Here are my code

```<code> <!DOCTYPE html>
<html>
<head>
<title>Fit Canvas Within Perticular area Using this code your canvas will fit inside any container </title>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"> </script>
<script type="text/javascript" src="http://5945822.swh.strato-hosting.eu//ma-test/test-0124-2/js/all.js"></script>

 <script type="text/html" id='canvas-template'>
        <% _.each(viewList,function(view,key,list){   %>

                    <div class="view-wrapper" data-editor-view-id="<%=view.viewId %>"  style="width:<%=view.imageWidth%>px; height:<%=view.imageHeight%>px; position:relative">
                        <img data-component-type="product-image" src="https://livingannuityspecialist.co.za/wp-content/uploads/2019/03/retirement.jpg" class="productImage"  width="<%=view.imageWidth%>" height="<%=view.imageHeight%>"  />
                        <div class="canvas-wrapper"  style="position:absolute; width:<%=view.width%>px; height:<%=view.height%>px; left: <%=view.left%>px; top: <%=view.top%>px;">
                                <canvas id="<%=view.applicationType%>_<%=view.viewId%>" width="<%=view.width%>" height="<%=view.height%>" ></canvas>
                        </div>
                    </div>
        <% }); %>

</script>

<body>

<div  id="target_container"  style="width:100%; height:100%;">

</div>
<button onClick="addImage()">Add Image </button>

<script>

/* List of canvas */
var canvas;
    var viewDetailsList=[
        {
        "width":1880,"height":977,"top":0,"left":0,"imageWidth":1880,"imageHeight":977,"viewId":2603,"title":"front","imageSrc":"1.png","applicationType":"editor"
        }]

        var template = $("#canvas-template").html();
        $('#target_container').html(_.template(template)({viewList:viewDetailsList}));

        var $targetContainer=$('#target_container');

        /* Calculate Scale Factor according to Outer container */
        function calculateScaleFactor(viewId) {
            var viewContainer = $('[data-editor-view-id="' + viewId + '"]');
            var cssWidthScale = $targetContainer.width() / viewContainer.width();
            var cssHeightScale = $targetContainer.height() / viewContainer.height();
            var scaleFactor = Math.min(cssWidthScale, cssHeightScale);
            return scaleFactor;
        }
        /* Fit Canvas to perticular target or div according to width and height of div
         Let's say If I wan to fix perticular canvas of width 1000px and height 1000px to 500px by 500px then I waant to calculate the scaleFactor for fitting 1000px canvas inside the 500px area.
        */
        function setCanvasCSS(viewId){
            var scaleFactor= calculateScaleFactor(viewId);
            var viewContainer = $('[data-editor-view-id="' + viewId + '"]');
            var scaling= 'scale(' + scaleFactor + ',' + scaleFactor + ')'
            viewContainer.css({'transform': scaling,'-webkit-transform': scaling,'-moz-transform': scaling,'-o-transform': scaling});
            var leftPos = ($targetContainer.width() - viewContainer.width() * scaleFactor) / 2;
            var topPos = ($targetContainer.height() - viewContainer.height() * scaleFactor) / 2;
            viewContainer.css({'left': leftPos,'top':topPos});

        }
        /* Iteration for Multiple Canvas*/
        $.each(viewDetailsList,function(key, view){
            setCanvasCSS(view.viewId);
        })

        /*Window.Resize canvas setting */
        $(window).resize(function(){
            setCanvasCSS(viewDetailsList[0].viewId);
                canvas.getObjects().forEach(function(obj){
                obj.setCoords();
                canvas.renderAll();
                 canvas.calcOffset();
            })

          });

         /* Create Canvas */
         canvas = new fabric.Canvas('editor_2603');

        /* Add Image */
         function addImage(){
            var imgURL = 'http://i.imgur.com/8rmMZI3.jpg';
             var imgObj = new Image();
            imgObj.src = imgURL
            imgObj.onload = function() {
              var image = new fabric.Image(imgObj);
              image.set({
                left: 10,
                top: 10,
              }).scale(0.2);
              canvas.add(image);
              image.setCoords();
              canvas.renderAll();
              canvas.calcOffset();

            };

         }
</script>

<style>
 #target_container{border:1px solid red;}
 .view-wrapper{transform-origin:0% 0%;overflow:hidden;}
 .canvas-wrapper{border: 5px solid green;}

</style>

</body>
</html>
</code>```

答:
I got the fixed I have updated the latest fabric.js and its working properly for me </p>

```<code><!DOCTYPE html>
<html>
<head>
<title>Fit Canvas Within Perticular area Using this code your canvas will fit inside any container </title>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"> </script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.0.0/fabric.js"></script>

 <script type="text/html" id='canvas-template'>
        <% _.each(viewList,function(view,key,list){   %>

                    <div class="view-wrapper" data-editor-view-id="<%=view.viewId %>"  style="width:<%=view.imageWidth%>px; height:<%=view.imageHeight%>px; position:relative">
                        <img data-component-type="product-image" src="https://livingannuityspecialist.co.za/wp-content/uploads/2019/03/retirement.jpg" class="productImage"  width="<%=view.imageWidth%>" height="<%=view.imageHeight%>"  />
                        <div class="canvas-wrapper"  style="position:absolute; width:<%=view.width%>px; height:<%=view.height%>px; left: <%=view.left%>px; top: <%=view.top%>px;">
                                <canvas id="<%=view.applicationType%>_<%=view.viewId%>" width="<%=view.width%>" height="<%=view.height%>" ></canvas>
                        </div>
                    </div>
        <% }); %>

</script>

<body>

<div  id="target_container"  style="width:100%; height:100%;">

</div>
<button onClick="addImage()">Add Image </button>

<script>

/* List of canvas */
var canvas;
    var viewDetailsList=[
        {
        "width":1880,"height":977,"top":0,"left":0,"imageWidth":1880,"imageHeight":977,"viewId":2603,"title":"front","imageSrc":"1.png","applicationType":"editor"
        }]

        var template = $("#canvas-template").html();
        $('#target_container').html(_.template(template)({viewList:viewDetailsList}));

        var $targetContainer=$('#target_container');

        /* Calculate Scale Factor according to Outer container */
        function calculateScaleFactor(viewId) {
            var viewContainer = $('[data-editor-view-id="' + viewId + '"]');
            var cssWidthScale = $targetContainer.width() / viewContainer.width();
            var cssHeightScale = $targetContainer.height() / viewContainer.height();
            var scaleFactor = Math.min(cssWidthScale, cssHeightScale);
            return scaleFactor;
        }
        /* Fit Canvas to perticular target or div according to width and height of div
         Let's say If I wan to fix perticular canvas of width 1000px and height 1000px to 500px by 500px then I waant to calculate the scaleFactor for fitting 1000px canvas inside the 500px area.
        */
        function setCanvasCSS(viewId){
            var scaleFactor= calculateScaleFactor(viewId);
            var viewContainer = $('[data-editor-view-id="' + viewId + '"]');
            var scaling= 'scale(' + scaleFactor + ',' + scaleFactor + ')'
            viewContainer.css({'transform': scaling,'-webkit-transform': scaling,'-moz-transform': scaling,'-o-transform': scaling});
            var leftPos = ($targetContainer.width() - viewContainer.width() * scaleFactor) / 2;
            var topPos = ($targetContainer.height() - viewContainer.height() * scaleFactor) / 2;
            viewContainer.css({'left': leftPos,'top':topPos});

        }
        /* Iteration for Multiple Canvas*/
        $.each(viewDetailsList,function(key, view){
            setCanvasCSS(view.viewId);
        })

        /*Window.Resize canvas setting */
        $(window).resize(function(){
            setCanvasCSS(viewDetailsList[0].viewId);
                canvas.getObjects().forEach(function(obj){
                obj.setCoords();
                canvas.renderAll();
                 canvas.calcOffset();
            })

          });

         /* Create Canvas */
         canvas = new fabric.Canvas('editor_2603');

        /* Add Image */
         function addImage(){
            var imgURL = 'http://i.imgur.com/8rmMZI3.jpg';
             var imgObj = new Image();
            imgObj.src = imgURL
            imgObj.onload = function() {
              var image = new fabric.Image(imgObj);
              image.set({
                left: 10,
                top: 10,
              }).scale(0.2);
              canvas.add(image);
              image.setCoords();
              canvas.renderAll();
              canvas.calcOffset();

            };

         }
</script>

<style>
 #target_container{border:1px solid red;}
 .view-wrapper{transform-origin:0% 0%;overflow:hidden;}
 .canvas-wrapper{border: 5px solid green;}

</style>

</body>
</html>
</code>```

Body:
I am trying to create a responsive canvas and while I am doing that I am facing issues related to the transform tool object movement and selection.

Can you please help me where I am doing wrong?

In this code, I am creating canvas dynamically using JSON and underscore js

Here are the steps

Launch the code

Resize te window

Check now you will see controls are not working.

Here are my code

 <!DOCTYPE html>

<title>Fit Canvas Within Perticular area Using this code your canvas will fit inside any container </title>
<meta charset="UTF-8">

<button onClick="addImage()">Add Image </button>

Body:
I got the fixed I have updated the latest fabric.js and its working properly for me

<!DOCTYPE html>
<html>
<head>
<title>Fit Canvas Within Perticular area Using this code your canvas will fit inside any container </title>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"> </script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.0.0/fabric.js"></script>

 <script type="text/html" id='canvas-template'>
        <% _.each(viewList,function(view,key,list){   %>

                    <div class="view-wrapper" data-editor-view-id="<%=view.viewId %>"  style="width:<%=view.imageWidth%>px; height:<%=view.imageHeight%>px; position:relative">
                        <img data-component-type="product-image" src="https://livingannuityspecialist.co.za/wp-content/uploads/2019/03/retirement.jpg" class="productImage"  width="<%=view.imageWidth%>" height="<%=view.imageHeight%>"  />
                        <div class="canvas-wrapper"  style="position:absolute; width:<%=view.width%>px; height:<%=view.height%>px; left: <%=view.left%>px; top: <%=view.top%>px;">
                                <canvas id="<%=view.applicationType%>_<%=view.viewId%>" width="<%=view.width%>" height="<%=view.height%>" ></canvas>
                        </div>
                    </div>
        <% }); %>

</script>

<body>

<div  id="target_container"  style="width:100%; height:100%;">

</div>
<button onClick="addImage()">Add Image </button>

<script>

/* List of canvas */
var canvas;
    var viewDetailsList=[
        {
        "width":1880,"height":977,"top":0,"left":0,"imageWidth":1880,"imageHeight":977,"viewId":2603,"title":"front","imageSrc":"1.png","applicationType":"editor"
        }]

        var template = $("#canvas-template").html();
        $('#target_container').html(_.template(template)({viewList:viewDetailsList}));

        var $targetContainer=$('#target_container');

        /* Calculate Scale Factor according to Outer container */
        function calculateScaleFactor(viewId) {
            var viewContainer = $('[data-editor-view-id="' + viewId + '"]');
            var cssWidthScale = $targetContainer.width() / viewContainer.width();
            var cssHeightScale = $targetContainer.height() / viewContainer.height();
            var scaleFactor = Math.min(cssWidthScale, cssHeightScale);
            return scaleFactor;
        }
        /* Fit Canvas to perticular target or div according to width and height of div
         Let's say If I wan to fix perticular canvas of width 1000px and height 1000px to 500px by 500px then I waant to calculate the scaleFactor for fitting 1000px canvas inside the 500px area.
        */
        function setCanvasCSS(viewId){
            var scaleFactor= calculateScaleFactor(viewId);
            var viewContainer = $('[data-editor-view-id="' + viewId + '"]');
            var scaling= 'scale(' + scaleFactor + ',' + scaleFactor + ')'
            viewContainer.css({'transform': scaling,'-webkit-transform': scaling,'-moz-transform': scaling,'-o-transform': scaling});
            var leftPos = ($targetContainer.width() - viewContainer.width() * scaleFactor) / 2;
            var topPos = ($targetContainer.height() - viewContainer.height() * scaleFactor) / 2;
            viewContainer.css({'left': leftPos,'top':topPos});

        }
        /* Iteration for Multiple Canvas*/
        $.each(viewDetailsList,function(key, view){
            setCanvasCSS(view.viewId);
        })

        /*Window.Resize canvas setting */
        $(window).resize(function(){
            setCanvasCSS(viewDetailsList[0].viewId);
                canvas.getObjects().forEach(function(obj){
                obj.setCoords();
                canvas.renderAll();
                 canvas.calcOffset();
            })

          });

         /* Create Canvas */
         canvas = new fabric.Canvas('editor_2603');

        /* Add Image */
         function addImage(){
            var imgURL = 'http://i.imgur.com/8rmMZI3.jpg';
             var imgObj = new Image();
            imgObj.src = imgURL
            imgObj.onload = function() {
              var image = new fabric.Image(imgObj);
              image.set({
                left: 10,
                top: 10,
              }).scale(0.2);
              canvas.add(image);
              image.setCoords();
              canvas.renderAll();
              canvas.calcOffset();

            };

         }
</script>

<style>
 #target_container{border:1px solid red;}
 .view-wrapper{transform-origin:0% 0%;overflow:hidden;}
 .canvas-wrapper{border: 5px solid green;}

</style>

</body>
</html>


问:
make center text view of thumb and move text view with Seek bar progress
For AndroidTV I have created a simple seek bar and text view. I am trying to align text view of seek bar thumb and trying to move with progress.

Tried these solutions but it's not working link1, link2

Sample Code

logic to get x position of text view

```<code>seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    @Override
    public void onProgressChanged(final SeekBar seekBar, final int progress, boolean fromUser) {
        if (fromUser) {
            int width = seekBar.getWidth()
                        - seekBar.getPaddingLeft()
                        - seekBar.getPaddingRight();
            float thumbPos = width
                             * seekBar.getProgress()
                             / seekBar.getMax();
            textView.setX(width );
        }
    }
}
</code>```

XML

```<code>    <TextView
        android:id="@+id/textView"
        android:layout_width="160dp"
        android:layout_height="90dp"
        android:layout_gravity="start"
        android:background="#ffff00"/>

  <SeekBar
        android:id="@+id/previewSeekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:min="1"
        android:max="10"/>

</RelativeLayout>
</code>```

Expected

Textview should move with seek bar progress.

Textview should be in the center of thumb and above seek bar like in screenshot.

Text view should move when progress > text view width/2 && progress

答:
Sorry for late answer, your logic is correct but it requires few changes.

```<code>float thumbPos = width * (seekBar.getProgress() / (float)seekBar.getMax())

textView.setTranslationX(thumbPos) ;
</code>```

seekBar.getProgress() is an int and seekBar.getMax() is also an int, if divide them they will return integer value, but we need float(in decimal) that's why I have added the changes

Body:
For AndroidTV I have created a simple seek bar and text view. I am trying to align text view of seek bar thumb and trying to move with progress.

Tried these solutions but it's not working link1, link2

Sample Code

logic to get x position of text view

seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    @Override
    public void onProgressChanged(final SeekBar seekBar, final int progress, boolean fromUser) {
        if (fromUser) {
            int width = seekBar.getWidth()
                        - seekBar.getPaddingLeft()
                        - seekBar.getPaddingRight();
            float thumbPos = width
                             * seekBar.getProgress()
                             / seekBar.getMax();
            textView.setX(width );
        }
    }
}

XML

    <TextView
        android:id="@+id/textView"
        android:layout_width="160dp"
        android:layout_height="90dp"
        android:layout_gravity="start"
        android:background="#ffff00"/>

  <SeekBar
        android:id="@+id/previewSeekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:min="1"
        android:max="10"/>

</RelativeLayout>

Expected

Textview should move with seek bar progress.

Textview should be in the center of thumb and above seek bar like in screenshot.

Text view should move when progress > text view width/2 && progress

Body:
Sorry for late answer, your logic is correct but it requires few changes.

float thumbPos = width * (seekBar.getProgress() / (float)seekBar.getMax())

textView.setTranslationX(thumbPos) ;

seekBar.getProgress() is an int and seekBar.getMax() is also an int, if divide them they will return integer value, but we need float(in decimal) that's why I have added the changes


问:
How to save images with the same name to the different direction using PIL and os.path?
While trying to split the path to get a name, I get the traceback:
TypeError: expected str, bytes or os.PathLike object, not JpegImageFile . How can I solve it or is there other methods?

I try to save resized images with the same name to a different direction. For this reason, I use os.path.split() functions.

```<code>import glob
from PIL import Image
import os
images = glob.glob("/Users/marialavrovskaa/Desktop/6_1/*")
path = "/Users/marialavrovskaa/Desktop/2.2/"
quality_val=95
for image in images:
    image = Image.open(image)
    image.thumbnail((640, 428), Image.ANTIALIAS)
    image_path_and_name = os.path.split(image)
    image_name_and_ext = os.path.splitext(image[0])
    name = image_name_and_ext[0] + '.png'
    name = os.path.splitext(image)[0] + '.png'
    file_path = os.path.join(path, name)
    image.save(file_path, quality=quality_val)
</code>```

答:
```<code>for image in images:
    image = Image.open(image)
    image.thumbnail((640, 428), Image.ANTIALIAS)
    image_path_and_name = os.path.split(image)
</code>```

When you say image = Image.open(image), you're overwriting the loop variable also named image, and it's no longer a splittable string.

Change one of the image variables to a different name.

Body:
While trying to split the path to get a name, I get the traceback:
TypeError: expected str, bytes or os.PathLike object, not JpegImageFile . How can I solve it or is there other methods?

I try to save resized images with the same name to a different direction. For this reason, I use os.path.split() functions.

import glob
from PIL import Image
import os
images = glob.glob("/Users/marialavrovskaa/Desktop/6_1/*")
path = "/Users/marialavrovskaa/Desktop/2.2/"
quality_val=95
for image in images:
    image = Image.open(image)
    image.thumbnail((640, 428), Image.ANTIALIAS)
    image_path_and_name = os.path.split(image)
    image_name_and_ext = os.path.splitext(image[0])
    name = image_name_and_ext[0] + '.png'
    name = os.path.splitext(image)[0] + '.png'
    file_path = os.path.join(path, name)
    image.save(file_path, quality=quality_val)

Body:
for image in images:
    image = Image.open(image)
    image.thumbnail((640, 428), Image.ANTIALIAS)
    image_path_and_name = os.path.split(image)

When you say image = Image.open(image), you're overwriting the loop variable also named image, and it's no longer a splittable string.

Change one of the image variables to a different name.


问:
How do I find out what directory my console app is running in?
How do I find out what directory my console app is running in with C#?</p>

OwnerDisplayName: John Sheehan

Body: Application.StartUpPath;

OwnerDisplayName: Rickey

ContentLicense: CC BY-SA 2.5


问:
Get a PHP object's ancestors in the inheritance tree
I have an object and want to list all parent classes up until stdClass or whatever.

I have added a polymorphic field to my database table (say categories) and want to automate my finder method so that super classes are also returned, this way i can jump into the inheritance tree at a point i know not necessarily the final subclass:

```<code>FoodCategory::find_by_id(10) === Category::find_by_id(10)

SELECT * FROM categories WHERE ..... AND type IN ('FoodCategory', 'Category');
</code>```

Roughly i guess:

```<code>function get_class_lineage($object){
    $class = get_parent_class($object);
    $lineage = array();
    while($class != 'stdClass'){
        $dummy_object = new $class();
        $lineage[] = $class = get_parent_class($dummy_object);
    }

    return $lineage;
}
</code>```

But this instantiates an object, does anyone know how to achieve this without?

Thanks for any input, i feel like i'm missing something obvious here.

答:
As you can read at manual you can also give a classname as a string to the function.

```<code>$class = get_class($this);
$lineage = array();
do {
  $lineage[] = $class;
  $class = get_parent_class($class);
} while ($class != 'stdClass');
</code>```

Here index 0 is the classname of the object itself:

ContentLicense: CC BY-SA 3.0

Body:
I have an object and want to list all parent classes up until stdClass or whatever.

I have added a polymorphic field to my database table (say categories) and want to automate my finder method so that super classes are also returned, this way i can jump into the inheritance tree at a point i know not necessarily the final subclass:

FoodCategory::find_by_id(10) === Category::find_by_id(10)

SELECT * FROM categories WHERE ..... AND type IN ('FoodCategory', 'Category');

Roughly i guess:

function get_class_lineage($object){
    $class = get_parent_class($object);
    $lineage = array();
    while($class != 'stdClass'){
        $dummy_object = new $class();
        $lineage[] = $class = get_parent_class($dummy_object);
    }

    return $lineage;
}

But this instantiates an object, does anyone know how to achieve this without?

Thanks for any input, i feel like i'm missing something obvious here.

Body:
As you can read at manual you can also give a classname as a string to the function.

$class = get_class($this);
$lineage = array();
do {
  $lineage[] = $class;
  $class = get_parent_class($class);
} while ($class != 'stdClass');

Here index 0 is the classname of the object itself:


问:
Alingment in HTML
I have this example code:

```<code><div style= "border : solid 2px #bebdbf;
  margin: auto;
  margin-top: 400px;
  background : #ffffff;
  color : #000000;
  padding : 4px;
  width : 200px;
  height : 250px;
  overflow : auto;">

  <?php
     foreach ($prueba as $pruebas) {
     print_r("$pruebas <br>");
  }?>
</div>

<div style= "border : solid 2px #bebdbf;
 background : #ffffff;
 margin: auto;
 color : #000000;
 padding : 4px;
 width : 200px;
 height : 250px;
 overflow : auto;">
    1<br />
    2<br />
    3<br />
    4<br />
    5<br />
    6<br />
    7<br />
    8<br />
    9<br />
    10<br />
</div>
</code>```

and I got this:

What I want is that the two divs being next to each other and not one in the top of other.

答:
Try adding display: inline-block; to the style attribute of both divs as I have done below.

```<code><div style= "border : solid 2px #bebdbf;
  margin: auto;
  margin-top: 400px;
  background : #ffffff;
  color : #000000;
  padding : 4px;
  width : 200px;
  height : 250px;
  overflow : auto;
  display: inline-block;">

  <?php
     foreach ($prueba as $pruebas) {
     print_r("$pruebas <br>");
  }?>
</div>

<div style= "border : solid 2px #bebdbf;
 background : #ffffff;
 margin: auto;
 color : #000000;
 padding : 4px;
 width : 200px;
 height : 250px;
 overflow : auto;
 display: inline-block;">
    1<br />
    2<br />
    3<br />
    4<br />
    5<br />
    6<br />
    7<br />
    8<br />
    9<br />
    10<br />
</div>
</code>```

Title: Alingment in HTML

Body:
I have this example code:

  <?php
     foreach ($prueba as $pruebas) {
     print_r("$pruebas
");
  }?>

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

and I got this:

What I want is that the two divs being next to each other and not one in the top of other.

Body:
Try adding display: inline-block; to the style attribute of both divs as I have done below.

<div style= "border : solid 2px #bebdbf;
  margin: auto;
  margin-top: 400px;
  background : #ffffff;
  color : #000000;
  padding : 4px;
  width : 200px;
  height : 250px;
  overflow : auto;
  display: inline-block;">

  <?php
     foreach ($prueba as $pruebas) {
     print_r("$pruebas <br>");
  }?>
</div>

<div style= "border : solid 2px #bebdbf;
 background : #ffffff;
 margin: auto;
 color : #000000;
 padding : 4px;
 width : 200px;
 height : 250px;
 overflow : auto;
 display: inline-block;">
    1<br />
    2<br />
    3<br />
    4<br />
    5<br />
    6<br />
    7<br />
    8<br />
    9<br />
    10<br />
</div>


问:
Convert columns into group by/counts
I have the below query that displays the result as follows:

How could I get the result displaying like this bearing in mind that more Client Types could be introduced:

```<code>Create Table #temp
(
    [Name] varchar(50),
    Country varchar(50),
    ClientType varchar(50)
)

insert into #temp
(
    Name,
    Country ,
    ClientType
)
select
    'Joe Bloggs',
    'USA',
    'Client Type 1'
union
select
    'John Doe',
    'Canada',
    'Client Type 1'
union
select
    'Jane Smith',
    'USA',
    'Client Type 2'

select
    Country,
    ClientType,
    count(*)
from
    #temp
group by
    Country,
    ClientType

drop table #temp
</code>```

答:
One possibility is to use conditional aggregation only counting a certain client type in a column.</p>

```<code>SELECT country [Country],
       count(CASE
               WHEN clienttype = 'Client Type 1' THEN
                 1
             END) [Client Type 1],
       count(CASE
               WHEN clienttype = 'Client Type 2' THEN
                 1
             END) [Client Type 2]
       FROM #temp
       GROUP BY country;
</code>```

Title: Convert columns into group by/counts

Body:
I have the below query that displays the result as follows:

How could I get the result displaying like this bearing in mind that more Client Types could be introduced:

Create Table #temp
(
    [Name] varchar(50),
    Country varchar(50),
    ClientType varchar(50)
)

insert into #temp
(
    Name,
    Country ,
    ClientType
)
select
    'Joe Bloggs',
    'USA',
    'Client Type 1'
union
select
    'John Doe',
    'Canada',
    'Client Type 1'
union
select
    'Jane Smith',
    'USA',
    'Client Type 2'

select
    Country,
    ClientType,
    count(*)
from
    #temp
group by
    Country,
    ClientType

drop table #temp

Body:
One possibility is to use conditional aggregation only counting a certain client type in a column.

SELECT country [Country],
       count(CASE
               WHEN clienttype = 'Client Type 1' THEN
                 1
             END) [Client Type 1],
       count(CASE
               WHEN clienttype = 'Client Type 2' THEN
                 1
             END) [Client Type 2]
       FROM #temp
       GROUP BY country;


问:
Error while running zipalign
I got this error when trying to export a signed apk in Eclipse

Error while running zipalign:
Unable to open
 as zip archive

I have run the Help->Check for Updates to make sure the latest update is installed and SDK tools also up to date.

答:
I had to run cmd from project folder where the

C:\Users\User\Documents\phone
  app\7\proj7\platforms\android\build\outputs\apkandroid-release-unsigned.apk
  is located and enter this in cmd
  C:\Users\User\AppData\Local\Android\Sdk\build-tools\26.0.0\zipalign -v
  4 android-release-unsigned.apk myApp-signed.apk

Title: Error while running zipalign


答:
This kind of operation is typically referred to as a pivot. Many major db vendors have some bespoke syntax that performs it but I tend to do it using standard sql:

```<code>SELECT
  country,
  SUM(CASE WHEN clienttype = 'Client Type 1' THEN 1 END) as ClientType1,
  SUM(CASE WHEN clienttype = 'Client Type 2' THEN 1 END) as ClientType2
FROM
  #temp
GROUP BY country
</code>```

If you were to run this without the groupby and sum keywords you would get a resultset with the country column (having repeated values) and a clienttype1 column that contains a 1 every time the client type was 1, and a null at all other times, and a clienttype2 column that was 1 whenever the client type was 2 and null at all other times

Grouping on country and summing our columns of mixed null/1 gives the count- null is considered to be zero

On sql server you will see a message "null is eliminated by aggregate operation" but it's an advisory and in this case desired. If it others you you can make the case when have an "else 0" clause have the same effect.

I could also have used COUNT instead of SUM, but for that to work out it really does have to be mixed 1/null because count will consider a value of 0 to be "a countable value" and count it as 1. The nulls are vital if using COUNT

Title: Convert columns into group by/counts

Body:
This kind of operation is typically referred to as a pivot. Many major db vendors have some bespoke syntax that performs it but I tend to do it using standard sql:

SELECT
  country,
  SUM(CASE WHEN clienttype = 'Client Type 1' THEN 1 END) as ClientType1,
  SUM(CASE WHEN clienttype = 'Client Type 2' THEN 1 END) as ClientType2
FROM
  #temp
GROUP BY country

If you were to run this without the groupby and sum keywords you would get a resultset with the country column (having repeated values) and a clienttype1 column that contains a 1 every time the client type was 1, and a null at all other times, and a clienttype2 column that was 1 whenever the client type was 2 and null at all other times

Grouping on country and summing our columns of mixed null/1 gives the count- null is considered to be zero

On sql server you will see a message "null is eliminated by aggregate operation" but it's an advisory and in this case desired. If it others you you can make the case when have an "else 0" clause have the same effect.

I could also have used COUNT instead of SUM, but for that to work out it really does have to be mixed 1/null because count will consider a value of 0 to be "a countable value" and count it as 1. The nulls are vital if using COUNT


问:
Monogame C# Timer (do something for 15 seconds every 3 seconds)
I am trying to create a timer, which, for example, every 3 seconds during eg 15 seconds will perform an action.

I tried to use gameTime.ElapsedGameTime.TotalSeconds and loop, but unfortunately it doesn't work.

I have an Attack () function that reduces player statistics when an enemy attacks it. I would like that in case of one particular enemy, this function for a specified period of time would subtract player's HP, eg for every 3 seconds. I guess it should be done in the Update function to access gameTime, unfortunately, I have no idea how to do it.

```<code>public override Stats Attack()
{
    attack = true;
    return new Stats(0, -stats.Damage, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
</code>```

```<code>public override void Update(GameTime gameTime)
{
    spriteDirection = Vector2.Zero;                                 // reset input
    Move(Direction);                                                // gets the state of my keyborad

    float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds; // make movement framerate independant

    spriteDirection *= Speed;                                       // add hero's speed to movement
    position += (spriteDirection * deltaTime);                      // adding deltaTime to stabilize movement
    totalPosition = new Vector2((int)((BottomBoundingBox.Center.X) / 32.0f), (int)((BottomBoundingBox.Center.Y) / 32.0f));

    base.Update(gameTime);
}
</code>```

答:
One way to do this would be to use coroutines. MonoGame does not have built-in support for them like other game engines, but they are not too complicated to implement yourself. You need some knowledge of the yield keyword and enumerators to understand them, but once abstracted away they make your game code way easier to write and understand.

Here's an example of what your gameplay logic would look using a Coroutine system like the one described below:

```<code>public void Attack(Enemy enemyAttacking)
{
    if (enemyAttacking.Type == "OneParticularEnemy")
    {
        StartCoroutine(RunDamageOverTimeAttack());
    }
}

// This coroutine starts a second coroutine that applies damage over time, it
// then waits 15 seconds before terminating the second coroutine.
public IEnumerator RunDamageOverTimeAttack()
{
    var cr = StartCoroutine(ApplyDamageOverTime());
    yield return 15000; // in milleseconds (ms), i.e. 15000 ms is 15 seconds
    cr.IsFinished = true;
}

// This coroutine applies the damage every 3 seconds until the coroutine is finished
public IEnumerator ApplyDamageOverTime()
{
    while (true)
    {
        ApplyDamageToPlayer();
        yield return 3000;
    }
}
</code>```

The code reads very close to the way you described the actual problem you're trying to solve. Now for the coroutine system...

The StartCouroutine method creates a Coroutine class instance and stores it. During the Update step of the game loop you iterate through the coroutines and update them, providing gameTime to calculate when the next step of the method should run. Each step executes the code in the routine until a yield is found OR until the method ends naturally. Once the coroutine is finished you clear them out. This logic looks something like this:

```<code>private List<Coroutine> coroutines = new List<Coroutine>();

public Coroutine StartCoroutine(IEnumerator routine)
{
    var cr = new Coroutine(routine);
    couroutines.Add(cr);
    return cr;
}

public void UpdateCoroutines(GameTime gameTime)
{
    // copied in case list is modified during coroutine updates
    var coroutinesToUpdate = coroutines.ToArray();

    foreach (coroutine in coroutinesToUpdate)
        coroutine.Update(gameTime);

    coroutines.RemoveAll(c => c.IsFinished);
}

public void Update(GameTime gameTime)
{
    // normal update logic that would invoke Attack(), then...
    UpdateCoroutines(gameTime);
}
</code>```

A Coroutine class is responsible for tracking the time remaining between steps of the routine, and tracking when the routine is finished. It looks something like this:

```<code>public class Coroutine
{
    private IEnumerator routine;
    private double? wait;

    public Coroutine(IEnumerator routine)
    {
        this.routine = routine;
    }

    public bool IsFinished { get; set; }

    public void Update(GameTime gameTime)
    {
        if (IsFinished) return;

        if (wait.HasValue)
        {
            var timeRemaining = wait.Value - gameTime.ElapsedGameTime.TotalMilliseconds;
            wait = timeRemaining < 0 ? null : timeRemaining;

            // If wait has a value we still have time to burn before the
            // the next increment, so we return here.
            if (wait.HasValue) return;
        }

        if (!routine.MoveNext())
        {
            IsFinished= true;
        }
        else
        {
            wait = routine.Current as double?;
        }
    }
}
</code>```

This may seem considerably more complex than other solutions provided here, and it may be overkill, but Coroutines allow you to forgo tracking a bunch of state in tracking variables, making complex scenarios easier to follow and cleaner to read. For example, here's a arrow spawning strategy I used Coroutines for in Ludum Dare 37. It spawns 3 arrows 600 milleseconds apart with a 3 second wait between them: https://github.com/srakowski/LD37/blob/477cf515d599eba7c4b55c3f57952865d894f741/src/LD37/GameObjects/BurstArrowSpawnBehavior.cs

If you'd like more social proof of the value of Coroutines take a look at Unity. Unity is one of the more popular game engines, and it has Coroutine support. They describe a scenario where it is useful in their documentation: https://docs.unity3d.com/Manual/Coroutines.html.

Body:
I am trying to create a timer, which, for example, every 3 seconds during eg 15 seconds will perform an action.

I tried to use gameTime.ElapsedGameTime.TotalSeconds and loop, but unfortunately it doesn't work.

I have an Attack () function that reduces player statistics when an enemy attacks it. I would like that in case of one particular enemy, this function for a specified period of time would subtract player's HP, eg for every 3 seconds. I guess it should be done in the Update function to access gameTime, unfortunately, I have no idea how to do it.

public override Stats Attack()
{
    attack = true;
    return new Stats(0, -stats.Damage, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}

public override void Update(GameTime gameTime)
{
    spriteDirection = Vector2.Zero;                                 // reset input
    Move(Direction);                                                // gets the state of my keyborad

    float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds; // make movement framerate independant

    spriteDirection *= Speed;                                       // add hero's speed to movement
    position += (spriteDirection * deltaTime);                      // adding deltaTime to stabilize movement
    totalPosition = new Vector2((int)((BottomBoundingBox.Center.X) / 32.0f), (int)((BottomBoundingBox.Center.Y) / 32.0f));

    base.Update(gameTime);
}

Body:
One way to do this would be to use coroutines. MonoGame does not have built-in support for them like other game engines, but they are not too complicated to implement yourself. You need some knowledge of the yield keyword and enumerators to understand them, but once abstracted away they make your game code way easier to write and understand.

Here's an example of what your gameplay logic would look using a Coroutine system like the one described below:

public void Attack(Enemy enemyAttacking)
{
    if (enemyAttacking.Type == "OneParticularEnemy")
    {
        StartCoroutine(RunDamageOverTimeAttack());
    }
}

// This coroutine starts a second coroutine that applies damage over time, it
// then waits 15 seconds before terminating the second coroutine.
public IEnumerator RunDamageOverTimeAttack()
{
    var cr = StartCoroutine(ApplyDamageOverTime());
    yield return 15000; // in milleseconds (ms), i.e. 15000 ms is 15 seconds
    cr.IsFinished = true;
}

// This coroutine applies the damage every 3 seconds until the coroutine is finished
public IEnumerator ApplyDamageOverTime()
{
    while (true)
    {
        ApplyDamageToPlayer();
        yield return 3000;
    }
}

The code reads very close to the way you described the actual problem you're trying to solve. Now for the coroutine system...

The StartCouroutine method creates a Coroutine class instance and stores it. During the Update step of the game loop you iterate through the coroutines and update them, providing gameTime to calculate when the next step of the method should run. Each step executes the code in the routine until a yield is found OR until the method ends naturally. Once the coroutine is finished you clear them out. This logic looks something like this:

private List<Coroutine> coroutines = new List<Coroutine>();

public Coroutine StartCoroutine(IEnumerator routine)
{
    var cr = new Coroutine(routine);
    couroutines.Add(cr);
    return cr;
}

public void UpdateCoroutines(GameTime gameTime)
{
    // copied in case list is modified during coroutine updates
    var coroutinesToUpdate = coroutines.ToArray();

    foreach (coroutine in coroutinesToUpdate)
        coroutine.Update(gameTime);

    coroutines.RemoveAll(c => c.IsFinished);
}

public void Update(GameTime gameTime)
{
    // normal update logic that would invoke Attack(), then...
    UpdateCoroutines(gameTime);
}

A Coroutine class is responsible for tracking the time remaining between steps of the routine, and tracking when the routine is finished. It looks something like this:

public class Coroutine
{
    private IEnumerator routine;
    private double? wait;

    public Coroutine(IEnumerator routine)
    {
        this.routine = routine;
    }

    public bool IsFinished { get; set; }

    public void Update(GameTime gameTime)
    {
        if (IsFinished) return;

        if (wait.HasValue)
        {
            var timeRemaining = wait.Value - gameTime.ElapsedGameTime.TotalMilliseconds;
            wait = timeRemaining < 0 ? null : timeRemaining;

            // If wait has a value we still have time to burn before the
            // the next increment, so we return here.
            if (wait.HasValue) return;
        }

        if (!routine.MoveNext())
        {
            IsFinished= true;
        }
        else
        {
            wait = routine.Current as double?;
        }
    }
}

This may seem considerably more complex than other solutions provided here, and it may be overkill, but Coroutines allow you to forgo tracking a bunch of state in tracking variables, making complex scenarios easier to follow and cleaner to read. For example, here's a arrow spawning strategy I used Coroutines for in Ludum Dare 37. It spawns 3 arrows 600 milleseconds apart with a 3 second wait between them: https://github.com/srakowski/LD37/blob/477cf515d599eba7c4b55c3f57952865d894f741/src/LD37/GameObjects/BurstArrowSpawnBehavior.cs

If you'd like more social proof of the value of Coroutines take a look at Unity. Unity is one of the more popular game engines, and it has Coroutine support. They describe a scenario where it is useful in their documentation: https://docs.unity3d.com/Manual/Coroutines.html.


问:
Maximum update depth exceeded. Infinite redirects and how to better structure my routing
First off, I'm very new to React so forgive my very basic question. I have my App component housing my React Router routes, and want to redirect to the login page if no authorised user is found but I'm getting the error 'Maximum update depth exceeded.'.

I (think I) understand that react is caught in an infinite loop of trying to redirect to /login, but can't really think of a cleaner way of addressing the issue / restructuring.

Initially my fix was to call redirectToLogin() which would set state.redirectToLogin so when it redirected it didn't try to again. While this worked I read a few comments elsewhere that stated setting state in the render function is a big no-no.

```<code>import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
import { Loading } from './components/loading/Loading';
import { Navbar } from './components/navbar/Navbar';
import AuthService from './services/auth-service';

import { Users } from './components/users/Users';
import { UsersCreate } from './components/users/users-create/UsersCreate';
import { Login } from './components/auth/Login';

import './App.scss';
import './styles/variables.scss';

type State = {
  loading: boolean,
  authenticated: boolean,
  redirectToLogin: boolean
}

class App extends Component<{}, State> {

  authService: AuthService;

  constructor(props: any) {
    super(props);
    this.authService = new AuthService();
    this.state = {
      loading: false,
      authenticated: false,
      redirectToLogin: false
    };

    // this.redirectToLogin = this.redirectToLogin.bind(this);

    // Intercept 401 responses and redirect to login
    AuthService.registerUnauthenticatedInterceptor();

  }

  componentDidMount() {
    // Check if user is authenticated
    if (AuthService.getUser()) {
      this.setState({
        authenticated: true
      });
    } else {
      this.setState({
        redirectToLogin: true
      })
    }
    this.setState<any>({ loading: false });
  }

  // redirectToLogin() {
  //   this.setState({
  //     redirectToLogin: false
  //   });
  //   return <Redirect to="/login" />
  // }

  render() {
    if (this.state.loading) {
      return <Loading />
    }
    if (!this.state.loading) {
      return (
        <div className="App">
          <Router>

            {
              this.state.authenticated ?
              <Navbar /> : null
            }
            {
              !this.state.authenticated && this.state.redirectToLogin ?
              <Redirect to="/login" /> : null
            }

            <Route exact path="/login" render={() => <Login />} />

            <div className="component-page">
              <div className="container-fluid">

                <Route exact path="/users" render={() => <Users />} />
                <Route exact path="/users/create" render={() => <UsersCreate />} />

              </div>
            </div>
          </Router>
        </div>
      )
    }
  }
}

export default App;

</code>```

I'm hoping there's an easy fix that I'm missing but I'm open to restructuring if there's a cleaner way.

答:
I think the problem is here

```<code>{
    !this.state.authenticated && this.state.redirectToLogin ?
    <Redirect to="/login" /> : null
}
</code>```

If the page success to redirect to "/login", this same component App is rendered right? Then componentDidUpdate() will again evaluate to the same result, and redirect will trigger again, in an infinite loop.

Since no matter this.state.authenticated is true or not, you will still be at the same App component, so before redirect, you need to check if you are already at "/login" or not.

```<code>componentDidUpdate() {
    // Check if user is authenticated
    if (AuthService.getUser()) {
      this.setState({
        authenticated: true
      });
    } else {
      if (this.props.location.pathname != '/login') {
         this.setState({
           redirectToLogin: true
         })
      }
    }
    this.setState<any>({ loading: false });
  }
</code>```

Body:
First off, I'm very new to React so forgive my very basic question. I have my App component housing my React Router routes, and want to redirect to the login page if no authorised user is found but I'm getting the error 'Maximum update depth exceeded.'.

I (think I) understand that react is caught in an infinite loop of trying to redirect to /login, but can't really think of a cleaner way of addressing the issue / restructuring.

Initially my fix was to call redirectToLogin() which would set state.redirectToLogin so when it redirected it didn't try to again. While this worked I read a few comments elsewhere that stated setting state in the render function is a big no-no.

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
import { Loading } from './components/loading/Loading';
import { Navbar } from './components/navbar/Navbar';
import AuthService from './services/auth-service';

import { Users } from './components/users/Users';
import { UsersCreate } from './components/users/users-create/UsersCreate';
import { Login } from './components/auth/Login';

import './App.scss';
import './styles/variables.scss';

type State = {
  loading: boolean,
  authenticated: boolean,
  redirectToLogin: boolean
}

class App extends Component<{}, State> {

  authService: AuthService;

  constructor(props: any) {
    super(props);
    this.authService = new AuthService();
    this.state = {
      loading: false,
      authenticated: false,
      redirectToLogin: false
    };

    // this.redirectToLogin = this.redirectToLogin.bind(this);

    // Intercept 401 responses and redirect to login
    AuthService.registerUnauthenticatedInterceptor();

  }

  componentDidMount() {
    // Check if user is authenticated
    if (AuthService.getUser()) {
      this.setState({
        authenticated: true
      });
    } else {
      this.setState({
        redirectToLogin: true
      })
    }
    this.setState<any>({ loading: false });
  }

  // redirectToLogin() {
  //   this.setState({
  //     redirectToLogin: false
  //   });
  //   return <Redirect to="/login" />
  // }

  render() {
    if (this.state.loading) {
      return <Loading />
    }
    if (!this.state.loading) {
      return (

          <Router>

            {
              this.state.authenticated ?
              <Navbar /> : null
            }
            {
              !this.state.authenticated && this.state.redirectToLogin ?
              <Redirect to="/login" /> : null
            }

            <Route exact path="/login" render={() => <Login />} />

                <Route exact path="/users" render={() => <Users />} />
                <Route exact path="/users/create" render={() => <UsersCreate />} />

          </Router>

      )
    }
  }
}

export default App;

I'm hoping there's an easy fix that I'm missing but I'm open to restructuring if there's a cleaner way.

Body:
I think the problem is here

{
    !this.state.authenticated && this.state.redirectToLogin ?
    <Redirect to="/login" /> : null
}

If the page success to redirect to "/login", this same component App is rendered right? Then componentDidUpdate() will again evaluate to the same result, and redirect will trigger again, in an infinite loop.

Since no matter this.state.authenticated is true or not, you will still be at the same App component, so before redirect, you need to check if you are already at "/login" or not.

componentDidUpdate() {
    // Check if user is authenticated
    if (AuthService.getUser()) {
      this.setState({
        authenticated: true
      });
    } else {
      if (this.props.location.pathname != '/login') {
         this.setState({
           redirectToLogin: true
         })
      }
    }
    this.setState<any>({ loading: false });
  }


答:
```<code>import glob
from PIL import Image
import os

images = glob.glob("Source_path")
path = r"Destination_path"
quality_val=95

for image in images:
    img = Image.open(image)
    img.thumbnail((640, 428), Image.ANTIALIAS)
    name = os.path.split(image)
    file_path = os.path.join(path, name[1])
    img.save(file_path, quality=quality_val)
</code>```

The primary problem with your code was that you were using a variable and an object under the same name image. Which was causing problems.

LOGICAL ERRORS:-

image_path_and_name is a needless variable in the code, as it is
used for nothing.

name has been initialized with totally different values twice,
instead use name = os.path.split(image) which serves the purpose
of both.

you should not try to explicitly define the extension of each image
as .png as it might create issues when dealing with other image
formats.

Title: How to save images with the same name to the different direction using PIL and os.path?

Body:
import glob
from PIL import Image
import os

images = glob.glob("Source_path")
path = r"Destination_path"
quality_val=95

for image in images:
    img = Image.open(image)
    img.thumbnail((640, 428), Image.ANTIALIAS)
    name = os.path.split(image)
    file_path = os.path.join(path, name[1])
    img.save(file_path, quality=quality_val)

The primary problem with your code was that you were using a variable and an object under the same name image. Which was causing problems.

LOGICAL ERRORS:-

image_path_and_name is a needless variable in the code, as it is
used for nothing.

name has been initialized with totally different values twice,
instead use name = os.path.split(image) which serves the purpose
of both.

you should not try to explicitly define the extension of each image
as .png as it might create issues when dealing with other image
formats.


问:
How can I convert the code below to let me scan in multiple objects with different .sks files for each?
I am creating an augmented reality application that detects 3D objects in space and has a label pop up above them. The current code lets me detect multiple object, but only lets one type of label (.sks file) pop up. I would like to be able to detect multiple objects each with a different label popping up above them.</p>

```<code>import UIKit
import SceneKit
import ARKit

class ViewController: UIViewController, ARSCNViewDelegate {

    @IBOutlet var sceneView: ARSCNView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set the view's delegate
        sceneView.delegate = self

        // Show statistics such as fps and timing information
        sceneView.showsStatistics = true

        // Create a new scene
        let scene = SCNScene()

        // Set the scene to the view
        sceneView.scene = scene
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Create a session configuration
        let configuration = ARWorldTrackingConfiguration()

        // Object Detection
        configuration.detectionObjects = ARReferenceObject.referenceObjects(inGroupNamed: "FlowerObjects", bundle: Bundle.main)!

        // Run the view's session
        sceneView.session.run(configuration)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        // Pause the view's session
        //sceneView.session.pause()
    }

    // MARK: - ARSCNViewDelegate

    func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {

        let node = SCNNode()

        if let objectAnchor = anchor as? ARObjectAnchor {
            let plane = SCNPlane(width: CGFloat(objectAnchor.referenceObject.extent.x * 1.0), height: CGFloat(objectAnchor.referenceObject.extent.y * 0.7))

            plane.cornerRadius = plane.width / 8

            let spriteKitScene = SKScene(fileNamed: "ProductInfo")

            plane.firstMaterial?.diffuse.contents = spriteKitScene
            plane.firstMaterial?.isDoubleSided = true
            plane.firstMaterial?.diffuse.contentsTransform = SCNMatrix4Translate(SCNMatrix4MakeScale(1, -1, 1), 0, 1, 0)

            let planeNode = SCNNode(geometry: plane)
            planeNode.position = SCNVector3Make(objectAnchor.referenceObject.center.x, objectAnchor.referenceObject.center.y + 0.5, objectAnchor.referenceObject.center.z) //y was 0.25

            node.addChildNode(planeNode)

        }

        return node
    }

    func session(_ session: ARSession, didFailWithError error: Error) {
        // Present an error message to the user

    }

    func sessionWasInterrupted(_ session: ARSession) {
        // Inform the user that the session has been interrupted, for example, by presenting an overlay

    }

    func sessionInterruptionEnded(_ session: ARSession) {
        // Reset tracking and/or remove existing anchors if consistent tracking is required

    }
}
</code>```

答:
An ARReferenceObject has a name variable of type String which is simply:

A descriptive name for the reference object.

When your add an ARReferenceObject to your Assets.xcassetts folder you have the option to set the name (which does actually get set automatically):

As such you can use this property name to handle what to show depending on the ARReferenceObject detected.
Personally, I would use the following delegate callback to add content although this is up to you:

```<code>func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor)
</code>```

As such a working example might look something like the following:

```<code>//-------------------------
//MARK: - ARSCNViewDelegate
//-------------------------

extension ViewController: ARSCNViewDelegate{

  func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {

    /*
     Check To See Whether AN ARObject Anhcor Has Been Detected
     Get The The Associated ARReferenceObject
     Get The Name Of The ARReferenceObject
     */
    guard let objectAnchor = anchor as? ARObjectAnchor else { return }

    let detectedObject = objectAnchor.referenceObject
    guard let detectedObjectName = detectedObject.name else { return }

    //Get The Extent & Center Of The ARReferenceObject
    let detectedObjectExtent = detectedObject.extent
    let detectedObjecCenter = detectedObject.center

    //Log The Data
    print("""
      An ARReferenceObject Named \(detectedObjectName) Has Been Detected
      The Extent Of The Object Is \(detectedObjectExtent)
      The Center Of The Object Is \(detectedObjecCenter)
      """)

    //Create A Different Scene For Each Detected Object
    node.addChildNode(createSKSceneForReferenceObject(detectedObject: detectedObject))
  }

  /// Creates A Unique SKScene Based On A Detected ARReferenceObject
  ///
  /// - Parameter detectedObject: ARReferenceObject
  /// - Returns: SCNNode
  func createSKSceneForReferenceObject(detectedObject: ARReferenceObject) -> SCNNode{

    let plane = SCNPlane(width: CGFloat(detectedObject.extent.x * 1.0),
                         height: CGFloat(detectedObject.extent.y * 0.7))

    plane.cornerRadius = plane.width / 8

    guard let validName = detectedObject.name else { return SCNNode() }

    let spriteKitScene = SKScene(fileNamed: validName)

    plane.firstMaterial?.diffuse.contents = spriteKitScene
    plane.firstMaterial?.isDoubleSided = true
    plane.firstMaterial?.diffuse.contentsTransform = SCNMatrix4Translate(SCNMatrix4MakeScale(1, -1, 1), 0, 1, 0)

    let planeNode = SCNNode(geometry: plane)
    planeNode.position = SCNVector3Make(detectedObject.center.x, detectedObject.center.y + 0.5, detectedObject.center.z)

    return planeNode
  }
}
</code>```

All the code is fully commented so it should make sense, and you will notice that I created a reusable function to generate different SKScenes, which of course could be modified to add different content e.g. SCNScene's, SCNNodes etc.

I am using the name of the ARReferenceObject to load a scene of the same name, but you could use an if/else or switch statement depending on what you need.

Hope it helps...
Hope it points you in the right direction.

Body:
I am creating an augmented reality application that detects 3D objects in space and has a label pop up above them. The current code lets me detect multiple object, but only lets one type of label (.sks file) pop up. I would like to be able to detect multiple objects each with a different label popping up above them.

import UIKit
import SceneKit
import ARKit

class ViewController: UIViewController, ARSCNViewDelegate {

    @IBOutlet var sceneView: ARSCNView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set the view's delegate
        sceneView.delegate = self

        // Show statistics such as fps and timing information
        sceneView.showsStatistics = true

        // Create a new scene
        let scene = SCNScene()

        // Set the scene to the view
        sceneView.scene = scene
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Create a session configuration
        let configuration = ARWorldTrackingConfiguration()

        // Object Detection
        configuration.detectionObjects = ARReferenceObject.referenceObjects(inGroupNamed: "FlowerObjects", bundle: Bundle.main)!

        // Run the view's session
        sceneView.session.run(configuration)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        // Pause the view's session
        //sceneView.session.pause()
    }

    // MARK: - ARSCNViewDelegate

    func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {

        let node = SCNNode()

        if let objectAnchor = anchor as? ARObjectAnchor {
            let plane = SCNPlane(width: CGFloat(objectAnchor.referenceObject.extent.x * 1.0), height: CGFloat(objectAnchor.referenceObject.extent.y * 0.7))

            plane.cornerRadius = plane.width / 8

            let spriteKitScene = SKScene(fileNamed: "ProductInfo")

            plane.firstMaterial?.diffuse.contents = spriteKitScene
            plane.firstMaterial?.isDoubleSided = true
            plane.firstMaterial?.diffuse.contentsTransform = SCNMatrix4Translate(SCNMatrix4MakeScale(1, -1, 1), 0, 1, 0)

            let planeNode = SCNNode(geometry: plane)
            planeNode.position = SCNVector3Make(objectAnchor.referenceObject.center.x, objectAnchor.referenceObject.center.y + 0.5, objectAnchor.referenceObject.center.z) //y was 0.25

            node.addChildNode(planeNode)

        }

        return node
    }

    func session(_ session: ARSession, didFailWithError error: Error) {
        // Present an error message to the user

    }

    func sessionWasInterrupted(_ session: ARSession) {
        // Inform the user that the session has been interrupted, for example, by presenting an overlay

    }

    func sessionInterruptionEnded(_ session: ARSession) {
        // Reset tracking and/or remove existing anchors if consistent tracking is required

    }
}

Body:
An ARReferenceObject has a name variable of type String which is simply:

A descriptive name for the reference object.

When your add an ARReferenceObject to your Assets.xcassetts folder you have the option to set the name (which does actually get set automatically):

As such you can use this property name to handle what to show depending on the ARReferenceObject detected.
Personally, I would use the following delegate callback to add content although this is up to you:

func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor)

As such a working example might look something like the following:

//-------------------------
//MARK: - ARSCNViewDelegate
//-------------------------

extension ViewController: ARSCNViewDelegate{

  func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {

    /*
     Check To See Whether AN ARObject Anhcor Has Been Detected
     Get The The Associated ARReferenceObject
     Get The Name Of The ARReferenceObject
     */
    guard let objectAnchor = anchor as? ARObjectAnchor else { return }

    let detectedObject = objectAnchor.referenceObject
    guard let detectedObjectName = detectedObject.name else { return }

    //Get The Extent & Center Of The ARReferenceObject
    let detectedObjectExtent = detectedObject.extent
    let detectedObjecCenter = detectedObject.center

    //Log The Data
    print("""
      An ARReferenceObject Named \(detectedObjectName) Has Been Detected
      The Extent Of The Object Is \(detectedObjectExtent)
      The Center Of The Object Is \(detectedObjecCenter)
      """)

    //Create A Different Scene For Each Detected Object
    node.addChildNode(createSKSceneForReferenceObject(detectedObject: detectedObject))
  }

  /// Creates A Unique SKScene Based On A Detected ARReferenceObject
  ///
  /// - Parameter detectedObject: ARReferenceObject
  /// - Returns: SCNNode
  func createSKSceneForReferenceObject(detectedObject: ARReferenceObject) -> SCNNode{

    let plane = SCNPlane(width: CGFloat(detectedObject.extent.x * 1.0),
                         height: CGFloat(detectedObject.extent.y * 0.7))

    plane.cornerRadius = plane.width / 8

    guard let validName = detectedObject.name else { return SCNNode() }

    let spriteKitScene = SKScene(fileNamed: validName)

    plane.firstMaterial?.diffuse.contents = spriteKitScene
    plane.firstMaterial?.isDoubleSided = true
    plane.firstMaterial?.diffuse.contentsTransform = SCNMatrix4Translate(SCNMatrix4MakeScale(1, -1, 1), 0, 1, 0)

    let planeNode = SCNNode(geometry: plane)
    planeNode.position = SCNVector3Make(detectedObject.center.x, detectedObject.center.y + 0.5, detectedObject.center.z)

    return planeNode
  }
}

All the code is fully commented so it should make sense, and you will notice that I created a reusable function to generate different SKScenes, which of course could be modified to add different content e.g. SCNScene's, SCNNodes etc.

I am using the name of the ARReferenceObject to load a scene of the same name, but you could use an if/else or switch statement depending on what you need.

Hope it helps...
Hope it points you in the right direction.


问:
How to parse a POINT object sent as string in JSON?
I'm fetching some data from an API and the response includes the user location in longitude and latitude.

This is to render an icon on a map according to the user's coordinates

That's the JSON object:

```<code>{
  ...
  "lonlat": "POINT (-42.796763 -5.077056)",
}
</code>```

I want to be able to parse this POINT object and get the value of latitude and longitude.

答:
You can use a regex to get the values, assuming they're always separated by a space.

const data = {
  "lonlat": "POINT (-42.796763 -5.077056)"
};

const regex = /[A-Z]+\s\((-?\d+\.\d+)\s(-?\d+\.\d+)\)/;
const [, longitude, latitude] = data.lonlat.match(regex);
console.log(longitude);
console.log(latitude);```

Body:
I'm fetching some data from an API and the response includes the user location in longitude and latitude.

This is to render an icon on a map according to the user's coordinates

That's the JSON object:

{
  ...
  "lonlat": "POINT (-42.796763 -5.077056)",
}

I want to be able to parse this POINT object and get the value of latitude and longitude.


问:
Unable to update JSX attribute based on URL parameter in a Gatsby app running in production
In production mode, a URL parameter value can not be used to render dynamic attribute values. The same URL parameter value can be used to render a specific component.

I have set up a repo with a minimum reproducible example.

https://github.com/mikepuglisi/gatsby-dynamic-attribute-bug

We've been able to work around this by storing the parameter values in state, but I don't see why that should be necessary (especially since it renders the correct div).

Relevant Code (src/pages/index.js)

```<code>const IndexPage = ({location}) => {
  const params = new URLSearchParams(location.search);
  const color = params.get('color');
  return (
      <Layout>
        <SEO title="Home" />
        <h1>Hi people</h1>
        { color ?
          <p style={{color: color}}>
            I SHOULD BE THE COLOR {color} in production mode even after hitting CTRL+F5 (hard refresh)
          </p> :
          <p>
            No Color was passed. Add ?color=blue to URL and hit CTRL+F5 to ensure a hard refresh
          </p>
        }

        <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
          <Image />
        </div>
        <Link to="/page-2/">Go to page 2</Link>
      </Layout>
    )
  }

</code>```

The url parameter ?color=blue should be able to render the appropriate div AND render the appropriate style. The div shows correctly, but the correct style does not.Issue Screenshot

答:
This problem seems to be how the hydration process works for server rendered React applications.

Short Answer

You need to set an initial state for the color and then update it in a useEffect hook:

```<code>const IndexPage = ({location}) => {
  const [color, setColor] = useState();
  useEffect(() => {
    setColor(new URLSearchParams(location.search).get('color'));
  }, location)
  return (
      <Layout>
        <SEO title="Home" />
        <h1>Hi people</h1>
        { color ?
          <p style={{color: color}}>
            I SHOULD BE THE COLOR {color} in production mode even after hitting CTRL+F5 (hard referesh)
          </p> :
          <p>
            No Color was passed. Add ?color=blue to URL and hit CTRL+F5 to ensure a hard refresh
          </p>
        }

        <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
          <Image />
        </div>
        <Link to="/page-2/">Go to page 2</Link>
      </Layout>
    )
  }
</code>```

Long Answer

When building your Gatsby app for production, it renders out static HTML for you using ReactDOMSever. When you first load a page in the browser, it firsts loads the static HTML and then it needs to boot up React and hydrate your app.

Upon hydrating your app, React will expect your HTML content to be identical to what would have been rendered on the first render of client-side rendered React application. However, in your case, this is not true.

On the first render for your React component, you should have a style attribute on your paragraph element with the value of the color found in the URL query params. When building the static HTML for the page, you will not have the style attribute on your paragraph element because query params don't exist on the server.

You might be wondering why the text content correctly renders the color value from your query params on the initial render. This is because the hydrate method can patch differences in text content, but it cannot patch differences in your HTML attributes, which is what is happening with your style attribute on the paragraph element.

From the React docs for the hydrate method:

React expects that the rendered content is identical between the server and the client. It can patch up differences in text content, but you should treat mismatches as bugs and fix them. In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive.

Because of this "mismatch" between the initial HTML content, you should instead set a default value for color as a state property, and then update that value when the component first mounts. That way, when you first load the app on the client and you have a color query param present, you will be able to update the state on mount to trigger a re-render of your React component.

Resources

Gatsby: Building the JavaScript App

ReactDOM hydrate() method

Body:
In production mode, a URL parameter value can not be used to render dynamic attribute values. The same URL parameter value can be used to render a specific component.

I have set up a repo with a minimum reproducible example.

https://github.com/mikepuglisi/gatsby-dynamic-attribute-bug

We've been able to work around this by storing the parameter values in state, but I don't see why that should be necessary (especially since it renders the correct div).

Relevant Code (src/pages/index.js)

const IndexPage = ({location}) => {
  const params = new URLSearchParams(location.search);
  const color = params.get('color');
  return (
      <Layout>
        <SEO title="Home" />

Hi people

        { color ?

            I SHOULD BE THE COLOR {color} in production mode even after hitting CTRL+F5 (hard refresh)

 :

            No Color was passed. Add ?color=blue to URL and hit CTRL+F5 to ensure a hard refresh

        }

        <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
          <Image />

        <Link to="/page-2/">Go to page 2</Link>
      </Layout>
    )
  }

The url parameter ?color=blue should be able to render the appropriate div AND render the appropriate style. The div shows correctly, but the correct style does not.Issue Screenshot

Body:
This problem seems to be how the hydration process works for server rendered React applications.

Short Answer

You need to set an initial state for the color and then update it in a useEffect hook:

const IndexPage = ({location}) => {
  const [color, setColor] = useState();
  useEffect(() => {
    setColor(new URLSearchParams(location.search).get('color'));
  }, location)
  return (
      <Layout>
        <SEO title="Home" />
        <h1>Hi people</h1>
        { color ?
          <p style={{color: color}}>
            I SHOULD BE THE COLOR {color} in production mode even after hitting CTRL+F5 (hard referesh)
          </p> :
          <p>
            No Color was passed. Add ?color=blue to URL and hit CTRL+F5 to ensure a hard refresh
          </p>
        }

        <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
          <Image />
        </div>
        <Link to="/page-2/">Go to page 2</Link>
      </Layout>
    )
  }

Long Answer

When building your Gatsby app for production, it renders out static HTML for you using ReactDOMSever. When you first load a page in the browser, it firsts loads the static HTML and then it needs to boot up React and hydrate your app.

Upon hydrating your app, React will expect your HTML content to be identical to what would have been rendered on the first render of client-side rendered React application. However, in your case, this is not true.

On the first render for your React component, you should have a style attribute on your paragraph element with the value of the color found in the URL query params. When building the static HTML for the page, you will not have the style attribute on your paragraph element because query params don't exist on the server.

You might be wondering why the text content correctly renders the color value from your query params on the initial render. This is because the hydrate method can patch differences in text content, but it cannot patch differences in your HTML attributes, which is what is happening with your style attribute on the paragraph element.

From the React docs for the hydrate method:

React expects that the rendered content is identical between the server and the client. It can patch up differences in text content, but you should treat mismatches as bugs and fix them. In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive.

Because of this "mismatch" between the initial HTML content, you should instead set a default value for color as a state property, and then update that value when the component first mounts. That way, when you first load the app on the client and you have a color query param present, you will be able to update the state on mount to trigger a re-render of your React component.

Resources

Gatsby: Building the JavaScript App

ReactDOM hydrate() method


问:
How to fix 'Extra attributes from the server: style' warning in console
I'm create a React template use nextjs, but here is a warning Extra attributes from the server: style. I don`t use style attributes in my template. How can I fix this?

答: After a bit of investigation, I found that the error was coming from an input component in my app. Specifically, for an input where type="password". I'm using LastPass so I tried turning it off and running the app again, and that seems to have solved the issue.


问:
How to code this javascript into jquery using child-parentnode?
I'm new to jquery, and i wanted to convert my javascript code that includes two select tags one main and the other for sub, clicking a different option in the main will display a different sub select tag because all of my select tags display are set to none, but i dont know how to structure a jquery

here's my HTML for my select tag

```<code>   <select name="category" id="c_type" onchange="selectChoice()">
     <option value=""></option>
     <option value="Learning Environment">Learning Environment</option>
     <option value="Learning Support">Learning Support</option>
     <option value="Technology Support">Technology Support</option>
     <option value="Wellness">Wellness, Health, and Nutrition</option>
    <option value="Training">Training and Skills Development</option>
    <option value="Financial">Financial Support and Subsidy</option>
    <option value="Assistive">Assistive Learning Devices for Students with Special Needs</option>

   </select>
   <select name="specifics1" id="LE" style="display:none">
     <option value=""></option>
     <option value="Classroom">Classroom</option>
     <option value="Laboratory Room">Laboratory Room</option>
   </select>
   <select name="specifics2" id="LS" style="display:none">
     <option value=""></option>
     <option value="Lab Equipments">Lab Equipments</option>
     <option value="School Supplies">School Supplies</option>
   </select>
   <select name="specifics3" id="TS" style="display:none">
     <option value=""></option>
    <option value="Computer Units">Computer Units</option>
    <option value="Internet">Internet Connectivity</option>
    </select>
    <select name="specifics4" id="WT" style="display:none">
     <option value=""></option">
    <option value="Feeding">Feeding Program</option>
    <option value="Medical Kits">Medical Kits</option>
    </select>
    <select name="specifics5" id="TAD" style="display:none">
    <option value=""></option>
    <option value="Pupil Training">Student/Pupil Training</option>
    <option value="Literacy Training">Literacy Training</option>
    </select>
    <select name="specifics6" id="FIN" style="display:none">
    <option value=""></option>
    <option value="Fare">Fare</option>
    <option value="Meals">Meals</option>
    </select>
    <select name="specifics7" id="ASL" style="display:none">
    <option value=""></option>
    <option value="Braile">Braile</option>
    <option value="Hearing Aids">Hearing Aids</option>
    </select>

</code>```

finally here is my javascript

```<code>function selectChoice(){
 var main = document.getElementById("c_type").value;
 var s1 = document.getElementById("LE");
 var s2 = document.getElementById("LS");
 var s3 = document.getElementById("TS");
 var s4 = document.getElementById("WT");
 var s5 = document.getElementById("TAD");
 var s6 = document.getElementById("FIN");
 var s7 = document.getElementById("ASL");
 if(main === "Learning Environment"){
    s1.style.display = "block";
    s2.style.display = "none";
    s3.style.display = "none";
    s4.style.display = "none";
    s5.style.display = "none";
    s6.style.display = "none";
    s7.style.display = "none";
    s1.required = true;
    s2.required = false;
    s3.required = false;
    s4.required = false;
    s5.required = false;
    s6.required = false;
    s7.required = false;
    s1.selectedIndex = 0;
    s2.selectedIndex = 0;
    s3.selectedIndex = 0;
    s4.selectedIndex = 0;
    s5.selectedIndex = 0;
    s6.selectedIndex = 0;
    s7.selectedIndex = 0;

}else if(main === "Learning Support"){
    s1.style.display = "none";
    s2.style.display = "block";
    s3.style.display = "none";
    s4.style.display = "none";
    s5.style.display = "none";
    s6.style.display = "none";
    s7.style.display = "none";
    s1.required = false;
    s2.required = true;
    s3.required = false;
    s4.required = false;
    s5.required = false;
    s6.required = false;
    s7.required = false;
    s1.selectedIndex = 0;
    s2.selectedIndex = 0;
    s3.selectedIndex = 0;
    s4.selectedIndex = 0;
    s5.selectedIndex = 0;
    s6.selectedIndex = 0;
    s7.selectedIndex = 0;

}else if(main === "Technology Support"){
    s1.style.display = "none";
    s2.style.display = "none";
    s3.style.display = "block";
    s4.style.display = "none";
    s5.style.display = "none";
    s6.style.display = "none";
    s7.style.display = "none";
    s1.required = false;
    s2.required = false;
    s3.required = true;
    s4.required = false;
    s5.required = false;
    s6.required = false;
    s7.required = false;
    s1.selectedIndex = 0;
    s2.selectedIndex = 0;
    s3.selectedIndex = 0;
    s4.selectedIndex = 0;
    s5.selectedIndex = 0;
    s6.selectedIndex = 0;
    s7.selectedIndex = 0;

}}
</code>```

Looking at it i have 7 sub select tags with different select names and ids so it will be probably long but its working, what i want is to shorten it using jquery but i don't know how,

答:
IMHO here is the shortest way to write a similar code, and much easier to maintain

const Category = [
  { type:'Learning Environment',                                       ref:'LE',  specs: [ 'Classroom', 'Laboratory Room' ] }
, { type:'Learning Support',                                           ref:'LS',  specs: [ 'Lab Equipments', 'School Supplies' ] }
, { type:'Technology Support',                                         ref:'TS',  specs: [ 'Computer Units', 'Internet Connectivity' ] }
, { type:'Wellness, Health, and Nutrition',                            ref:'WT',  specs: [ 'Feeding Program', 'Medical Kits' ] }
, { type:'Training and Skills Development',                            ref:'TAD', specs: [ 'Student/Pupil Training', 'Literacy Training' ] }
, { type:'Financial Support and Subsidy',                              ref:'FIN', specs: [ 'Fare', 'Meals' ] }
, { type:'Assistive Learning Devices for Students with Special Needs', ref:'ASL', specs: [ 'Braile', 'Hearing Aids' ] }
];

const Select_category = document.querySelector('#c_type')
,     Select_specs    = document.querySelector('#specs')
;

// first initialisation on load...
let item = 0;
Select_category[item++] = new Option('','');
for (let cat of Category)
{
  Select_category[item++] = new Option(cat.type, cat.ref );
}
// ... end initialisation.

Select_category.onchange = function()
{
  Select_specs.innerHTML = null;

  if (Select_category.value === ''){
    Select_specs.classList.add('noDisplay');
  }
  else
  {
    let item = 0;
    Select_specs[item++] = new Option('','');

    Category.find(cat=>cat.ref===Select_category.value).specs.forEach((spec,index)=>{
      Select_specs[item++] = new Option(spec, index );
    })
    Select_specs.classList.remove('noDisplay');
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.noDisplay { display: none; }</code>```

<select name="category" id="c_type" ></select>

<select name="specs" id="specs" class="noDisplay"></select>```

Body:
I'm new to jquery, and i wanted to convert my javascript code that includes two select tags one main and the other for sub, clicking a different option in the main will display a different sub select tag because all of my select tags display are set to none, but i dont know how to structure a jquery

here's my HTML for my select tag

   <select name="category" id="c_type" onchange="selectChoice()">
     <option value=""></option>
     <option value="Learning Environment">Learning Environment</option>
     <option value="Learning Support">Learning Support</option>
     <option value="Technology Support">Technology Support</option>
     <option value="Wellness">Wellness, Health, and Nutrition</option>
    <option value="Training">Training and Skills Development</option>
    <option value="Financial">Financial Support and Subsidy</option>
    <option value="Assistive">Assistive Learning Devices for Students with Special Needs</option>

   </select>
   <select name="specifics1" id="LE" style="display:none">
     <option value=""></option>
     <option value="Classroom">Classroom</option>
     <option value="Laboratory Room">Laboratory Room</option>
   </select>
   <select name="specifics2" id="LS" style="display:none">
     <option value=""></option>
     <option value="Lab Equipments">Lab Equipments</option>
     <option value="School Supplies">School Supplies</option>
   </select>
   <select name="specifics3" id="TS" style="display:none">
     <option value=""></option>
    <option value="Computer Units">Computer Units</option>
    <option value="Internet">Internet Connectivity</option>
    </select>
    <select name="specifics4" id="WT" style="display:none">
     <option value=""></option">
    <option value="Feeding">Feeding Program</option>
    <option value="Medical Kits">Medical Kits</option>
    </select>
    <select name="specifics5" id="TAD" style="display:none">
    <option value=""></option>
    <option value="Pupil Training">Student/Pupil Training</option>
    <option value="Literacy Training">Literacy Training</option>
    </select>
    <select name="specifics6" id="FIN" style="display:none">
    <option value=""></option>
    <option value="Fare">Fare</option>
    <option value="Meals">Meals</option>
    </select>
    <select name="specifics7" id="ASL" style="display:none">
    <option value=""></option>
    <option value="Braile">Braile</option>
    <option value="Hearing Aids">Hearing Aids</option>
    </select>

finally here is my javascript

function selectChoice(){
 var main = document.getElementById("c_type").value;
 var s1 = document.getElementById("LE");
 var s2 = document.getElementById("LS");
 var s3 = document.getElementById("TS");
 var s4 = document.getElementById("WT");
 var s5 = document.getElementById("TAD");
 var s6 = document.getElementById("FIN");
 var s7 = document.getElementById("ASL");
 if(main === "Learning Environment"){
    s1.style.display = "block";
    s2.style.display = "none";
    s3.style.display = "none";
    s4.style.display = "none";
    s5.style.display = "none";
    s6.style.display = "none";
    s7.style.display = "none";
    s1.required = true;
    s2.required = false;
    s3.required = false;
    s4.required = false;
    s5.required = false;
    s6.required = false;
    s7.required = false;
    s1.selectedIndex = 0;
    s2.selectedIndex = 0;
    s3.selectedIndex = 0;
    s4.selectedIndex = 0;
    s5.selectedIndex = 0;
    s6.selectedIndex = 0;
    s7.selectedIndex = 0;

}else if(main === "Learning Support"){
    s1.style.display = "none";
    s2.style.display = "block";
    s3.style.display = "none";
    s4.style.display = "none";
    s5.style.display = "none";
    s6.style.display = "none";
    s7.style.display = "none";
    s1.required = false;
    s2.required = true;
    s3.required = false;
    s4.required = false;
    s5.required = false;
    s6.required = false;
    s7.required = false;
    s1.selectedIndex = 0;
    s2.selectedIndex = 0;
    s3.selectedIndex = 0;
    s4.selectedIndex = 0;
    s5.selectedIndex = 0;
    s6.selectedIndex = 0;
    s7.selectedIndex = 0;

}else if(main === "Technology Support"){
    s1.style.display = "none";
    s2.style.display = "none";
    s3.style.display = "block";
    s4.style.display = "none";
    s5.style.display = "none";
    s6.style.display = "none";
    s7.style.display = "none";
    s1.required = false;
    s2.required = false;
    s3.required = true;
    s4.required = false;
    s5.required = false;
    s6.required = false;
    s7.required = false;
    s1.selectedIndex = 0;
    s2.selectedIndex = 0;
    s3.selectedIndex = 0;
    s4.selectedIndex = 0;
    s5.selectedIndex = 0;
    s6.selectedIndex = 0;
    s7.selectedIndex = 0;

}}

Looking at it i have 7 sub select tags with different select names and ids so it will be probably long but its working, what i want is to shorten it using jquery but i don't know how,

Body:
IMHO here is the shortest way to write a similar code, and much easier to maintain

const Category = [
  { type:'Learning Environment',                                       ref:'LE',  specs: [ 'Classroom', 'Laboratory Room' ] }
, { type:'Learning Support',                                           ref:'LS',  specs: [ 'Lab Equipments', 'School Supplies' ] }
, { type:'Technology Support',                                         ref:'TS',  specs: [ 'Computer Units', 'Internet Connectivity' ] }
, { type:'Wellness, Health, and Nutrition',                            ref:'WT',  specs: [ 'Feeding Program', 'Medical Kits' ] }
, { type:'Training and Skills Development',                            ref:'TAD', specs: [ 'Student/Pupil Training', 'Literacy Training' ] }
, { type:'Financial Support and Subsidy',                              ref:'FIN', specs: [ 'Fare', 'Meals' ] }
, { type:'Assistive Learning Devices for Students with Special Needs', ref:'ASL', specs: [ 'Braile', 'Hearing Aids' ] }
];

const Select_category = document.querySelector('#c_type')
,     Select_specs    = document.querySelector('#specs')
;

// first initialisation on load...
let item = 0;
Select_category[item++] = new Option('','');
for (let cat of Category)
{
  Select_category[item++] = new Option(cat.type, cat.ref );
}
// ... end initialisation.

Select_category.onchange = function()
{
  Select_specs.innerHTML = null;

  if (Select_category.value === ''){
    Select_specs.classList.add('noDisplay');
  }
  else
  {
    let item = 0;
    Select_specs[item++] = new Option('','');

    Category.find(cat=>cat.ref===Select_category.value).specs.forEach((spec,index)=>{
      Select_specs[item++] = new Option(spec, index );
    })
    Select_specs.classList.remove('noDisplay');
  }
}

.noDisplay { display: none; }

<select name="category" id="c_type" ></select>

<select name="specs" id="specs" class="noDisplay"></select>


问:
How to pass NSManagedObjectContext through objects
I'm wondering which is the best way to pass NSManagedObjectContext in IOS Application.
I used to add an NSManagedObjectContext property with retain (not assign) and create custom init method... but i'm not sure that this's a best practice. Here an example of a Class which need a NSManagedObjectContext.

```<code>@interface CatSelectVC : UIViewController {
    NSArray *catList;
    NSManagedObjectContext *context;
}
@property(nonatomic,retain) NSManagedObjectContext *context;
-(CatSelectVC*)initWithContext:(NSManagedObjectContext*) theContext;
</code>```

and i implement custom init straightforward assigning theContext to self.context.
context is synthesized...

```<code>-(CatSelectVC*)initWithContext:(NSManagedObjectContext*)theContext{
  self = [super init];

  if(self !=nil){
     self.context = theContext;
  }

  return self;
}
</code>```

Is this a good method ? what about retain the context ? would be a better solution to use assign instead of retain for context property ?

答:
I tend to get the Context from a passed object.

```<code>NSManagedObjectContext *context = self.currentExercise.managedObjectContext;
</code>```

I think you definitely want to retain the context.

EDIT:

I would suggest The book entitled "Core Data" by Marcus Zarra or the iDeveloperTV video with Marcus Zarra and Scotty.

Body:
I'm wondering which is the best way to pass NSManagedObjectContext in IOS Application.
I used to add an NSManagedObjectContext property with retain (not assign) and create custom init method... but i'm not sure that this's a best practice. Here an example of a Class which need a NSManagedObjectContext.

@interface CatSelectVC : UIViewController {
    NSArray *catList;
    NSManagedObjectContext *context;
}
@property(nonatomic,retain) NSManagedObjectContext *context;
-(CatSelectVC*)initWithContext:(NSManagedObjectContext*) theContext;

and i implement custom init straightforward assigning theContext to self.context.
context is synthesized...

-(CatSelectVC*)initWithContext:(NSManagedObjectContext*)theContext{
  self = [super init];

  if(self !=nil){
     self.context = theContext;
  }

  return self;
}

Is this a good method ? what about retain the context ? would be a better solution to use assign instead of retain for context property ?

Body:
I tend to get the Context from a passed object.

NSManagedObjectContext *context = self.currentExercise.managedObjectContext;

I think you definitely want to retain the context.

EDIT:

I would suggest The book entitled "Core Data" by Marcus Zarra or the iDeveloperTV video with Marcus Zarra and Scotty.


问:
Issue with storing a file_get_contents into session as a integer
When developing a PHP website, I ran into a issue with storing a file_get_contents response as a integer in $_SESSION. This is to display a updated rank for off-site data.

I've already tried putting (int) before the response of the web server that I am pulling the data from.

$grouprank = file_get_contents(""); /* returns a 3-digit integer such as (102) */

$_SESSION['rank']       = $grouprank;
```

I wish to store the result of $grouprank as a integer in $_SESSION['rank'].

答:
```<code>session_start();
$grouprank = file_get_contents("must-have-a-filename.here");
$_SESSION['rank'] = intval( $grouprank );
</code>```

Body:
When developing a PHP website, I ran into a issue with storing a file_get_contents response as a integer in $_SESSION. This is to display a updated rank for off-site data.

I've already tried putting (int) before the response of the web server that I am pulling the data from.

$grouprank = file_get_contents(""); /* returns a 3-digit integer such as (102) */

$_SESSION['rank']       = $grouprank;

I wish to store the result of $grouprank as a integer in $_SESSION['rank'].