问:
Remove elements or attributes from input file which are defined in external XML file
I want to maintain an external XML file in which I will keep those elements/attributes which should be removed from an input file. So, whenever a new element/attribute need to be removed, I will just add that in my external XML file.

I created an XSLT which is removing an element by matching names in an incoming file with my external file. Problem is, this is not matching all the elements, only first occurrence is getting removed. Elements/attributes which I want to remove those can come anywhere in an input file.

My XSLT:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="ISO-8859-1" indent="yes"/>
    <xsl:template match="/">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="*">
        <xsl:copy>
            <!-- @=attribuutti -->
            <xsl:copy-of select="@*"/>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="node()[name() = name(document('TagsDB.xml')/INVOICE_CENTER/ElementsToRemove/*)]"/>
</xsl:stylesheet>
</code>```

Input.XML

```<code><INVOICE_CENTER>
    <CONTENT_FRAME>
        <Test1>123</Test1>
        <INVOICES>
            <INVOICE>
                <HEADER>
                    <PROCESS_CODE>00</PROCESS_CODE>
                </HEADER>
                <ROWS>
                    <ROW>
                        <ROW_NUMBER>0</ROW_NUMBER>
                        <Test2>12345</Test2>
                    </ROW>
                </ROWS>
            </INVOICE>
        </INVOICES>
    </CONTENT_FRAME>
</INVOICE_CENTER>
</code>```

My External file (TagsDB.xml) where I mentioned element/attribute which should be removed:

```<code><INVOICE_CENTER>
    <ElementsToRemove>
        <Test1/>
        <Test2/>
    </ElementsToRemove>
    <AttributesToRemove Att1="" Att2=""/>
</INVOICE_CENTER>
</code>```

Expected result is:

```<code><INVOICE_CENTER>
    <CONTENT_FRAME>
        <INVOICES>
            <INVOICE>
                <HEADER>
                    <PROCESS_CODE>00</PROCESS_CODE>
                </HEADER>
                <ROWS>
                    <ROW>
                        <ROW_NUMBER>0</ROW_NUMBER>
                        </ROW>
                </ROWS>
            </INVOICE>
        </INVOICES>
    </CONTENT_FRAME>
</INVOICE_CENTER>
</code>```

So, Test1 and Test2 should be removed from the XML because those are defined in my external XML file.

答:
The name() function returns the name of the first node in the selected node-set. You need to formulate your condition as:

if the external document does not contain an element whose name is equal to the name of this element

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="*">
    <xsl:if test="not(document('TagsDB.xml')/INVOICE_CENTER/ElementsToRemove/*[name()=name(current())])">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>
</code>```

To handle attributes too, you can do:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="*">
    <xsl:if test="not(document('TagsDB.xml')/INVOICE_CENTER/ElementsToRemove/*[name()=name(current())])">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:if>
</xsl:template>

<xsl:template match="@*">
    <xsl:if test="not(document('TagsDB.xml')/INVOICE_CENTER/AttributesToRemove/@*[name()=name(current())])">
        <xsl:copy/>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>
</code>```

Body:
I want to maintain an external XML file in which I will keep those elements/attributes which should be removed from an input file. So, whenever a new element/attribute need to be removed, I will just add that in my external XML file.

I created an XSLT which is removing an element by matching names in an incoming file with my external file. Problem is, this is not matching all the elements, only first occurrence is getting removed. Elements/attributes which I want to remove those can come anywhere in an input file.

My XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="ISO-8859-1" indent="yes"/>
    <xsl:template match="/">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="*">
        <xsl:copy>

            <xsl:copy-of select="@*"/>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="node()[name() = name(document('TagsDB.xml')/INVOICE_CENTER/ElementsToRemove/*)]"/>
</xsl:stylesheet>

Input.XML

<INVOICE_CENTER>
    <CONTENT_FRAME>
        <Test1>123</Test1>
        <INVOICES>
            <INVOICE>

                    <PROCESS_CODE>00</PROCESS_CODE>

                <ROWS>
                    <ROW>
                        <ROW_NUMBER>0</ROW_NUMBER>
                        <Test2>12345</Test2>
                    </ROW>
                </ROWS>
            </INVOICE>
        </INVOICES>
    </CONTENT_FRAME>
</INVOICE_CENTER>

My External file (TagsDB.xml) where I mentioned element/attribute which should be removed:

<INVOICE_CENTER>
    <ElementsToRemove>
        <Test1/>
        <Test2/>
    </ElementsToRemove>
    <AttributesToRemove Att1="" Att2=""/>
</INVOICE_CENTER>

Expected result is:

<INVOICE_CENTER>
    <CONTENT_FRAME>
        <INVOICES>
            <INVOICE>

                    <PROCESS_CODE>00</PROCESS_CODE>

                <ROWS>
                    <ROW>
                        <ROW_NUMBER>0</ROW_NUMBER>
                        </ROW>
                </ROWS>
            </INVOICE>
        </INVOICES>
    </CONTENT_FRAME>
</INVOICE_CENTER>

So, Test1 and Test2 should be removed from the XML because those are defined in my external XML file.

Body:
The name() function returns the name of the first node in the selected node-set. You need to formulate your condition as:

if the external document does not contain an element whose name is equal to the name of this element

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="*">
    <xsl:if test="not(document('TagsDB.xml')/INVOICE_CENTER/ElementsToRemove/*[name()=name(current())])">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

To handle attributes too, you can do:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="*">
    <xsl:if test="not(document('TagsDB.xml')/INVOICE_CENTER/ElementsToRemove/*[name()=name(current())])">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:if>
</xsl:template>

<xsl:template match="@*">
    <xsl:if test="not(document('TagsDB.xml')/INVOICE_CENTER/AttributesToRemove/@*[name()=name(current())])">
        <xsl:copy/>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>


来源: stackexchange

问:
android string gallery can't display from beginning of the screen
i had creating string gallery but android string gallery can't display from beginning of the screen. it displayed. any solution??

thanks inn advance.

```<code>private Context cont;
private String [] stringid=new String[]{"Index-Nifty","Positional calls","Intraday calls","InvestmentIdea","Optional calls","BTST-STBT calls"};

public TabGallary(Context c) {
    cont = c;
}

public int getCount(){
    return stringid.length;
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    TextView view = new TextView(cont);

    //Fixing width & height for String to display
    view.setLayoutParams(new Gallery.LayoutParams(125, 20));
    view.setSoundEffectsEnabled(true);
    view.setText(stringid[position]);
    view.setSingleLine();

    Intent intent = new Intent();
    startActivity(intent);
    return view;
}

private void startActivity(Intent intent) {
    // TODO Auto-generated method stub
}
</code>```

答:
hey.. for dat u have to use LayoutInflater

first u create an XML file "demo.xml"

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget44"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center_horizontal">
    <TextView
        android:id="@+id/txt1_gvi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#051b4d"
        android:gravity="center_horizontal"
        android:textColorHighlight="#656565"
        android:textSize="10sp">
    </TextView>
</LinearLayout>
</code>```

now ur adaptor class should be like following..
here instead of context u have to pass activity..
eg
instead of public TabGallary(Context c) u have to public TabGallary(Activity a)

```<code>    public Activity activity;
    private static LayoutInflater inflater=null;
    private String [] stringid=new String[]{"Index-Nifty","Positional calls","Intraday calls","InvestmentIdea","Optional calls","BTST-STBT calls"};

    public TabGallary(Activity a) {
        activity = a;
        inflater =  (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount(){
        return stringid.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {
      View v;
      if (convertView == null)
      {
           LayoutInflater li = getLayoutInflater();
           v = li.inflate(R.layout.demo, null);
           TextView tv1 = (TextView)v.findViewById(R.id.txt1_gvi);
           tv1.setText(stringid[position]);
           v.setOnClickListener(new OnClickListener()
           {
                    @Override
                    public void onClick(View v)
                    {
                  // Call intent or perform ur activity;
                    }
           });
      }
      else
      {
       v= convertView;
      }

      return v;
   }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i had creating string gallery but android string gallery can't display from beginning of the screen. it displayed. any solution??

thanks inn advance.

private Context cont;
private String [] stringid=new String[]{"Index-Nifty","Positional calls","Intraday calls","InvestmentIdea","Optional calls","BTST-STBT calls"};

public TabGallary(Context c) {
    cont = c;
}

public int getCount(){
    return stringid.length;
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    TextView view = new TextView(cont);

    //Fixing width & height for String to display
    view.setLayoutParams(new Gallery.LayoutParams(125, 20));
    view.setSoundEffectsEnabled(true);
    view.setText(stringid[position]);
    view.setSingleLine();

    Intent intent = new Intent();
    startActivity(intent);
    return view;
}

private void startActivity(Intent intent) {
    // TODO Auto-generated method stub
}

Body:
hey.. for dat u have to use LayoutInflater

first u create an XML file "demo.xml"

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget44"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center_horizontal">
    <TextView
        android:id="@+id/txt1_gvi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#051b4d"
        android:gravity="center_horizontal"
        android:textColorHighlight="#656565"
        android:textSize="10sp">
    </TextView>
</LinearLayout>

now ur adaptor class should be like following..
here instead of context u have to pass activity..
eg
instead of public TabGallary(Context c) u have to public TabGallary(Activity a)

    public Activity activity;
    private static LayoutInflater inflater=null;
    private String [] stringid=new String[]{"Index-Nifty","Positional calls","Intraday calls","InvestmentIdea","Optional calls","BTST-STBT calls"};

    public TabGallary(Activity a) {
        activity = a;
        inflater =  (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount(){
        return stringid.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {
      View v;
      if (convertView == null)
      {
           LayoutInflater li = getLayoutInflater();
           v = li.inflate(R.layout.demo, null);
           TextView tv1 = (TextView)v.findViewById(R.id.txt1_gvi);
           tv1.setText(stringid[position]);
           v.setOnClickListener(new OnClickListener()
           {
                    @Override
                    public void onClick(View v)
                    {
                  // Call intent or perform ur activity;
                    }
           });
      }
      else
      {
       v= convertView;
      }

      return v;
   }

ContentLicense: CC BY-SA 3.0


问:
How to send controller action in url parameter in Asp.net Web Api?
Typically you call an action of a controller like so http://hostname/MyController/MyAction
I have a requirement for my Web Api to have routes like this one:
http://hostname/MyController?action=MyAction, i.e., pass the action in url parameter.

My controller:

```<code>public class MyController : ApiController
{
    [HttpGet]
    [Route("WHAT SHOULD BE HERE??")]
    public IHttpActionResult MyAction()
    {
        // some code
    }
}
</code>```

Any ideas how I can write such a routing?

答:
After more than a year I can come back to this question and answer it myself.
The solution you can use here is to write your own ActionSelector - this is the class Web Api framework uses to select actions, by default it uses System.Web.Http.Controllers.ApiControllerActionSelector, which you can override.

So lets say your controller looks like this:

```<code>public class MyController : ApiController
{
    [HttpGet]
    public IHttpActionResult MyAction()
    {
        // some code
    }
}
</code>```

Then you can create your own action selector like this (the code might be improved I wrote it very quickly):

```<code>public class QueryParameterActionSelector : ApiControllerActionSelector
{
    public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
    {
        var mapping = GetActionMapping(controllerContext.ControllerDescriptor);

        var parameters = controllerContext.Request.GetQueryNameValuePairs();
        foreach (var parameter in parameters)
        {
            if (parameter.Key == "action")
            {
                if (mapping.Contains(parameter.Value))
                {
                    // Provided that all of your actions have unique names.
                    // Otherwise mapping[parameter.Value] will return multiple actions and you will have to match by the method parameters.
                    return mapping[parameter.Value].First();
                }
            }
        }

        return null;
    }
}
</code>```

And then finally you have to register this action selector in WebApiConfig.Register method. It will look like this:

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}"
        );

        config.Services.Replace(typeof(IHttpActionSelector), new QueryParameterActionSelector());
    }
}
</code>```

Now you can call your action like this http://hostname/controller?action=MyAction

ContentLicense: CC BY-SA 4.0

Body:
Typically you call an action of a controller like so http://hostname/MyController/MyAction
I have a requirement for my Web Api to have routes like this one:
http://hostname/MyController?action=MyAction, i.e., pass the action in url parameter.

My controller:

public class MyController : ApiController
{
    [HttpGet]
    [Route("WHAT SHOULD BE HERE??")]
    public IHttpActionResult MyAction()
    {
        // some code
    }
}

Any ideas how I can write such a routing?

Body:
After more than a year I can come back to this question and answer it myself.
The solution you can use here is to write your own ActionSelector - this is the class Web Api framework uses to select actions, by default it uses System.Web.Http.Controllers.ApiControllerActionSelector, which you can override.

So lets say your controller looks like this:

public class MyController : ApiController
{
    [HttpGet]
    public IHttpActionResult MyAction()
    {
        // some code
    }
}

Then you can create your own action selector like this (the code might be improved I wrote it very quickly):

public class QueryParameterActionSelector : ApiControllerActionSelector
{
    public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
    {
        var mapping = GetActionMapping(controllerContext.ControllerDescriptor);

        var parameters = controllerContext.Request.GetQueryNameValuePairs();
        foreach (var parameter in parameters)
        {
            if (parameter.Key == "action")
            {
                if (mapping.Contains(parameter.Value))
                {
                    // Provided that all of your actions have unique names.
                    // Otherwise mapping[parameter.Value] will return multiple actions and you will have to match by the method parameters.
                    return mapping[parameter.Value].First();
                }
            }
        }

        return null;
    }
}

And then finally you have to register this action selector in WebApiConfig.Register method. It will look like this:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}"
        );

        config.Services.Replace(typeof(IHttpActionSelector), new QueryParameterActionSelector());
    }
}

Now you can call your action like this http://hostname/controller?action=MyAction


问:
How can I stop the countdown until the localStorage expires?
The following script makes a countdown until it reaches the set number (in this case 76), after which it starts again the countdown and so on. Updating the page the countdown does not reset until the localStorage expires.

I want that when the countdown reaches 76 it stops and doesn't start counting again. This until the localStorage expires. Please how can I do this?

```

```var min = 80;
var max = 85;
var random = Math.floor(Math.random() * (+max - +min)) + +min;

if (localStorage.getItem("counter")) {
  if (localStorage.getItem("counter") >= 1000000000) { // Duration of localStorage
    var value = random;
  } else {
    var value = localStorage.getItem("counter");
  }
} else {
  var value = random;
}

document.getElementById('divCounter').innerHTML = value;

var counter = function () {
  if (value <= 76) { // End count down. <= or >=
    localStorage.setItem("counter", random);
    value = random;
  } else {
    value = parseInt(value) - 1; // + 1 or - 1
    localStorage.setItem("counter", value);
  }

  document.getElementById('divCounter').innerHTML = value;
};

var interval = setInterval(function () {
  counter();
}, 1000); // speed count
```

答:
This is my best guess at your intention:

```<code>// If there's a count in localStorage but it is expired then
//      set value to a random between 80 and 85
// else
//      set value to the count in localStorage

// Display the count in a div and decrease it by 1 every second.
// If the count falls below 76 then
//      stop counting down and
//      reset the localStorage counter to the random value

        const min = 80;
        const max = 85;
        const stopValue = 76;
        const duration = 1000000000;
        const rnd = Math.floor(Math.random() * (max - min)) + min;

        const counter = () => {
            const lsCounter = localStorage.getItem('counter');

            let retval;

            if(lsCounter && lsCounter <= duration){
                retval = lsCounter - 1;
                if(lsCounter <= stopValue){
                    clearInterval(interval);
                    retval = rnd;
                }
            }else{
                retval = rnd;
            }
            localStorage.setItem('counter', retval);
            document.getElementById('divCounter').innerHTML = retval;
        }
        let interval = setInterval(function () {
            counter();
        }, 1000);
</code>```

Is this correct?

Body:
The following script makes a countdown until it reaches the set number (in this case 76), after which it starts again the countdown and so on. Updating the page the countdown does not reset until the localStorage expires.

I want that when the countdown reaches 76 it stops and doesn't start counting again. This until the localStorage expires. Please how can I do this?

var min = 80;
var max = 85;
var random = Math.floor(Math.random() * (+max - +min)) + +min;

if (localStorage.getItem("counter")) {
  if (localStorage.getItem("counter") >= 1000000000) { // Duration of localStorage
    var value = random;
  } else {
    var value = localStorage.getItem("counter");
  }
} else {
  var value = random;
}

document.getElementById('divCounter').innerHTML = value;

var counter = function () {
  if (value <= 76) { // End count down. <= or >=
    localStorage.setItem("counter", random);
    value = random;
  } else {
    value = parseInt(value) - 1; // + 1 or - 1
    localStorage.setItem("counter", value);
  }

  document.getElementById('divCounter').innerHTML = value;
};

var interval = setInterval(function () {
  counter();
}, 1000); // speed count

Body:
This is my best guess at your intention:

// If there's a count in localStorage but it is expired then
//      set value to a random between 80 and 85
// else
//      set value to the count in localStorage

// Display the count in a div and decrease it by 1 every second.
// If the count falls below 76 then
//      stop counting down and
//      reset the localStorage counter to the random value

        const min = 80;
        const max = 85;
        const stopValue = 76;
        const duration = 1000000000;
        const rnd = Math.floor(Math.random() * (max - min)) + min;

        const counter = () => {
            const lsCounter = localStorage.getItem('counter');

            let retval;

            if(lsCounter && lsCounter <= duration){
                retval = lsCounter - 1;
                if(lsCounter <= stopValue){
                    clearInterval(interval);
                    retval = rnd;
                }
            }else{
                retval = rnd;
            }
            localStorage.setItem('counter', retval);
            document.getElementById('divCounter').innerHTML = retval;
        }
        let interval = setInterval(function () {
            counter();
        }, 1000);

Is this correct?


问:
Way to understand this code. How is it working?
I was exploring scopes in javascript and came to know this problem. I don't understand how this problem is working.

function checkType() {
  return foo;
  foo = 10;

  function foo() {};
  var foo = 11;
};

console.log(typeof checkType())```

My question is this how does javascript compiler decide to return function not variable. Any reference or explanation are welcome.

答:
This is how the compiler will compile the above code..

```<code>function checkType() {
  var foo = function() {}; /* function will be hoisted to the top,
                              and will be assigned to the variable as
                              the name is the same for the two.. */
  return foo;

  // Code will never reach here as you are returning before this
  foo = 10;
  foo = 11;
};

console.log(typeof checkType());
</code>```

Functions which are defined using function() syntax will be hoisted, in this case, the nested function will be hoisted insde the checkType() and hence, the checkType() returns the function instead of the integer.

Note: Because the function was defined using function(){} syntax, it
  was hoisted to the parent function scope, else, if the function was
  defined using var foo = function() {} then the hoisting would not
  have worked in the same way, your function would've returned undefined instead.

More reference on Scoping & Hoisting

http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting/

Body:
I was exploring scopes in javascript and came to know this problem. I don't understand how this problem is working.

function checkType() {
  return foo;
  foo = 10;

  function foo() {};
  var foo = 11;
};

console.log(typeof checkType())

My question is this how does javascript compiler decide to return function not variable. Any reference or explanation are welcome.

Body:
This is how the compiler will compile the above code..

function checkType() {
  var foo = function() {}; /* function will be hoisted to the top,
                              and will be assigned to the variable as
                              the name is the same for the two.. */
  return foo;

  // Code will never reach here as you are returning before this
  foo = 10;
  foo = 11;
};

console.log(typeof checkType());

Functions which are defined using function() syntax will be hoisted, in this case, the nested function will be hoisted insde the checkType() and hence, the checkType() returns the function instead of the integer.

Note: Because the function was defined using function(){} syntax, it
  was hoisted to the parent function scope, else, if the function was
  defined using var foo = function() {} then the hoisting would not
  have worked in the same way, your function would've returned undefined instead.

More reference on Scoping & Hoisting

http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting/


答:
First all the function declarations are hoisted in a scope. So first of all the code moves the variable foo to the top of the scope and initialize its value to function.

The second declaration of variable is not hoisted because the function declaration is already hoisted. So the code is same as

```<code>function checkType() {
  var foo = function(){}
  return foo;
  foo = 10;

  foo = 11;
};
</code>```

Title: Way to understand this code. How is it working?

Body:
First all the function declarations are hoisted in a scope. So first of all the code moves the variable foo to the top of the scope and initialize its value to function.

The second declaration of variable is not hoisted because the function declaration is already hoisted. So the code is same as

function checkType() {
  var foo = function(){}
  return foo;
  foo = 10;

  foo = 11;
};


问:
Push notification can not get on mobile using laravel
I am trying to send push notification to a mobile device using the following function but it can not send. I am checking through firebase, it works but it can not send through my coding.

This is my function & give result as follows,
Result=

"{"multicast_id":7523757847702384710,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1558857210405129%6298e0406298e040"}]}"

```<code>public function sendNotification(Request $req)
{
      $fcm_token=$req->input('fcm_token');
      $json_data=[
    "to" =>  $fcm_token,
    "notification" => [
        "body" => "hello",
        "title" => "hello"
    ]

];

      $data = json_encode($json_data);
//FCM API end-point
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = 'AIzaSyDF4_rqij_Bt4zC3GNEVbNFvwX1HHxy5Mo';
//header with content_type api key
$headers = array(
    'Content-Type:application/json',
    'Authorization:key='.$server_key
);
//CURL request to route notification to FCM connection server (provided by Google)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if ($result === FALSE) {
    die('Oops! FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);

dd($result);

}
</code>```

When I send a notification, mobile gets the push notification.

答:
In laravel we usually use brozot package to send push notification through laravel instead of using the core php.

https://packagist.org/packages/brozot/laravel-fcm

Body:
I am trying to send push notification to a mobile device using the following function but it can not send. I am checking through firebase, it works but it can not send through my coding.

This is my function & give result as follows,
Result=

"{"multicast_id":7523757847702384710,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1558857210405129%6298e0406298e040"}]}"

public function sendNotification(Request $req)
{
      $fcm_token=$req->input('fcm_token');
      $json_data=[
    "to" =>  $fcm_token,
    "notification" => [
        "body" => "hello",
        "title" => "hello"
    ]

];

      $data = json_encode($json_data);
//FCM API end-point
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = 'AIzaSyDF4_rqij_Bt4zC3GNEVbNFvwX1HHxy5Mo';
//header with content_type api key
$headers = array(
    'Content-Type:application/json',
    'Authorization:key='.$server_key
);
//CURL request to route notification to FCM connection server (provided by Google)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if ($result === FALSE) {
    die('Oops! FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);

dd($result);

}

When I send a notification, mobile gets the push notification.


问:
Distinct Event based on how it was created
I'm doing DDD analysis using event-storming, and run into this question:

Can we or should we define distinct events (e.g.: RouteCreatedByUser and RouteCreatedFromImport) based on how it was created?

Will "it depends" be the answer again? (e.g.: depends, if the way it was created will affect subsequent process / how the aggregate will be treated).

Or will the answer be flat out "no", just make one event (RouteCreated)?

答:
You should always consider if your events have distinict business
  significance. If they do, they should be separate. This allows them to
  evolve independently.

Also, see how many things are common and how much is different. If you find some things which are different but not really generalisable, you should split the events. No use in having unused fields with lots of conditions when something is applicable and when it isn't.

If you fail to catch this distinction you would end up with low cohesion, lots of unused fields etc. Remember, that even sourcing is primarily about having an immutable event log. What it means is while you can modify the events if you need to do some simple schema migrations (in general, you shouldn't but sometimes it just makes more sense), you can never put any events in between or delete events.


问:
Radio button selection via tabs
There are 3 accordions on a page with 4-5 radio buttons inside each one of them. All have the same name group. On init the first radio of first accordion is selected already.

When selecting the radio buttons by pressing tabs, the second accordion opens. But on pressing the next tab, it skips the radio buttons and moves on to the next accordion.

This is because the user can select only one option with the same name.

What I want is the second options should be selectable via tabbing, but the name attribute should remain the same. That's the condition-can't be changed because it has a lot of dependencies. How can we achieve this?

I added tabindex values to radios, but no use.

答:
Edit: Here give this a whirl!

This will recognize if an accordion has a tabbable input, not only that but it will open the accordion for you if tabbing through and its not opened but yet has tabable inputs that you wouldn't want your users to miss out on inputing values into.

I hope i was able to guide you i the right direction for this.

$('button').keydown(function(e) {
  var code = (e.keyCode ? e.keyCode : e.which);
  if (code == 9) {
    var visibleAccordionInputs = $(this.nextElementSibling).find($(`input[type][tabindex != '-1']:visible`));

    var hiddenAccordionInputs = $(this.nextElementSibling).find($(`input[type][tabindex != '-1']:hidden`));

    if (hiddenAccordionInputs.length) {
      alert('pressed tab on an accordian with tabbable inputs that are not visible, lets open the accordion.');
      $(this.nextElementSibling).show();
    }

    if (visibleAccordionInputs.length) {
      alert('pressed tab on an accordian with visible tabbable inputs')
      visibleAccordionInputs[0].focus();
    }

  }
});

function toggleAccordion(elem) {
  var accordionContent = $(elem.nextElementSibling);

  accordionContent.toggle();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<div class="w3-container">

  <h2>Accordions</h2>
  <p>An accordion is used to show (and hide) HTML content:</p>

  <button class="w3-btn w3-block w3-black w3-left-align" onClick="toggleAccordion(this)">Open Section 1</button>
  <div class="w3-container">
    <h4>Section 1</h4>
    <p>Some text..</p>
  </div>

  <button class="w3-btn w3-block w3-black w3-left-align" onClick="toggleAccordion(this)">Open Section 2</button>
  <div class="w3-container">
    <h4>Section 2</h4>
    <p>Some text..</p>
    <div class="w3-row">
      <div class="w3-half">
        <input id="milk" class="w3-check" type="checkbox" checked="checked">
        <label>Milk</label>
        <br>
        <input id="sugar" class="w3-check" type="checkbox">
        <label>Sugar</label>
        <br>
        <input id="lemon" class="w3-check" type="checkbox" disabled="">
        <label>Lemon (Disabled)</label>
        <br><br>
      </div>

      <div class="w3-half">
        <input id="male" class="w3-radio" type="radio" name="gender" value="male" checked="">
        <label>Male</label>
        <br>
        <input id="female" class="w3-radio" type="radio" name="gender" value="female">
        <label>Female</label>
        <br>
        <input id="unknown" class="w3-radio" type="radio" name="gender" value="" disabled="">
        <label>Don't know (Disabled)</label>
      </div>
    </div>
  </div>
</div></code>```

Title: Radio button selection via tabs

Body:
Edit: Here give this a whirl!

This will recognize if an accordion has a tabbable input, not only that but it will open the accordion for you if tabbing through and its not opened but yet has tabable inputs that you wouldn't want your users to miss out on inputing values into.

I hope i was able to guide you i the right direction for this.

$('button').keydown(function(e) {
  var code = (e.keyCode ? e.keyCode : e.which);
  if (code == 9) {
    var visibleAccordionInputs = $(this.nextElementSibling).find($(`input[type][tabindex != '-1']:visible`));

    var hiddenAccordionInputs = $(this.nextElementSibling).find($(`input[type][tabindex != '-1']:hidden`));

    if (hiddenAccordionInputs.length) {
      alert('pressed tab on an accordian with tabbable inputs that are not visible, lets open the accordion.');
      $(this.nextElementSibling).show();
    }

    if (visibleAccordionInputs.length) {
      alert('pressed tab on an accordian with visible tabbable inputs')
      visibleAccordionInputs[0].focus();
    }

  }
});

function toggleAccordion(elem) {
  var accordionContent = $(elem.nextElementSibling);

  accordionContent.toggle();
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<div class="w3-container">

  <h2>Accordions</h2>
  <p>An accordion is used to show (and hide) HTML content:</p>

  <button class="w3-btn w3-block w3-black w3-left-align" onClick="toggleAccordion(this)">Open Section 1</button>
  <div class="w3-container">
    <h4>Section 1</h4>
    <p>Some text..</p>
  </div>

  <button class="w3-btn w3-block w3-black w3-left-align" onClick="toggleAccordion(this)">Open Section 2</button>
  <div class="w3-container">
    <h4>Section 2</h4>
    <p>Some text..</p>
    <div class="w3-row">
      <div class="w3-half">
        <input id="milk" class="w3-check" type="checkbox" checked="checked">
        <label>Milk</label>
        <br>
        <input id="sugar" class="w3-check" type="checkbox">
        <label>Sugar</label>
        <br>
        <input id="lemon" class="w3-check" type="checkbox" disabled="">
        <label>Lemon (Disabled)</label>
        <br><br>
      </div>

      <div class="w3-half">
        <input id="male" class="w3-radio" type="radio" name="gender" value="male" checked="">
        <label>Male</label>
        <br>
        <input id="female" class="w3-radio" type="radio" name="gender" value="female">
        <label>Female</label>
        <br>
        <input id="unknown" class="w3-radio" type="radio" name="gender" value="" disabled="">
        <label>Don't know (Disabled)</label>
      </div>
    </div>
  </div>
</div>


问:
What to select next, for building Desktop-application?
I have been reading Groovy, and I'm half way down. I started to love groovy a lot, and apply it to solve some simple real world problem; As I love building web applications, i would go for reading Grails webframework as I know Groovy.

But If I want to build desktop-applications, which framework will be the good choice? I wanted to create a simple IDE for Groovy language(or say for any language), that can do syntax highlighting and other kind of stuffs.As mentioned earlier, I love Groovy a lot when compared to Java; And Griffon is a framework that is built on Groovy, mainly for creating Desktop-appplications. But I didn't find enough resources for Griffon!

Is Griffon is the good framework for those people who know and love Groovy(as I do)? Can I choose it for building a simple IDE as mentioned above? Or there are any other framework that is built on Groovy, which is good when compare to Griffon?

答:
The problem I have found with Griffon is that a number of the plugins are a bit out of date in that they aren't using the latest UI libraries (e.g. Flamingo, Substance, and SwingXBuilder, altho I think this has just been upgraded to use SwingX 1.6).

I am using SwingBuilder directly, with a few extensions I have added via my own builder implementation:

http://code.google.com/p/ousia

If you want to build an IDE I can recommend the RSyntaxTextArea component, as it has great support for many programming languages and is pretty simple to use:

http://fifesoft.com/rsyntaxtextarea/


问:
File writer is writing the string with no "Line breaks"
It is a simple "file writing program" that scans a text file from the given directory and stores its content into a string initialized as " words" . Now, when the content is concatenated into the string. The spaces and the line breaks are preserved. However, when I attempt to write that string words into a file. The spaces are preserved but the lines breaks are lost.
For example:
Original String:
Hello. I am stuck in UMT.
Get me out of here.
File Writing:
Hello, I am stuck in UMT. Get me out of here.
Notice the new line is not preserved? No line break? No " \n" ?</p>

```<code>package testing;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Reader{ {

String words="this is a a new file created by me :D \n";
File file = new File("C:/file.txt");

  try {
        Scanner scan= new Scanner(file);
        while(scan.hasNextLine()){
        words= words.concat(scan.nextLine() + "\r ");
        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null,
ex);
    }

System.out.println(words);

try {
    FileWriter writer = new FileWriter("D:/newfile.txt");
    writer.write(words);
    writer.close();
} catch (IOException ex) {
    Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
}

}}
</code>```

答:
Try:

```<code>words= words.concat(scan.nextLine() + "\r\n" );
</code>```

The nextLine() scans each line without the line break. So you have to manually insert one.
Also, on Linux and MacOS machines, next line is \n but on most Windows machines, next line is \r\n.

Body:
It is a simple "file writing program" that scans a text file from the given directory and stores its content into a string initialized as " words" . Now, when the content is concatenated into the string. The spaces and the line breaks are preserved. However, when I attempt to write that string words into a file. The spaces are preserved but the lines breaks are lost.
For example:
Original String:
Hello. I am stuck in UMT.
Get me out of here.
File Writing:
Hello, I am stuck in UMT. Get me out of here.
Notice the new line is not preserved? No line break? No " \n" ?

package testing;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Reader{ {

String words="this is a a new file created by me :D \n";
File file = new File("C:/file.txt");

  try {
        Scanner scan= new Scanner(file);
        while(scan.hasNextLine()){
        words= words.concat(scan.nextLine() + "\r ");
        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null,
ex);
    }

System.out.println(words);

try {
    FileWriter writer = new FileWriter("D:/newfile.txt");
    writer.write(words);
    writer.close();
} catch (IOException ex) {
    Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
}

}}

Body:
Try:

words= words.concat(scan.nextLine() + "\r\n" );

The nextLine() scans each line without the line break. So you have to manually insert one.
Also, on Linux and MacOS machines, next line is \n but on most Windows machines, next line is \r\n.


问:
IntegrationServices Only Runs Part of SSIS Package
I have a SSIS Package that looks like this:

It runs fine via Visual Studio or DTEXEC in command line.  I have deployed it, as seen here:

When I connect to and run it via C# in my WinForm it only seems to run the 'Truncate Table' task.  I comes back and says it was Successful, but it only ran part of the package, which I DO NOT call Successful.

Here is the code I'm using to connect and run:

```<code>// Create a connection to the server
string sqlConnectionString = "Data Source=BSQL_01;Initial Catalog=master;Integrated Security=SSPI;";
SqlConnection sqlConnection = new SqlConnection(sqlConnectionString);
MessageBox.Show("Created Connection");
// Create the Integration Services object
IntegrationServices integrationServices = new IntegrationServices(sqlConnection);

// Get the Integration Services catalog
Catalog catalog = integrationServices.Catalogs["SSISDB"];
MessageBox.Show("Created Catalog");

// Get the folder
CatalogFolder folder = catalog.Folders["PORGImport"];
MessageBox.Show("Created Folder");

// Get the project
ProjectInfo project = folder.Projects["PORGImport"];
MessageBox.Show("Created Project");

// Get the package
PackageInfo package = project.Packages["PORGImport.dtsx"];
MessageBox.Show("Created Package");

// Run the package
long executionIdentifier = package.Execute(false, null);

ExecutionOperation executionOperation = integrationServices.Catalogs["SSISDB"].Executions[executionIdentifier];

while (!executionOperation.Completed) {
    System.Threading.Thread.Sleep(5000);
    executionOperation.Refresh();
    MessageBox.Show("Running...");
}

if (executionOperation.Status == Operation.ServerOperationStatus.Success) {
    Console.WriteLine("Success");
    MessageBox.Show("Success");

} else if (executionOperation.Status == Operation.ServerOperationStatus.Failed) {
    Console.WriteLine("Failed");
    MessageBox.Show("Failed");

} else {
    Console.WriteLine("Something Went Really Wrong");
    MessageBox.Show("Oh Crap");
}
</code>```

I looked in the package on the SQL Server and I see this error:

Purchase File Loop: Warning: The For Each File enumerator is empty.
  The For Each File enumerator did not find any files that matched the
  file pattern, or the specified directory was empty.

Which doesn't make sense to me since it's all running from my PC, I have access to the directory, it runs fine via command line and via Visual Studio.

Environment

MS SQL Server 2014 (v12.0.5546.0)

MS Visual Studio 15 (v14 Update 3)

答:
Check that Variables values are assigned

From the screenshots, it looks like you are using expressions in the for each loop container since the fx mark is shown on the top left corner. Make sure you have assigned the variable before executing the packages.

How to change SSIS variable values in C#

Body:
I have a SSIS Package that looks like this:

It runs fine via Visual Studio or DTEXEC in command line.  I have deployed it, as seen here:

When I connect to and run it via C# in my WinForm it only seems to run the 'Truncate Table' task.  I comes back and says it was Successful, but it only ran part of the package, which I DO NOT call Successful.

Here is the code I'm using to connect and run:

// Create a connection to the server
string sqlConnectionString = "Data Source=BSQL_01;Initial Catalog=master;Integrated Security=SSPI;";
SqlConnection sqlConnection = new SqlConnection(sqlConnectionString);
MessageBox.Show("Created Connection");
// Create the Integration Services object
IntegrationServices integrationServices = new IntegrationServices(sqlConnection);

// Get the Integration Services catalog
Catalog catalog = integrationServices.Catalogs["SSISDB"];
MessageBox.Show("Created Catalog");

// Get the folder
CatalogFolder folder = catalog.Folders["PORGImport"];
MessageBox.Show("Created Folder");

// Get the project
ProjectInfo project = folder.Projects["PORGImport"];
MessageBox.Show("Created Project");

// Get the package
PackageInfo package = project.Packages["PORGImport.dtsx"];
MessageBox.Show("Created Package");

// Run the package
long executionIdentifier = package.Execute(false, null);

ExecutionOperation executionOperation = integrationServices.Catalogs["SSISDB"].Executions[executionIdentifier];

while (!executionOperation.Completed) {
    System.Threading.Thread.Sleep(5000);
    executionOperation.Refresh();
    MessageBox.Show("Running...");
}

if (executionOperation.Status == Operation.ServerOperationStatus.Success) {
    Console.WriteLine("Success");
    MessageBox.Show("Success");

} else if (executionOperation.Status == Operation.ServerOperationStatus.Failed) {
    Console.WriteLine("Failed");
    MessageBox.Show("Failed");

} else {
    Console.WriteLine("Something Went Really Wrong");
    MessageBox.Show("Oh Crap");
}

I looked in the package on the SQL Server and I see this error:

Purchase File Loop: Warning: The For Each File enumerator is empty.
  The For Each File enumerator did not find any files that matched the
  file pattern, or the specified directory was empty.

Which doesn't make sense to me since it's all running from my PC, I have access to the directory, it runs fine via command line and via Visual Studio.

Environment

MS SQL Server 2014 (v12.0.5546.0)

MS Visual Studio 15 (v14 Update 3)


问:
Purpose of cmove instruction in x86 assembly?
When disassembling an executable I encountered the cmove instruction. I've already searched on the Internet but I've only found that it's a conditional move, and if the source and destination are equal a mov occurs. What I don't understand yet is why I need it, since it doesn't change the operands. What is its purpose?

答:
The purpose of cmov is to allow software (in some cases) to avoid a branch.

For example, if you have this code:

```<code>    cmp eax,ebx
    jne .l1
    mov eax,edx
.l1:
</code>```

..then when a modern CPU sees the jne branch it will take a guess about whether the branch will be taken or not taken, and then start speculatively executing instructions based on the guess. If the guess is wrong there's a performance penalty, because the CPU has to discard any speculatively executed work and then start fetching and executing the correct path.

For a conditional move (e.g. cmove eax,edx) the CPU doesn't need to guess which code will be executed and the cost of a mispredicted branch is avoided. However, the CPU can't know if the value in eax will change or not, which means that later instructions that depend on the results of the conditional move have to wait until the conditional move completes (instead of being speculatively executed with an assumed value and not stalling).

This means that if the branch can be easily predicted a branch can be faster; and if the branch can't be easily predicted the condition move can be faster.

Note that a conditional move is never strictly needed (it can always be done with a branch instead) - it's more like an optional optimization.

Body:
The purpose of cmov is to allow software (in some cases) to avoid a branch.

For example, if you have this code:

    cmp eax,ebx
    jne .l1
    mov eax,edx
.l1:

..then when a modern CPU sees the jne branch it will take a guess about whether the branch will be taken or not taken, and then start speculatively executing instructions based on the guess. If the guess is wrong there's a performance penalty, because the CPU has to discard any speculatively executed work and then start fetching and executing the correct path.

For a conditional move (e.g. cmove eax,edx) the CPU doesn't need to guess which code will be executed and the cost of a mispredicted branch is avoided. However, the CPU can't know if the value in eax will change or not, which means that later instructions that depend on the results of the conditional move have to wait until the conditional move completes (instead of being speculatively executed with an assumed value and not stalling).

This means that if the branch can be easily predicted a branch can be faster; and if the branch can't be easily predicted the condition move can be faster.

Note that a conditional move is never strictly needed (it can always be done with a branch instead) - it's more like an optional optimization.


问:
Nested routing in angular 7, using modules and lazy loading
I am having trouble creating angular routes. I have implemented feature modules and I am using routing for each of those modules. I want the routes to go from app to layout to dashboard and then to accounts. The route is not created properly, it seems dashboard is being skipped and route goes directly to accounts. Here is what it looks like when i use augury to debug the routes.

Here is my code for each route. each route is in a module of its own. I would really like to keep the routes separated in modules. Any suggestions would be greatly appreciated.

//app routes

const appRoutes: Routes = [
  { path: "login", component: LoginComponent },
  {
    path: "",
    canActivate: [AuthGaurdService],
    loadChildren: "./layouts/layouts.module#LayoutsModule"
  },
  { path: "**", component: PageNotFoundComponent }
];

//layout routes

const LayoutRoutes: Routes = [
  {
    path: "",
    component: LayoutsComponent,
    canActivate: [AuthGaurdService],
    children: [
      {
        path: "",
        canActivateChild: [AuthGaurdService],
        children: [
          {
            path: "account-information",
            loadChildren: "../account-information/account-information.module#AccountInformationModule"
          },
          {
            path: "",
            loadChildren: "../dashboard/dashboard.module#DashboardModule"
          },
        ]
      }

    ]
  }
];

//dashboard routes

const routes: Routes = [
  {
    path: "",
    component: DashboardComponent,
    canActivate: [AuthGaurdService],
    children: [{
      path: "",
      canActivateChild: [AuthGaurdService],
      children: [
        {
          path: "accounts",
          loadChildren: "./accounts/accounts.module#AccountsModule"
        },
        {
          path: "",
          component: HomeComponent
        }
      ]
    }]
  }
];

//account routes

const AccountsRoutes: Routes = [
  {
    path: "accounts",
    component: AccountsComponent,
    canActivate: [AuthGaurdService],
    children: [
      {
        path: "",
        canActivateChild: [AuthGaurdService],
        children: [
          { path: "transactions", component: TransactionsComponent },
          { path: "summary", component: SummaryComponent },
          { path: "earnings", component: EarningsComponent }
        ]
      }

    ]
  }
];```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--app.html -->
<router-outlet></router-outlet>

<!-- layout.html -->
<div class="page-container">
  <app-navbar></app-navbar>
  <div class="page-content-wrapper ">
    <div class="content">
      <router-outlet></router-outlet>
    </div>
    <div class="container-fluid container-fixed-lg footer">
      <app-footer></app-footer>
    </div>
  </div>
</div>

<!-- dashboard.html -->
<div class="page-container">
  <app-navbar></app-navbar>
  <div class="page-content-wrapper ">
    <div class="content">
      <router-outlet></router-outlet>
    </div>
    <div class="container-fluid container-fixed-lg footer">
      <app-footer></app-footer>
    </div>
  </div>
</div>

<!-- accounts -->
<router-outlet></router-outlet></code>```

this is what my page looks like when i to home

this is the for accounts/summary

and my side menu looks like this
let retail: Array<Menu> = [
  {
    name: "Home",
    router_link: "",
    submenu: [],
    toggle_submenu: false,
    icon: ""
  },
  {
    name: "Accounts",
    router_link: "accounts/summary",
    toggle_submenu: false,
    icon: "",
    submenu: [
      {
        name: "Summary",
        router_link: "accounts/summary",
        toggle_submenu: false,
        icon: "",
        submenu: []
      },
      {
        name: "Tansactions",
        router_link: "accounts/transactions",
        toggle_submenu: false,
        icon: "",
        submenu: []
      },
      {
        name: "Earnings",
        router_link: "accounts/earnings",
        toggle_submenu: false,
        icon: "",
        submenu: []
      }
    ]
  },
  {
    name: "Sales",
    router_link: "sales",
    toggle_submenu: false,
    icon: "",
    submenu: []
  },
  {
    name: "Inventory",
    router_link: "inventory",
    toggle_submenu: false,
    icon: "",
    submenu: []
  },
  {
    name: "Upload",
    router_link: "upload",
    toggle_submenu: false,
    icon: "",
    submenu: []
  }
];

答:
As I havn't seen your complete code, my guess is that your not able to properly navigate to your routes.

When you use lazy loaded modules, you don't need to provide the the prefix in child routes. For example In your AppModule:

```<code>{
    path: '', component: HomeComponent
    },
   {path: 'dashboard',
    loadChildren: './dashboard/dashboard.module#DashboardModule'
  }
</code>```

And in your DashboardModule

```<code>{
    path: '', component: DashboardComponent,
  },{
    path: 'accounts',
    loadChildren: '../accounts/accounts.module#AccountsModule'
  }
</code>```

Then in order to go to a route in your dashboard.component.html
You will write

```<code><a [routerLink]="['accounts']"> Account</a>
</code>```

Instead of

```<code><a [routerLink]="['/dashboard', 'accounts']"> Account</a>
</code>```

because in child lazy loaded modules the root path starts from the parent module which loaded it.

I have created a stackblitz demo with a similar scenario.

Hope it helps.

Body:
I am having trouble creating angular routes. I have implemented feature modules and I am using routing for each of those modules. I want the routes to go from app to layout to dashboard and then to accounts. The route is not created properly, it seems dashboard is being skipped and route goes directly to accounts. Here is what it looks like when i use augury to debug the routes.

Here is my code for each route. each route is in a module of its own. I would really like to keep the routes separated in modules. Any suggestions would be greatly appreciated.

//app routes

const appRoutes: Routes = [
  { path: "login", component: LoginComponent },
  {
    path: "",
    canActivate: [AuthGaurdService],
    loadChildren: "./layouts/layouts.module#LayoutsModule"
  },
  { path: "**", component: PageNotFoundComponent }
];

//layout routes

const LayoutRoutes: Routes = [
  {
    path: "",
    component: LayoutsComponent,
    canActivate: [AuthGaurdService],
    children: [
      {
        path: "",
        canActivateChild: [AuthGaurdService],
        children: [
          {
            path: "account-information",
            loadChildren: "../account-information/account-information.module#AccountInformationModule"
          },
          {
            path: "",
            loadChildren: "../dashboard/dashboard.module#DashboardModule"
          },
        ]
      }

    ]
  }
];

//dashboard routes

const routes: Routes = [
  {
    path: "",
    component: DashboardComponent,
    canActivate: [AuthGaurdService],
    children: [{
      path: "",
      canActivateChild: [AuthGaurdService],
      children: [
        {
          path: "accounts",
          loadChildren: "./accounts/accounts.module#AccountsModule"
        },
        {
          path: "",
          component: HomeComponent
        }
      ]
    }]
  }
];

//account routes

const AccountsRoutes: Routes = [
  {
    path: "accounts",
    component: AccountsComponent,
    canActivate: [AuthGaurdService],
    children: [
      {
        path: "",
        canActivateChild: [AuthGaurdService],
        children: [
          { path: "transactions", component: TransactionsComponent },
          { path: "summary", component: SummaryComponent },
          { path: "earnings", component: EarningsComponent }
        ]
      }

    ]
  }
];

<router-outlet></router-outlet>

  <app-navbar></app-navbar>

      <router-outlet></router-outlet>

      <app-footer></app-footer>

  <app-navbar></app-navbar>

      <router-outlet></router-outlet>

      <app-footer></app-footer>

<router-outlet></router-outlet>

this is what my page looks like when i to home

this is the for accounts/summary

and my side menu looks like this
let retail: Array<Menu> = [
  {
    name: "Home",
    router_link: "",
    submenu: [],
    toggle_submenu: false,
    icon: ""
  },
  {
    name: "Accounts",
    router_link: "accounts/summary",
    toggle_submenu: false,
    icon: "",
    submenu: [
      {
        name: "Summary",
        router_link: "accounts/summary",
        toggle_submenu: false,
        icon: "",
        submenu: []
      },
      {
        name: "Tansactions",
        router_link: "accounts/transactions",
        toggle_submenu: false,
        icon: "",
        submenu: []
      },
      {
        name: "Earnings",
        router_link: "accounts/earnings",
        toggle_submenu: false,
        icon: "",
        submenu: []
      }
    ]
  },
  {
    name: "Sales",
    router_link: "sales",
    toggle_submenu: false,
    icon: "",
    submenu: []
  },
  {
    name: "Inventory",
    router_link: "inventory",
    toggle_submenu: false,
    icon: "",
    submenu: []
  },
  {
    name: "Upload",
    router_link: "upload",
    toggle_submenu: false,
    icon: "",
    submenu: []
  }
];

Body:
As I havn't seen your complete code, my guess is that your not able to properly navigate to your routes.

When you use lazy loaded modules, you don't need to provide the the prefix in child routes. For example In your AppModule:

{
    path: '', component: HomeComponent
    },
   {path: 'dashboard',
    loadChildren: './dashboard/dashboard.module#DashboardModule'
  }

And in your DashboardModule

{
    path: '', component: DashboardComponent,
  },{
    path: 'accounts',
    loadChildren: '../accounts/accounts.module#AccountsModule'
  }

Then in order to go to a route in your dashboard.component.html
You will write

<a [routerLink]="['accounts']"> Account</a>

Instead of

<a [routerLink]="['/dashboard', 'accounts']"> Account</a>

because in child lazy loaded modules the root path starts from the parent module which loaded it.

I have created a stackblitz demo with a similar scenario.

Hope it helps.


问:
bitshifting does not propertly work for short values
I've a little problem with bitshifting short values:

```<code>System.out.println(Integer.toBinaryString(0b1100010001000100 >>> 12); // works correctly, output: 1100
System.out.println(Integer.toBinaryString( 0xFFFF & (short)(0b1100010001000100) >>> 12)) // does not work correctly, output: 1111111111111100
</code>```

What's the problem and how can I handle it?

答:
To be clear, 0xFFFF & (short)(0b1100010001000100) >>> 12 means 0xFFFF & ((short)(0b1100010001000100) >>> 12). So the bitwise AND is last, after shifting.

There is a rule that a short is converted to int before shifting (and most other operations), so that short is first sign-extended to a int, more leading ones appear because the value is negative. If the bitwise AND happened between this implicit conversion and the shift, the extra ones would be removed:

```<code>(0xFFFF & (short)(0b1100010001000100)) >>> 12
</code>```

Body:
I've a little problem with bitshifting short values:

System.out.println(Integer.toBinaryString(0b1100010001000100 >>> 12); // works correctly, output: 1100
System.out.println(Integer.toBinaryString( 0xFFFF & (short)(0b1100010001000100) >>> 12)) // does not work correctly, output: 1111111111111100

What's the problem and how can I handle it?

Body:
To be clear, 0xFFFF & (short)(0b1100010001000100) >>> 12 means 0xFFFF & ((short)(0b1100010001000100) >>> 12). So the bitwise AND is last, after shifting.

There is a rule that a short is converted to int before shifting (and most other operations), so that short is first sign-extended to a int, more leading ones appear because the value is negative. If the bitwise AND happened between this implicit conversion and the shift, the extra ones would be removed:

(0xFFFF & (short)(0b1100010001000100)) >>> 12


问:
Aligning elements side by side in HTML
I am working on a website(this is my first website as a developer) and I was wondering if someone could help me align these to items next to each other horizontally. I don't know how to code HTML so I am completely unfamiliar with this. For the most part when developing sites I go and make due with what is online to help but this instance I am with your help.

The site is using WordPress and this is going to be a page. With a table from W-P Table reloaded and a Google map.
Here is the code currently:

```<code><p style="text-align: left;">[table id=4 /]<small></small></p><p style="text-align: right;">
<iframe src="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=Avie's+SKi+Sports+100+Main+Street,+Westerly,+R+02891-2194&aq=&sll=41.375316,-71.831092&sspn=0.006948,0.016512&vpsrc=0&g=100+Main+Street,+Westerly,+R+02891-2194&ie=UTF8&hq=Avie's+SKi+Sports+100+Main+Street,+Westerly,+R+02891-2194&hnear=&radius=15000&t=m&ll=41.379063,-71.831102&spn=0.015457,0.027466&z=15&iwloc=lyrftr:m,9024240540147588029,41.375323,-71.831043&output=embed" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" width="640" height="480"></iframe>
<small><a style="color: #0000ff; text-align: left;" href="http://maps.google.com/maps?f=q&source=embed&hl=en&geocode=&q=Avie%27s+SKi+Sports+100+Main+Street,+Westerly,+R+02891-2194&aq=&sll=41.375316,-71.831092&sspn=0.006948,0.016512&vpsrc=0&g=100+Main+Street,+Westerly,+R+02891-2194&ie=UTF8&hq=Avie%27s+SKi+Sports+100+Main+Street,+Westerly,+R+02891-2194&hnear=&radius=15000&t=m&ll=41.379063,-71.831102&spn=0.015457,0.027466&z=15&iwloc=lyrftr:m,9024240540147588029,41.375323,-71.831043">View Larger Map</a></small></p>
</code>```

答: I had a similar problem. I tried to use the CSS route but failed. If you are using Wordpress the easiest way would be to place 2 columns in the section you want the division. then place one element in each and then target their HTML codes accordingly. </p>

Title: Aligning elements side by side in HTML

Body:
I am working on a website(this is my first website as a developer) and I was wondering if someone could help me align these to items next to each other horizontally. I don't know how to code HTML so I am completely unfamiliar with this. For the most part when developing sites I go and make due with what is online to help but this instance I am with your help.

The site is using WordPress and this is going to be a page. With a table from W-P Table reloaded and a Google map.
Here is the code currently:

[table id=4 /]

<iframe src="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=Avie's+SKi+Sports+100+Main+Street,+Westerly,+R+02891-2194&aq=&sll=41.375316,-71.831092&sspn=0.006948,0.016512&vpsrc=0&g=100+Main+Street,+Westerly,+R+02891-2194&ie=UTF8&hq=Avie's+SKi+Sports+100+Main+Street,+Westerly,+R+02891-2194&hnear=&radius=15000&t=m&ll=41.379063,-71.831102&spn=0.015457,0.027466&z=15&iwloc=lyrftr:m,9024240540147588029,41.375323,-71.831043&output=embed" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" width="640" height="480">
<a style="color: #0000ff; text-align: left;" href="http://maps.google.com/maps?f=q&source=embed&hl=en&geocode=&q=Avie%27s+SKi+Sports+100+Main+Street,+Westerly,+R+02891-2194&aq=&sll=41.375316,-71.831092&sspn=0.006948,0.016512&vpsrc=0&g=100+Main+Street,+Westerly,+R+02891-2194&ie=UTF8&hq=Avie%27s+SKi+Sports+100+Main+Street,+Westerly,+R+02891-2194&hnear=&radius=15000&t=m&ll=41.379063,-71.831102&spn=0.015457,0.027466&z=15&iwloc=lyrftr:m,9024240540147588029,41.375323,-71.831043">View Larger Map


问:
Manipulate some of the numeric value columns in a data frame that includes characters as well
I have a data frame with both character and numeric columns. In some of the numeric columns, I would like to test if the value is grater than 1 and if so, I would like to change it to 1.

I have managed to turn all different from 0 values to 1 but that includes characters and a column I want to leave untouched as well...

Example data frame:

```<code>> species<- c("Pinus halepensis", "Majorana syriaca", "Iris
> palaestina","Velezia fasciculata")
> rarness<- c("F", "CC", "F", "O")
> endangered<-c(0,0,0,6.8) plot1<- c(1,2,1,1) plot2<- c(0,1,0,0)
> df<-as.data.frame(cbind(species, rarness, endangered, plot1, plot2))
</code>```

This does not work for some reason:

```<code>Test<-df %>%
  mutate(plot1 = ifelse(plot1 > 1, 1, plot1))
</code>```

This works but changes characters as well

```<code>df[df>1]<-1
</code>```

I would like the columns "plot1" and "Plot2" to consist only of characters 0 and 1 while others remain the same.

Thanks!

Idan

答:
You can also make a copy before applying you condition. You need to specify the columns to process only those column. If you have just two columns, you can do it manualy like this:

```<code># Create copy
test <- df

# Update specific column
test$plot1[(as.numeric(test$plot1)) > 1]  <- 1
test$plot2[(as.numeric(test$plot2)) > 1]  <- 1
test
#               species rarness endangered plot1 plot2
# 1    Pinus halepensis       F          0     1     0
# 2    Majorana syriaca      CC          0     1     1
# 3     Iris palaestina       F          0     1     0
# 4 Velezia fasciculata       O        6.8     1     0
</code>```

Generalisation:

Now, suppose you want to process a set of columns. You can re-use the previous tips in a function that you apply to all columns. I suggest you to have a look at the apply family. Here a nice explanation. In our task, lapply seems appropriated (doc).

```<code># Your dataframe
species<- c("Pinus halepensis", "Majorana syriaca", "Iris palaestina","Velezia fasciculata")
rarness<- c("F", "CC", "F", "O")
endangered<-c(0,0,0,6.8)
plot1<- c(1,2,1,1)
plot2<- c(0,1,0,0)
df<- as.data.frame(cbind(species, rarness, endangered, plot1, plot2))

# Extend the dataframe with new random columns for the example
df2 <- data.frame(replicate(10,sample(-5:5,4,rep=TRUE)))
df[names(df2)] <-  df2
df
#               species rarness endangered plot1 plot2 X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
# 1    Pinus halepensis       F          0     1     0 -4 -2  4  4  0  5 -1 -5  3   2
# 2    Majorana syriaca      CC          0     2     1  5 -3 -2  3  3 -1  0  5  2   4
# 3     Iris palaestina       F          0     1     0 -1  2 -2  5  3  2  3  3 -1  -3
# 4 Velezia fasciculata       O        6.8     1     0 -5 -3  4  5  5 -4  4 -5 -4  -3

# Create copy
test <- df

# Function to apply at each column
set_threshold <- function(col){
  col <- as.numeric(col);
  col[col > 1]  <- 1;
  return (col);
}

# Select all column names after the index 4
col_names <- tail(names(test),-3)
col_names
# [1] "plot1" "plot2" "X1"    "X2"    "X3"    "X4"    "X5"    "X6"    "X7"    "X8"    "X9"    "X10"

# Process each column
test[col_names] <- lapply(test[col_names], FUN = set_threshold)
test
#               species rarness endangered plot1 plot2 X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
# 1    Pinus halepensis       F          0     1     1 -4 -2  1  1  0  1 -1 -5  1   1
# 2    Majorana syriaca      CC          0     1     1  1 -3 -2  1  1 -1  0  1  1   1
# 3     Iris palaestina       F          0     1     1 -1  1 -2  1  1  1  1  1 -1  -3
# 4 Velezia fasciculata       O        6.8     1     1 -5 -3  1  1  1 -4  1 -5 -4  -3
</code>```

I use tail to select all the columns names after the index 4 (e.g. remove all element until index 3) (doc). A discussion on how to subset a list.

Body:
I have a data frame with both character and numeric columns. In some of the numeric columns, I would like to test if the value is grater than 1 and if so, I would like to change it to 1.

I have managed to turn all different from 0 values to 1 but that includes characters and a column I want to leave untouched as well...

Example data frame:

> species<- c("Pinus halepensis", "Majorana syriaca", "Iris
> palaestina","Velezia fasciculata")
> rarness<- c("F", "CC", "F", "O")
> endangered<-c(0,0,0,6.8) plot1<- c(1,2,1,1) plot2<- c(0,1,0,0)
> df<-as.data.frame(cbind(species, rarness, endangered, plot1, plot2))

This does not work for some reason:

Test<-df %>%
  mutate(plot1 = ifelse(plot1 > 1, 1, plot1))

This works but changes characters as well

df[df>1]<-1

I would like the columns "plot1" and "Plot2" to consist only of characters 0 and 1 while others remain the same.

Thanks!

Idan

Body:
You can also make a copy before applying you condition. You need to specify the columns to process only those column. If you have just two columns, you can do it manualy like this:

# Create copy
test <- df

# Update specific column
test$plot1[(as.numeric(test$plot1)) > 1]  <- 1
test$plot2[(as.numeric(test$plot2)) > 1]  <- 1
test
#               species rarness endangered plot1 plot2
# 1    Pinus halepensis       F          0     1     0
# 2    Majorana syriaca      CC          0     1     1
# 3     Iris palaestina       F          0     1     0
# 4 Velezia fasciculata       O        6.8     1     0

Generalisation:

Now, suppose you want to process a set of columns. You can re-use the previous tips in a function that you apply to all columns. I suggest you to have a look at the apply family. Here a nice explanation. In our task, lapply seems appropriated (doc).

# Your dataframe
species<- c("Pinus halepensis", "Majorana syriaca", "Iris palaestina","Velezia fasciculata")
rarness<- c("F", "CC", "F", "O")
endangered<-c(0,0,0,6.8)
plot1<- c(1,2,1,1)
plot2<- c(0,1,0,0)
df<- as.data.frame(cbind(species, rarness, endangered, plot1, plot2))

# Extend the dataframe with new random columns for the example
df2 <- data.frame(replicate(10,sample(-5:5,4,rep=TRUE)))
df[names(df2)] <-  df2
df
#               species rarness endangered plot1 plot2 X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
# 1    Pinus halepensis       F          0     1     0 -4 -2  4  4  0  5 -1 -5  3   2
# 2    Majorana syriaca      CC          0     2     1  5 -3 -2  3  3 -1  0  5  2   4
# 3     Iris palaestina       F          0     1     0 -1  2 -2  5  3  2  3  3 -1  -3
# 4 Velezia fasciculata       O        6.8     1     0 -5 -3  4  5  5 -4  4 -5 -4  -3

# Create copy
test <- df

# Function to apply at each column
set_threshold <- function(col){
  col <- as.numeric(col);
  col[col > 1]  <- 1;
  return (col);
}

# Select all column names after the index 4
col_names <- tail(names(test),-3)
col_names
# [1] "plot1" "plot2" "X1"    "X2"    "X3"    "X4"    "X5"    "X6"    "X7"    "X8"    "X9"    "X10"

# Process each column
test[col_names] <- lapply(test[col_names], FUN = set_threshold)
test
#               species rarness endangered plot1 plot2 X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
# 1    Pinus halepensis       F          0     1     1 -4 -2  1  1  0  1 -1 -5  1   1
# 2    Majorana syriaca      CC          0     1     1  1 -3 -2  1  1 -1  0  1  1   1
# 3     Iris palaestina       F          0     1     1 -1  1 -2  1  1  1  1  1 -1  -3
# 4 Velezia fasciculata       O        6.8     1     1 -5 -3  1  1  1 -4  1 -5 -4  -3

I use tail to select all the columns names after the index 4 (e.g. remove all element until index 3) (doc). A discussion on how to subset a list.


问:
Download Folder as Zip Google Drive API
I currently have a Google App Script in Google Sheet that gives me the URL of a folder, which I can then use to download. Though it is an extra step I would like to remove, and get the URL of the zipped content directly.

Here's my code (google app script):

```<code>function downloadSelectedScripts() {
  // ...
  var scriptFiles = getScriptFiles(scriptFileNames)
  var tempFolder = copyFilesToTempFolder(scriptFiles)
  Browser.msgBox(tempFolder.getUrl())
}

function copyFilesToTempFolder(files) {
  var tempFolder = DriveApp.getFolderById(FOLDERS.TEMP)
  var tempSubFolder = tempFolder.createFolder('download_' + Date.now())

  for (var i in files) {
    var file = files[i]
    file.makeCopy(file.getName(), tempSubFolder)
  }

  return tempSubFolder
}
</code>```

答:
You want to compress all files in a folder as a zip file.

The folder has no subfolders.

All files are only text files.

The total size of all files is less than 50 MB.

You want to retrieve the URL for downloading the zip file.

If my understanding is correct, how about this sample script? The flow of this script is as follows.

Retrieve folder.

Retrieve blobs of all files in the folder.

Compress blobs and retrieve a blob of zip.

Create a zip blob as a file.

Retrieve URL for downloading.

Sample script:

When you use this script, please set the folder ID of folder that you want to compress.

```<code>function myFunction() {
  var folderId = "###"; // Please set the folder ID here.

  var folder = DriveApp.getFolderById(folderId);
  var files = folder.getFiles();
  var blobs = [];
  while (files.hasNext()) {
    blobs.push(files.next().getBlob());
  }
  var zipBlob = Utilities.zip(blobs, folder.getName() + ".zip");
  var fileId = DriveApp.createFile(zipBlob).getId();
  var url = "https://drive.google.com/uc?export=download&id=" + fileId;
  Logger.log(url);
}
</code>```

Result:

The direct link of the zip file is returned as follows.

```<code>https://drive.google.com/uc?export=download&id=###
</code>```

Note:

In the current stage, unfortunately, the folders cannot be included in the zip data with Google Apps Script.

In this sample script, the filename of zip file is the folder name. So please modify it for your situation.

If you want to download the zip file without login to Google, please share the file.

Reference:

zip(blobs, name)

Title: Download Folder as Zip Google Drive API

Body:
I currently have a Google App Script in Google Sheet that gives me the URL of a folder, which I can then use to download. Though it is an extra step I would like to remove, and get the URL of the zipped content directly.

Here's my code (google app script):

function downloadSelectedScripts() {
  // ...
  var scriptFiles = getScriptFiles(scriptFileNames)
  var tempFolder = copyFilesToTempFolder(scriptFiles)
  Browser.msgBox(tempFolder.getUrl())
}

function copyFilesToTempFolder(files) {
  var tempFolder = DriveApp.getFolderById(FOLDERS.TEMP)
  var tempSubFolder = tempFolder.createFolder('download_' + Date.now())

  for (var i in files) {
    var file = files[i]
    file.makeCopy(file.getName(), tempSubFolder)
  }

  return tempSubFolder
}

Body:
You want to compress all files in a folder as a zip file.

The folder has no subfolders.

All files are only text files.

The total size of all files is less than 50 MB.

You want to retrieve the URL for downloading the zip file.

If my understanding is correct, how about this sample script? The flow of this script is as follows.

Retrieve folder.

Retrieve blobs of all files in the folder.

Compress blobs and retrieve a blob of zip.

Create a zip blob as a file.

Retrieve URL for downloading.

Sample script:

When you use this script, please set the folder ID of folder that you want to compress.

function myFunction() {
  var folderId = "###"; // Please set the folder ID here.

  var folder = DriveApp.getFolderById(folderId);
  var files = folder.getFiles();
  var blobs = [];
  while (files.hasNext()) {
    blobs.push(files.next().getBlob());
  }
  var zipBlob = Utilities.zip(blobs, folder.getName() + ".zip");
  var fileId = DriveApp.createFile(zipBlob).getId();
  var url = "https://drive.google.com/uc?export=download&id=" + fileId;
  Logger.log(url);
}

Result:

The direct link of the zip file is returned as follows.

https://drive.google.com/uc?export=download&id=###

Note:

In the current stage, unfortunately, the folders cannot be included in the zip data with Google Apps Script.

In this sample script, the filename of zip file is the folder name. So please modify it for your situation.

If you want to download the zip file without login to Google, please share the file.

Reference:

zip(blobs, name)


问:
Trying to display any number that is entered into a url, using Django 1.1
I'm currently learning regex patterns, using DJango 1.1. More specifically, I am trying to display whatever number is entered into the url using the '\d+' pattern. I'm brand new to DJango, so I hope that description wasn't too vague. Any help would be greatly appreciated.

My urls.py url pattern is:

url(r'^(?P<number>\d+)$', views.show)
```

<p>My <strong>views.py</strong> method is: </p>

<pre class="lang-py prettyprint-override"><code>def show(request, number):
    return HttpResponse("placeholder to display blog number: {number}")
</code>```

I don't quite understand what i'm missing.

If I enter the number 20 into my url: localhost:0000/20, I'm expecting to see an output of:

placeholder to display number: 20
```

<p>But instead, I get an output of:</p>

<pre class="lang-py prettyprint-override"><code>placeholder to display number: {number}
</code>```

答:
Update HttpResponse to:

```<code>return HttpResponse(<b>f</b>"placeholder to display blog number: {number}")</code>```

More information can be found on documentation regarding formatted string literals.

FYI: this solution will work for python 3.6+, for other python versions you can format the string in following way:

```<code>return HttpResponse(
    "placeholder to display blog number: {number}".format(number=number)
)</code>```

Body:
I'm currently learning regex patterns, using DJango 1.1. More specifically, I am trying to display whatever number is entered into the url using the '\d+' pattern. I'm brand new to DJango, so I hope that description wasn't too vague. Any help would be greatly appreciated.

My urls.py url pattern is:

url(r'^(?P<number>\d+)$', views.show)

My views.py method is:

def show(request, number):
    return HttpResponse("placeholder to display blog number: {number}")

I don't quite understand what i'm missing.

If I enter the number 20 into my url: localhost:0000/20, I'm expecting to see an output of:

placeholder to display number: 20

But instead, I get an output of:

placeholder to display number: {number}

Body:
Update HttpResponse to:

return HttpResponse(f"placeholder to display blog number: {number}")

More information can be found on documentation regarding formatted string literals.

FYI: this solution will work for python 3.6+, for other python versions you can format the string in following way:

return HttpResponse(
    "placeholder to display blog number: {number}".format(number=number)
)


问:
Boost.Test: Looking for a working non-Trivial Test Suite Example / Tutorial
The Boost.Test documentation and examples don't really seem to contain any non-trivial examples and so far the two tutorials I've found here and here while helpful are both fairly basic.

I would like to have a master test suite for the entire project, while maintaining per module suites of unit tests and fixtures that can be run independently.  I'll also be using a mock server to test various networking edge cases.

I'm on Ubuntu 8.04, but I'll take any example Linux or Windows since I'm writing my own makefiles anyways.

Edit

As a test I did the following:

```<code>// test1.cpp
#define BOOST_TEST_MODULE Regression
#include <boost/test/included/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(test1_suite)

BOOST_AUTO_TEST_CASE(Test1)
{
    BOOST_CHECK(2 < 1);
}

BOOST_AUTO_TEST_SUITE_END()

// test2.cpp
#include <boost/test/included/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(test2_suite)

BOOST_AUTO_TEST_CASE(Test1)
{
    BOOST_CHECK(1<2);
}

BOOST_AUTO_TEST_SUITE_END()
</code>```

Then I compile it:    g++ test1.cpp test2.cpp -o tests

This gives me about a bazillion "multiple definition of" errors during linking.

When it's all in a single file it works fine.

答:
When I only start with Boost.Test the following article with source code was very helpful:
Boost test setup and usage</p>

Body:
The Boost.Test documentation and examples don't really seem to contain any non-trivial examples and so far the two tutorials I've found here and here while helpful are both fairly basic.

I would like to have a master test suite for the entire project, while maintaining per module suites of unit tests and fixtures that can be run independently.  I'll also be using a mock server to test various networking edge cases.

I'm on Ubuntu 8.04, but I'll take any example Linux or Windows since I'm writing my own makefiles anyways.

Edit

As a test I did the following:

// test1.cpp
#define BOOST_TEST_MODULE Regression
#include <boost/test/included/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(test1_suite)

BOOST_AUTO_TEST_CASE(Test1)
{
    BOOST_CHECK(2 < 1);
}

BOOST_AUTO_TEST_SUITE_END()

// test2.cpp
#include <boost/test/included/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(test2_suite)

BOOST_AUTO_TEST_CASE(Test1)
{
    BOOST_CHECK(1<2);
}

BOOST_AUTO_TEST_SUITE_END()

Then I compile it:    g++ test1.cpp test2.cpp -o tests

This gives me about a bazillion "multiple definition of" errors during linking.

When it's all in a single file it works fine.


问:
I want to know the versions that I need to use to run a java selenium code
When I ran a simple java selenium code to start faceboook application, I am getting error "Timed out waiting for driver server to start."

```<code>Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_211'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:202)
    at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:188)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
    at newpackage.PractAuto.main(PractAuto.java:10)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:40026/status] to be available after 20002 ms
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:197)
    ... 9 more
Caused by: java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:156)
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
    ... 10 more
</code>```

My Code:

```<code>package newpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

public class PractAuto {
    public static void main(String[] args) throws InterruptedException {
          System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");
          WebDriver driver = new ChromeDriver();
          driver.manage().window().maximize();
          driver.get("https://www.facebook.com/login/");
          Thread.sleep(5000);
          driver.findElement(By.name("email")).sendKeys("arunkumar3625@gmail.com");
          driver.findElement(By.name("pass")).sendKeys("Password");
          driver.findElement(By.id("loginbutton")).click();
          driver.findElement(By.name("mercurymessages")).click();
          driver.findElement(By.cssSelector("a[href*='https://www.facebook.com/messages/conversation-8148306']")).click();

    }
</code>```

Chrome browser is opening successfully but I'm getting the above error.

答:
You can check the latest version for selenium and the webdrivers through this link
https://www.seleniumhq.org/download/

Also, you can share your code for better understanding of the error reason.

After checking your code, you are setting the property of the driver to a wrong path. Property webdriver.chrome.driver should be the chrome driver not the chrome executable file.

Download it from that link: https://www.seleniumhq.org/download/

Body:
When I ran a simple java selenium code to start faceboook application, I am getting error "Timed out waiting for driver server to start."

Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_211'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:202)
    at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:188)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
    at newpackage.PractAuto.main(PractAuto.java:10)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:40026/status] to be available after 20002 ms
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:197)
    ... 9 more
Caused by: java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:156)
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
    ... 10 more

My Code:

package newpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

public class PractAuto {
    public static void main(String[] args) throws InterruptedException {
          System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");
          WebDriver driver = new ChromeDriver();
          driver.manage().window().maximize();
          driver.get("https://www.facebook.com/login/");
          Thread.sleep(5000);
          driver.findElement(By.name("email")).sendKeys("arunkumar3625@gmail.com");
          driver.findElement(By.name("pass")).sendKeys("Password");
          driver.findElement(By.id("loginbutton")).click();
          driver.findElement(By.name("mercurymessages")).click();
          driver.findElement(By.cssSelector("a[href*='https://www.facebook.com/messages/conversation-8148306']")).click();

    }

Chrome browser is opening successfully but I'm getting the above error.


问:
How to correctly display a multi - criteria dataset on a heatmap?
I have a dataset in a numpy array in the below format. Each "column" is a separate criteria. I want to display a heatmap where each "column" would correspond to the score range within that column:

[[ 226      600   3.33    915.     92.6    98.6 ]
  [ 217      700   3.34    640.    93.7    98.5 ]
  [ 213      900   3.35    662.    88.8    96.  ]
  ...
  [ 108      600    2.31   291.     64.     70.4 ]
  [ 125      800    3.36   1094.    65.5    84.1 ]
  [ 109      400    2.44   941.     52.3    68.7 ]]

I have written a function to generate a heatmap:

```<code>def HeatMap(data):

    #generate heatmap figure
    figure = plt.figure()
    sub_figure = figure.add_subplot(111)
    heatmap = sub_figure.imshow(data, interpolation='nearest',cmap='jet', aspect=0.05)

    #generate color bar
    cbar = figure.colorbar(ax=sub_figure, mappable=heatmap, orientation='horizontal')
    cbar.set_label('Scores')

    plt.show()
</code>```

This is what the function generates:

As per above, it can be seen that the problem lies in my function somewhere as the Scores range from 0 to a maximum value in the dataset of 2500. How can I amend my function so that the heatmap displays the scores in the columns according to their range rather than the range of the whole dataset? My first thoughts are to change the array dimensions to something like [[226],[600]] etc. but not sure if that's the solution

Thanks for your help

答:
You cannot have a separate cmap for each column.

If you want to see the variation in each column as per their own range, you can normalize the data by column before plotting the heatmap.

Code

import numpy as np

x = np.array([[1000,  10,   0.5],
              [ 765,   5,  0.35],
              [ 800,   7,  0.09]])

x_normed = x / x.max(axis=0)

print(x_normed)
# [[ 1.     1.     1.   ]
#  [ 0.765  0.5    0.7  ]
#  [ 0.8    0.7    0.18 ]]

# Plot the heatmap for x_normed.
```

This will preserve the variation in each column.

Body:
I have a dataset in a numpy array in the below format. Each "column" is a separate criteria. I want to display a heatmap where each "column" would correspond to the score range within that column:

[[ 226      600   3.33    915.     92.6    98.6 ]
  [ 217      700   3.34    640.    93.7    98.5 ]
  [ 213      900   3.35    662.    88.8    96.  ]
  ...
  [ 108      600    2.31   291.     64.     70.4 ]
  [ 125      800    3.36   1094.    65.5    84.1 ]
  [ 109      400    2.44   941.     52.3    68.7 ]]

I have written a function to generate a heatmap:

def HeatMap(data):

    #generate heatmap figure
    figure = plt.figure()
    sub_figure = figure.add_subplot(111)
    heatmap = sub_figure.imshow(data, interpolation='nearest',cmap='jet', aspect=0.05)

    #generate color bar
    cbar = figure.colorbar(ax=sub_figure, mappable=heatmap, orientation='horizontal')
    cbar.set_label('Scores')

    plt.show()

This is what the function generates:

As per above, it can be seen that the problem lies in my function somewhere as the Scores range from 0 to a maximum value in the dataset of 2500. How can I amend my function so that the heatmap displays the scores in the columns according to their range rather than the range of the whole dataset? My first thoughts are to change the array dimensions to something like [[226],[600]] etc. but not sure if that's the solution

Thanks for your help

Body:
You cannot have a separate cmap for each column.

If you want to see the variation in each column as per their own range, you can normalize the data by column before plotting the heatmap.

Code

import numpy as np

x = np.array([[1000,  10,   0.5],
              [ 765,   5,  0.35],
              [ 800,   7,  0.09]])

x_normed = x / x.max(axis=0)

print(x_normed)
# [[ 1.     1.     1.   ]
#  [ 0.765  0.5    0.7  ]
#  [ 0.8    0.7    0.18 ]]

# Plot the heatmap for x_normed.

This will preserve the variation in each column.