问:
I accidentally typo'd "npm i npm" and it installed a bunch of node modules I didn't need. How can I revert?
I'm new, and I'm lost because I think I messed up my whole program. I cannot install anymore node variations. I'm using Visual Studio Code. And after the code below I typed "npm uninstall npm" thinking it would fix it, but it seems not.

I tried npm uninstall npm and it didn't work. :/

```<code>npm WARN discord.js@11.5.0 requires a peer of bufferutil@^4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of erlpack@discordapp/erlpack but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of libsodium-wrappers@^0.7.3 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of node-opus@^0.2.7 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of opusscript@^0.0.6 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of sodium@^2.0.3 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of @discordjs/uws@^10.149.0 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js-commando@0.10.0 requires a peer of sqlite@^2.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN westeros-bot@1.0.0 No description
npm WARN westeros-bot@1.0.0 No repository field.

+ npm@6.9.0
added 426 packages from 800 contributors and audited 12108 packages in 45.684s
found 12 high severity vulnerabilities
  run `npm audit fix` to fix them, or `npm audit` for details```

AFTER

```c:\Users\madel\Desktop\Westeros Bot\dist>npm uninstall npm
npm WARN discord.js@11.5.0 requires a peer of bufferutil@^4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of erlpack@discordapp/erlpack but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of libsodium-wrappers@^0.7.3 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of node-opus@^0.2.7 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of opusscript@^0.0.6 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of sodium@^2.0.3 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of @discordjs/uws@^10.149.0 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js-commando@0.10.0 requires a peer of sqlite@^2.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN westeros-bot@1.0.0 No description
npm WARN westeros-bot@1.0.0 No repository field.

removed 426 packages and audited 12 packages in 7.294s
found 0 vulnerabilities```
```

答: You can try npm remove npm and run npm install to update package-lock.json file.

Body:
I'm new, and I'm lost because I think I messed up my whole program. I cannot install anymore node variations. I'm using Visual Studio Code. And after the code below I typed "npm uninstall npm" thinking it would fix it, but it seems not.

I tried npm uninstall npm and it didn't work. :/

npm WARN discord.js@11.5.0 requires a peer of bufferutil@^4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of erlpack@discordapp/erlpack but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of libsodium-wrappers@^0.7.3 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of node-opus@^0.2.7 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of opusscript@^0.0.6 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of sodium@^2.0.3 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of @discordjs/uws@^10.149.0 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js-commando@0.10.0 requires a peer of sqlite@^2.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN westeros-bot@1.0.0 No description
npm WARN westeros-bot@1.0.0 No repository field.

+ npm@6.9.0
added 426 packages from 800 contributors and audited 12108 packages in 45.684s
found 12 high severity vulnerabilities
  run `npm audit fix` to fix them, or `npm audit` for details```

AFTER

```c:\Users\madel\Desktop\Westeros Bot\dist>npm uninstall npm
npm WARN discord.js@11.5.0 requires a peer of bufferutil@^4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of erlpack@discordapp/erlpack but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of libsodium-wrappers@^0.7.3 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of node-opus@^0.2.7 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of opusscript@^0.0.6 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of sodium@^2.0.3 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js@11.5.0 requires a peer of @discordjs/uws@^10.149.0 but none is installed. You must install peer dependencies yourself.
npm WARN discord.js-commando@0.10.0 requires a peer of sqlite@^2.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN westeros-bot@1.0.0 No description
npm WARN westeros-bot@1.0.0 No repository field.

removed 426 packages and audited 12 packages in 7.294s
found 0 vulnerabilities```


来源: stackexchange

问:
C# error when read Excel file, this is a strange error
When I read (*.xls) file in C# I get an error.

I see lots of topic about "DCOM Access Denied Problem" and configuration of related problem in SO, but non of them solved my problem. all permission and administrator account was checked.  this is image of error:

Update: this is logged error by app :

```<code>Error       : The remote procedure call failed. (Exception from HRESULT: 0x800706BE)
Stack Trace : at Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad)
   at Pardic.WebProcess.frmGetPrice.worker_DoWork(Object sender, DoWorkEventArgs e)
^^-------------------------------------------------------------------^^
Source      : Microsoft.Office.Interop.Excel
Method      : Quit
Date        : 02:21:19 ب.ظ
Time        : 07/03/1398
Computer    : DESKTOP-2QPBGQ1
Error       : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
Stack Trace : at Microsoft.Office.Interop.Excel.ApplicationClass.Quit()
   at Pardic.WebProcess.frmGetPrice.worker_DoWork(Object sender, DoWorkEventArgs e)
</code>```

This is Event Windows logs:

```<code>Log Name:      Application
Source:        Application Error
Date:          5/28/2019 2:16:11 PM
Event ID:      1000
Task Category: (100)
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      DESKTOP-2QPBGQ1
Description:
Faulting application name: EXCEL.EXE, version: 15.0.4420.1017, time stamp: 0x506741b5
Faulting module name: ntdll.dll, version: 10.0.14393.2214, time stamp: 0x5ac2f612
Exception code: 0xc0000005
Fault offset: 0x000000000004961c
Faulting process id: 0x1934
Faulting application start time: 0x01d5153a29e7eeb5
Faulting application path: C:\Program Files\Microsoft Office\Office15\EXCEL.EXE
Faulting module path: C:\Windows\SYSTEM32\ntdll.dll
Report Id: 9910317c-cd4c-49b2-8869-76f88b722123
Faulting package full name:
Faulting package-relative application ID:
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Application Error" />
    <EventID Qualifiers="0">1000</EventID>
    <Level>2</Level>
    <Task>100</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2019-05-28T09:46:11.052916900Z" />
    <EventRecordID>20076</EventRecordID>
    <Channel>Application</Channel>
    <Computer>DESKTOP-2QPBGQ1</Computer>
    <Security />
  </System>
  <EventData>
    <Data>EXCEL.EXE</Data>
    <Data>15.0.4420.1017</Data>
    <Data>506741b5</Data>
    <Data>ntdll.dll</Data>
    <Data>10.0.14393.2214</Data>
    <Data>5ac2f612</Data>
    <Data>c0000005</Data>
    <Data>000000000004961c</Data>
    <Data>1934</Data>
    <Data>01d5153a29e7eeb5</Data>
    <Data>C:\Program Files\Microsoft Office\Office15\EXCEL.EXE</Data>
    <Data>C:\Windows\SYSTEM32\ntdll.dll</Data>
    <Data>9910317c-cd4c-49b2-8869-76f88b722123</Data>
    <Data>
    </Data>
    <Data>
    </Data>
  </EventData>
</Event>
</code>```

and this is list of installed program:

```<code>    public static System.Collections.Generic.List<Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo> ReadResult(string fileAddress)
        {
            List<Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo> retList = new List<Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo>();
            Microsoft.Office.Interop.Excel.Application oXL;
            oXL = new Microsoft.Office.Interop.Excel.Application();
            try
            {
                Microsoft.Office.Interop.Excel.Workbook theWorkbook = oXL.Workbooks.Open(fileAddress);
                Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
                foreach (Microsoft.Office.Interop.Excel.Worksheet item in sheets)
                {
                    if (item.Name.Contains("Main"))
                    {
                        Microsoft.Office.Interop.Excel.Range ShtRange = item.UsedRange;
                        int CodeColumnNum = 0;
                        int PriceColumnNum = 0;
                        int NameColumnNum = 0;
                        int num = 0;
                        for (num = 1; num <= ShtRange.Columns.Count; num++)
                        {
                            try
                            {
                                string temp = string.Empty;
                                try
                                {
                                    temp = ShtRange.Cells[1, num].Value2.ToString();
                                }
                                catch
                                {
                                    temp = string.Empty;
                                }
                                if (temp.Contains("كد دارو"))
                                    CodeColumnNum = num;
                                if (temp.Contains("تغيير قيمت"))
                                    PriceColumnNum = num;
                                if (temp.Contains("نام دارو"))
                                    NameColumnNum = num;
                            }
                            catch (Exception ex)
                            {
                                if (CodeColumnNum > 0 && PriceColumnNum > 0 && NameColumnNum > 0)
                                    break;
                                oXL.Quit();
                                throw ex;
                            }
                        }

                        for (num = 2; num <= ShtRange.Rows.Count; num++)
                        {
                            Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo drug = new Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo();
                            string Codetemp = string.Empty;
                            try
                            {
                                Codetemp = ShtRange.Cells[num, CodeColumnNum].Value2.ToString();
                            }
                            catch
                            {
                                Codetemp = string.Empty;
                            }
                            string Pricetemp = string.Empty;
                            try
                            {
                                Pricetemp = ShtRange.Cells[num, PriceColumnNum].Value2.ToString();
                            }
                            catch
                            {
                                Pricetemp = string.Empty;
                            }
                            drug.Drug_Code = CodeAnalize(Codetemp);
                            drug.Drug_Price = PriceAnalize(Pricetemp);
                            drug.Drug_Name = ShtRange.Cells[num, NameColumnNum].Value2;
                            if (drug.Drug_Price != string.Empty && drug.Drug_Code != string.Empty)
                                retList.Add(drug);
                        }
                    }
                }

             theWorkbook.Save();
                return retList;
            }
            catch //(Exception ex)
            {
                return null;
            }
            finally
            {
                oXL.Quit();
            }
        }
</code>```

this problem is appears when I reinstall windows and office. installation office is 2013 (both office and win are 64 bit)

Update:

答:
Avoid Interop unless you really need it!

For Excel you can use EPPlus which is a great C# Library for read/write Excel-Files.

It works perfertly and does not require Excel to be installed on the PC.

EDIT: As changing from Interop to EPPlus is not an option for the author and with the additionally provided error information I'd like to add the folowwing to my answer.

The error is "Access Denied". So I can think of two causes:

Insufficient rights for the user to open that workbook or to start an excel process.

The workbook is in use by another process (Excel, ...)

For 1: check if the executing user can access the workbook and is allowed to start excel. Note that for an IIS-Webapplication the User is "IIS Application pool User" and not Admin.

For 2: This is what Hans mentioned before. Make sure no other instance of Excel is running.

ContentLicense: CC BY-SA 4.0

Body:
When I read (*.xls) file in C# I get an error.

I see lots of topic about "DCOM Access Denied Problem" and configuration of related problem in SO, but non of them solved my problem. all permission and administrator account was checked.  this is image of error:

Update: this is logged error by app :

Error       : The remote procedure call failed. (Exception from HRESULT: 0x800706BE)
Stack Trace : at Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad)
   at Pardic.WebProcess.frmGetPrice.worker_DoWork(Object sender, DoWorkEventArgs e)
^^-------------------------------------------------------------------^^
Source      : Microsoft.Office.Interop.Excel
Method      : Quit
Date        : 02:21:19 ب.ظ
Time        : 07/03/1398
Computer    : DESKTOP-2QPBGQ1
Error       : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
Stack Trace : at Microsoft.Office.Interop.Excel.ApplicationClass.Quit()
   at Pardic.WebProcess.frmGetPrice.worker_DoWork(Object sender, DoWorkEventArgs e)

This is Event Windows logs:

Log Name:      Application
Source:        Application Error
Date:          5/28/2019 2:16:11 PM
Event ID:      1000
Task Category: (100)
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      DESKTOP-2QPBGQ1
Description:
Faulting application name: EXCEL.EXE, version: 15.0.4420.1017, time stamp: 0x506741b5
Faulting module name: ntdll.dll, version: 10.0.14393.2214, time stamp: 0x5ac2f612
Exception code: 0xc0000005
Fault offset: 0x000000000004961c
Faulting process id: 0x1934
Faulting application start time: 0x01d5153a29e7eeb5
Faulting application path: C:\Program Files\Microsoft Office\Office15\EXCEL.EXE
Faulting module path: C:\Windows\SYSTEM32\ntdll.dll
Report Id: 9910317c-cd4c-49b2-8869-76f88b722123
Faulting package full name:
Faulting package-relative application ID:
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Application Error" />
    <EventID Qualifiers="0">1000</EventID>
    <Level>2</Level>
    <Task>100</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2019-05-28T09:46:11.052916900Z" />
    <EventRecordID>20076</EventRecordID>
    <Channel>Application</Channel>
    <Computer>DESKTOP-2QPBGQ1</Computer>
    <Security />
  </System>
  <EventData>
    <Data>EXCEL.EXE</Data>
    <Data>15.0.4420.1017</Data>
    <Data>506741b5</Data>
    <Data>ntdll.dll</Data>
    <Data>10.0.14393.2214</Data>
    <Data>5ac2f612</Data>
    <Data>c0000005</Data>
    <Data>000000000004961c</Data>
    <Data>1934</Data>
    <Data>01d5153a29e7eeb5</Data>
    <Data>C:\Program Files\Microsoft Office\Office15\EXCEL.EXE</Data>
    <Data>C:\Windows\SYSTEM32\ntdll.dll</Data>
    <Data>9910317c-cd4c-49b2-8869-76f88b722123</Data>
    <Data>
    </Data>
    <Data>
    </Data>
  </EventData>
</Event>

and this is list of installed program:

    public static System.Collections.Generic.List<Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo> ReadResult(string fileAddress)
        {
            List<Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo> retList = new List<Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo>();
            Microsoft.Office.Interop.Excel.Application oXL;
            oXL = new Microsoft.Office.Interop.Excel.Application();
            try
            {
                Microsoft.Office.Interop.Excel.Workbook theWorkbook = oXL.Workbooks.Open(fileAddress);
                Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
                foreach (Microsoft.Office.Interop.Excel.Worksheet item in sheets)
                {
                    if (item.Name.Contains("Main"))
                    {
                        Microsoft.Office.Interop.Excel.Range ShtRange = item.UsedRange;
                        int CodeColumnNum = 0;
                        int PriceColumnNum = 0;
                        int NameColumnNum = 0;
                        int num = 0;
                        for (num = 1; num <= ShtRange.Columns.Count; num++)
                        {
                            try
                            {
                                string temp = string.Empty;
                                try
                                {
                                    temp = ShtRange.Cells[1, num].Value2.ToString();
                                }
                                catch
                                {
                                    temp = string.Empty;
                                }
                                if (temp.Contains("كد دارو"))
                                    CodeColumnNum = num;
                                if (temp.Contains("تغيير قيمت"))
                                    PriceColumnNum = num;
                                if (temp.Contains("نام دارو"))
                                    NameColumnNum = num;
                            }
                            catch (Exception ex)
                            {
                                if (CodeColumnNum > 0 && PriceColumnNum > 0 && NameColumnNum > 0)
                                    break;
                                oXL.Quit();
                                throw ex;
                            }
                        }

                        for (num = 2; num <= ShtRange.Rows.Count; num++)
                        {
                            Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo drug = new Pardic.DataAwareCtrls.Progress.InsuranceDrugInfo();
                            string Codetemp = string.Empty;
                            try
                            {
                                Codetemp = ShtRange.Cells[num, CodeColumnNum].Value2.ToString();
                            }
                            catch
                            {
                                Codetemp = string.Empty;
                            }
                            string Pricetemp = string.Empty;
                            try
                            {
                                Pricetemp = ShtRange.Cells[num, PriceColumnNum].Value2.ToString();
                            }
                            catch
                            {
                                Pricetemp = string.Empty;
                            }
                            drug.Drug_Code = CodeAnalize(Codetemp);
                            drug.Drug_Price = PriceAnalize(Pricetemp);
                            drug.Drug_Name = ShtRange.Cells[num, NameColumnNum].Value2;
                            if (drug.Drug_Price != string.Empty && drug.Drug_Code != string.Empty)
                                retList.Add(drug);
                        }
                    }
                }

             theWorkbook.Save();
                return retList;
            }
            catch //(Exception ex)
            {
                return null;
            }
            finally
            {
                oXL.Quit();
            }
        }

this problem is appears when I reinstall windows and office. installation office is 2013 (both office and win are 64 bit)

Update:


问:
How to fix wrong cultural infos in azure?
Even though i am using the right region for the WebApp, its displaying the wrong time format and currency. So how can i change the region in order to fit my country (Germany).

I have tried to change the plan to a different region. Didnt work (used us before and changed to eu west)

答:
I suggest you, refer Implementing custom cultures, CultureInfo, localize Azure App Service for more details.

Here you can find all the supported culture list:

http://customcultures.azurewebsites.net/

just deploying the code to the region wont help . you can use i18N though to implement it.

The i18n library is designed to replace the use of .NET resources in favor of an easier, globally recognized standard for localizing ASP.NET-based web applications.

you can find the sample here. Hope it helps.


问:
Need to select values from a column using a list of strings using pandas.str()
Need to search a string column values from a list of strings. The strings in the search list are only a substring of the values in the column

```<code>df = pd.DataFrame(data={'text':['abc def', 'def ghi', 'poi opo', 'aswwf', 'abcs  sd'], 'id':[1, 2, 3, 4, 5]})

Out [1]:
    text     id
0   abc def  1
1   def ghi  2
2   poi opo  3
3   aswwf    4
4   abcs sd  5

search = ['abc', 'poi']
</code>```

Required:

```<code>
Out [2]:
    text     id
0   abc def  1
1   poi opo  3
2   abcs sd  5
</code>```

答:
@jezrael'answer is great, provided the patterns to search contain no special characters like |. But you can process every element at a time and do a global or at the end. If you want to search strings containing special characters, you can use:

```<code>df[pd.concat([df.text.str.contains(i, regex=False) for i in search], axis=1).any(axis=1)]
</code>```

it gives as expected:

```<code>       text  id
0   abc def   1
2   poi opo   3
4  abcs  sd   5
</code>```

Body:
Need to search a string column values from a list of strings. The strings in the search list are only a substring of the values in the column

df = pd.DataFrame(data={'text':['abc def', 'def ghi', 'poi opo', 'aswwf', 'abcs  sd'], 'id':[1, 2, 3, 4, 5]})

Out [1]:
    text     id
0   abc def  1
1   def ghi  2
2   poi opo  3
3   aswwf    4
4   abcs sd  5

search = ['abc', 'poi']

Required:

Out [2]:
    text     id
0   abc def  1
1   poi opo  3
2   abcs sd  5

Body:
@jezrael'answer is great, provided the patterns to search contain no special characters like |. But you can process every element at a time and do a global or at the end. If you want to search strings containing special characters, you can use:

df[pd.concat([df.text.str.contains(i, regex=False) for i in search], axis=1).any(axis=1)]

it gives as expected:

       text  id
0   abc def   1
2   poi opo   3
4  abcs  sd   5


问:
Laravel or MySQL where correctly word
I have a question. I can not solve it.

I have this database

```<code>+--------+---------------+
|    id  |      name     |
+--------+---------------+
|    1   |     backup    |
+--------+---------------+
|    2   |     BACKUP    |
+--------+---------------+
</code>```

My Model is Post
I use where clause to find name  called backup

```<code>Post::where('name','backup')->get();
</code>```

But i got 2 posts not 1 post

Please help me this problem
Thank you

答:
Please use </p>

```<code>Post::where('name', 'LIKE', 'backup')->first();
</code>```

Title: Laravel or MySQL where correctly word

Body:
I have a question. I can not solve it.

I have this database

+--------+---------------+
|    id  |      name     |
+--------+---------------+
|    1   |     backup    |
+--------+---------------+
|    2   |     BACKUP    |
+--------+---------------+

My Model is Post
I use where clause to find name  called backup

Post::where('name','backup')->get();

But i got 2 posts not 1 post

Please help me this problem
Thank you

Body:
Please use

Post::where('name', 'LIKE', 'backup')->first();


问:
Where can I find source code of ldconfig?
I want to peek into its implementation,where is it available?</p>

答: ldconfig is the part of glibc library.

ContentLicense: CC BY-SA 3.0

Body: ldconfig is the part of glibc library.


问:
could someone explain me why there should be a for loop in this code
I am learning python from a book (python crash course by Eric Matthes)
but i find this code imposible for me to understand.</p>

```<code>def build_profile(first, last, **user_info):
         """Build a dictionary containing everything we know about a user."""
   profile = {}
   profile['first_name'] = first
   profile['last_name'] = last
   for key, value in user_info.items():
      profile[key] = value
   return profile
user_profile = build_profile('albert', 'einstein',
                  location='princeton',
                   field='physics')
print(user_profile)
</code>```

答:
You can check this GeeksforGeeks article for more details. In short, **user_info is a dict that contains  any additional named arguments you pass as key-value pairs. So in order to include it in the profile dict, we loop over its items().

For example, if I call build_profile('Steve', 'William', age=24), you would see that user_info would be {'age': 24}.

In the example you've included, it would be {'location':'princeton', 'field':'physics'}.

Body:
I am learning python from a book (python crash course by Eric Matthes)
but i find this code imposible for me to understand.

def build_profile(first, last, **user_info):
         """Build a dictionary containing everything we know about a user."""
   profile = {}
   profile['first_name'] = first
   profile['last_name'] = last
   for key, value in user_info.items():
      profile[key] = value
   return profile
user_profile = build_profile('albert', 'einstein',
                  location='princeton',
                   field='physics')
print(user_profile)


问:
Correct use of Angular TypeScript constructor - Can't resolve all parameters for
```<code>@Injectable({
  providedIn: 'root',
  /* useFactory: () => new MyService(MyAnotherService.myInteger) */
})
export class MyService{

  constructor(private someInteger?: number) {
    // doThings with someInteger
  }
</code>```

--aot build will complain that Warning: Can't resolve all parameters for...

In fact, due to the useFactory: () part, we are still able to run our application correctly. But I do not know if this is the right way or not

We can, of course, change the constructor to

```<code>constructor(private anotherService?: MyAnotherService) {
        // doThings with anotherService
      }
</code>```

To shut the build warning,
However I do not think that MyService should be dependent on MyAnotherService when It can be just dependent on a primitive, It's also bad for code reusability

What is the best thing to do in this situation?

My idea is that. Angular use Decorator to instruct that it is an Angular component ( am I right? )
So the main logic body should not always be coupled to Angular DI logic, especially if It is a service. We can pull the service code and plug it elsewhere ( Using DI or not )

答:
The common practice is to put so little logic in it as possible.
Most of the time the constructor is used to inject dependencies.

```<code>constructor(private anotherService: AnotherService) {
    // **don't** do Things with anotherService
  }
</code>```

and then use it in another functions

```<code>ngOnInit() {
   this.anotherService.getValue().subscribe((value) => {
      // do something
   });
}
</code>```

The function ngOnInit() will be called when the DOM from the component was created, all dependencies was injected and all inputs was binded. It's common practice to use the ngOnInit() even if the logic doesn't depend on DOM, input binding or Dependencie injection.

Body:
@Injectable({
  providedIn: 'root',
  /* useFactory: () => new MyService(MyAnotherService.myInteger) */
})
export class MyService{

  constructor(private someInteger?: number) {
    // doThings with someInteger
  }

--aot build will complain that Warning: Can't resolve all parameters for...

In fact, due to the useFactory: () part, we are still able to run our application correctly. But I do not know if this is the right way or not

We can, of course, change the constructor to

constructor(private anotherService?: MyAnotherService) {
        // doThings with anotherService
      }

To shut the build warning,
However I do not think that MyService should be dependent on MyAnotherService when It can be just dependent on a primitive, It's also bad for code reusability

What is the best thing to do in this situation?

My idea is that. Angular use Decorator to instruct that it is an Angular component ( am I right? )
So the main logic body should not always be coupled to Angular DI logic, especially if It is a service. We can pull the service code and plug it elsewhere ( Using DI or not )

Body:
The common practice is to put so little logic in it as possible.
Most of the time the constructor is used to inject dependencies.

constructor(private anotherService: AnotherService) {
    // **don't** do Things with anotherService
  }

and then use it in another functions

ngOnInit() {
   this.anotherService.getValue().subscribe((value) => {
      // do something
   });
}

The function ngOnInit() will be called when the DOM from the component was created, all dependencies was injected and all inputs was binded. It's common practice to use the ngOnInit() even if the logic doesn't depend on DOM, input binding or Dependencie injection.


问:
Icons do not load in tab bar scene/stack
I am trying to set up my tab bar with icons, but my screen only displays the scene text without icons:

To help simplify, I made a function that takes in props of an icon name and outputs an Icon element called TabIcon, but this function doesn't run. I tested this by placing an alert in the function. I removed most scenes and only left submit to simplify code, it is near the bottom of the code. Here is my router.js:

```<code>import React from 'react';
import { Scene, Router, ActionConst, Stack, Modal, Tabs } from 'react-native-router-flux';
import { View, Text, Icon } from 'react-native-elements';
//Splash Component
import Splash from '../components/Splash/Splash';

//Authentication Scenes
//removed import screens to simplify

import { StackNavigator } from 'react-navigation';

//Import Store, actions
import store from '../redux/store'
import { checkLoginStatus } from "../modules/auth/actions";

import { color, navTitleStyle } from "../styles/theme";

function TabIcon(props) {
    return (
      <View style={styles.container}>
        <Icon
          color={props.tintColor}
          name={props.iconName}
          size={26}
          />
      </View>
    )
  }

  const styles = {
    container: {
      width: 48,
      height: 42,
      padding: 5,
      justifyContent: 'center',
      alignItems: 'center',
    }
  };

export default class extends React.Component {
    constructor() {
        super();
        this.state = {
            isReady: false,
            isLoggedIn: false
        }
    }

    componentDidMount() {
        let _this = this;
        store.dispatch(checkLoginStatus((isLoggedIn) => {
            _this.setState({isReady: true, isLoggedIn});
        }));
    }

    render() {
        if (!this.state.isReady)
            return <Splash/>

        return (
            <Router>
                <Scene key="root" hideNavBar
                        navigationBarStyle={{backgroundColor: "#fff"}}
                        titleStyle={navTitleStyle}
                        backButtonTintColor={color.black}
                >
                    <Stack key="Main" tabs={true} initial={this.state.isLoggedIn}>
                        //here's the scene that uses the TabIcon function//////////////////
                        <Scene key="Submit" component={Submit} title="Submit" icon={TabIcon} iconName='timer' />
                    </Stack>
                </Scene>
            </Router>
        )
    }
}
</code>```

答:
In my solution it worked: if Icon={myIcon} is not working, try tabBarLabel={myIcon}

```<code>                <Scene key="tabs" hideNavBar tabs={true}
                tabBarStyle={}>
                    <Scene key="roomTab" tabBarLabel={roomIcon} >
                        <Scene
                            key="rooms"
                            hideNavBar
                            component={Rooms}
                            initial={true}
                        />
                    </Scene>
</code>```

Body:
I am trying to set up my tab bar with icons, but my screen only displays the scene text without icons:

To help simplify, I made a function that takes in props of an icon name and outputs an Icon element called TabIcon, but this function doesn't run. I tested this by placing an alert in the function. I removed most scenes and only left submit to simplify code, it is near the bottom of the code. Here is my router.js:

import React from 'react';
import { Scene, Router, ActionConst, Stack, Modal, Tabs } from 'react-native-router-flux';
import { View, Text, Icon } from 'react-native-elements';
//Splash Component
import Splash from '../components/Splash/Splash';

//Authentication Scenes
//removed import screens to simplify

import { StackNavigator } from 'react-navigation';

//Import Store, actions
import store from '../redux/store'
import { checkLoginStatus } from "../modules/auth/actions";

import { color, navTitleStyle } from "../styles/theme";

function TabIcon(props) {
    return (
      <View style={styles.container}>
        <Icon
          color={props.tintColor}
          name={props.iconName}
          size={26}
          />
      </View>
    )
  }

  const styles = {
    container: {
      width: 48,
      height: 42,
      padding: 5,
      justifyContent: 'center',
      alignItems: 'center',
    }
  };

export default class extends React.Component {
    constructor() {
        super();
        this.state = {
            isReady: false,
            isLoggedIn: false
        }
    }

    componentDidMount() {
        let _this = this;
        store.dispatch(checkLoginStatus((isLoggedIn) => {
            _this.setState({isReady: true, isLoggedIn});
        }));
    }

    render() {
        if (!this.state.isReady)
            return <Splash/>

        return (
            <Router>
                <Scene key="root" hideNavBar
                        navigationBarStyle={{backgroundColor: "#fff"}}
                        titleStyle={navTitleStyle}
                        backButtonTintColor={color.black}
                >
                    <Stack key="Main" tabs={true} initial={this.state.isLoggedIn}>
                        //here's the scene that uses the TabIcon function//////////////////
                        <Scene key="Submit" component={Submit} title="Submit" icon={TabIcon} iconName='timer' />
                    </Stack>
                </Scene>
            </Router>
        )
    }
}

Body:
In my solution it worked: if Icon={myIcon} is not working, try tabBarLabel={myIcon}

                <Scene key="tabs" hideNavBar tabs={true}
                tabBarStyle={}>
                    <Scene key="roomTab" tabBarLabel={roomIcon} >
                        <Scene
                            key="rooms"
                            hideNavBar
                            component={Rooms}
                            initial={true}
                        />
                    </Scene>


问:
Change ID of an element where Class is X
I'm trying to change the ID of a div via Ajax.

Because the ID has a dynamic value I added a class to the div.

My php code:

```<code>    echo '<div id="pagemenu">
            <ul id="tabpanel">';
$tel = 0;
while($totaalklanten > -4)
{
    $tel++;
    echo '<li><a href="#'.$tel.'" name="'.$tel.'" onclick="listklant(\'klant.php\',this.name)">'.$tel.'</a></li>';
    $totaalklanten = $totaalklanten - 5;
}
echo '</ul>';
echo '<div class="changeme" id="default">';
//Lots of query of php stuff here to execute
echo '</div>
</code>```

The div with the class 'changeme' is the victim.

My Ajax code so far:

```<code>xmlhttp = new XMLHttpRequest();

function listklant(serverPage, pagenum)
{
    xmlhttp.open("GET", serverPage);

    document.getElementsByClassName('changeme').id = pagenum;
    alert(document.getElementById(pagenum));
    alert(document.getElementsByClassName('changeme').id);

    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            obj.innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.send(null);
}
</code>```

The first alert gives me 'null' :(...

Yet the second alert gives me the right value, so 'pagenum' was applied succesfully.

What am I doing wrong? And how to fix it?

(If there is anything else I can improve, please give a shout)

答:
```<code>document.getElementsByClassName('changeme').id = pagenum;
</code>```

This line of code does not set the id of elements with the class changeme. getElementsByClassName returns a NodeList containing the elements.  You are setting an id property on the NodeList.  Obviously, this is not reflected on the elements within the list.

To do this, work on the elements themselves.  If you have one element with the class, that is simple:

```<code>document.getElementsByClassName('changeme')[0].id = pagenum;
</code>```

If you have more elements, you'll need a loop:

```<code>var els = document.getElementsByClassName('changeme');
for (var i = 0; i < els.length; i++ ) {
    els[i].id = pagenum;
}
</code>```

However, it's probably a bad idea to change an element's id.  Using a class might well be a better idea here.

Edit To explain why your second alert works, it is because the same NodeList is returned by the call to getElementsByClassName.  From the spec:

When the method [getElementsByClassName] is invoked on an HTMLElement object again with the same argument, the user agent may return the same object as the object returned by the earlier call.

Body:
I'm trying to change the ID of a div via Ajax.

Because the ID has a dynamic value I added a class to the div.

My php code:

    echo '

';
$tel = 0;
while($totaalklanten > -4)
{
    $tel++;
    echo '
'.$tel.'
';
    $totaalklanten = $totaalklanten - 5;
}
echo '
';
echo '
';
//Lots of query of php stuff here to execute
echo '

The div with the class 'changeme' is the victim.

My Ajax code so far:

xmlhttp = new XMLHttpRequest();

function listklant(serverPage, pagenum)
{
    xmlhttp.open("GET", serverPage);

    document.getElementsByClassName('changeme').id = pagenum;
    alert(document.getElementById(pagenum));
    alert(document.getElementsByClassName('changeme').id);

    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            obj.innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.send(null);
}

The first alert gives me 'null' :(...

Yet the second alert gives me the right value, so 'pagenum' was applied succesfully.

What am I doing wrong? And how to fix it?

(If there is anything else I can improve, please give a shout)

Body:
document.getElementsByClassName('changeme').id = pagenum;

This line of code does not set the id of elements with the class changeme. getElementsByClassName returns a NodeList containing the elements.  You are setting an id property on the NodeList.  Obviously, this is not reflected on the elements within the list.

To do this, work on the elements themselves.  If you have one element with the class, that is simple:

document.getElementsByClassName('changeme')[0].id = pagenum;

If you have more elements, you'll need a loop:

var els = document.getElementsByClassName('changeme');
for (var i = 0; i < els.length; i++ ) {
    els[i].id = pagenum;
}

However, it's probably a bad idea to change an element's id.  Using a class might well be a better idea here.

Edit To explain why your second alert works, it is because the same NodeList is returned by the call to getElementsByClassName.  From the spec:

When the method [getElementsByClassName] is invoked on an HTMLElement object again with the same argument, the user agent may return the same object as the object returned by the earlier call.


问:
What are the possible Android Element-Attributes for custom styles?
I have the following code example:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="GreenText" parent="TextAppearance.AppCompat">
        <item name="android:textColor">#00FF00</item>
    </style>
</resources>
</code>```

Does anyone knows where to find a list with all available "Attribute-Keys" for the name-attribute?

An example would be android:### for Padding, Text-Size and Margin

答: I found the list of all available attribute keys here: https://developer.android.com/reference/android/view/View.html#lattrs</p>

Body:
I have the following code example:

<?xml version="1.0" encoding="utf-8"?>
<resources>

</resources>

Does anyone knows where to find a list with all available "Attribute-Keys" for the name-attribute?

An example would be android:### for Padding, Text-Size and Margin


问:
How to truncate a list if condition is satisfied
I have a list of values and basically I want to go through the list, and check if I have more than 20 consecutive values below a certain minimum. If that is true I want to end the list where the last number above minimum was.

I tried the following with no success :

```<code>for j in range(0,len(List)):
    if all(k<minimumthreshold for k in List[j:j+20]):
        List= [e for e in List if e != j]
</code>```

答:
You should so something like this -
(Consider this as a  pseudo-code)</p>

```<code>your_list = [.....]
counter = 0
stop_at = 20  #Set it accordingly
minimum = 30  # Set it accordingly
split_at_index = None
for index, list_item in enumerate(your_list):
    if list_item < minimum:
        counter += 1
    else:
        counter = 0
        continue
    if counter == stop_at:
        split_at_index = index
        break
new_list = your_list[:split_at_index]
</code>```

Body:
I have a list of values and basically I want to go through the list, and check if I have more than 20 consecutive values below a certain minimum. If that is true I want to end the list where the last number above minimum was.

I tried the following with no success :

for j in range(0,len(List)):
    if all(k<minimumthreshold for k in List[j:j+20]):
        List= [e for e in List if e != j]

Body:
You should so something like this -
(Consider this as a  pseudo-code)

your_list = [.....]
counter = 0
stop_at = 20  #Set it accordingly
minimum = 30  # Set it accordingly
split_at_index = None
for index, list_item in enumerate(your_list):
    if list_item < minimum:
        counter += 1
    else:
        counter = 0
        continue
    if counter == stop_at:
        split_at_index = index
        break
new_list = your_list[:split_at_index]


问:
Detect errors from Informatica Log via ETL
I am writing data in flat files using Informatica, with a Transaction Control Transformation to split the output in several files.

I need to know if a particular file fails to be created and to write down in a log table this incidence. I have forced some errors (v.g. forcing a non-existent directory in the filename.) and then I have attempted to capture the error.

Defining Error Log Type (Config Object tab) in the session properties does not show any relevant exception.

Checking Write Backward Compatible Session Log File (Properties tab) in the session properties does work.

However, the backward compatible log file is not easy to decrypt. I could recognize the error I forced.

```<code>WRITER_1_*_1> WRT_8004 Writer initialization failed [Error opening session output file [/path-to-file/fake-path/filename.csv] [error=No such file or directory]]. Writer terminating.
WRITER_1_*_1> CMN_1761 Timestamp Event: [Mon May 27 18:20:28 2019]
WRITER_1_*_1> WRT_8064 Error opening session output file [/path-to-file/fake-path/filename.csv] [errno=2] [error=No such file or directory]
WRITER_1_*_1> WRT_8333 Rolling back all the targets due to fatal session error.
WRITER_1_*_1> CMN_1761 Timestamp Event: [Mon May 27 18:20:28 2019]
WRITER_1_*_1> WRT_8081 Writer run terminated. [Error in loading data to target table [MAPPING_CSV]]
</code>```

For this specific error I could capture some part of the strings above, however I would like to know if there is some general way to recognize an error, and not get confused with false positives such as

```<code>MAPPING> TM_6307 DTM error log disabled.
</code>```

or

```<code>DBG_21216 Finished transformations for Source Qualifier [LKPTRANS{{DSQ}}]. Total errors [0]
</code>```

I plan to capture error messages, decode them and then write them in a database table.

Thank you in advance.

答: If you choose to log errors to table instead of file, it will include relevant field values at the time the error occurred. I'd suggest using filename port instead of transaction control and then the filename port will hold the name of the error file the record failed with.  </p>

Body:
I am writing data in flat files using Informatica, with a Transaction Control Transformation to split the output in several files.

I need to know if a particular file fails to be created and to write down in a log table this incidence. I have forced some errors (v.g. forcing a non-existent directory in the filename.) and then I have attempted to capture the error.

Defining Error Log Type (Config Object tab) in the session properties does not show any relevant exception.

Checking Write Backward Compatible Session Log File (Properties tab) in the session properties does work.

However, the backward compatible log file is not easy to decrypt. I could recognize the error I forced.

WRITER_1_*_1> WRT_8004 Writer initialization failed [Error opening session output file [/path-to-file/fake-path/filename.csv] [error=No such file or directory]]. Writer terminating.
WRITER_1_*_1> CMN_1761 Timestamp Event: [Mon May 27 18:20:28 2019]
WRITER_1_*_1> WRT_8064 Error opening session output file [/path-to-file/fake-path/filename.csv] [errno=2] [error=No such file or directory]
WRITER_1_*_1> WRT_8333 Rolling back all the targets due to fatal session error.
WRITER_1_*_1> CMN_1761 Timestamp Event: [Mon May 27 18:20:28 2019]
WRITER_1_*_1> WRT_8081 Writer run terminated. [Error in loading data to target table [MAPPING_CSV]]

For this specific error I could capture some part of the strings above, however I would like to know if there is some general way to recognize an error, and not get confused with false positives such as

MAPPING> TM_6307 DTM error log disabled.

or

DBG_21216 Finished transformations for Source Qualifier [LKPTRANS{{DSQ}}]. Total errors [0]

I plan to capture error messages, decode them and then write them in a database table.

Thank you in advance.


问:
PHP object with soap XML identity claim property
I'm using PHP. I have an object that has a mobile phone as identity claim property. So my object looks like {'http:schemas.cmlsoap.org/ws/2005/05/dentity/claims/mobilephone': 1231231}. What's the easiest way to get that property value?

I tried using curly bracket {} to access that property value, but no good.

答: I ended up using get_object_vars and then accessing it as an array. </p>


问:
Cypress visit and wait timeouts ignored
I created a test where I setup a route, try to visit a page which makes an API request to the route and then wait for the route response:

```<code>cy
    .server()
    .route('GET', '/api/testing')
    .as('testing');
cy.visit('/index.html', { timeout: 60000 });
cy.wait('@testing', { timeout: 60000 });
</code>```

This only waits for the Cypress global default responseTimeout of 30 seconds and then fails the API request.

Here's the error message logged by Cypress in the console:

Cypress errored attempting to make an http request to this url:
  https://localhost:4200/api/testing

The error was:

ESOCKETTIMEDOUT

The stack trace was:

Error: ESOCKETTIMEDOUT

      at ClientRequest. (…\node_modules\cypress\dist\Cypress\resources\app\packages\server\node_modules\request\request.js:778:19)

      at Object.onceWrapper (events.js:314:30)

      at emitNone (events.js:105:13)

      at ClientRequest.emit (events.js:207:7)

      at TLSSocket.emitTimeout (_http_client.js:722:34)

      at Object.onceWrapper (events.js:314:30)

      at emitNone (events.js:105:13)

      at TLSSocket.emit (events.js:207:7)

      at TLSSocket.Socket._onTimeout (net.js:402:8)
      at ontimeout (timers.js:469:11)

      at tryOnTimeout (timers.js:304:5)

      at Timer.listOnTimeout (timers.js:264:5)

Adding a responseTimeout to the global config of Cypress will increase the timeout, but why isn't the timeout for either the visit or the wait occurring?

答:
.vist() and .wait() didn't work for me, error logs on cypress suggested using .request() instead which works fine.

cy.server();
cy.request('/api/path').then((xhr) => {
  console.log(xhr.body)
})```

Title: Cypress visit and wait timeouts ignored

Body:
I created a test where I setup a route, try to visit a page which makes an API request to the route and then wait for the route response:

cy
    .server()
    .route('GET', '/api/testing')
    .as('testing');
cy.visit('/index.html', { timeout: 60000 });
cy.wait('@testing', { timeout: 60000 });

This only waits for the Cypress global default responseTimeout of 30 seconds and then fails the API request.

Here's the error message logged by Cypress in the console:

Cypress errored attempting to make an http request to this url:
  https://localhost:4200/api/testing

The error was:

ESOCKETTIMEDOUT

The stack trace was:

Error: ESOCKETTIMEDOUT

      at ClientRequest. (…\node_modules\cypress\dist\Cypress\resources\app\packages\server\node_modules\request\request.js:778:19)

      at Object.onceWrapper (events.js:314:30)

      at emitNone (events.js:105:13)

      at ClientRequest.emit (events.js:207:7)

      at TLSSocket.emitTimeout (_http_client.js:722:34)

      at Object.onceWrapper (events.js:314:30)

      at emitNone (events.js:105:13)

      at TLSSocket.emit (events.js:207:7)

      at TLSSocket.Socket._onTimeout (net.js:402:8)
      at ontimeout (timers.js:469:11)

      at tryOnTimeout (timers.js:304:5)

      at Timer.listOnTimeout (timers.js:264:5)

Adding a responseTimeout to the global config of Cypress will increase the timeout, but why isn't the timeout for either the visit or the wait occurring?


问:
Adding a row spanning column header to a knitr kable table
kableExtra can add header rows with items spanning multiple columns in tables produces with kable

```<code>library(tidyverse)
library(knitr)
library(kableExtra)
mat <- matrix(1:4,2,dimnames=list(c("a","b"),c("x","y")))
mat %>% kable("html") %>% add_header_above(c(" " = 1,"row header" = 2))
</code>```

I would like to have a column header also, like this:

Can it be done?

答:
i don't think you can do it but i found a way to fix your issue

```<code>mat <- data.frame(a = c("row header","row header"),b = c("a","b"),c = c("x","y"))
mat %>% kable("html") %>% add_header_above(c(" " = 1,"row header" = 2))

kable(mat, align = "c",col.names = c("","","")) %>%
kable_styling(bootstrap_options = "striped", full_width = F, position = "left",font_size = 12)%>%
column_spec(1, bold = T) %>%
collapse_rows(columns = 1, valign = "middle")%>%
add_header_above(c(" " = 1, "row header" = 2))
</code>```

i hope this helps you

Body:
kableExtra can add header rows with items spanning multiple columns in tables produces with kable

library(tidyverse)
library(knitr)
library(kableExtra)
mat <- matrix(1:4,2,dimnames=list(c("a","b"),c("x","y")))
mat %>% kable("html") %>% add_header_above(c(" " = 1,"row header" = 2))

I would like to have a column header also, like this:

Can it be done?

Body:
i don't think you can do it but i found a way to fix your issue

mat <- data.frame(a = c("row header","row header"),b = c("a","b"),c = c("x","y"))
mat %>% kable("html") %>% add_header_above(c(" " = 1,"row header" = 2))

kable(mat, align = "c",col.names = c("","","")) %>%
kable_styling(bootstrap_options = "striped", full_width = F, position = "left",font_size = 12)%>%
column_spec(1, bold = T) %>%
collapse_rows(columns = 1, valign = "middle")%>%
add_header_above(c(" " = 1, "row header" = 2))

i hope this helps you


问:
How to convert object in to an array in javascript in protractor
How to convert object into an array in javascript in protractor.

This is my code:-

```<code>var jsonResponse = JSON.stringify(response);
console.log('---------response is: ' + jsonResponse);
</code>```

then I got below output:-

```<code>{"statusCode":200,"body":{"oBody":{"payLoad":{"sLoginId":"HDB_TW_DSA@softcell.com","iInstId":4019}}}}
</code>```

Now, I want 200 as an output

I tried this below code for that

```<code>var result = Object.keys(jsonResponse).map(function(key) {
console.log([Number(key), jsonResponse[key]]);
</code>```

But I'm getting below output

```<code>[ 0, '{' ]
[ 1, '"' ]
[ 2, 's' ]
[ 3, 't' ]
[ 4, 'a' ]
[ 5, 't' ]
[ 6, 'u' ]
[ 7, 's' ]
...
</code>```

like this

but I want output as

```<code>[{"statusCode":200,"body":{"oBody":{"payLoad":{"sLoginId":"HDB_TW_DSA@softcell.com","iInstId":4019}}}}]
</code>```

so, I can use 0th element of array.

答:
As i understood your question correctly then you are trying to structure json in required format so that you can access it's data. If this is the case then my recommendation is to use node-json-transform npm that would allow you to create structure as per your need.

use npm i node-json-transform

For more information refer this link

Body:
How to convert object into an array in javascript in protractor.

This is my code:-

var jsonResponse = JSON.stringify(response);
console.log('---------response is: ' + jsonResponse);

then I got below output:-

{"statusCode":200,"body":{"oBody":{"payLoad":{"sLoginId":"HDB_TW_DSA@softcell.com","iInstId":4019}}}}

Now, I want 200 as an output

I tried this below code for that

var result = Object.keys(jsonResponse).map(function(key) {
console.log([Number(key), jsonResponse[key]]);

But I'm getting below output

[ 0, '{' ]
[ 1, '"' ]
[ 2, 's' ]
[ 3, 't' ]
[ 4, 'a' ]
[ 5, 't' ]
[ 6, 'u' ]
[ 7, 's' ]
...

like this

but I want output as

[{"statusCode":200,"body":{"oBody":{"payLoad":{"sLoginId":"HDB_TW_DSA@softcell.com","iInstId":4019}}}}]

so, I can use 0th element of array.


问:
Liquibase Code generated for a conditional index gives error in MS SQL Server
I have this following index in my SQL Server Database

CREATE NONCLUSTERED INDEX XCR_ACTIVE ON dbo.CS_PA_VEH_BASE ( ETL_ACTIVE_FL )
WHERE ETL_ACTIVE_FL = 'N' ON "default";
```
<p>for which <code>liquibase</code> gives out following:</p>
<pre class="lang-xml prettyprint-override"><code><createIndex indexName="XCR_ACTIVE" tableName="CS_PA_VEH_DELTA">
    <column computed="true" name="([ETL_ACTIVE_FL]='N')"/>
</createIndex>
</code>```

But when I want to execute it (also in MS SQL Server) I get the following

```<code>> **Error:**  (14.2) 05-24-19 11:43:05 (E) (13004:15088) RUN-050304: |Session JOB_ODS_Liquibase Function call <raise_exception ( Liquibase
> update error: 1: Unexpected error running Liquibase: Incorrect syntax
> near '('. [Failed SQL: CREATE NONCLUSTERED INDEX XCR_ACTIVE ON
> [dbo].[CS_PA_VEH_DELTA](([ETL_ACTIVE_FL]='N'))] ) > failed, due to
> error <50316>: <Liquibase update error:-1: Unexpected error running
> Liquibase: Incorrect syntax near '('. [Failed SQL: CREATE NONCLUSTERED
> INDEX XCR_ACTIVE ON [dbo].[CS_PA_VEH_DELTA](([ETL_ACTIVE_FL]='N'))]>.
</code>```

I hope it's not the first time this is happening to someone.

答:
Nothing is mentioned about "Indexes with Filter" in the standard Liquibase documentation:
https://www.liquibase.org/documentation/changes/create_index.html
but what Nathan mentions here http://forum.liquibase.org/topic/how-to-create-conditional-indexes-using-createindex?reply=true about modifySQL should work.</p>

Body:
I have this following index in my SQL Server Database

CREATE NONCLUSTERED INDEX XCR_ACTIVE ON dbo.CS_PA_VEH_BASE ( ETL_ACTIVE_FL )
WHERE ETL_ACTIVE_FL = 'N' ON "default";

for which liquibase gives out following:

<createIndex indexName="XCR_ACTIVE" tableName="CS_PA_VEH_DELTA">
    <column computed="true" name="([ETL_ACTIVE_FL]='N')"/>
</createIndex>

But when I want to execute it (also in MS SQL Server) I get the following

> **Error:**  (14.2) 05-24-19 11:43:05 (E) (13004:15088) RUN-050304: |Session JOB_ODS_Liquibase Function call <raise_exception ( Liquibase
> update error: 1: Unexpected error running Liquibase: Incorrect syntax
> near '('. [Failed SQL: CREATE NONCLUSTERED INDEX XCR_ACTIVE ON
> [dbo].[CS_PA_VEH_DELTA](([ETL_ACTIVE_FL]='N'))] ) > failed, due to
> error <50316>: <Liquibase update error:-1: Unexpected error running
> Liquibase: Incorrect syntax near '('. [Failed SQL: CREATE NONCLUSTERED
> INDEX XCR_ACTIVE ON [dbo].[CS_PA_VEH_DELTA](([ETL_ACTIVE_FL]='N'))]>.

I hope it's not the first time this is happening to someone.


问:
Deprecated methods in rxjs v6
I try to use combineLatest:

```<code>import { combineLatest } from 'rxjs/Observable';
</code>```

but I get the warning

```<code>combineLatest is deprecated: Deprecated in favor of static combineLatest.
</code>```

If I follow the solution provided in the RxJS v5.x to v6 Update Guide as it is stated here and I write

```<code>import { combineLatest } from 'rxjs';
</code>```

then I get the tslint message:

```<code>This import is blacklisted, import a submodule instead
</code>```

which seems a bit a snake biting its own tail...

If I use

```<code>import { combineLatest } from 'rxjs/internal/observable/combineLatest';
</code>```

then it works without warning messages, but as far as I know, it's not recommended to import internal packages (correct me if I'm wrong).

Disabling tslint messages doesn't seem acceptable to me.

Example:

```<code>this.Subscription = combineLatest([a,b])
    .pipe(
      map( (...) )
    ).subscribe( (...) );
</code>```

Which is the appropriate solution? Thanks.

答:
Since this is the sanctioned by the official documentation way of importing combineLatest, tslint is just being silly here.

Edit your tslint.json and remove rxjs the "import-blacklist" entry.

Title: Deprecated methods in rxjs v6

Body:
I try to use combineLatest:

import { combineLatest } from 'rxjs/Observable';

but I get the warning

combineLatest is deprecated: Deprecated in favor of static combineLatest.

If I follow the solution provided in the RxJS v5.x to v6 Update Guide as it is stated here and I write

import { combineLatest } from 'rxjs';

then I get the tslint message:

This import is blacklisted, import a submodule instead

which seems a bit a snake biting its own tail...

If I use

import { combineLatest } from 'rxjs/internal/observable/combineLatest';

then it works without warning messages, but as far as I know, it's not recommended to import internal packages (correct me if I'm wrong).

Disabling tslint messages doesn't seem acceptable to me.

Example:

this.Subscription = combineLatest([a,b])
    .pipe(
      map( (...) )
    ).subscribe( (...) );

Which is the appropriate solution? Thanks.


问:
calculating price with two values
So I have something like this...

I have a form where you select your gender and input your weight. each gender has different ranges of prices for example if your a male and your weight is greater than 200 your price is 20, if your a female and your weight is greater than 200 your price is 15, and if your male and your weight is less than 200 your price is 10, for the female if her weight is less than 200 her price is 7     . i have been trying to make it possible with jquery and PHP but it only seems to work with select option and won't work with input data.

this is my index.php

```<code>   <div class="container">

      <div class="row">
       <div class="col-xs-3 col-xs-offset-2">
        <h3>gender:</h3>
        <!-- select gender -->
         <select class="form-control" id="gender">
         <option>female</option>
        <option>male</option>
         </select>
        </div>
       <div class="col-xs-3">
         <h3>weight </h3>
          <!-- input weight -->
       <input type="" name="weight" id="weight">
        </div>

         </div>
      <div id="ticketInfo">
        <h3 id="yourTicket">No gender Selected</h3>
     </div>
     </div>
    <script src="js/jquery-1.12.2.js"></script>
   <script src="js/bootstrap.js"></script>
     <script src="js/scripts.js"></script>
</code>```

this is my script

```<code>  function Ticket(gender, weight) {
  this.gender=gender;
  this.weight=weight;

     }

   Ticket.prototype.getPrice=function() {
     var price;

   if((this.gender==="male ")||(this.weight=>"200 ")){
       price=20;
        }
    if((this.gender==="female ")||(this.weight=>"200 ")) {
      price=15;
     }
     if((this.gender==="male ")||(this.weight=<"200 ")) {
    price=10;
    }
   if((this.gender==="female ")||(this.weight=<"200 ")) {
    price=7;
   }

  return price;
 }

$("select").change(function() {
  var genderOptions=[];
  $("select option:selected").each(function() {
   genderOptions.push($(this).text() + " ");
 });
 var newTicket = new
 Ticket(genderOptions[0],genderOptions[1],genderOptions[2]);
 $("#yourTicket").text(newTicket.gender + newTicket.weight + " $" +
 newTicket.getPrice().toFixed(2));
   });
</code>```

at the end in trying to multiply the price by the weight. any help will be really appreciated, thanks in advance.

答:
Remove the empty string added in gender options.push.Afterwards ,working fine

genderOptions.push($(this).text())

Title: calculating price with two values

Body:
So I have something like this...

I have a form where you select your gender and input your weight. each gender has different ranges of prices for example if your a male and your weight is greater than 200 your price is 20, if your a female and your weight is greater than 200 your price is 15, and if your male and your weight is less than 200 your price is 10, for the female if her weight is less than 200 her price is 7     . i have been trying to make it possible with jquery and PHP but it only seems to work with select option and won't work with input data.

this is my index.php

gender:

         <select class="form-control" id="gender">
         <option>female</option>
        <option>male</option>
         </select>

weight

       <input type="" name="weight" id="weight">

No gender Selected

this is my script

  function Ticket(gender, weight) {
  this.gender=gender;
  this.weight=weight;

     }

   Ticket.prototype.getPrice=function() {
     var price;

   if((this.gender==="male ")||(this.weight=>"200 ")){
       price=20;
        }
    if((this.gender==="female ")||(this.weight=>"200 ")) {
      price=15;
     }
     if((this.gender==="male ")||(this.weight=<"200 ")) {
    price=10;
    }
   if((this.gender==="female ")||(this.weight=<"200 ")) {
    price=7;
   }

  return price;
 }

$("select").change(function() {
  var genderOptions=[];
  $("select option:selected").each(function() {
   genderOptions.push($(this).text() + " ");
 });
 var newTicket = new
 Ticket(genderOptions[0],genderOptions[1],genderOptions[2]);
 $("#yourTicket").text(newTicket.gender + newTicket.weight + " $" +
 newTicket.getPrice().toFixed(2));
   });

at the end in trying to multiply the price by the weight. any help will be really appreciated, thanks in advance.


问:
What is the default font family of a Flutter app?
How I can retrieve the current font family name for flutter app and what is the default one ?

I have tried

```<code>Theme.of(context).textTheme.
</code>```

and

```<code>Theme.of(context).
</code>```

but there is no attribute for the font family.

答:
The default font of MaterialApp is described in

/flutter/packages/flutter/lib/src/material/typography.dart

on iOS, the default TextTheme is

```<code>  static const TextTheme whiteCupertino = TextTheme(
    display4   : TextStyle(debugLabel: 'whiteCupertino display4',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display3   : TextStyle(debugLabel: 'whiteCupertino display3',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display2   : TextStyle(debugLabel: 'whiteCupertino display2',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display1   : TextStyle(debugLabel: 'whiteCupertino display1',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    headline   : TextStyle(debugLabel: 'whiteCupertino headline',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    title      : TextStyle(debugLabel: 'whiteCupertino title',      fontFamily: '.SF UI Display', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    subhead    : TextStyle(debugLabel: 'whiteCupertino subhead',    fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    body2      : TextStyle(debugLabel: 'whiteCupertino body2',      fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    body1      : TextStyle(debugLabel: 'whiteCupertino body1',      fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    caption    : TextStyle(debugLabel: 'whiteCupertino caption',    fontFamily: '.SF UI Text',    inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    button     : TextStyle(debugLabel: 'whiteCupertino button',     fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    subtitle   : TextStyle(debugLabel: 'whiteCupertino subtitle',   fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    overline   : TextStyle(debugLabel: 'whiteCupertino overline',   fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
  );
</code>```

on Android, the default TextTheme is

```<code> static const TextTheme whiteMountainView = TextTheme(
    display4   : TextStyle(debugLabel: 'whiteMountainView display4',   fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display3   : TextStyle(debugLabel: 'whiteMountainView display3',   fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display2   : TextStyle(debugLabel: 'whiteMountainView display2',   fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display1   : TextStyle(debugLabel: 'whiteMountainView display1',   fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    headline   : TextStyle(debugLabel: 'whiteMountainView headline',   fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    title      : TextStyle(debugLabel: 'whiteMountainView title',      fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    subhead    : TextStyle(debugLabel: 'whiteMountainView subhead',    fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    body2      : TextStyle(debugLabel: 'whiteMountainView body2',      fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    body1      : TextStyle(debugLabel: 'whiteMountainView body1',      fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    caption    : TextStyle(debugLabel: 'whiteMountainView caption',    fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    button     : TextStyle(debugLabel: 'whiteMountainView button',     fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    subtitle   : TextStyle(debugLabel: 'whiteMountainView subtitle',   fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    overline   : TextStyle(debugLabel: 'whiteMountainView overline',   fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
  );
</code>```

and you can retrieve the font family by the following code

```<code>DefaultTextStyle.of(context).style.fontFamily
</code>```

Body:
How I can retrieve the current font family name for flutter app and what is the default one ?

I have tried

Theme.of(context).textTheme.

and

Theme.of(context).

but there is no attribute for the font family.

Body:
The default font of MaterialApp is described in

/flutter/packages/flutter/lib/src/material/typography.dart

on iOS, the default TextTheme is

  static const TextTheme whiteCupertino = TextTheme(
    display4   : TextStyle(debugLabel: 'whiteCupertino display4',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display3   : TextStyle(debugLabel: 'whiteCupertino display3',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display2   : TextStyle(debugLabel: 'whiteCupertino display2',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display1   : TextStyle(debugLabel: 'whiteCupertino display1',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    headline   : TextStyle(debugLabel: 'whiteCupertino headline',   fontFamily: '.SF UI Display', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    title      : TextStyle(debugLabel: 'whiteCupertino title',      fontFamily: '.SF UI Display', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    subhead    : TextStyle(debugLabel: 'whiteCupertino subhead',    fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    body2      : TextStyle(debugLabel: 'whiteCupertino body2',      fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    body1      : TextStyle(debugLabel: 'whiteCupertino body1',      fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    caption    : TextStyle(debugLabel: 'whiteCupertino caption',    fontFamily: '.SF UI Text',    inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    button     : TextStyle(debugLabel: 'whiteCupertino button',     fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    subtitle   : TextStyle(debugLabel: 'whiteCupertino subtitle',   fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    overline   : TextStyle(debugLabel: 'whiteCupertino overline',   fontFamily: '.SF UI Text',    inherit: true, color: Colors.white,   decoration: TextDecoration.none),
  );

on Android, the default TextTheme is

 static const TextTheme whiteMountainView = TextTheme(
    display4   : TextStyle(debugLabel: 'whiteMountainView display4',   fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display3   : TextStyle(debugLabel: 'whiteMountainView display3',   fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display2   : TextStyle(debugLabel: 'whiteMountainView display2',   fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    display1   : TextStyle(debugLabel: 'whiteMountainView display1',   fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    headline   : TextStyle(debugLabel: 'whiteMountainView headline',   fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    title      : TextStyle(debugLabel: 'whiteMountainView title',      fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    subhead    : TextStyle(debugLabel: 'whiteMountainView subhead',    fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    body2      : TextStyle(debugLabel: 'whiteMountainView body2',      fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    body1      : TextStyle(debugLabel: 'whiteMountainView body1',      fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    caption    : TextStyle(debugLabel: 'whiteMountainView caption',    fontFamily: 'Roboto', inherit: true, color: Colors.white70, decoration: TextDecoration.none),
    button     : TextStyle(debugLabel: 'whiteMountainView button',     fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    subtitle   : TextStyle(debugLabel: 'whiteMountainView subtitle',   fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
    overline   : TextStyle(debugLabel: 'whiteMountainView overline',   fontFamily: 'Roboto', inherit: true, color: Colors.white,   decoration: TextDecoration.none),
  );

and you can retrieve the font family by the following code

DefaultTextStyle.of(context).style.fontFamily


问:
Correctively Django query datetime for data/object one hour from now
i am filtering Django query to getting updatetime last one hour from now,  The model has a DateTimeField.

this is for getting all updatetime that update one hour ago, i've tried using datetime.now() - timedelta(hours = 1), and using range(min,max)

views i am using (generics.ListAPIView):

models

updatetime = models.DateTimeField(blank=True, null=True)

onehours = datetime.now() - timedelta(hours=1)
queryset = TbDevice.objects.filter(updatetime__gte=onehours).order_by('-updatetime')

this codes should return updatetime from last hour ago, for example at 2 pm  should return only last hour, but actually all data which has same day showed up

i checked by changing value updatetime manually , only data greater than 06:48:00 showed up when recent time at 14:57:00

is there influence both of them ?
different type
Update time in my DB
in Postman

using timezone
Using timezone form django.utils the result is
with my current time

答:
Gotcha!!

you're in Indonesia(GMT+7). Your DB(using system timezone) and django(using UTC timezone) has 7 hours of time difference.

try your query using timezone aware datetime format.

```<code>from django.utils import timezone
one_h_ago = timezone.now()-timezone.timedelta(hours=1)
queryset = TbDevice.object.filter(updatetime__gte=one_h_ago)
</code>```

In postman you're getting "updatetime": "2019-05-28T22:33:00+7:00" the T in the response tells us that you have enabled timezone support. You have settings.USE_TZ and settings.TIME_ZONE set.

Hope this helps. Let me know if you have any questions.

Happy to help :)

This is for your knowledge:

From comments I see your model as:

```<code>class TbDevice(models.Model):
    nickname = models.CharField(max_length=32, blank=True, null=True)
    email = models.CharField(max_length=64, blank=True, null=True)
    status = models.CharField(max_length=64, blank=True, null=True)
    createtime = models.DateTimeField(blank=True, null=True)
    updatetime = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'device'
</code>```

for createtime and updatetime you should be using

```<code>createtime = models.DateTimeField(auto_now_add=True)
updatetime = models.DateTimeField(auto_now=True)
</code>```

check auto_now and auto_now_add for more info.

Body:
Gotcha!!

you're in Indonesia(GMT+7). Your DB(using system timezone) and django(using UTC timezone) has 7 hours of time difference.

try your query using timezone aware datetime format.

from django.utils import timezone
one_h_ago = timezone.now()-timezone.timedelta(hours=1)
queryset = TbDevice.object.filter(updatetime__gte=one_h_ago)

In postman you're getting "updatetime": "2019-05-28T22:33:00+7:00" the T in the response tells us that you have enabled timezone support. You have settings.USE_TZ and settings.TIME_ZONE set.

Hope this helps. Let me know if you have any questions.

Happy to help :)

This is for your knowledge:

From comments I see your model as:

class TbDevice(models.Model):
    nickname = models.CharField(max_length=32, blank=True, null=True)
    email = models.CharField(max_length=64, blank=True, null=True)
    status = models.CharField(max_length=64, blank=True, null=True)
    createtime = models.DateTimeField(blank=True, null=True)
    updatetime = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'device'

for createtime and updatetime you should be using

createtime = models.DateTimeField(auto_now_add=True)
updatetime = models.DateTimeField(auto_now=True)

check auto_now and auto_now_add for more info.


问:
Why do all my decoded Strings have '?' at the end? Java String decoding
I am retrieving tweets from Twitter using the Tweepy library (Python) and Kafka. The text is encoded in UTF-8 as this line shows:

```<code>self.producer.send('my-topic', data.encode('UTF-8'))
</code>```

Where "data" is a String. Then, this data is stored into an Oracle NoSQL database in key-value format. For this reason, the tweet itself is encoded. I do this with Java:

```<code>Value myValue = Value.createValue(msg.value().getBytes("UTF-8"));
</code>```

Finally, the tweets are retrieved by a Formatter developed in Java. In order to store it in a relational schema, I have to parse the tweet so I retrieve it as a String.

```<code>String data = new String(value.toByteArray(),StandardCharsets.UTF_8);
</code>```

As you see, I maintain UTF-8 encoding in all the steps I make. However, when I see the text of the tweet in my database it's always cut. For example:

RT @briIIohead: the hardest pill i had to swallow this year was learning that no matter how good you could be to somebody, no matter how mu?

Notice how it ends with '?' symbol, and it has been clearly cut. Well, this happens with every long tweet. I mean, if the text is like 30 characters long, then it shows fine, however anything longer than 100 or so is cut.

At first I thought it could be my table definition, but the field "Text" is declared as VARCHAR2(400 CHAR) which is the maximum number of characters a tweet can have in the social network.

Any ideas on how can I spot what's cutting the text and putting the '?' symbol at the end?

How "data" looks like:

```<code>{"created_at":"Tue May 28 09:23:36 +0000 2019","id":1133302792129351681,"id_str":"1133302792129351681","text":"RT @AppleEDU: Learn, create, and do more with iPad in your classroom. Get the free Everyone Can Create curriculum and bring projects to lif\u2026","source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":1060510851889750022,"id_str":"1060510851889750022","name":"Rem.0112","screen_name":"0112Rem","location":"Mawson Lakes, Adelaide","url":null,"description":null,"translator_type":"none","protected":false,"verified":false,"followers_count":739,"friends_count":1853,"listed_count":10,"favourites_count":33406,"statuses_count":36936,"created_at":"Thu Nov 08 12:34:25 +0000 2018","utc_offset":null,"time_zone":null,"geo_enabled":true,"lang":null,"contributors_enabled":false,"is_translator":false,"profile_background_color":"F5F8FA","profile_background_image_url":"","profile_background_image_url_https":"","profile_background_tile":false,"profile_link_color":"1DA1F2","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/1093157842163355649\/6oAdJTCs_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/1093157842163355649\/6oAdJTCs_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/1060510851889750022\/1546155144","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Thu May 23 15:15:16 +0000 2019","id":1131579354964725760,"id_str":"1131579354964725760","text":"Learn, create, and do more with iPad in your classroom. Get the free Everyone Can Create curriculum and bring proje\u2026 https:\/\/t.co\/aeeSPTXtFx","source":"\u003ca href=\"https:\/\/ads-api.twitter.com\" rel=\"nofollow\"\u003eTwitter Ads Composer\u003c\/a\u003e","truncated":true,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":468741166,"id_str":"468741166","name":"Apple Education","screen_name":"AppleEDU","location":"Cupertino, CA","url":null,"description":"Spark new ideas, create more aha moments, and teach in ways you\u2019ve always imagined. Follow @AppleEDU for tips, updates, and inspiration.","translator_type":"none","protected":false,"verified":true,"followers_count":728781,"friends_count":273,"listed_count":2594,"favourites_count":13189,"statuses_count":2766,"created_at":"Thu Jan 19 21:26:14 +0000 2012","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":null,"contributors_enabled":false,"is_translator":false,"profile_background_color":"F0F0F0","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"0088CC","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":false,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/892429342046691328\/2SOlm_09_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/892429342046691328\/2SOlm_09_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/468741166\/1530123538","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"extended_tweet":{"full_text":"Learn, create, and do more with iPad in your classroom. Get the free Everyone Can Create curriculum and bring projects to life through music, drawing, video and photography.","display_text_range":[0,173],"entities":{"hashtags":[],"urls":[],"user_mentions":[],"symbols":[]}},"quote_count":0,"reply_count":3,"retweet_count":3,"favorite_count":58,"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/aeeSPTXtFx","expanded_url":"https:\/\/twitter.com\/i\/web\/status\/1131579354964725760","display_url":"twitter.com\/i\/web\/status\/1\u2026","indices":[117,140]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"scopes":{"followers":false},"filter_level":"low","lang":"en"},"is_quote_status":false,"quote_count":0,"reply_count":0,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"urls":[],"user_mentions":[{"screen_name":"AppleEDU","name":"Apple Education","id":468741166,"id_str":"468741166","indices":[3,12]}],"symbols":[]},"favorited":false,"retweeted":false,"filter_level":"low","lang":"en","timestamp_ms":"1559035416048"}
</code>```

I also must mention that this whole chunk is what's encoded. Then decoded, and finally parsed to be introduced in the database. All fields are correctly decoded and parsed, except "text" that's cut

答:
According to the official documentation, a tweet has no more than "140" characters (that is a broad definition); but lately they changed it to 280.

That same document says:

Twitter counts the length of a Tweet using the Normalization Form C (NFC) version of the text.

So they first normalize the text (I'll let you figure out how this is done is java). And later they say:

Twitter also counts the number of codepoints in the text rather than UTF-8 bytes.

Thus:

```<code>String test = "RT @briIIohead: the hardest pill i had to swallow this year was learning that no matter how good you could be to somebody, no matter how mu";
System.out.println(test.codePoints().count()); // 139
</code>```

It seems that the initial tweet was 280 "characters" and your library that you use is not aware of that, so it only uses the previous 140 ones. Since that does some chunking, it seems that the chunking is wrong too it removes some "partial" bytes at the end. When you try to print those - java does not know what those (at the end) bytes actually mean (because of some wrong chunking) and simply says ? (which is the default strategy on what to show when it simply does not understand something).

Body:
I am retrieving tweets from Twitter using the Tweepy library (Python) and Kafka. The text is encoded in UTF-8 as this line shows:

self.producer.send('my-topic', data.encode('UTF-8'))

Where "data" is a String. Then, this data is stored into an Oracle NoSQL database in key-value format. For this reason, the tweet itself is encoded. I do this with Java:

Value myValue = Value.createValue(msg.value().getBytes("UTF-8"));

Finally, the tweets are retrieved by a Formatter developed in Java. In order to store it in a relational schema, I have to parse the tweet so I retrieve it as a String.

String data = new String(value.toByteArray(),StandardCharsets.UTF_8);

As you see, I maintain UTF-8 encoding in all the steps I make. However, when I see the text of the tweet in my database it's always cut. For example:

RT @briIIohead: the hardest pill i had to swallow this year was learning that no matter how good you could be to somebody, no matter how mu?

Notice how it ends with '?' symbol, and it has been clearly cut. Well, this happens with every long tweet. I mean, if the text is like 30 characters long, then it shows fine, however anything longer than 100 or so is cut.

At first I thought it could be my table definition, but the field "Text" is declared as VARCHAR2(400 CHAR) which is the maximum number of characters a tweet can have in the social network.

Any ideas on how can I spot what's cutting the text and putting the '?' symbol at the end?

How "data" looks like:

{"created_at":"Tue May 28 09:23:36 +0000 2019","id":1133302792129351681,"id_str":"1133302792129351681","text":"RT @AppleEDU: Learn, create, and do more with iPad in your classroom. Get the free Everyone Can Create curriculum and bring projects to lif\u2026","source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":1060510851889750022,"id_str":"1060510851889750022","name":"Rem.0112","screen_name":"0112Rem","location":"Mawson Lakes, Adelaide","url":null,"description":null,"translator_type":"none","protected":false,"verified":false,"followers_count":739,"friends_count":1853,"listed_count":10,"favourites_count":33406,"statuses_count":36936,"created_at":"Thu Nov 08 12:34:25 +0000 2018","utc_offset":null,"time_zone":null,"geo_enabled":true,"lang":null,"contributors_enabled":false,"is_translator":false,"profile_background_color":"F5F8FA","profile_background_image_url":"","profile_background_image_url_https":"","profile_background_tile":false,"profile_link_color":"1DA1F2","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/1093157842163355649\/6oAdJTCs_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/1093157842163355649\/6oAdJTCs_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/1060510851889750022\/1546155144","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Thu May 23 15:15:16 +0000 2019","id":1131579354964725760,"id_str":"1131579354964725760","text":"Learn, create, and do more with iPad in your classroom. Get the free Everyone Can Create curriculum and bring proje\u2026 https:\/\/t.co\/aeeSPTXtFx","source":"\u003ca href=\"https:\/\/ads-api.twitter.com\" rel=\"nofollow\"\u003eTwitter Ads Composer\u003c\/a\u003e","truncated":true,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":468741166,"id_str":"468741166","name":"Apple Education","screen_name":"AppleEDU","location":"Cupertino, CA","url":null,"description":"Spark new ideas, create more aha moments, and teach in ways you\u2019ve always imagined. Follow @AppleEDU for tips, updates, and inspiration.","translator_type":"none","protected":false,"verified":true,"followers_count":728781,"friends_count":273,"listed_count":2594,"favourites_count":13189,"statuses_count":2766,"created_at":"Thu Jan 19 21:26:14 +0000 2012","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":null,"contributors_enabled":false,"is_translator":false,"profile_background_color":"F0F0F0","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"0088CC","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":false,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/892429342046691328\/2SOlm_09_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/892429342046691328\/2SOlm_09_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/468741166\/1530123538","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"extended_tweet":{"full_text":"Learn, create, and do more with iPad in your classroom. Get the free Everyone Can Create curriculum and bring projects to life through music, drawing, video and photography.","display_text_range":[0,173],"entities":{"hashtags":[],"urls":[],"user_mentions":[],"symbols":[]}},"quote_count":0,"reply_count":3,"retweet_count":3,"favorite_count":58,"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/aeeSPTXtFx","expanded_url":"https:\/\/twitter.com\/i\/web\/status\/1131579354964725760","display_url":"twitter.com\/i\/web\/status\/1\u2026","indices":[117,140]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"scopes":{"followers":false},"filter_level":"low","lang":"en"},"is_quote_status":false,"quote_count":0,"reply_count":0,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"urls":[],"user_mentions":[{"screen_name":"AppleEDU","name":"Apple Education","id":468741166,"id_str":"468741166","indices":[3,12]}],"symbols":[]},"favorited":false,"retweeted":false,"filter_level":"low","lang":"en","timestamp_ms":"1559035416048"}

I also must mention that this whole chunk is what's encoded. Then decoded, and finally parsed to be introduced in the database. All fields are correctly decoded and parsed, except "text" that's cut

Body:
According to the official documentation, a tweet has no more than "140" characters (that is a broad definition); but lately they changed it to 280.

That same document says:

Twitter counts the length of a Tweet using the Normalization Form C (NFC) version of the text.

So they first normalize the text (I'll let you figure out how this is done is java). And later they say:

Twitter also counts the number of codepoints in the text rather than UTF-8 bytes.

Thus:

String test = "RT @briIIohead: the hardest pill i had to swallow this year was learning that no matter how good you could be to somebody, no matter how mu";
System.out.println(test.codePoints().count()); // 139

It seems that the initial tweet was 280 "characters" and your library that you use is not aware of that, so it only uses the previous 140 ones. Since that does some chunking, it seems that the chunking is wrong too it removes some "partial" bytes at the end. When you try to print those - java does not know what those (at the end) bytes actually mean (because of some wrong chunking) and simply says ? (which is the default strategy on what to show when it simply does not understand something).


问:
Different results when run on different screen sizes
I'm getting different results of the same screen when run on different phone sizes:

The second phone screen is my desired outcome. Using expanded initially helped me solve an issue with the first phone screen (where there was an extra space below the green bar). Later I realized that I was getting overflow on the second phone screen. Thus, I solved the overflow by using SingleChildScrollView. However that somehow cause the first phone screen to have the issue of the extra space again.

Code:

    final quizBottomContentText = Container(
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.only(left:30.0, right:30.0, top: 30.0, bottom: 30),
      child: Text(
        questions[questionNum].title,
        style: TextStyle(fontSize: 18.0),
      )
    );

    final quizOptions = Container(
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.only(bottom: 20.0),
      child: Center(
        child: Column(
                  children: questions[questionNum].options.map<Widget>(
                    (option) =>  SimpleRoundButton(
                        backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
                        buttonText: Text(option,
                            style: TextStyle(
                                color: Colors.white
                            ),
                        ),
                        textColor: Colors.white,
                        onPressed: (){},
                    ),
              ).toList(),
        )
      )
    );

    final countdown = CountdownWidget(
          width: MediaQuery.of(context).size.width,
          duration: 20,
          triviaState: triviaState,
        );

    final quizBottomContent = Expanded(
      child: SingleChildScrollView(
        child: Container(
        width: MediaQuery.of(context).size.width,
          child: Column(
            children: <Widget>[quizBottomContentText, quizOptions, countdown],
          ),
        )
      )
    );
```

答:
Because you're app is not responsive. See, you're passing size in a hard coded way

eg: padding: EdgeInsets.only(bottom: 20.0)

What this means? Mean that in your emulator, you'll get a result, maybe is what you expect, but in another device, maybe in a iPhone Xs Max, the result is diferent, so, what can you do?

You'll have two options here, the first, use the MediaQuery component. I'll show you how and why I use the way I use for a better understanding.

In Flutter, we have the MediaQuery component with a lot of propierty, one of them, is this: MediaQuery.of(context).size.width (Which gets your device's full width size). Everything fine till here, right? If you print this in diferent devices, you'll get diferente results, which means that a Padding with 20 from left/right will be different in both devices.

I made a calculation to kinda ''hack'' this and make it responsive, get this:
MediaQuery.of(context).size.width and divide by 400. Why 400? Me and a friend discovered this and when we divided, we've got a value almost next to 1 in very different devices, so, if you get the result (eg 1.5) and multiplies by 20, you'll make your app kinda of responsive. It's a way, the second way it's to use the LayoutBuilder which need a context and a constraints as parameters.

With constraints, you can manipulate to show differents model designs in differents devices, like, buildConventionalDesig for devices with width less than 400, an example, or buildBiggerDesign for a bigger phone, like iPhone Xs Max.

There's an article that you could be your reference to help you, check it:
Build Response UIs in Flutter. It doesn't cover this trick with MediaQuery, but maybe you can get a new insight.

Hope this have helped.