问:
Vlookups in SQL
I am attempting to write a Query that will pull in a description for each Segment of an account code. The table looks like :

What I am wanting to do is have each CTRC section to pull in the CTDESC for the CTACCT that matches Example:

My original data has over 4 million rows so i cannot export to excel in order to do a normal Vlookup. I only have one table with all of this data and have not been able to get self join to be able to pull in all rows I can only do it one section at a time.

```<code>SELECT TOP 10
       RTRIM(a.CTACCT) AS [CTACCT],
       RTRIM(a.CTRC01) AS [CTRC01],
       NULLIF(CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02)), CONCAT(RTRIM(a.CTrc01), '-')) AS [CTRC02],
       NULLIF(CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-', RTRIM(a.CTrc03)), CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-')) AS [CTRC03],
       NULLIF(CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-', RTRIM(a.CTrc03), '-', RTRIM(a.CTrc04)), CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-', RTRIM(a.CTrc03), '-')) AS [CTRC04],
       NULLIF(CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-', RTRIM(a.CTrc03), '-', RTRIM(a.CTrc04), '-', RTRIM(a.CTrc05)), CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-', RTRIM(a.CTrc03), '-', RTRIM(a.CTrc04), '-')) AS [CTRC05],
       NULLIF(CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-', RTRIM(a.CTrc03), '-', RTRIM(a.CTrc04), '-', RTRIM(a.CTrc05), '-', RTRIM(a.CTrc06)), CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-', RTRIM(a.CTrc03), '-', RTRIM(a.CTrc04), '-', RTRIM(a.CTrc05), '-')) AS [CTRC06],
       a.CTDESC AS [CTDESC],
       a.CTSEGN AS [CTSEGN]
FROM [PSA].[dbo].[SMFD35_GLDBFA_GLPCT] a WITH (NOLOCK);
</code>```

I am using SQL Server.

答:
There's a couple ways to do this, since you already have the values in your tables one approach would be to add an id field from the original table and tag which CTRC (LevelNr) corresponds to the CTACCT in the results:

```<code>select A.CTACCT, max(B.CTRC01) AS CTRC01,
  max(case when B.LevelNr = 1 then B.Description else null end) AS CTRC01_Description,
  max(case when A.LevelNr >=2 then B.CTRC02 else null end) AS CTRC02,
  max(case when A.LevelNr >=2 and B.LevelNr = 2 then B.Description else null end) AS CTRC02_Description,
  max(case when A.LevelNr >=3 then B.CTRC03 else null end) AS CTRC03,
  max(case when A.LevelNr >=3 and B.LevelNr = 3 then B.Description else null end) AS CTRC03_Description
from @MyResults A
  inner join @MyResults B on A.id = B.id
group by A.[CTACCT], A.id, A.LevelNr
order by A.[CTACCT], A.id, A.LevelNr
</code>```

Results:

```<code>CT_ACCT        CTRC01 CTRC01_Description CTRC02   CTRC02_Description CTRC03        CTRC03_Description
001            001    Company            NULL     NULL               NULL          NULL
001-0000       001    Company            001-0000 Department         NULL          NULL
001-0000-0000  001    Company            001-0000 Department         001-0000-0000 Location
</code>```

This should really be a discussion about database design, though.  If you have data that stores each CTRC value separately that's where grouping functions like STRING_AGG() and PIVOT come into play.

Assuming you can get your data in a state like below using UNION queries:

```<code>id RowNr CTAcct
1  1     001
1  2     0000
1  3     0000
2  1     002
2  2     0000
2  3     0000
</code>```

You can then get all your account numbers and descriptions together as below (STRING_AGG is nicer, but FOR XML will do the trick for your version):

```<code>select [CTACCT], id, RowNr, Description
from
(
select RowNr, id,
  STUFF((SELECT '-' + [CTACCT]
    from @CTACCTS A where A.[id] = T.[id] and A.[RowNr] <= T.[RowNr]
    FOR XML PATH('')),1, 1,'') as [CTACCT]
from @CTACCTS T
) A left join @CTDESCRIPTIONS D ON A.[CTACCT] = D.[CTACCT]
</code>```

Results:

```<code>CTACCT        id RowNr Description
001           1  1     Company
001-0000      1  2     Department
001-0000-0000 1  3     Location
</code>```

Finally you can then do something similar to the above to group things back together.  This may seem like extra work but has the advantage of avoiding redundancy.

Of course, you could also do a series of update statements, but generally non-set based routines aren't recommended in SQL Server.

Title: Vlookups in SQL

Body:
I am attempting to write a Query that will pull in a description for each Segment of an account code. The table looks like :

What I am wanting to do is have each CTRC section to pull in the CTDESC for the CTACCT that matches Example:

My original data has over 4 million rows so i cannot export to excel in order to do a normal Vlookup. I only have one table with all of this data and have not been able to get self join to be able to pull in all rows I can only do it one section at a time.

SELECT TOP 10
       RTRIM(a.CTACCT) AS [CTACCT],
       RTRIM(a.CTRC01) AS [CTRC01],
       NULLIF(CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02)), CONCAT(RTRIM(a.CTrc01), '-')) AS [CTRC02],
       NULLIF(CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-', RTRIM(a.CTrc03)), CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-')) AS [CTRC03],
       NULLIF(CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-', RTRIM(a.CTrc03), '-', RTRIM(a.CTrc04)), CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-', RTRIM(a.CTrc03), '-')) AS [CTRC04],
       NULLIF(CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-', RTRIM(a.CTrc03), '-', RTRIM(a.CTrc04), '-', RTRIM(a.CTrc05)), CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-', RTRIM(a.CTrc03), '-', RTRIM(a.CTrc04), '-')) AS [CTRC05],
       NULLIF(CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-', RTRIM(a.CTrc03), '-', RTRIM(a.CTrc04), '-', RTRIM(a.CTrc05), '-', RTRIM(a.CTrc06)), CONCAT(RTRIM(a.CTrc01), '-', RTRIM(a.CTrc02), '-', RTRIM(a.CTrc03), '-', RTRIM(a.CTrc04), '-', RTRIM(a.CTrc05), '-')) AS [CTRC06],
       a.CTDESC AS [CTDESC],
       a.CTSEGN AS [CTSEGN]
FROM [PSA].[dbo].[SMFD35_GLDBFA_GLPCT] a WITH (NOLOCK);

I am using SQL Server.

Body:
There's a couple ways to do this, since you already have the values in your tables one approach would be to add an id field from the original table and tag which CTRC (LevelNr) corresponds to the CTACCT in the results:

select A.CTACCT, max(B.CTRC01) AS CTRC01,
  max(case when B.LevelNr = 1 then B.Description else null end) AS CTRC01_Description,
  max(case when A.LevelNr >=2 then B.CTRC02 else null end) AS CTRC02,
  max(case when A.LevelNr >=2 and B.LevelNr = 2 then B.Description else null end) AS CTRC02_Description,
  max(case when A.LevelNr >=3 then B.CTRC03 else null end) AS CTRC03,
  max(case when A.LevelNr >=3 and B.LevelNr = 3 then B.Description else null end) AS CTRC03_Description
from @MyResults A
  inner join @MyResults B on A.id = B.id
group by A.[CTACCT], A.id, A.LevelNr
order by A.[CTACCT], A.id, A.LevelNr

Results:

CT_ACCT        CTRC01 CTRC01_Description CTRC02   CTRC02_Description CTRC03        CTRC03_Description
001            001    Company            NULL     NULL               NULL          NULL
001-0000       001    Company            001-0000 Department         NULL          NULL
001-0000-0000  001    Company            001-0000 Department         001-0000-0000 Location

This should really be a discussion about database design, though.  If you have data that stores each CTRC value separately that's where grouping functions like STRING_AGG() and PIVOT come into play.

Assuming you can get your data in a state like below using UNION queries:

id RowNr CTAcct
1  1     001
1  2     0000
1  3     0000
2  1     002
2  2     0000
2  3     0000

You can then get all your account numbers and descriptions together as below (STRING_AGG is nicer, but FOR XML will do the trick for your version):

select [CTACCT], id, RowNr, Description
from
(
select RowNr, id,
  STUFF((SELECT '-' + [CTACCT]
    from @CTACCTS A where A.[id] = T.[id] and A.[RowNr] <= T.[RowNr]
    FOR XML PATH('')),1, 1,'') as [CTACCT]
from @CTACCTS T
) A left join @CTDESCRIPTIONS D ON A.[CTACCT] = D.[CTACCT]

Results:

CTACCT        id RowNr Description
001           1  1     Company
001-0000      1  2     Department
001-0000-0000 1  3     Location

Finally you can then do something similar to the above to group things back together.  This may seem like extra work but has the advantage of avoiding redundancy.

Of course, you could also do a series of update statements, but generally non-set based routines aren't recommended in SQL Server.


来源: stackexchange

问:
Two-way data-binding with double value in EditText
In Android we can use 2-way data-binding with @= in front of variable. But, that variable is a double. So for displaying it in EditText, I need to convert it to String using String.valueOf(pojo.value).

If I attach = in front for two-way data binding it simply just not compile.

If I attach a onTextChanged and set the value there, I looses the cursor. Is there any workaround?

Edit:

It worked with InverseBindingAdapter but doesn't allow . (period)  to be typed.

答:
Here's how I did it.

```<code>    //-------------------------------------------------------------------------------------------------//

    @BindingAdapter("app:text")
    fun setDoubleInTextView(tv: TextView, dbl: Double?) {

        try {
              //This will occur when view is first created or when the leading zero is omitted
        if (dbl == null && (tv.text.toString() == "" || tv.text.toString() == ".")) return

            //Check to see what's already there
            val tvDbl = tv.text.toString().toDouble()
            //If it's the same as what we've just entered then return
            // This is when then the double was typed rather than binded
            if (tvDbl == dbl)
                return

            //If it's a new number then set it in the tv
            tv.text = dbl?.toString()

        } catch (nfe: java.lang.NumberFormatException) {

            //This is usually caused when tv.text is blank and we've entered the first digit
            tv.text = dbl?.toString() ?: ""

        }//catch

    }//setDoubleInTextView

    //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//

    @InverseBindingAdapter(attribute = "app:text")
    fun getDoubleFromTextView(editText: TextView): Double? {

        return try {
            editText.text.toString().toDouble()
        } catch (e: NumberFormatException) {
            null
        }//catch

    }//getDoubleFromTextView

    //-------------------------------------------------------------------------------------------------//

    @BindingAdapter("textAttrChanged")
    fun setTextChangeListener(editText: TextView, listener: InverseBindingListener) {
        editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) = listener.onChange()

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                Log.d(TAG, "beforeTextChanged $p0")
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                Log.d(TAG, "onTextChanged $p0")
            }

        })
    }

    //-------------------------------------------------------------------------------------------------//

  <EditText
    style="@style/TextAppearance.MaterialComponents.Body1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/price"
    android:inputType="numberDecimal"
    app:text="@={viewModel.tempProductPrice}"/>
</code>```

The EditText has the following setting to force the correct input

```<code>    android:inputType="numberDecimal"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here's how I did it.

    //-------------------------------------------------------------------------------------------------//

    @BindingAdapter("app:text")
    fun setDoubleInTextView(tv: TextView, dbl: Double?) {

        try {
              //This will occur when view is first created or when the leading zero is omitted
        if (dbl == null && (tv.text.toString() == "" || tv.text.toString() == ".")) return

            //Check to see what's already there
            val tvDbl = tv.text.toString().toDouble()
            //If it's the same as what we've just entered then return
            // This is when then the double was typed rather than binded
            if (tvDbl == dbl)
                return

            //If it's a new number then set it in the tv
            tv.text = dbl?.toString()

        } catch (nfe: java.lang.NumberFormatException) {

            //This is usually caused when tv.text is blank and we've entered the first digit
            tv.text = dbl?.toString() ?: ""

        }//catch

    }//setDoubleInTextView

    //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//

    @InverseBindingAdapter(attribute = "app:text")
    fun getDoubleFromTextView(editText: TextView): Double? {

        return try {
            editText.text.toString().toDouble()
        } catch (e: NumberFormatException) {
            null
        }//catch

    }//getDoubleFromTextView

    //-------------------------------------------------------------------------------------------------//

    @BindingAdapter("textAttrChanged")
    fun setTextChangeListener(editText: TextView, listener: InverseBindingListener) {
        editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) = listener.onChange()

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                Log.d(TAG, "beforeTextChanged $p0")
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                Log.d(TAG, "onTextChanged $p0")
            }

        })
    }

    //-------------------------------------------------------------------------------------------------//

  <EditText
    style="@style/TextAppearance.MaterialComponents.Body1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/price"
    android:inputType="numberDecimal"
    app:text="@={viewModel.tempProductPrice}"/>

The EditText has the following setting to force the correct input

    android:inputType="numberDecimal"

ContentLicense: CC BY-SA 4.0


问:
Django Blog App urls functionality
I am trying to integrate the following blog APP https://github.com/nathanborror/django-basic-apps ,so in my main urls.py i have included the blog urls as (r'^blog/',include('basic.blog.urls')),  Now my question is that now when i point my browser to the blog APP http://127.0.0.1/blog/ i get a message as "Post archive",How to proceed from here i.e, how to post blog and retrieve the same.What is the url to be used..The following is the blog urls

```<code>from django.conf.urls.defaults import *

urlpatterns = patterns('basic.blog.views',
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$',
    view='post_detail',
    name='blog_detail'
),
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/$',
    view='post_archive_day',
    name='blog_archive_day'
),
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/$',
    view='post_archive_month',
    name='blog_archive_month'
),
url(r'^(?P<year>\d{4})/$',
    view='post_archive_year',
    name='blog_archive_year'
),
url(r'^categories/(?P<slug>[-\w]+)/$',
    view='category_detail',
    name='blog_category_detail'
),
url (r'^categories/$',
    view='category_list',
    name='blog_category_list'
),
url(r'^tags/(?P<slug>[-\w]+)/$',
    view='tag_detail',
    name='blog_tag_detail'
),
url (r'^search/$',
    view='search',
    name='blog_search'
),
url(r'^page/(?P<page>\d+)/$',
    view='post_list',
    name='blog_index_paginated'
),
url(r'^$',
    view='post_list',
   name='blog_index'
),
)
</code>```

答: There are no URLs specific to post creation, so you need to do it via the Admin interface. I looked at the code and there is a specific template for creating/modifying post objects.

Title: Django Blog App urls functionality

Body:
I am trying to integrate the following blog APP https://github.com/nathanborror/django-basic-apps ,so in my main urls.py i have included the blog urls as (r'^blog/',include('basic.blog.urls')),  Now my question is that now when i point my browser to the blog APP http://127.0.0.1/blog/ i get a message as "Post archive",How to proceed from here i.e, how to post blog and retrieve the same.What is the url to be used..The following is the blog urls

from django.conf.urls.defaults import *

urlpatterns = patterns('basic.blog.views',
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$',
    view='post_detail',
    name='blog_detail'
),
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/$',
    view='post_archive_day',
    name='blog_archive_day'
),
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/$',
    view='post_archive_month',
    name='blog_archive_month'
),
url(r'^(?P<year>\d{4})/$',
    view='post_archive_year',
    name='blog_archive_year'
),
url(r'^categories/(?P<slug>[-\w]+)/$',
    view='category_detail',
    name='blog_category_detail'
),
url (r'^categories/$',
    view='category_list',
    name='blog_category_list'
),
url(r'^tags/(?P<slug>[-\w]+)/$',
    view='tag_detail',
    name='blog_tag_detail'
),
url (r'^search/$',
    view='search',
    name='blog_search'
),
url(r'^page/(?P<page>\d+)/$',
    view='post_list',
    name='blog_index_paginated'
),
url(r'^$',
    view='post_list',
   name='blog_index'
),
)


问:
Deserialize JSON to List in C# in a console application
Error

Cannot deserialize the current JSON object (e.g. {"name":"value"})
  into type 'System.Collections.Generic.List`1[ConsoleApp1.Menu]'
  because the type requires a JSON array (e.g. [1,2,3]) to deserialize
  correctly. To fix this error either change the JSON to a JSON array
  (e.g. [1,2,3]) or change the deserialized type so that it is a normal
  .NET type (e.g. not a primitive type like integer, not a collection
  type like an array or List) that can be deserialized from a JSON
  object. JsonObjectAttribute can also be added to the type to force it
  to deserialize from a JSON object. Path 'Test', line 3, position 9.

Question

Why do I get this error?

At the end I want to achieve to write every menu item in the console. For now I am stuck with this error. How do I achieve a result (Output) like this:

```<code>ID: 1 Name: Frosted Pumpkin Bread
ID: 2 Name: Ground to Go
...
</code>```

The Console application

```<code>using System;
using System.Collections.Generic;
using System.Net;
using Newtonsoft.Json;

namespace ConsoleApp1
{
    public class MenuItem
    {
        public string ID { get; set; }
        public string Description { get; set; }
        public string Summary { get; set; }
        public string Name { get; set; }
        public string ImageFile { get; set; }
    }

    public class Menu
    {
        public List<MenuItem> Test { get; set; }
    }

    class Program
    {

        static void Main(string[] args)
        {
          var webclient = new WebClient();
          var json = webclient.DownloadString(@"C:\Users\devuser\source\repos\ConsoleApp1\ConsoleApp1\data.json");
          var model = JsonConvert.DeserializeObject<List<Menu>>(json);

            foreach (var item in model)
            {
                Console.WriteLine();
            }
        }
    }
}
</code>```

My JSON-File looks like this

```<code>
{

  "Test": [

    {
      "ID": "1",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "A seasonal delight we offer every autumn.  Pumpking bread with just a bit of spice, cream cheese frosting with just a hint of home.",
      "Name": "Frosted Pumpkin Bread",
      "ImageFile": "pumpkinbread.png"
    },
    {
      "ID": "2",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "Love our coffee? Take it with you so you never have to be without!",
      "Name": "Ground to Go",
      "ImageFile": "granola.png"
    },
    {
      "ID": "3",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "Do you prefer to grind your own coffee? No problem, we'll give you the beans.",
      "Name": "Bean there, done that!",
      "ImageFile": "beans.jpg"
    },
    {
      "ID": "4",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "They're just as round as donuts, but far more healthy! Freshly made every morning before sunrise.",
      "Name": "Fresh Bagels",
      "ImageFile": "bagel.png"
    },
    {
      "ID": "5",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "We've got strawberries, blueberries, apples, bananas - we could list them all, but we'd prefer you come take a look!",
      "Name": "Fresh Fruit",
      "ImageFile": "strawberries.png"
    }
  ]
}
</code>```

答:
Change this line

```<code>var model = JsonConvert.DeserializeObject<List<Menu>>(json);
</code>```

to

```<code>var model = JsonConvert.DeserializeObject<Menu>(json);
</code>```

This is because given json represents an object Menu which contains a List<MenuItem> called Test.

Sample code.

DotNetFiddle Code Link

P.S. Sample code used a string initialisation instead of loading json from a file.

Body:
Error

Cannot deserialize the current JSON object (e.g. {"name":"value"})
  into type 'System.Collections.Generic.List`1[ConsoleApp1.Menu]'
  because the type requires a JSON array (e.g. [1,2,3]) to deserialize
  correctly. To fix this error either change the JSON to a JSON array
  (e.g. [1,2,3]) or change the deserialized type so that it is a normal
  .NET type (e.g. not a primitive type like integer, not a collection
  type like an array or List) that can be deserialized from a JSON
  object. JsonObjectAttribute can also be added to the type to force it
  to deserialize from a JSON object. Path 'Test', line 3, position 9.

Question

Why do I get this error?

At the end I want to achieve to write every menu item in the console. For now I am stuck with this error. How do I achieve a result (Output) like this:

ID: 1 Name: Frosted Pumpkin Bread
ID: 2 Name: Ground to Go
...

The Console application

using System;
using System.Collections.Generic;
using System.Net;
using Newtonsoft.Json;

namespace ConsoleApp1
{
    public class MenuItem
    {
        public string ID { get; set; }
        public string Description { get; set; }
        public string Summary { get; set; }
        public string Name { get; set; }
        public string ImageFile { get; set; }
    }

    public class Menu
    {
        public List<MenuItem> Test { get; set; }
    }

    class Program
    {

        static void Main(string[] args)
        {
          var webclient = new WebClient();
          var json = webclient.DownloadString(@"C:\Users\devuser\source\repos\ConsoleApp1\ConsoleApp1\data.json");
          var model = JsonConvert.DeserializeObject<List<Menu>>(json);

            foreach (var item in model)
            {
                Console.WriteLine();
            }
        }
    }
}

My JSON-File looks like this

{

  "Test": [

    {
      "ID": "1",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "A seasonal delight we offer every autumn.  Pumpking bread with just a bit of spice, cream cheese frosting with just a hint of home.",
      "Name": "Frosted Pumpkin Bread",
      "ImageFile": "pumpkinbread.png"
    },
    {
      "ID": "2",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "Love our coffee? Take it with you so you never have to be without!",
      "Name": "Ground to Go",
      "ImageFile": "granola.png"
    },
    {
      "ID": "3",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "Do you prefer to grind your own coffee? No problem, we'll give you the beans.",
      "Name": "Bean there, done that!",
      "ImageFile": "beans.jpg"
    },
    {
      "ID": "4",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "They're just as round as donuts, but far more healthy! Freshly made every morning before sunrise.",
      "Name": "Fresh Bagels",
      "ImageFile": "bagel.png"
    },
    {
      "ID": "5",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "We've got strawberries, blueberries, apples, bananas - we could list them all, but we'd prefer you come take a look!",
      "Name": "Fresh Fruit",
      "ImageFile": "strawberries.png"
    }
  ]
}

Body:
Change this line

var model = JsonConvert.DeserializeObject<List<Menu>>(json);

to

var model = JsonConvert.DeserializeObject<Menu>(json);

This is because given json represents an object Menu which contains a List<MenuItem> called Test.

Sample code.

DotNetFiddle Code Link

P.S. Sample code used a string initialisation instead of loading json from a file.


问:
Resharper Alt Enter not working
Help, I can't function without Resharper. All of a sudden my Alt+Enter ↵ shortcut (to bring up the action list) has stopped working. Anybody experienced this or know how to fix?

答:
Thanks Josh ... your suggestion worked for me. The steps I took on VS 2010 were:

ReSharper -> Options -> Environment -> Visual Studio Integration ->
  Keyboard Shortcuts (Visual Studio) -> Apply Scheme (button)

Title: Resharper Alt Enter not working


问:
I'm getting this error for my verilog code, "Illegal operation for constant expression"
when ever I compile this code, I get the following errors.

```<code>module mv2_generate
(
    input [127:0] c_array [1:0],
    input [127:0] p_array [1:0],
    input [127:0] p1_array [1:0],
    output reg [15:0] min_mv
);

   //genvar index;
   integer a, b, index, m;
  //genvar m;
  // a= (m*7)+m+7;
  // b= (m*7)+m;

   reg [7:0] read_dataC;  //registers for C,P,P'
   reg [7:0] read_dataP;
   reg [7:0] read_dataP1;
   reg [15:0] out_pe0;
   reg pe0_en;
   pe PE0(.a(read_dataC),.b(read_dataP),.en(pe0_en),.pe_out(out_pe0));

always @*
begin
//generate
   for (index=0; index<2; index=index+1)
    begin
    // assign  n=n+1;
    //  a=7;
    //  b=0;

      for (m=0; m<16; m=m+1)
      begin
       if(index<2)
        begin
         if (m>=0)
          begin
           read_dataC = c_array [index] [(m*7)+m+7:(m*7)+m];
           read_dataP = p_array [index] [(m*7)+m+7:(m*7)+m];
           // read_dataC = c_array [index] [a:b];
          // read_dataP = p_array [index] [a:b];
          #50;
          $display("pe out: %d",out_pe0);
          //pe PE0(read_dataC, read_dataP, out_pe0);
         end

       // a= a+8;
       // b= b+8;
       end
      end
    end
  end
//endgenerate

     //assign min_mv= out_pe0;

endmodule

 //
 module pe(input [7:0] a, input [7:0] b, input en, output reg [7:0] pe_out);
       //reg [15:0] acc_temp = acc;
        always @* begin
        //$display("End of Sim: %d", en);
         if(en) begin
               if (a<b) begin
                        assign pe_out = b - a;
                 end
                 else if (a==b) begin
                       assign pe_out = 8'd0;
                 end
                 else begin
                       assign pe_out = a - b;
                 end
                 //acc_temp = acc_temp + pe_out;
                 //acc = acc_temp;
                  //$display("End of Sim: %d", acc);
             end
             else begin
              pe_out = 8'd0;
             end
             end
        endmodule
</code>```

The errors

```<code>ncverilog(64): 15.20-s029: (c) Copyright 1995-2017 Cadence Design Systems, Inc.
file: mv2test.v
           read_dataC = c_array [index] [(m*7)+m+7:(m*7)+m];
                                          |
ncvlog: *E,NOTPAR (mv2test.v,38|42): Illegal operand for constant expression [4(IEEE)].
           read_dataC = c_array [index] [(m*7)+m+7:(m*7)+m];
                                               |
ncvlog: *E,NOTPAR (mv2test.v,38|47): Illegal operand for constant expression [4(IEEE)].
           read_dataC = c_array [index] [(m*7)+m+7:(m*7)+m];
                                                    |
ncvlog: *E,NOTPAR (mv2test.v,38|52): Illegal operand for constant expression [4(IEEE)].
           read_dataC = c_array [index] [(m*7)+m+7:(m*7)+m];
                                                         |
ncvlog: *E,NOTPAR (mv2test.v,38|57): Illegal operand for constant expression [4(IEEE)].
           read_dataP = p_array [index] [(m*7)+m+7:(m*7)+m];
                                          |
ncvlog: *E,NOTPAR (mv2test.v,39|42): Illegal operand for constant expression [4(IEEE)].
           read_dataP = p_array [index] [(m*7)+m+7:(m*7)+m];
                                               |
ncvlog: *E,NOTPAR (mv2test.v,39|47): Illegal operand for constant expression [4(IEEE)].
           read_dataP = p_array [index] [(m*7)+m+7:(m*7)+m];
                                                    |
ncvlog: *E,NOTPAR (mv2test.v,39|52): Illegal operand for constant expression [4(IEEE)].
           read_dataP = p_array [index] [(m*7)+m+7:(m*7)+m];
                                                         |
ncvlog: *E,NOTPAR (mv2test.v,39|57): Illegal operand for constant expression [4(IEEE)].
    module worklib.mv2_generate:v
        errors: 8, warnings: 0
module pe(input [7:0] a, input [7:0] b, input en, output reg [7:0] pe_out);
        |
ncvlog: *W,RECOME (mv2test.v,83|8): recompiling design unit worklib.pe:v.
    First compiled from line 59 of mv2test.v.
ncverilog: *E,VLGERR: An error occurred during parsing.  Review the log file for errors with the code *E and fix those identified problems to proceed.  Exiting with code (status 1).
</code>```

答:
This is illegal in Verilog (and SystemVerilog):

```<code>c_array [index] [(m*7)+m+7:(m*7)+m];
</code>```

Specifically, you cannot have a variable on the right hand side of a : in a part select. Instead you need to write either this:

```<code>c_array [index] [(m*7)+m+7 -: 8];
</code>```

or this:

```<code>c_array [index] [(m*7)+m +: 8];
</code>```

The value on the left hand side of the -: and +: operators is the starting index. The number on the right hand side is the width. This must be constant. Hence, your error. The -: operator counts down from the starting index; the +: operator counts up. The direction of the original array declaration does not matter: you can use either operator irrespective of the direction of the array.

Body:
when ever I compile this code, I get the following errors.

module mv2_generate
(
    input [127:0] c_array [1:0],
    input [127:0] p_array [1:0],
    input [127:0] p1_array [1:0],
    output reg [15:0] min_mv
);

   //genvar index;
   integer a, b, index, m;
  //genvar m;
  // a= (m*7)+m+7;
  // b= (m*7)+m;

   reg [7:0] read_dataC;  //registers for C,P,P'
   reg [7:0] read_dataP;
   reg [7:0] read_dataP1;
   reg [15:0] out_pe0;
   reg pe0_en;
   pe PE0(.a(read_dataC),.b(read_dataP),.en(pe0_en),.pe_out(out_pe0));

always @*
begin
//generate
   for (index=0; index<2; index=index+1)
    begin
    // assign  n=n+1;
    //  a=7;
    //  b=0;

      for (m=0; m<16; m=m+1)
      begin
       if(index<2)
        begin
         if (m>=0)
          begin
           read_dataC = c_array [index] [(m*7)+m+7:(m*7)+m];
           read_dataP = p_array [index] [(m*7)+m+7:(m*7)+m];
           // read_dataC = c_array [index] [a:b];
          // read_dataP = p_array [index] [a:b];
          #50;
          $display("pe out: %d",out_pe0);
          //pe PE0(read_dataC, read_dataP, out_pe0);
         end

       // a= a+8;
       // b= b+8;
       end
      end
    end
  end
//endgenerate

     //assign min_mv= out_pe0;

endmodule

 //
 module pe(input [7:0] a, input [7:0] b, input en, output reg [7:0] pe_out);
       //reg [15:0] acc_temp = acc;
        always @* begin
        //$display("End of Sim: %d", en);
         if(en) begin
               if (a<b) begin
                        assign pe_out = b - a;
                 end
                 else if (a==b) begin
                       assign pe_out = 8'd0;
                 end
                 else begin
                       assign pe_out = a - b;
                 end
                 //acc_temp = acc_temp + pe_out;
                 //acc = acc_temp;
                  //$display("End of Sim: %d", acc);
             end
             else begin
              pe_out = 8'd0;
             end
             end
        endmodule

The errors

ncverilog(64): 15.20-s029: (c) Copyright 1995-2017 Cadence Design Systems, Inc.
file: mv2test.v
           read_dataC = c_array [index] [(m*7)+m+7:(m*7)+m];
                                          |
ncvlog: *E,NOTPAR (mv2test.v,38|42): Illegal operand for constant expression [4(IEEE)].
           read_dataC = c_array [index] [(m*7)+m+7:(m*7)+m];
                                               |
ncvlog: *E,NOTPAR (mv2test.v,38|47): Illegal operand for constant expression [4(IEEE)].
           read_dataC = c_array [index] [(m*7)+m+7:(m*7)+m];
                                                    |
ncvlog: *E,NOTPAR (mv2test.v,38|52): Illegal operand for constant expression [4(IEEE)].
           read_dataC = c_array [index] [(m*7)+m+7:(m*7)+m];
                                                         |
ncvlog: *E,NOTPAR (mv2test.v,38|57): Illegal operand for constant expression [4(IEEE)].
           read_dataP = p_array [index] [(m*7)+m+7:(m*7)+m];
                                          |
ncvlog: *E,NOTPAR (mv2test.v,39|42): Illegal operand for constant expression [4(IEEE)].
           read_dataP = p_array [index] [(m*7)+m+7:(m*7)+m];
                                               |
ncvlog: *E,NOTPAR (mv2test.v,39|47): Illegal operand for constant expression [4(IEEE)].
           read_dataP = p_array [index] [(m*7)+m+7:(m*7)+m];
                                                    |
ncvlog: *E,NOTPAR (mv2test.v,39|52): Illegal operand for constant expression [4(IEEE)].
           read_dataP = p_array [index] [(m*7)+m+7:(m*7)+m];
                                                         |
ncvlog: *E,NOTPAR (mv2test.v,39|57): Illegal operand for constant expression [4(IEEE)].
    module worklib.mv2_generate:v
        errors: 8, warnings: 0
module pe(input [7:0] a, input [7:0] b, input en, output reg [7:0] pe_out);
        |
ncvlog: *W,RECOME (mv2test.v,83|8): recompiling design unit worklib.pe:v.
    First compiled from line 59 of mv2test.v.
ncverilog: *E,VLGERR: An error occurred during parsing.  Review the log file for errors with the code *E and fix those identified problems to proceed.  Exiting with code (status 1).

Body:
This is illegal in Verilog (and SystemVerilog):

c_array [index] [(m*7)+m+7:(m*7)+m];

Specifically, you cannot have a variable on the right hand side of a : in a part select. Instead you need to write either this:

c_array [index] [(m*7)+m+7 -: 8];

or this:

c_array [index] [(m*7)+m +: 8];

The value on the left hand side of the -: and +: operators is the starting index. The number on the right hand side is the width. This must be constant. Hence, your error. The -: operator counts down from the starting index; the +: operator counts up. The direction of the original array declaration does not matter: you can use either operator irrespective of the direction of the array.


问:
Reversing CGRect - Swift
How can I reverse my origin.x? my origin.x started from right I want start from left. For example these origins of x in my application started from the far right:

1) 351.0

2) 304.0

3) 257.0

4) 210.0

5) 163.0

6) 116.0

7) 69.0

8) 22.0

How can I reverse these origins and started from 22.0 and end to 351.0 ?

Code:

```<code>var ansWithoutSpaces = String()
ansWithoutSpaces = answersString.replacingOccurrences(of: " ", with: "")

var targetHeigt = CGFloat()
let viewWidth = self.view.frame.size.width

if viewWidth == 320 {
    targetHeigt = 2.5
} else {
    targetHeigt = 5
}

let yAxis : Int = Int((self.view.frame.height) * 60%)
let lenghtOfChar = ansWithoutSpaces as NSString
// char count
let width: Int = Int(view.frame.size.width) - 40
// frame width
var targetWidth: Int = (width - (lenghtOfChar.length - 1) * 5) / lenghtOfChar.length

if targetWidth > 50 {
    if viewWidth == 320 {
        targetWidth = 38
    } else if viewWidth == 375 {
        targetWidth = 45
    } else {
        targetWidth = 50
    }
}

let totalWidth: Int = (targetWidth * lenghtOfChar.length) + ((lenghtOfChar.length - 1) * 5)

for x in 0..<ansWithoutSpaces.count {
    let xAxis: Int = (width / 2) - (totalWidth / 2) + (x * targetWidth) + (x * 5) + 20
    let targetLabel = UILabel(frame: CGRect(x: CGFloat(xAxis), y: CGFloat(yAxis), width: CGFloat(targetWidth), height: targetHeigt))

        ...
}
</code>```

答:
@Nordeast solved it:</p>

```<code>for x in (0..<ansWithoutSpaces.count).reversed() {
        ...
}
</code>```

Title: Reversing CGRect - Swift

Body:
How can I reverse my origin.x? my origin.x started from right I want start from left. For example these origins of x in my application started from the far right:

1) 351.0

2) 304.0

3) 257.0

4) 210.0

5) 163.0

6) 116.0

7) 69.0

8) 22.0

How can I reverse these origins and started from 22.0 and end to 351.0 ?

Code:

var ansWithoutSpaces = String()
ansWithoutSpaces = answersString.replacingOccurrences(of: " ", with: "")

var targetHeigt = CGFloat()
let viewWidth = self.view.frame.size.width

if viewWidth == 320 {
    targetHeigt = 2.5
} else {
    targetHeigt = 5
}

let yAxis : Int = Int((self.view.frame.height) * 60%)
let lenghtOfChar = ansWithoutSpaces as NSString
// char count
let width: Int = Int(view.frame.size.width) - 40
// frame width
var targetWidth: Int = (width - (lenghtOfChar.length - 1) * 5) / lenghtOfChar.length

if targetWidth > 50 {
    if viewWidth == 320 {
        targetWidth = 38
    } else if viewWidth == 375 {
        targetWidth = 45
    } else {
        targetWidth = 50
    }
}

let totalWidth: Int = (targetWidth * lenghtOfChar.length) + ((lenghtOfChar.length - 1) * 5)

for x in 0..<ansWithoutSpaces.count {
    let xAxis: Int = (width / 2) - (totalWidth / 2) + (x * targetWidth) + (x * 5) + 20
    let targetLabel = UILabel(frame: CGRect(x: CGFloat(xAxis), y: CGFloat(yAxis), width: CGFloat(targetWidth), height: targetHeigt))

        ...
}

Body:
@Nordeast solved it:

for x in (0..<ansWithoutSpaces.count).reversed() {
        ...
}


问:
Why does not my code in C++ that declares an (local) int array without doing anything initialize by zeros?
I have two C++ codes in which the one has an global int array while the other code has a local array whose length is determined by user input (so at runtime).
Both arrays are not explicitly initialized.

#include <iostream>
using namespace std;
int M = 1000;
int a[M];
int main() {
  for(int i = 0; i < M; i++)
    cout << a[i];
  cout << endl;
}
```

<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
using namespace std;
int main() {
  int M;
  cin >> M;
  int a[M];
  for(int i = 0; i < M; i++)
    cout << a[i];
  cout << endl;
}

</code>```

I observed that the global array is filled with zeros, while the local array (whose length is determined at runtime) is not filled with zeros and instead filled with a random numbers (but same at a time).
I used the g++ compiler.

What is this behavior?
Does C++ standard define this behavior?

答:
From the C++ 17 Standard (11.6 Initializers)

12 If no initializer is specified for an object, the object is
  default-initialized. When storage for an object with automatic or
  dynamic storage duration is obtained, the object has an indeterminate
  value, and if no initialization is performed for the object, that
  object retains an indeterminate value until that value is replaced
  (8.18). [ Note: Objects with static or thread storage duration are
  zero-initialized, see 6.6.2. — end note ]

So the array declared in the global namespace has the static storage duration and zero-initialized

While the array declared in main has the automatic storage duration and has indeterminate values of its elements.

Pay attention to that the variable length arrays is not a standard C++ feature.

```<code>int M = 1000;
int a[M];
</code>```

or

```<code>cin >> M;
int a[M];
</code>```

That is the both programs are not standard compliant.

And moreover variable length arrays may not be explicitly initialized in a declaration.

They can be supported by some compilers as their own language extensions.

Body:
I have two C++ codes in which the one has an global int array while the other code has a local array whose length is determined by user input (so at runtime).
Both arrays are not explicitly initialized.

#include <iostream>
using namespace std;
int M = 1000;
int a[M];
int main() {
  for(int i = 0; i < M; i++)
    cout << a[i];
  cout << endl;
}

#include <iostream>
using namespace std;
int main() {
  int M;
  cin >> M;
  int a[M];
  for(int i = 0; i < M; i++)
    cout << a[i];
  cout << endl;
}

I observed that the global array is filled with zeros, while the local array (whose length is determined at runtime) is not filled with zeros and instead filled with a random numbers (but same at a time).
I used the g++ compiler.

What is this behavior?
Does C++ standard define this behavior?

Body:
From the C++ 17 Standard (11.6 Initializers)

12 If no initializer is specified for an object, the object is
  default-initialized. When storage for an object with automatic or
  dynamic storage duration is obtained, the object has an indeterminate
  value, and if no initialization is performed for the object, that
  object retains an indeterminate value until that value is replaced
  (8.18). [ Note: Objects with static or thread storage duration are
  zero-initialized, see 6.6.2. — end note ]

So the array declared in the global namespace has the static storage duration and zero-initialized

While the array declared in main has the automatic storage duration and has indeterminate values of its elements.

Pay attention to that the variable length arrays is not a standard C++ feature.

int M = 1000;
int a[M];

or

cin >> M;
int a[M];

That is the both programs are not standard compliant.

And moreover variable length arrays may not be explicitly initialized in a declaration.

They can be supported by some compilers as their own language extensions.


问:
delete file other than particular extension file format
i have a lot of different type of files in one folder. i need to delete the files but except the pdf file.
I tried to display the pdf file only. but i need to delete the other than pdf files</p>

```<code>ls -1 | xargs file | grep 'PDF document,' | sed 's/:.*//'
</code>```

答:
```<code>ls |xargs file|awk -F":" '!($2~/PDF document/){print $1}'|xargs rm -rf
</code>```

Body:
i have a lot of different type of files in one folder. i need to delete the files but except the pdf file.
I tried to display the pdf file only. but i need to delete the other than pdf files

ls -1 | xargs file | grep 'PDF document,' | sed 's/:.*//'


问:
R won't find objects
I have an R program from my school that uses a lot of .r and .rd files (the program is an example, tested to work on R 3.5.3, which is what I compiled from source on Zorin OS 15.1, everything updated.) for basketball data science. All these files come from BasketballAnalyzeR. I put all the .r and .rd files on the same directory as the example program that uses them, but when I run the program it throws a lot of errors that say 'Object not found', whereas these objects are on the external .r and .rd files. How can I fix this? Some of those files have commands that start with \ is that a problem? Also, I see comments that say stuff like @export which are highlighted in blue, is that also a problem? Sorry, I am new to R.

答: So all I needed to do was install the package instead of using the .R and .Rd files on my working directory.</p>

Title: R won't find objects


问:
How to fetch json data using vuejs component?
I want to access json data from external file using vue component but I am not able to get any output in web page.The below is my code which I have tried.Can  anyone help me out?

The below is Json data that included the models which I want to display on web page

```<code>{
    "models": [
      {
        "title": "IRIS",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 3

      },
      {
        "title": "LILAC",
        "project": "ABC",
        "category": "DOUBLE",
        "bedrooms": 4

      },
      {
        "title": "ASTER",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 4

      }
    ]
  }
</code>```

Vue.component('single-model', {

  data: function() {
    return {
      myData: []

    }
  },
  template: `

{{model.title}}

`,

  created: function() {
    this.fetchData();
  },

  methods: {
    fetchData: function() {
      var url = 'j.json';
      axios.get(url)
        .then(function(res) {
          this.myData = res.data.models;

        });
    }
  }
});
var vm = new Vue({
  el: '#app',
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>

    <div id="app">
      <single-model></single-model>

    </div></code>```

答:
this on your code is not referring to your Vue Component.

I think, the easiest way to solve this issue is by creating a new variable to refer to your Vue Component

```<code>fetchData: function() {
      var url = 'j.json';
      var self = this;

      axios.get(url)
        .then(function(res) {
          self.myData = res.data.models;

        });
    }
</code>```

Body:
I want to access json data from external file using vue component but I am not able to get any output in web page.The below is my code which I have tried.Can  anyone help me out?

The below is Json data that included the models which I want to display on web page

{
    "models": [
      {
        "title": "IRIS",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 3

      },
      {
        "title": "LILAC",
        "project": "ABC",
        "category": "DOUBLE",
        "bedrooms": 4

      },
      {
        "title": "ASTER",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 4

      }
    ]
  }

Vue.component('single-model', {

  data: function() {
    return {
      myData: []

    }
  },
  template: `

{{model.title}}

`,

  created: function() {
    this.fetchData();
  },

  methods: {
    fetchData: function() {
      var url = 'j.json';
      axios.get(url)
        .then(function(res) {
          this.myData = res.data.models;

        });
    }
  }
});
var vm = new Vue({
  el: '#app',
});

      <single-model></single-model>

Body:
this on your code is not referring to your Vue Component.

I think, the easiest way to solve this issue is by creating a new variable to refer to your Vue Component

fetchData: function() {
      var url = 'j.json';
      var self = this;

      axios.get(url)
        .then(function(res) {
          self.myData = res.data.models;

        });
    }


问:
Looking for ionic app that works on offfline mode (i.e. without internet)
I have an ionic 1 (angularjs) app, which doesn't work offline, on first launch user creates account, logs in and next time he opens app he is already logged in.

The scenario is I am looking for is an offline mode(that is without internet connection), here if the user is not connected to internet he's not allowed to explore the app, here i want to let the user explore the app even without internet connection, with the credentials already logged in.

A lot of resources suggests to use localstorage, but i can't find any relevant resources regarding the same.

I have spent hour reading and testing different approaches but well even more confused than ever. It seems to me as such important feature of hybrid app that there should be a good implementation... Would appreciate any help/suggestions/examples/links...

My ultimate goal would be that once authorized user can access and manipulate his profile data even if in offline mode. That means that opening app allready logs him in an his profile info is stored as well.

My minimum viable goal would be that when app is opened app recognizes user, checks as logged in, redirects to logged in state and makes http to get all user details. While user is waiting for that response there are loading spinners but he can start to use logged in app experience.

答:
bro just store your token generated by the server or user data in local storage, If the user is in the local storage then redirect the page other send it to the login page,

local storage like

to set =>

```<code>localStorage.setItem('auth-token', JSON.stringify(access_token));
</code>```

to get =>

```<code>JSON.parse(localStorage.getItem('auth-token'));
</code>```

Also, you can use Storage plugins to store any data.

Body:
bro just store your token generated by the server or user data in local storage, If the user is in the local storage then redirect the page other send it to the login page,

local storage like

to set =>

localStorage.setItem('auth-token', JSON.stringify(access_token));

to get =>

JSON.parse(localStorage.getItem('auth-token'));

Also, you can use Storage plugins to store any data.


问:
Can't change value of object variable that is a result of a query in Javascript / ExpressJS / Mongodb
So I have the following code:

```<code>let addSubmissions = await Submission.find({"type": "add-information"}, (err) => {
    if(err) {
        console.log(err)
        req.flash('error', 'No "add submissions" were found')
        res.redirect('/admin')
    }
})

for(let addKey in addSubmissions) {
    let currentAddSubmissionAircraft = addSubmissions[addKey].aircraft

    let addSubmissionAircraft = await Aircraft.findById(currentAddSubmissionAircraft, {name: 1}, (err) => {
        if(err) {
            console.log(err)
            req.flash('error', 'No aircraft was found with the given ID')
            res.redirect('/admin')
        }
    })

    addSubmissions[addKey].aircraft = addSubmissionAircraft.name
}
</code>```

I get all the submissions from the Submission collection in MongoDB and assign them to the addSubmissions variable. One of it's fields is 'aircraft' and it's value is an id from another collection called 'aircrafts'.

In the for loop I search the aircraft with the 'aircraft' field (which is the id) from the submissions and I want to change the value of 'addSubmissions.aircraft' from the id to the name of the aircraft.

For some reason the object is not changing.

Any idea why?

Thanks :)

答:
You must to set in your function find, a method called lean().

```<code>Submission.find({}).lean().then()
</code>```

There is another question: Can't add a new property to an object returned by Mongoose query

Body:
So I have the following code:

let addSubmissions = await Submission.find({"type": "add-information"}, (err) => {
    if(err) {
        console.log(err)
        req.flash('error', 'No "add submissions" were found')
        res.redirect('/admin')
    }
})

for(let addKey in addSubmissions) {
    let currentAddSubmissionAircraft = addSubmissions[addKey].aircraft

    let addSubmissionAircraft = await Aircraft.findById(currentAddSubmissionAircraft, {name: 1}, (err) => {
        if(err) {
            console.log(err)
            req.flash('error', 'No aircraft was found with the given ID')
            res.redirect('/admin')
        }
    })

    addSubmissions[addKey].aircraft = addSubmissionAircraft.name
}

I get all the submissions from the Submission collection in MongoDB and assign them to the addSubmissions variable. One of it's fields is 'aircraft' and it's value is an id from another collection called 'aircrafts'.

In the for loop I search the aircraft with the 'aircraft' field (which is the id) from the submissions and I want to change the value of 'addSubmissions.aircraft' from the id to the name of the aircraft.

For some reason the object is not changing.

Any idea why?

Thanks :)

Body:
You must to set in your function find, a method called lean().

Submission.find({}).lean().then()

There is another question: Can't add a new property to an object returned by Mongoose query


问:
How to set npm credentials using `npm login` without reading from stdin?
I'm trying to automate npm publish inside a Docker container, but I receive an error when the npm login command tries to read the username and email:

npm login << EOF
username
password
email
EOF
```
<p>It works in a Bash terminal, but in a container (without <code>stdin</code>) it shows error:</p>
<pre class="lang-sh prettyprint-override"><code>Username: Password: npm ERR! cb() never called!
npm ERR! not ok code 0
</code>```

According to npm-adduser:

The username, password, and email are read in from prompts.

How can I run npm login without using stdin?

答:
Depends on jq and three ENV vars set:

```<code>export NPM_REGISTRY_DOMAIN=
export NPM_REGISTRY_USER=
export NPM_REGISTRY_PASSWORD=

json="{\"name\": \""$NPM_REGISTRY_USER"\", \"password\": \""$NPM_REGISTRY_PASSWORD"\"}"

TOKEN=$(curl -s \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X PUT --data "$json" \
  --user "$NPM_REGISTRY_USER":"$NPM_REGISTRY_PASSWORD" \
  https://"$NPM_REGISTRY_DOMAIN"/-/user/org.couchdb.user:"$NPM_REGISTERY_USER" | \
            jq -r '.token'
    )

npm config set registry https://"$NPM_REGISTRY_DOMAIN"
npm set //"$NPM_REGISTRY_DOMAIN"/:_authToken "$TOKEN"
</code>```

Based on the answer from https://stackoverflow.com/a/35831310/1663462

Body:
I'm trying to automate npm publish inside a Docker container, but I receive an error when the npm login command tries to read the username and email:

npm login << EOF
username
password
email
EOF

It works in a Bash terminal, but in a container (without stdin) it shows error:

Username: Password: npm ERR! cb() never called!
npm ERR! not ok code 0

According to npm-adduser:

The username, password, and email are read in from prompts.

How can I run npm login without using stdin?

Body:
Depends on jq and three ENV vars set:

export NPM_REGISTRY_DOMAIN=
export NPM_REGISTRY_USER=
export NPM_REGISTRY_PASSWORD=

json="{\"name\": \""$NPM_REGISTRY_USER"\", \"password\": \""$NPM_REGISTRY_PASSWORD"\"}"

TOKEN=$(curl -s \
  -H "Accept: application/json" \
  -H "Content-Type:application/json" \
  -X PUT --data "$json" \
  --user "$NPM_REGISTRY_USER":"$NPM_REGISTRY_PASSWORD" \
  https://"$NPM_REGISTRY_DOMAIN"/-/user/org.couchdb.user:"$NPM_REGISTERY_USER" | \
            jq -r '.token'
    )

npm config set registry https://"$NPM_REGISTRY_DOMAIN"
npm set //"$NPM_REGISTRY_DOMAIN"/:_authToken "$TOKEN"

Based on the answer from https://stackoverflow.com/a/35831310/1663462


问:
Conditional validation in a JavaScript web form
I am working on a web form using JavaScript for validation.  This is only one section of a much larger form.

The form has a question that asks the user if they have a Social Security Number. (SocialSecurity field)  It has two radio buttons, one yes and one no.  IF the user answers yes, then another field (SSN) becomes visible.  Otherwise, it stays hidden.   This part is actually working. (the show/hide of the SSN field)

The JS needs to do two things.  IF the user answers yes, then the SSN field becomes required, and must validate that it has 9 integers.   BUT, if the user answers no, then SSN field, which will stay hidden must no longer be required.

What I am having difficulty with, is getting the SSN to be required only if the user answers yes, and validate it correctly under that circumstance.

Online Demo

Here is the code:

```<code><div class="field SocialSecurity">
<span id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_lb" class="EditingFormLabel">Do you have a Social Security Number?</span>
<div id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_ncpsocialsecurity" class="EditingFormControlNestedControl editing-form-control-nested-control">
<span id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list" class="radio radio-list-vertical">
<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" value="As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number." />
<label for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0">As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.</label><br />
<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_1" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" value="Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number." />
<label for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_1">Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.</label>
</span>

</div></div>

<div class="field SSN">
<label id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_lb" class="EditingFormLabel" for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_txtText">Social Security Number</label>
<div id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_ncpssn" class="EditingFormControlNestedControl editing-form-control-nested-control">
<input name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SSN$txtText" type="text" maxlength="9" id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_txtText" class="form-control" />
</div> </div>

$('.field.SocialSecurity input[type=radio]').on("change", function() {
  switch ($(this).val()) {
    case 'As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.':
      $('.field.SSN').show();
      $('.field.SSN input').focus();
      break;

    case 'Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.':
      $('.field.SSN').hide();
      break;
  }
});

//Here is the SS format validation section

function validateSSN() {
  if (!validateRequiredTextField('SSN', 'Social Security Number'))
    return false;

  var value = $('.field.SSN input').val();

  if (!isInteger(value) ||
    (value.length != 9) ||
    (value == '000000000') ||
    (value == '111111111') ||
    (value == '222222222') ||
    (value == '333333333') ||
    (value == '444444444') ||
    (value == '555555555') ||
    (value == '666666666') ||
    (value == '777777777') ||
    (value == '888888888') ||
    (value == '999999999') ||
    (value == '123456789')) {
    $('.field.SSN input').focus();
    alert("Invalid: Social Security Number");
    return false;
  }

  return true;
}

//overall form validation - section on SSN
function validateForm()

if (!validateSSN())
  return false;
</code>```

答:
Update your validateform() function as below</p>

```<code>function validateForm()
{
if($("#p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0").is(':checked'))
{
    if($(".field.SSN input").val().trim() == "")
    {
        alert("You must provide SSN!");
        // Instead of alert, you can also apply some style to textBox e.g. red borders
        return false;
    }
    else if (!validateSSN())
    {
        return false;
    }
}
}
</code>```

Body:
I am working on a web form using JavaScript for validation.  This is only one section of a much larger form.

The form has a question that asks the user if they have a Social Security Number. (SocialSecurity field)  It has two radio buttons, one yes and one no.  IF the user answers yes, then another field (SSN) becomes visible.  Otherwise, it stays hidden.   This part is actually working. (the show/hide of the SSN field)

The JS needs to do two things.  IF the user answers yes, then the SSN field becomes required, and must validate that it has 9 integers.   BUT, if the user answers no, then SSN field, which will stay hidden must no longer be required.

What I am having difficulty with, is getting the SSN to be required only if the user answers yes, and validate it correctly under that circumstance.

Online Demo

Here is the code:

Do you have a Social Security Number?

<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" value="As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number." />
As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.

<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_1" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" value="Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number." />
Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.

Social Security Number

<input name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SSN$txtText" type="text" maxlength="9" id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_txtText" class="form-control" />

$('.field.SocialSecurity input[type=radio]').on("change", function() {
  switch ($(this).val()) {
    case 'As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.':
      $('.field.SSN').show();
      $('.field.SSN input').focus();
      break;

    case 'Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.':
      $('.field.SSN').hide();
      break;
  }
});

//Here is the SS format validation section

function validateSSN() {
  if (!validateRequiredTextField('SSN', 'Social Security Number'))
    return false;

  var value = $('.field.SSN input').val();

  if (!isInteger(value) ||
    (value.length != 9) ||
    (value == '000000000') ||
    (value == '111111111') ||
    (value == '222222222') ||
    (value == '333333333') ||
    (value == '444444444') ||
    (value == '555555555') ||
    (value == '666666666') ||
    (value == '777777777') ||
    (value == '888888888') ||
    (value == '999999999') ||
    (value == '123456789')) {
    $('.field.SSN input').focus();
    alert("Invalid: Social Security Number");
    return false;
  }

  return true;
}

//overall form validation - section on SSN
function validateForm()

if (!validateSSN())
  return false;

Body:
Update your validateform() function as below

function validateForm()
{
if($("#p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0").is(':checked'))
{
    if($(".field.SSN input").val().trim() == "")
    {
        alert("You must provide SSN!");
        // Instead of alert, you can also apply some style to textBox e.g. red borders
        return false;
    }
    else if (!validateSSN())
    {
        return false;
    }
}
}


Title: Pandas max along n rows

Body:
I have a dataframe with date time index as below

137962500   137975000   137987500   138000000   138012500   138025000   138037500   138050000   138062500
Datetime
2020-02-05 11:06:00+00:00   -112.0  -114.0  -114.0  -114.0  -114.0  -116.0  -114.0  -114.0  -114.0
2020-02-05 11:07:00+00:00   -112.0  -111.0  -112.0  -112.0  -112.0  -112.0  -113.0  -113.0  -112.0
2020-02-05 11:08:00+00:00   -113.0  -112.0  -112.0  -112.0  -112.0  -112.0  -112.0  -112.0  -112.0
2020-02-05 11:09:00+00:00   -111.0  -112.0  -111.0  -112.0  -112.0  -112.0  -112.0  -112.0  -112.0
2020-02-05 11:10:00+00:00   -111.0  -112.0  -111.0  -112.0  -113.0  -113.0  -112.0  -112.0  -112.0

I am aware of df.max(axis=0) to get the max value along every row. How can we extend this concept to group the dataframe into n columns and get the max within each group?
This is to be able to reduce the number of columns in a 'wide' data format and yet retaining the max values within each small group of columns.

Thanks

Body:
Let say you want to assign the columns into groups of 4:

group_size = 4
groups = np.arange(df.columns.shape[0]) // group_size
labels = df.columns.to_series().groupby(groups).transform(lambda g: f'{g.min()} - {g.max()}')

df.groupby(labels, axis=1).max()

Result:

                           137962500 - 138000000  138012500 - 138050000  138062500 - 138062500
Datetime
2020-02-05 11:06:00+00:00                 -112.0                 -114.0                 -114.0
2020-02-05 11:07:00+00:00                 -111.0                 -112.0                 -112.0
2020-02-05 11:08:00+00:00                 -112.0                 -112.0                 -112.0
2020-02-05 11:09:00+00:00                 -111.0                 -112.0                 -112.0
2020-02-05 11:10:00+00:00                 -111.0                 -112.0                 -112.0


问:
Select query to group records in output json using BigQuery
I have a datetime partitioned table in BigQuery with a schema like:

```<code>timestamp      TIMESTAMP  REQUIRED
customer_id    STRING     REQUIRED
plant_id       STRING     REQUIRED
inverters      RECORD     REPEATED
inverters. id  STRING     REQUIRED
...
</code>```

So, if I do a SELECT * FROMmy_table`, it will generate a JSON with a structure like:

```<code>[
  {
    "timestamp": "2019-10-20 20:00:00 UTC",
    "customer_id": "5d3f1aee5f70740d54c416e1",
    "plant_id": "5d658cb25f70747626153e83",
    "inverters": [
      {
        "id": "5d77e3225f70746ec02bd8e7",
        ...
      },
      ...
    ]
  },
  ...
]
</code>```

And that format works well in most of my use cases, except for one.

So, if I wanted the id's of all the inverters i would do

```<code>SELECT DISTINCT id
FROM `my_table`
CROSS JOIN UNNEST(inverters)
</code>```

But I also need the timestamps grouped by inverter, but if I do, let's say, a nested query for getting the timestamps by id, like:

```<code>SELECT inverter, timestamp
FROM (
  SELECT DISTINCT id
  FROM `my_table`
  CROSS JOIN UNNEST(inverters)
) AS inverter, `my_table`
</code>```

then the resulting json would be:

```<code>[
  {
    "inverter": {
      "id": "5d791a505f70744c233b819d"
    },
    "timestamp": "2020-01-21 11:15:00 UTC"
  },
  {
    "inverter": {
      "id": "5d791a505f70744c233b819d"
    },
    "timestamp": "2020-01-21 00:20:00 UTC"
  },
  {
    "inverter": {
      "id": "5d791a505f70744c233b819d"
    },
    "timestamp": "2020-01-21 04:05:00 UTC"
  },
  ...
]
</code>```

Now, that was a long introduction.

The question is: Is there a way of querying the data so the result of the query looks something like the following?

```<code>[
  {
    "inverter": {
      "id": "5d791a505f70744c233b819d",
      "timestamp": [
        "2020-01-21 11:15:00 UTC",
        "2020-01-21 00:20:00 UTC",
        "2020-01-21 04:05:00 UTC",
        ...
      ]
    },
  ...
]
</code>```

答:
Is this what you want?

```<code>SELECT inverter.id, ARRAY_AGG(timestamp)
FROM `my_table` t CROSS JOIN
     UNNEST(t.inverters) inverter
GROUP BY inverter.id;
</code>```

You say that SELECT * returns JSON.  I think this is a function of your API.  When you use the BigQuery API, you don't see JSON.

Body:
I have a datetime partitioned table in BigQuery with a schema like:

timestamp      TIMESTAMP  REQUIRED
customer_id    STRING     REQUIRED
plant_id       STRING     REQUIRED
inverters      RECORD     REPEATED
inverters. id  STRING     REQUIRED
...

So, if I do a SELECT * FROMmy_table`, it will generate a JSON with a structure like:

[
  {
    "timestamp": "2019-10-20 20:00:00 UTC",
    "customer_id": "5d3f1aee5f70740d54c416e1",
    "plant_id": "5d658cb25f70747626153e83",
    "inverters": [
      {
        "id": "5d77e3225f70746ec02bd8e7",
        ...
      },
      ...
    ]
  },
  ...
]

And that format works well in most of my use cases, except for one.

So, if I wanted the id's of all the inverters i would do

SELECT DISTINCT id
FROM `my_table`
CROSS JOIN UNNEST(inverters)

But I also need the timestamps grouped by inverter, but if I do, let's say, a nested query for getting the timestamps by id, like:

SELECT inverter, timestamp
FROM (
  SELECT DISTINCT id
  FROM `my_table`
  CROSS JOIN UNNEST(inverters)
) AS inverter, `my_table`

then the resulting json would be:

[
  {
    "inverter": {
      "id": "5d791a505f70744c233b819d"
    },
    "timestamp": "2020-01-21 11:15:00 UTC"
  },
  {
    "inverter": {
      "id": "5d791a505f70744c233b819d"
    },
    "timestamp": "2020-01-21 00:20:00 UTC"
  },
  {
    "inverter": {
      "id": "5d791a505f70744c233b819d"
    },
    "timestamp": "2020-01-21 04:05:00 UTC"
  },
  ...
]

Now, that was a long introduction.

The question is: Is there a way of querying the data so the result of the query looks something like the following?

[
  {
    "inverter": {
      "id": "5d791a505f70744c233b819d",
      "timestamp": [
        "2020-01-21 11:15:00 UTC",
        "2020-01-21 00:20:00 UTC",
        "2020-01-21 04:05:00 UTC",
        ...
      ]
    },
  ...
]

Body:
Is this what you want?

SELECT inverter.id, ARRAY_AGG(timestamp)
FROM `my_table` t CROSS JOIN
     UNNEST(t.inverters) inverter
GROUP BY inverter.id;

You say that SELECT * returns JSON.  I think this is a function of your API.  When you use the BigQuery API, you don't see JSON.


问:
Android - Firebase Auth Not Working After PC Format
I'm using Firebase Authentication in my Android app. Recently, I have formatted my PC and installed Ubuntu 18.04 LTS (It has Ubuntu 16 installed before the format), and after I installed Android Studio and tried the app, the Google sign in was not working, there is an ApiException thrown on those two lines:

```<code>GoogleSignInAccount account = task.getResult(ApiException.class);
            firebaseAuthWithGoogle(account);
</code>```

The stack trace:

```<code>com.google.android.gms.common.api.ApiException: 10:
        at com.google.android.gms.common.internal.ApiExceptionUtil.fromStatus(Unknown Source)
        at com.google.android.gms.auth.api.signin.GoogleSignIn.getSignedInAccountFromIntent(Unknown Source)
        at com.game.ameer.ta7adialma3rifa.fragments.login.LoginFragment.onActivityResult(LoginFragment.java:220)
        at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:151)
        at com.game.ameer.ta7adialma3rifa.activities.LoginActivity.onActivityResult(LoginActivity.java:38)
        at android.app.Activity.dispatchActivityResult(Activity.java:7303)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4516)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4563)
        at android.app.ActivityThread.-wrap22(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1698)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6776)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
</code>```

This didn't happen before I format the PC, and I believe that the problem is not in the code but in Firebase configuration, with some sort of token or certificate. What is causing the problem? And how to solve it?

答:
It's most probably because the debug SHA-1 signing-certificate added to your Firebase project has changed after the format. You may need to update the key for your app on the Firebase Console. The same goes for the API keys of the connected project on the Google Cloud Console.

To get your new SHA-1 key, use the following in any terminal (on Linux/macOS):

```<code>keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
</code>```

See here for more details

Body:
I'm using Firebase Authentication in my Android app. Recently, I have formatted my PC and installed Ubuntu 18.04 LTS (It has Ubuntu 16 installed before the format), and after I installed Android Studio and tried the app, the Google sign in was not working, there is an ApiException thrown on those two lines:

GoogleSignInAccount account = task.getResult(ApiException.class);
            firebaseAuthWithGoogle(account);

The stack trace:

com.google.android.gms.common.api.ApiException: 10:
        at com.google.android.gms.common.internal.ApiExceptionUtil.fromStatus(Unknown Source)
        at com.google.android.gms.auth.api.signin.GoogleSignIn.getSignedInAccountFromIntent(Unknown Source)
        at com.game.ameer.ta7adialma3rifa.fragments.login.LoginFragment.onActivityResult(LoginFragment.java:220)
        at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:151)
        at com.game.ameer.ta7adialma3rifa.activities.LoginActivity.onActivityResult(LoginActivity.java:38)
        at android.app.Activity.dispatchActivityResult(Activity.java:7303)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4516)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4563)
        at android.app.ActivityThread.-wrap22(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1698)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6776)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

This didn't happen before I format the PC, and I believe that the problem is not in the code but in Firebase configuration, with some sort of token or certificate. What is causing the problem? And how to solve it?

Body:
It's most probably because the debug SHA-1 signing-certificate added to your Firebase project has changed after the format. You may need to update the key for your app on the Firebase Console. The same goes for the API keys of the connected project on the Google Cloud Console.

To get your new SHA-1 key, use the following in any terminal (on Linux/macOS):

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

See here for more details


问:
How can I get items from a list from a specific index?
How can I get only the items ahead of a specified index in a list?
Example:

```<code>var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
print(numbers[3..]);
</code>```

Output: 4, 5, 6, 7, 8, 9, 10

答:
You can use the skip method, to skip a number of elements at the start of a List, for example:</p>

```<code>var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
print(numbers.skip(3)); //Returns an iterable: (4, 5, 6, 7, 8, 9, 10)
</code>```

Body:
How can I get only the items ahead of a specified index in a list?
Example:

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
print(numbers[3..]);

Output: 4, 5, 6, 7, 8, 9, 10

Body:
You can use the skip method, to skip a number of elements at the start of a List, for example:

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
print(numbers.skip(3)); //Returns an iterable: (4, 5, 6, 7, 8, 9, 10)


问:
Laravel 5.5 How to get eloquent relationship count?
I have three tables as define below

User

id

name

Post

id

text

user_id

Comments

id

text

post_id

This is User model User.php

```<code>class User
{
     public function post()
    {
       return $this->hasMany(Post::class);
    }
}
</code>```

This is my post model Post.php

```<code>    class Post
    {
       public function comments()
       {
          return $this->hasMany(Comment::class);
       }
   }
</code>```

Issue:

I want to display no.of comments per user using eloquent eager loading.

Can anyone help me with that? Thanks in advance.

答:
You may define a new hasManyThrough relationship (docs) for user's comments:

class User
{
    public function comments()
    {
        return $this->hasManyThrough(
            'App\Comment',
            'App\Post',
            'user_id', // Foreign key on posts table...
            'post_id', // Foreign key on comments table...
            'id', // Local key on users table...
            'id' // Local key on posts table...
        );
    }
}
```

<p>Now you can count each user's comments (Laravel docs):</p>

<pre class="lang-php prettyprint-override"><code>$users = App\User::withCount('comments')->get();

foreach ($users as $user) {
    echo $user->comments_count;
}
</code>```

Body:
I have three tables as define below

User

id

name

Post

id

text

user_id

Comments

id

text

post_id

This is User model User.php

class User
{
     public function post()
    {
       return $this->hasMany(Post::class);
    }
}

This is my post model Post.php

    class Post
    {
       public function comments()
       {
          return $this->hasMany(Comment::class);
       }
   }

Issue:

I want to display no.of comments per user using eloquent eager loading.

Can anyone help me with that? Thanks in advance.

Body:
You may define a new hasManyThrough relationship (docs) for user's comments:

class User
{
    public function comments()
    {
        return $this->hasManyThrough(
            'App\Comment',
            'App\Post',
            'user_id', // Foreign key on posts table...
            'post_id', // Foreign key on comments table...
            'id', // Local key on users table...
            'id' // Local key on posts table...
        );
    }
}

Now you can count each user's comments (Laravel docs):

$users = App\User::withCount('comments')->get();

foreach ($users as $user) {
    echo $user->comments_count;
}


问:
Create columns based on count in data.table
I have a data as below:

```<code>Col1  Col2   Col3  Col4
1     7000     73     6
1     7000     73     7
1     7000     73     8
1     7000     73     9
1     7000     73    10
1     7000     73    11
1     7000     73    12
1     4000    117     6
1     4000    117     9
</code>```

I want to count the number by Col1 and Col2. And then, based on the count to create 5 new columns. I know how to count but how can I create 5 new columns based on the count.

```<code>Col1  Col2   Count   NewCol1  NewCol2  NewCol3  NewCol4  NewCol5
1     7000       7         6        7        8        9       10
1     4000       2         6        9        NA      NA       NA
</code>```

Col3 can be ignored actually.

There is one thing that Count ranges from 1 to more than 5. Therefore, if Count > 5, I do not need to have NewCol6, NewCol7, and etc.

答:
We create a frequency column with 'add_count', grouped by 'Col1', 'Col2', then create a sequence naming column ('nm1'), use complete to expand the data for missing combinations and reshape to 'wide' format with pivot_wider

```<code>library(dplyr)
library(tidyr)
library(stringr)
df1 %>%
    add_count(Col1, Col2) %>%
    group_by(Col1, Col2) %>%
    slice(seq_len(5)) %>%
    mutate(nm1 = str_c("NewCol", row_number())) %>%
    complete(nm1 = str_c("NewCol", 1:5)) %>%
    ungroup %>%
    dplyr::select(-Col3) %>%
    fill(n) %>%
    pivot_wider(names_from = nm1, values_from = Col4)
# A tibble: 2 x 8
#   Col1  Col2     n NewCol1 NewCol2 NewCol3 NewCol4 NewCol5
#  <int> <int> <int>   <int>   <int>   <int>   <int>   <int>
#1     1  4000     1       6      NA      NA      NA      NA
#2     1  7000     2       6       7      NA      NA      NA
</code>```

With the second dataset

```<code>df2 %>%
        add_count(Col1, Col2) %>%
        group_by(Col1, Col2) %>%
        slice(seq_len(5)) %>%
        mutate(nm1 = str_c("NewCol", row_number())) %>%
        complete(nm1 = str_c("NewCol", 1:5)) %>%
        ungroup %>%
        dplyr::select(-Col3) %>%
        fill(n) %>%
        pivot_wider(names_from = nm1, values_from = Col4)
# A tibble: 2 x 8
#   Col1  Col2     n NewCol1 NewCol2 NewCol3 NewCol4 NewCol5
#  <int> <int> <int>   <int>   <int>   <int>   <int>   <int>
#1     1  4000     2       6       9      NA      NA      NA
#2     1  7000     7       6       7       8       9      10
</code>```

Or using data.table

```<code>library(data.table)
dcast(setDT(df2)[, n  := .N, .(Col1, Col2)][,
   head(.SD, 5), .(Col1, Col2)], Col1 + Col2 + n ~
  factor(paste0("NewCol", rowid(Col1, Col2)),
       levels = paste0("NewCol", 1:5)), value.var = 'Col4')
#   Col1 Col2 n NewCol1 NewCol2 NewCol3 NewCol4 NewCol5
#1:    1 4000 2       6       9      NA      NA      NA
#2:    1 7000 7       6       7       8       9      10
</code>```

data

```<code>df1 <- structure(list(Col1 = c(1L, 1L, 1L), Col2 = c(7000L, 7000L, 4000L
), Col3 = c(73L, 73L, 117L), Col4 = c(6L, 7L, 6L)),
 class = "data.frame", row.names = c(NA,
-3L))

df2 <- structure(list(Col1 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L),
    Col2 = c(7000L, 7000L, 7000L, 7000L, 7000L, 7000L, 7000L,
    4000L, 4000L), Col3 = c(73L, 73L, 73L, 73L, 73L, 73L, 73L,
    117L, 117L), Col4 = c(6L, 7L, 8L, 9L, 10L, 11L, 12L, 6L,
    9L)), class = "data.frame", row.names = c(NA, -9L))
</code>```

Body:
I have a data as below:

Col1  Col2   Col3  Col4
1     7000     73     6
1     7000     73     7
1     7000     73     8
1     7000     73     9
1     7000     73    10
1     7000     73    11
1     7000     73    12
1     4000    117     6
1     4000    117     9

I want to count the number by Col1 and Col2. And then, based on the count to create 5 new columns. I know how to count but how can I create 5 new columns based on the count.

Col1  Col2   Count   NewCol1  NewCol2  NewCol3  NewCol4  NewCol5
1     7000       7         6        7        8        9       10
1     4000       2         6        9        NA      NA       NA

Col3 can be ignored actually.

There is one thing that Count ranges from 1 to more than 5. Therefore, if Count > 5, I do not need to have NewCol6, NewCol7, and etc.

Body:
We create a frequency column with 'add_count', grouped by 'Col1', 'Col2', then create a sequence naming column ('nm1'), use complete to expand the data for missing combinations and reshape to 'wide' format with pivot_wider

library(dplyr)
library(tidyr)
library(stringr)
df1 %>%
    add_count(Col1, Col2) %>%
    group_by(Col1, Col2) %>%
    slice(seq_len(5)) %>%
    mutate(nm1 = str_c("NewCol", row_number())) %>%
    complete(nm1 = str_c("NewCol", 1:5)) %>%
    ungroup %>%
    dplyr::select(-Col3) %>%
    fill(n) %>%
    pivot_wider(names_from = nm1, values_from = Col4)
# A tibble: 2 x 8
#   Col1  Col2     n NewCol1 NewCol2 NewCol3 NewCol4 NewCol5
#  <int> <int> <int>   <int>   <int>   <int>   <int>   <int>
#1     1  4000     1       6      NA      NA      NA      NA
#2     1  7000     2       6       7      NA      NA      NA

With the second dataset

df2 %>%
        add_count(Col1, Col2) %>%
        group_by(Col1, Col2) %>%
        slice(seq_len(5)) %>%
        mutate(nm1 = str_c("NewCol", row_number())) %>%
        complete(nm1 = str_c("NewCol", 1:5)) %>%
        ungroup %>%
        dplyr::select(-Col3) %>%
        fill(n) %>%
        pivot_wider(names_from = nm1, values_from = Col4)
# A tibble: 2 x 8
#   Col1  Col2     n NewCol1 NewCol2 NewCol3 NewCol4 NewCol5
#  <int> <int> <int>   <int>   <int>   <int>   <int>   <int>
#1     1  4000     2       6       9      NA      NA      NA
#2     1  7000     7       6       7       8       9      10

Or using data.table

library(data.table)
dcast(setDT(df2)[, n  := .N, .(Col1, Col2)][,
   head(.SD, 5), .(Col1, Col2)], Col1 + Col2 + n ~
  factor(paste0("NewCol", rowid(Col1, Col2)),
       levels = paste0("NewCol", 1:5)), value.var = 'Col4')
#   Col1 Col2 n NewCol1 NewCol2 NewCol3 NewCol4 NewCol5
#1:    1 4000 2       6       9      NA      NA      NA
#2:    1 7000 7       6       7       8       9      10

data

df1 <- structure(list(Col1 = c(1L, 1L, 1L), Col2 = c(7000L, 7000L, 4000L
), Col3 = c(73L, 73L, 117L), Col4 = c(6L, 7L, 6L)),
 class = "data.frame", row.names = c(NA,
-3L))

df2 <- structure(list(Col1 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L),
    Col2 = c(7000L, 7000L, 7000L, 7000L, 7000L, 7000L, 7000L,
    4000L, 4000L), Col3 = c(73L, 73L, 73L, 73L, 73L, 73L, 73L,
    117L, 117L), Col4 = c(6L, 7L, 8L, 9L, 10L, 11L, 12L, 6L,
    9L)), class = "data.frame", row.names = c(NA, -9L))


问:
Making Global Tasks in VS Code
Is there a way to make "global" tasks, or do I always need to copy the same tasks.json into every project directory. VSCode seems to require that the task be in a .vscode directory within the current project folder.</p>

答:
User level tasks is an available feature since VSCode January 2020 (version 1.42).

From the Release Notes:

Tasks declared in tasks.json are now supported at the User Settings level. If you have a build script that you use across many projects, or if you don't want your tasks in a project folder, you can add your tasks in the user tasks.json file. Run the Tasks: Open User Tasks command to create user level tasks and these tasks will be available across all folders and workspaces. Only the shell and process task types are supported here.

In the Command Palette (CTRL + SHIFT + P) type:

```<code>> Tasks: Open User Tasks
</code>```

Title: Making Global Tasks in VS Code

Body:
User level tasks is an available feature since VSCode January 2020 (version 1.42).

From the Release Notes:

Tasks declared in tasks.json are now supported at the User Settings level. If you have a build script that you use across many projects, or if you don't want your tasks in a project folder, you can add your tasks in the user tasks.json file. Run the Tasks: Open User Tasks command to create user level tasks and these tasks will be available across all folders and workspaces. Only the shell and process task types are supported here.

In the Command Palette (CTRL + SHIFT + P) type:

> Tasks: Open User Tasks


问:
MySQL Question - I want to eliminate all text within any parenthesis
Just checking to see if any of you would have a solution for this – from the below text like this I want to eliminate all text within any parenthesis.

Input –

PAY - addition,FILES (aaaaaaaaaaaaaa/bbbbbbbbbbbs i.e. ssss,ffff – i.e. cccccc),DED (ppppppp, llllll, fffff gggg),LOSS (ddddd, hhhhhh – i.e.),F TO G ( “F” is switching to “G”)

Output –

PAY - addition,FILES,DED,LOSS,F TO G

答:
Another on for MYSQL8.0:

```<code>SET @input:="PAY - addition,FILES (aaaaaaaaaaaaaa/bbbbbbbbbbbs i.e. ssss,ffff – i.e. cccccc),DED (ppppppp, llllll, fffff gggg),LOSS (ddddd, hhhhhh – i.e.),F TO G ( “F” is switching to “G”)";

with recursive cte as (
    select
        0 i,
        @input as text
    union all
    select
        i+1,
        CASE WHEN instr(text,'(') >0 AND instr(text,')')>instr(text,'(') THEN REPLACE(text, substring(text,instr(text,'('),instr(text,')')-instr(text,'(')+1), '') ELSE '' END
    from cte
    where  i<10
) select text from cte where text<>'' order by i desc limit 1;
</code>```

output:

```<code>+------------------------------------------+
| text                                     |
+------------------------------------------+
| PAY - addition,FILES ,DED ,LOSS ,F TO G  |
+------------------------------------------+
1 row in set (0.00 sec)
</code>```

Body:
Another on for MYSQL8.0:

SET @input:="PAY - addition,FILES (aaaaaaaaaaaaaa/bbbbbbbbbbbs i.e. ssss,ffff – i.e. cccccc),DED (ppppppp, llllll, fffff gggg),LOSS (ddddd, hhhhhh – i.e.),F TO G ( “F” is switching to “G”)";

with recursive cte as (
    select
        0 i,
        @input as text
    union all
    select
        i+1,
        CASE WHEN instr(text,'(') >0 AND instr(text,')')>instr(text,'(') THEN REPLACE(text, substring(text,instr(text,'('),instr(text,')')-instr(text,'(')+1), '') ELSE '' END
    from cte
    where  i<10
) select text from cte where text<>'' order by i desc limit 1;

output:

+------------------------------------------+
| text                                     |
+------------------------------------------+
| PAY - addition,FILES ,DED ,LOSS ,F TO G  |
+------------------------------------------+
1 row in set (0.00 sec)


问:
Javascript: Refresh parent page without entirely reloading
After a user has logged in via a fancybox (javascript) popup I wish to reload the parent page so they can access the logged in features.

Currently I am doing this with:

```<code><a href="javascript:window.top.location.reload(true)" class="continue">Continue</a>
</code>```

This works great, but the only issue is that it completely reloads the entire page: redownloads all the css & javascipt, etc.

All I want to do is reload the page normally, not a full refresh. How can I achieve this?

(I do not know the exact URL because the login can be done from any page via the fancybox, so I can't hardcode the URL.)

答:
Use:

```<code>location.replace(location.href.split('#')[0]);
</code>```

The split on hash is required, otherwise an url with a hash will not be refreshed.

If you want to keep the previous load in browser history, use assign instead of replace.

href is not currently supported by Opera, according to MDN.

Body:
After a user has logged in via a fancybox (javascript) popup I wish to reload the parent page so they can access the logged in features.

Currently I am doing this with:

Continue

This works great, but the only issue is that it completely reloads the entire page: redownloads all the css & javascipt, etc.

All I want to do is reload the page normally, not a full refresh. How can I achieve this?

(I do not know the exact URL because the login can be done from any page via the fancybox, so I can't hardcode the URL.)

Body:
Use:

location.replace(location.href.split('#')[0]);

The split on hash is required, otherwise an url with a hash will not be refreshed.

If you want to keep the previous load in browser history, use assign instead of replace.

href is not currently supported by Opera, according to MDN.