问:
C# - Lambda vs nested loops
Is is possible to convert following into a simpler more readable linq or lambda expression?

```<code>Dictionary<int, int> selectedProgramTierCombo = new Dictionary<int,int>();
foreach (int mainTierID in doc.TierID)
{
    foreach (PriceProgram priceProgram in doc.CommitmentProgram.PricingPrograms)
    {
        foreach (ProgramTier progTier in priceProgram.Tiers)
        {
            if (progTier.TierID == mainTierID )
            {
                selectedProgramTierCombo.Add(priceProgram.ProgramID, progTier.TierID);
            }
        }
    }
}
</code>```

Essentially doc.TierID is a an array (int[]) of TierIDs that client is currently on. Also the doc object contains a CommitmentProgram object which contains a list of PriceProgram. So, All I am trying to do is get the PriceProgram.ProgramID for each TierID.

The relationship between PriceProgram and TierID is that each PriceProgram has a list of tiers (ProgramTier object) and ProgramTier oject contains the corresponding TierID that we already have.

Let me know if my explaination doesn't make sense and I'll try to elaborate.

Edit

Jon,
I am getting The name 'priceProgram' does not exist in the current context error when I try to compile what you have suggested:

```<code>Dictionary<int, int> selectedProgramTierCombo =
    (from mainTierID in doc.TierID
     from priceProgram in doc.CommitmentProgram.PricingPrograms
     **join progTier in priceProgram.Tiers on mainTierID equals progTier.TierID**
     select new { priceProgram.ProgramID, progTier.TierID })
    .ToDictionary(x => x.ProgramID, x => x.TierID);
</code>```

答:
Absolutely, it's very easy - but I'll have to change the type of your selectedProgramTierCombo variable, as otherwise it won't compile:

EDIT: Oops, given that the tiers depends on priceProgram, you need another nested from clause, I think:

```<code>Dictionary<int, int> selectedProgramTierCombo =
    (from mainTierID in doc.TierID
     from priceProgram in doc.CommitmentProgram.PricingPrograms
     from progTier in priceProgram.Tiers
     where mainTierID == progTier.TierID
     select new { priceProgram.ProgramID, progTier.TierID })
    .ToDictionary(x => x.ProgramID, x => x.TierID);
</code>```

At least, that's what I think you want. If you could clarify what you really want instead of List<int, int> (which isn't valid) we can help further.

To be honest, it's not clear to me why you're using progTier at all - you know that progTier.TierID is the same as mainTierID, and you're not using it apart from that...

Title: C# - Lambda vs nested loops

Body:
Is is possible to convert following into a simpler more readable linq or lambda expression?

Dictionary<int, int> selectedProgramTierCombo = new Dictionary<int,int>();
foreach (int mainTierID in doc.TierID)
{
    foreach (PriceProgram priceProgram in doc.CommitmentProgram.PricingPrograms)
    {
        foreach (ProgramTier progTier in priceProgram.Tiers)
        {
            if (progTier.TierID == mainTierID )
            {
                selectedProgramTierCombo.Add(priceProgram.ProgramID, progTier.TierID);
            }
        }
    }
}

Essentially doc.TierID is a an array (int[]) of TierIDs that client is currently on. Also the doc object contains a CommitmentProgram object which contains a list of PriceProgram. So, All I am trying to do is get the PriceProgram.ProgramID for each TierID.

The relationship between PriceProgram and TierID is that each PriceProgram has a list of tiers (ProgramTier object) and ProgramTier oject contains the corresponding TierID that we already have.

Let me know if my explaination doesn't make sense and I'll try to elaborate.

Edit

Jon,
I am getting The name 'priceProgram' does not exist in the current context error when I try to compile what you have suggested:

Dictionary<int, int> selectedProgramTierCombo =
    (from mainTierID in doc.TierID
     from priceProgram in doc.CommitmentProgram.PricingPrograms
     **join progTier in priceProgram.Tiers on mainTierID equals progTier.TierID**
     select new { priceProgram.ProgramID, progTier.TierID })
    .ToDictionary(x => x.ProgramID, x => x.TierID);

Body:
Absolutely, it's very easy - but I'll have to change the type of your selectedProgramTierCombo variable, as otherwise it won't compile:

EDIT: Oops, given that the tiers depends on priceProgram, you need another nested from clause, I think:

Dictionary<int, int> selectedProgramTierCombo =
    (from mainTierID in doc.TierID
     from priceProgram in doc.CommitmentProgram.PricingPrograms
     from progTier in priceProgram.Tiers
     where mainTierID == progTier.TierID
     select new { priceProgram.ProgramID, progTier.TierID })
    .ToDictionary(x => x.ProgramID, x => x.TierID);

At least, that's what I think you want. If you could clarify what you really want instead of List<int, int> (which isn't valid) we can help further.

To be honest, it's not clear to me why you're using progTier at all - you know that progTier.TierID is the same as mainTierID, and you're not using it apart from that...


来源: stackexchange

问:
How to do element wise operation for two tensors?
Say, I have two Tensors A and B, both with shape [-1, m, d]. How could I get a Tensor C with shape [-1, m*(m-1)/2, d] so than C_ij = A_i + B_j? Where + is an element wise addition. I know there is an element-wise operation named tf.add, but how should I use it? Thanks a lot.</p>

答: TensorFlow overloads operators so A + B should work.

ContentLicense: CC BY-SA 3.0


问:
What does using something::something::something mean (c++)?
So I just started as an intern and the code that I'm supposed to be working on is scattered within like 10 different directories and 100 files and who knows how many namespaces. I've never worked with this before, and I'm really confused how they are all being linked together.

I keep seeing these sorts of statements one after the other, ex:

```<code>using something10::something2::something6;
using isThisANamespace::iHaveNoIdeaIfThisIsAClassNameOrWhat::something599;
using randomName::otherRandomName::randomName99999;
using something4::something3::something8766678788787987987698;
</code>```

Whenever I try to google what using does, I only find results with using namespace. Is using now just a shorter way of using namespace? Some of the things they are using appear to be folder names and file names though. My company mentor doesn't know c++ so he can't help me alas.

Also, if these are all namespaces, then wouldn't using so many of them conflict? Can you call namespace::classname::function? And when you do this do you still have to include the filename for that class?

Please help me learn how to call a function buried in another directory that is also in 4 namespaces. I'm very lost.

答:
check below link, hopefully it will help you on what you are looking for
https://www.tutorialspoint.com/cplusplus/cpp_namespaces.htm</p>

Body:
So I just started as an intern and the code that I'm supposed to be working on is scattered within like 10 different directories and 100 files and who knows how many namespaces. I've never worked with this before, and I'm really confused how they are all being linked together.

I keep seeing these sorts of statements one after the other, ex:

using something10::something2::something6;
using isThisANamespace::iHaveNoIdeaIfThisIsAClassNameOrWhat::something599;
using randomName::otherRandomName::randomName99999;
using something4::something3::something8766678788787987987698;

Whenever I try to google what using does, I only find results with using namespace. Is using now just a shorter way of using namespace? Some of the things they are using appear to be folder names and file names though. My company mentor doesn't know c++ so he can't help me alas.

Also, if these are all namespaces, then wouldn't using so many of them conflict? Can you call namespace::classname::function? And when you do this do you still have to include the filename for that class?

Please help me learn how to call a function buried in another directory that is also in 4 namespaces. I'm very lost.


问:
How to deseralize an XML thats a DataTable?
I have an XML file, and when I used XSD tool to create a class object from the XML, I get a message saying "A column named 'link' already belongs to this DataTable: cannot set a nested table to the same name.

I want to know how I can correctly deserialize this XML file so that I can display the data on an app. This XML file is basically just Rss news feed data.

You can see the entire XML file structure here: https://github.com/karimo94/XMLDemo/blob/master/leaguenews.xml

答: I tried both ways and honestly, I couldn't get it to deserialize properly without errors. Luckily, I was able to use rss2json.com and that converted the Rss feed into a json which I could parse using Newtonsoft Json.Net</p>


问:
Optimizing a SQL query on SQL Server
I have a SQL query on SQL Server that needs to be optimized.
It takes almost 16 minutes to run it.

```<code>SELECT DISTINCT DeptNo,
                BrandDesc,
                MfgDesc,
                CountOfActiveSKUs =
                    COALESCE((SELECT COUNT(*)
                                FROM dbo.SKU k
                               WHERE k.Status = 'A'
                                 AND k.BrandDesc = s.BrandDesc
                                 AND k.MfgDesc = s.MfgDesc
                                 AND k.DeptNo = s.DeptNo),
                             0)
           FROM dbo.SKU s
       ORDER BY BrandDesc
</code>```

I came up with the following, but it doesn't seems it grabs records that have CountOfActiveSKUs = 0.

```<code>SELECT DISTINCT DeptNo,
                BrandDesc,
                MfgDesc,
                CountOfActiveSKUs = COALESCE(Count(*), 0)
           FROM dbo.SKU
          WHERE Status = 'A'
       GROUP BY BrandDesc, MfgDesc, DeptNo
       ORDER BY BrandDesc
</code>```

Any help is appreciated,
Thank you!

答:
Try this</p>

```<code>SELECT s.DeptNo, s.BrandDesc, s.MfgDesc, count(k.Status) as CountOfActiveSKUs
FROM  dbo.SKU s LEFT OUTER JOIN
dbo.SKU k ON
k.Status = 'A' AND k.BrandDesc = s.BrandDesc
AND k.MfgDesc = s.MfgDesc AND k.DeptNo = s.DeptNo
GROUP BY s.DeptNo, s.BrandDesc, s.MfgDesc
ORDER BY BrandDesc
</code>```

Title: Optimizing a SQL query on SQL Server

Body:
I have a SQL query on SQL Server that needs to be optimized.
It takes almost 16 minutes to run it.

SELECT DISTINCT DeptNo,
                BrandDesc,
                MfgDesc,
                CountOfActiveSKUs =
                    COALESCE((SELECT COUNT(*)
                                FROM dbo.SKU k
                               WHERE k.Status = 'A'
                                 AND k.BrandDesc = s.BrandDesc
                                 AND k.MfgDesc = s.MfgDesc
                                 AND k.DeptNo = s.DeptNo),
                             0)
           FROM dbo.SKU s
       ORDER BY BrandDesc

I came up with the following, but it doesn't seems it grabs records that have CountOfActiveSKUs = 0.

SELECT DISTINCT DeptNo,
                BrandDesc,
                MfgDesc,
                CountOfActiveSKUs = COALESCE(Count(*), 0)
           FROM dbo.SKU
          WHERE Status = 'A'
       GROUP BY BrandDesc, MfgDesc, DeptNo
       ORDER BY BrandDesc

Any help is appreciated,
Thank you!

Body:
Try this

SELECT s.DeptNo, s.BrandDesc, s.MfgDesc, count(k.Status) as CountOfActiveSKUs
FROM  dbo.SKU s LEFT OUTER JOIN
dbo.SKU k ON
k.Status = 'A' AND k.BrandDesc = s.BrandDesc
AND k.MfgDesc = s.MfgDesc AND k.DeptNo = s.DeptNo
GROUP BY s.DeptNo, s.BrandDesc, s.MfgDesc
ORDER BY BrandDesc


问:
How to deploy locally trained TensorFlow graph file to Google Cloud Platform?
I've followed the TensorFlow for Poets tutorial and replaced the stock flower_photos with a few classes of my own. Now I've got my labels.txt file and my graph.pb saved on my local machine.

Is there a way for me to deploy this pre-trained model to Google Cloud Platform? I've been reading the docs and all I can find are instructions on how to create, train, and deploy models from within their ML Engine. But I don't want to spend money training my model on Google's servers when I only need them to host my model so I can call it for predictions.

Anyone else run into the same problem?

答:
Partial answer only, unfortunately, but I have been able to accomplish this...but with some ongoing issues that I have not yet resolved. I ported over the trained pb and txt files to my server, installed Tensorflow, and am calling the trained model via HTTP request. It works perfectly...on the first run. Then fails every other time.

tensorflow deployment on openshift, errors with gunicorn and mod_wsgi

Surprised there are not more people out there trying to go after this general issue.


问:
c remove new line char help
Im fairly new to c sorry if this is a stupid question!

i have this:

```<code>  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question)));
  memq= question;
</code>```

however the question variable always has a new line on the end of it !
how do i remove this / prevent it happening?

i have tried this:

```<code>  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question))-sizeof(char));
  memq= question;
</code>```

there was no effect!

答:
In both cases, memq = question is wrong.  You've just lost your pointer to new newly-allocated space, and instead copied the address of the first character of question to memq

Use strcpy or memcpy instead, to copy the contents of the string pointed to by question to the contents of the memory pointed to by memq.

ContentLicense: CC BY-SA 2.5

Title: c remove new line char help

Body:
Im fairly new to c sorry if this is a stupid question!

i have this:

  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question)));
  memq= question;

however the question variable always has a new line on the end of it !
how do i remove this / prevent it happening?

i have tried this:

  fgets(question,200,stdin);
  char *memq = malloc(sizeof(strlen(question))-sizeof(char));
  memq= question;

there was no effect!


问:
How can I update NodeJS and NPM to their latest versions?

I just installed Node.js & NPM (Node Package Manager)

I installed NPM for access to additional Node.js Modules.

After I installed Node.js & NPM I noticed that neither were the latest versions available.

I would like to know: How do I upgrade Node.js, NPM, and my Node.js Modules to their latest versions?

Do I need to uninstall Node.js & NPM and reinstall the latest versions?

Here is the link to what I have tried so far. This link is a section from npm.

答:
First check your NPM version

```<code>npm -v
</code>```

1) Update NPM to current version:

View curent NPM version:

```<code>npm view npm version
</code>```

Update npm to current version:

```<code>npm i -g npm
</code>```

2) List all available NPM versions and make a custom install/update/roll-back

View all versions including "alpha", "beta" and "rc" (release candidate)

```<code>npm view npm versions --json
</code>```

Reinstall NPM to a specific version chosen from the versions list - for example to 5.0.3

```<code>npm i -g npm@5.0.3
</code>```

Installing one version will automatically remove the one currently installed.

For Linux and iOS prepend commands with sudo

ContentLicense: CC BY-SA 4.0

Body:
First check your NPM version

npm -v

1) Update NPM to current version:

View curent NPM version:

npm view npm version

Update npm to current version:

npm i -g npm

2) List all available NPM versions and make a custom install/update/roll-back

View all versions including "alpha", "beta" and "rc" (release candidate)

npm view npm versions --json

Reinstall NPM to a specific version chosen from the versions list - for example to 5.0.3

npm i -g npm@5.0.3

Installing one version will automatically remove the one currently installed.

For Linux and iOS prepend commands with sudo


问:
Writing or Copying File To Network Share in C#
I've written a Windows Service that impersonates session 0 to access local printers and prints money orders to networked dot-matrix printers. That part works great, and the idea is that the client terminals (running 3.5 desktop app) will generate an xml file that is written to (or copied, I don't care) to a share on that machine, and the Print Queue Service will pick these up every few seconds, order them by number and store, and send the job to the correct store's printer. That all works.

However our issue is that we can't save the xml files to the remote share without first saving credentials on every single computer. Despite sharing it with EVERYONE having read/write/modify access to the share, it won't work. Obviously the client is unwilling to type in a username and password for 300+ computers.

I've tried everything I can think of. I've tried impersonation using WindowsIdentity and WindowsImpersonationContext, but I always get "The name provided is not a properly formed account name." no matter if I use name@domain or domain\name, or the application quits with no error messages logged in the event viewer or our database. I've tried using the code found here which maps the drive successfully but I am denied access to it. I've tried alternative code to use LogonUser from the Windows API (doesn't work). I've shared and re-shared the folder with the least restrictive permissions I can find. Nothing works.

Any suggestions on what we can do at this point? The code is here:

```<code> foreach (MoneyOrderPrinterLineItem item in this.Lines)
        {
            string path = Globals.MoneyOrderPrintJobsPath + Globals.Store.StoreNameID.ToString("0#") +
                (Globals.DrawerContext.GetActiveDrawer()?.DrawerNameOnly) + Security.UserName + item.Number +
                DateTime.Now.ToString("MMddyyyy") + DateTime.Now.ToString("hhmmss") + ".xml";

            try
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.Encoding = ASCIIEncoding.Unicode;

                //create a new file for each money order
                using (FileStream stream = new FileStream(path, FileMode.CreateNew))
                {
                    using (XmlWriter writer = XmlWriter.Create(stream, settings))
                    {
                        writer.WriteStartDocument();
                        writer.WriteStartElement("PrintJob");

                        writer.WriteStartElement("Source");
                        writer.WriteElementString("Name", Security.UserName);
                        writer.WriteElementString("Store", Globals.Store.StoreNameID.ToString("0#"));
                        writer.WriteElementString("StoreID", Globals.Store.ID.ToString());
                        writer.WriteElementString("Drawer", Globals.DrawerContext.GetActiveDrawer()?.DrawerNameOnly);
                        writer.WriteElementString("DateTime", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString());
                        writer.WriteElementString("Machine", Environment.MachineName);
                        writer.WriteElementString("PrinterName", Globals.Store.MoneyOrderPrinter);
                        writer.WriteEndElement();

                        writer.WriteStartElement("Details");
                        writer.WriteElementString("Number", item.Number);
                        writer.WriteElementString("Payee", item.Payee);
                        writer.WriteElementString("Remitter", item.Remitter);
                        writer.WriteElementString("AmountDesc", item.AmountText);
                        writer.WriteElementString("Amount", item.Amount.ToString("F2"));
                        writer.WriteElementString("Fee", item.Fee.ToString("F2"));
                        writer.WriteElementString("BusinessDate", item.Date);
                        writer.WriteElementString("Notes", item.StoreNotes);
                        writer.WriteEndElement();

                        writer.WriteEndElement();
                        writer.WriteEndDocument();
                        writer.Close();
                    }
                }
            }
            catch (IOException ioEX)
            {
                Methods.ProcessException(ioEX, true);
            }
            catch (Exception ex)
            {
                Methods.ProcessException(ex, true);
            }
        }
</code>```

All of the machines are on the same domain. The global money order path is \\WEB2012R2-DEV\MOPrints

答: The suggestion to use our web service to save the files locally worked beautifully. Thanks everyone!</p>

Body:
I've written a Windows Service that impersonates session 0 to access local printers and prints money orders to networked dot-matrix printers. That part works great, and the idea is that the client terminals (running 3.5 desktop app) will generate an xml file that is written to (or copied, I don't care) to a share on that machine, and the Print Queue Service will pick these up every few seconds, order them by number and store, and send the job to the correct store's printer. That all works.

However our issue is that we can't save the xml files to the remote share without first saving credentials on every single computer. Despite sharing it with EVERYONE having read/write/modify access to the share, it won't work. Obviously the client is unwilling to type in a username and password for 300+ computers.

I've tried everything I can think of. I've tried impersonation using WindowsIdentity and WindowsImpersonationContext, but I always get "The name provided is not a properly formed account name." no matter if I use name@domain or domain\name, or the application quits with no error messages logged in the event viewer or our database. I've tried using the code found here which maps the drive successfully but I am denied access to it. I've tried alternative code to use LogonUser from the Windows API (doesn't work). I've shared and re-shared the folder with the least restrictive permissions I can find. Nothing works.

Any suggestions on what we can do at this point? The code is here:

 foreach (MoneyOrderPrinterLineItem item in this.Lines)
        {
            string path = Globals.MoneyOrderPrintJobsPath + Globals.Store.StoreNameID.ToString("0#") +
                (Globals.DrawerContext.GetActiveDrawer()?.DrawerNameOnly) + Security.UserName + item.Number +
                DateTime.Now.ToString("MMddyyyy") + DateTime.Now.ToString("hhmmss") + ".xml";

            try
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.Encoding = ASCIIEncoding.Unicode;

                //create a new file for each money order
                using (FileStream stream = new FileStream(path, FileMode.CreateNew))
                {
                    using (XmlWriter writer = XmlWriter.Create(stream, settings))
                    {
                        writer.WriteStartDocument();
                        writer.WriteStartElement("PrintJob");

                        writer.WriteStartElement("Source");
                        writer.WriteElementString("Name", Security.UserName);
                        writer.WriteElementString("Store", Globals.Store.StoreNameID.ToString("0#"));
                        writer.WriteElementString("StoreID", Globals.Store.ID.ToString());
                        writer.WriteElementString("Drawer", Globals.DrawerContext.GetActiveDrawer()?.DrawerNameOnly);
                        writer.WriteElementString("DateTime", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString());
                        writer.WriteElementString("Machine", Environment.MachineName);
                        writer.WriteElementString("PrinterName", Globals.Store.MoneyOrderPrinter);
                        writer.WriteEndElement();

                        writer.WriteStartElement("Details");
                        writer.WriteElementString("Number", item.Number);
                        writer.WriteElementString("Payee", item.Payee);
                        writer.WriteElementString("Remitter", item.Remitter);
                        writer.WriteElementString("AmountDesc", item.AmountText);
                        writer.WriteElementString("Amount", item.Amount.ToString("F2"));
                        writer.WriteElementString("Fee", item.Fee.ToString("F2"));
                        writer.WriteElementString("BusinessDate", item.Date);
                        writer.WriteElementString("Notes", item.StoreNotes);
                        writer.WriteEndElement();

                        writer.WriteEndElement();
                        writer.WriteEndDocument();
                        writer.Close();
                    }
                }
            }
            catch (IOException ioEX)
            {
                Methods.ProcessException(ioEX, true);
            }
            catch (Exception ex)
            {
                Methods.ProcessException(ex, true);
            }
        }

All of the machines are on the same domain. The global money order path is \\WEB2012R2-DEV\MOPrints


问:
vmware_vm_facts vCenter password validation failing
I am using Ansible and vCenter to provision a VM. When I run my playbook, I get an authentication error:

Cannot complete login due to an incorrect user name or password.

However, using the same credentials, I am able to log into vCenter manually.

Here is my simplified playbook:

```<code>---
- name: create a new VM on an ESX server
  hosts: localhost
  connection: local

  tasks:

    - name: include vars
      include_vars:
        dir: 'group_vars/prod'
        files_matching: 'secret-esx.yml'

    - name: gather facts from target host
      local_action:
        module: vmware_vm_facts
        hostname: vi-devops-esx9.lab.vi.local
        username: "{{ esx_username }}"
        password: "{{ esx_password }}"
        validate_certs: no
      register: qe_facts
</code>```

Why can I access vCenter, but vmware_vm_facts cannot with the same credentials?

答: My hostname was incorrect. Fixing my hostname fixed the authentication error.</p>

Body:
I am using Ansible and vCenter to provision a VM. When I run my playbook, I get an authentication error:

Cannot complete login due to an incorrect user name or password.

However, using the same credentials, I am able to log into vCenter manually.

Here is my simplified playbook:

---
- name: create a new VM on an ESX server
  hosts: localhost
  connection: local

  tasks:

    - name: include vars
      include_vars:
        dir: 'group_vars/prod'
        files_matching: 'secret-esx.yml'

    - name: gather facts from target host
      local_action:
        module: vmware_vm_facts
        hostname: vi-devops-esx9.lab.vi.local
        username: "{{ esx_username }}"
        password: "{{ esx_password }}"
        validate_certs: no
      register: qe_facts

Why can I access vCenter, but vmware_vm_facts cannot with the same credentials?


问:
bitwise shift for a string holding a numeric hex. in perl
I have a string

```<code>$string = "0x0"
</code>```

Now I want to basically use this string as a number and do a bitwise shift i.e my aim is to

```<code>$C = $string <<4 ;
</code>```

But when I do this it says :

```<code>Argument "0x0" isn't numeric in left bitshift (<<)
</code>```

Can someone please help to execute this ?

答:
As mentioned, you have to convert it to a numeric value and use sprintf to turn back to a hexadecimal value.

```<code>sprintf ("0x%x" , hex($string) << 4);
</code>```

Body:
I have a string

$string = "0x0"

Now I want to basically use this string as a number and do a bitwise shift i.e my aim is to

$C = $string <<4 ;

But when I do this it says :

Argument "0x0" isn't numeric in left bitshift (<<)

Can someone please help to execute this ?

Body:
As mentioned, you have to convert it to a numeric value and use sprintf to turn back to a hexadecimal value.

sprintf ("0x%x" , hex($string) << 4);


问:
In Javascript is there a way to nest arrays eg. location>country>continent?
For example lets say I have a list of locations. I want those locations in an array based on what country they are in but I also want those countries in an array based on continent.

So something like
var regionName = [Europe[France, England[London, Birmingham], Spain]];

Thanks for any info and sorry I am so new at this!

答:
Yes, you can nest arrays. I usually work with an object that represents something in the real world and then have multiple arrays within it or make an array of objects, each with several pieces of information. Those object-oriented data structures are usually more useful than nested arrays but it really depends on what you're doing.

Here are some resources. If you could give me more info about your problem, I'd probably be able to help you more effectively:

http://www.elated.com/articles/nested-arrays-in-javascript/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections

For your specific question location>country>continent, you could look at this pseudocode for an idea:

let location = [place1, place2,...]

let country = [location1, location2, ...]

let continent = [country1, country2...]

The specifics don't matter. The key note in Javascript is that you specify the index of each array in sequence like so:

console.log (continent[0][0][0]);

Hope that helps.


问:
How to make console program to disappear and work in background?
How can I make console program disappear and work in the background?
I mean, I don't want to see the program, but I want to see it running in the task manager.

Thanks.

答:
Assuming a MS Windows XP environment:

My suggestion would be to consider making a Windows Service to do what you are asking, though another possibility would be to set something up within msconfig to run the program at startup or in the startup group within the "Start->All Programs->StartUp" section.

If you are on a Mac, Linux or some other O/S, there may exist a similar function to act as a place to run programs within the background.

OwnerDisplayName: Tal

OwnerDisplayName: JB King


问:
View.Title == ViewData["Title"]
am confused right now with Razor ViewEngine for ASP.NET MVC.

most of you would say:

```<code>View.Title
</code>```

is the same with

```<code>ViewData["Title"]
</code>```

after running the application I get this

Compiler Error Message: CS0103: The
  name 'View' does not exist in the
  current context

what gives? did I miss something?
am using VWD 2010 Express + ASP.NET MVC 3 R2

答:
It's been changed to ViewBag in the latest RC.

```<code>ViewBag.Title = "Test";
</code>```

See ScottGu's post on breaking changes in the latest MVC 3 release candidate.

Title: View.Title == ViewData["Title"]

Body:
am confused right now with Razor ViewEngine for ASP.NET MVC.

most of you would say:

View.Title

is the same with

ViewData["Title"]

after running the application I get this

Compiler Error Message: CS0103: The
  name 'View' does not exist in the
  current context

what gives? did I miss something?
am using VWD 2010 Express + ASP.NET MVC 3 R2

Body:
It's been changed to ViewBag in the latest RC.

ViewBag.Title = "Test";

See ScottGu's post on breaking changes in the latest MVC 3 release candidate.


问:
how to call a method from a menu of methods?
I am learning about methods and am trying to make a menu of methods that do simple conversions. I don't know how to call a method from the menu and make it do the function. I would like to know how to call a method AND make it run with inputs not using the scanner class except in main.

```<code>public static void main(String[] args) {
    displayMenu();
    Scanner keyboard = new Scanner(System.in);
    int selection = keyboard.nextInt();
    switch(selection) {
    case 1:
        FahrToCel();
        break;
    case 2:
        CelToFahr();
        break;
    case 3:
        LbToKilo();
        break;
    case 4:
        KiloToLb();
        break;
   }

}

public static void displayMenu() {
    System.out.println("Enter 1 for Fahrenheit to Celsius" );
    System.out.println("Enter 2 for Celsius to Fahrenheit");
    System.out.println("Enter 3 for lb to kg");
    System.out.println("Enter 4 for kg to lb");
    return;

public static double FahrToCel() {

    double Fahrenheit = ???;
    double Celsius = 5 * (Fahrenheit - 32) / 9;

    return Celsius;

}

public static double CelToFahr() {
    double Celsius = ???;
    double Fahrenheit = (9 * Celsius / 5) + 32;
    return Fahrenheit;

}

public static double LbtoKilo() {
    double pounds = ???;
    double factor = 0.454;
    double Kilogram = pounds * factor;

    return Kilogram;

}
public static double KiloToLb() {
    double kilograms = ???;
    double factor = 0.454;
    double Pound = kilograms / factor;
    return Pound;

}
</code>```

the ??? are the variables that i want to get user input, but idk how to do that without making a new Scanner in each method.

idk how to get the inputs in the methods either.

When I run the code, I get the displayMenu options and i can input 1,2,3,4 but then nothing happens after that

答:
You probably want to make your code something like this. Your issue is that you are not actually supplying any values to be converted but this should fix it.

```<code>public static void main(String[] args) {
    displayMenu();
    double result;
    Scanner keyboard = new Scanner(System.in);
    int selection = keyboard.nextInt();
    System.out.println("What number do you want converted?");
    int toBeConverted = keyboard.nextInt();
    switch(selection) {
    case 1:
        result = fahrToCel(toBeConverted);
        break;
    case 2:
        result = celToFahr(toBeConverted);
        break;
    case 3:
        result = lbToKilo(toBeConverted);
        break;
    case 4:
        result = kiloToLb(toBeConverted);
        break;
   }
   System.out.println(result);

}

public static void displayMenu() {
    System.out.println("Enter 1 for Fahrenheit to Celsius" );
    System.out.println("Enter 2 for Celsius to Fahrenheit");
    System.out.println("Enter 3 for lb to kg");
    System.out.println("Enter 4 for kg to lb");
    return;
}

public static double fahrToCel(int fahrenheit) {

    double celsius = 5 * (fahrenheit - 32) / 9;

    return celsius;

}

public static double celToFahr(int celsius) {
    double fahrenheit = (9 * celsius / 5) + 32;
    return fahrenheit;

}

public static double lbtoKilo(int lb) {
    double factor = 0.454;
    double kilogram = lb * factor;

    return kilogram;

}
public static double kiloToLb(int kilo) {
    double factor = 0.454;
    double pound = kilo / factor;
    return pound;

}
</code>```

I also made all your variable and method names lower case as that is good coding practice. Usually only class names are capitalized in traditional java practice. No practical benefit but of course it is always better to follow convention.

Body:
I am learning about methods and am trying to make a menu of methods that do simple conversions. I don't know how to call a method from the menu and make it do the function. I would like to know how to call a method AND make it run with inputs not using the scanner class except in main.

public static void main(String[] args) {
    displayMenu();
    Scanner keyboard = new Scanner(System.in);
    int selection = keyboard.nextInt();
    switch(selection) {
    case 1:
        FahrToCel();
        break;
    case 2:
        CelToFahr();
        break;
    case 3:
        LbToKilo();
        break;
    case 4:
        KiloToLb();
        break;
   }

}

public static void displayMenu() {
    System.out.println("Enter 1 for Fahrenheit to Celsius" );
    System.out.println("Enter 2 for Celsius to Fahrenheit");
    System.out.println("Enter 3 for lb to kg");
    System.out.println("Enter 4 for kg to lb");
    return;

public static double FahrToCel() {

    double Fahrenheit = ???;
    double Celsius = 5 * (Fahrenheit - 32) / 9;

    return Celsius;

}

public static double CelToFahr() {
    double Celsius = ???;
    double Fahrenheit = (9 * Celsius / 5) + 32;
    return Fahrenheit;

}

public static double LbtoKilo() {
    double pounds = ???;
    double factor = 0.454;
    double Kilogram = pounds * factor;

    return Kilogram;

}
public static double KiloToLb() {
    double kilograms = ???;
    double factor = 0.454;
    double Pound = kilograms / factor;
    return Pound;

}

the ??? are the variables that i want to get user input, but idk how to do that without making a new Scanner in each method.

idk how to get the inputs in the methods either.

When I run the code, I get the displayMenu options and i can input 1,2,3,4 but then nothing happens after that

Body:
You probably want to make your code something like this. Your issue is that you are not actually supplying any values to be converted but this should fix it.

public static void main(String[] args) {
    displayMenu();
    double result;
    Scanner keyboard = new Scanner(System.in);
    int selection = keyboard.nextInt();
    System.out.println("What number do you want converted?");
    int toBeConverted = keyboard.nextInt();
    switch(selection) {
    case 1:
        result = fahrToCel(toBeConverted);
        break;
    case 2:
        result = celToFahr(toBeConverted);
        break;
    case 3:
        result = lbToKilo(toBeConverted);
        break;
    case 4:
        result = kiloToLb(toBeConverted);
        break;
   }
   System.out.println(result);

}

public static void displayMenu() {
    System.out.println("Enter 1 for Fahrenheit to Celsius" );
    System.out.println("Enter 2 for Celsius to Fahrenheit");
    System.out.println("Enter 3 for lb to kg");
    System.out.println("Enter 4 for kg to lb");
    return;
}

public static double fahrToCel(int fahrenheit) {

    double celsius = 5 * (fahrenheit - 32) / 9;

    return celsius;

}

public static double celToFahr(int celsius) {
    double fahrenheit = (9 * celsius / 5) + 32;
    return fahrenheit;

}

public static double lbtoKilo(int lb) {
    double factor = 0.454;
    double kilogram = lb * factor;

    return kilogram;

}
public static double kiloToLb(int kilo) {
    double factor = 0.454;
    double pound = kilo / factor;
    return pound;

}

I also made all your variable and method names lower case as that is good coding practice. Usually only class names are capitalized in traditional java practice. No practical benefit but of course it is always better to follow convention.


问:
I am having trouble in reading date and time from an excel sheet using python
```<code>import xlwt
import xlrd, xlutils

wb = xlwt.Workbook()
outsheet = wb.add_sheet('Page 1')

files = [r'c:\file1', r'C:c:\file2',]

outrow = 0

for f in files:

insheet = xlrd.open_workbook(f,formatting_info=True).sheets()[0]
for row in range(insheet.nrows):
    for col in range(insheet.ncols):
        outsheet.write(outrow, col,insheet.cell_value(row, col))
    outrow += 1
wb.save(r'C:\combined.xls')
</code>```

i get output as

42753.61492

42753.61492

42753.61492

42753.61492

42753.61492

where i was looking something as this

                        2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-20 09:10:06 a

答:
You just need to set the number format when you're writing the output workbook, the same as you would in Excel. This is done by including another parameter on your outsheet.write() call.

Unfortunately the "official" documentation for xlwt is pretty difficult to use. Much better is the old tutorial PDF. There you should read up on styles (XFStyle and easyxf).

Or even better still is to ditch xlwt altogether and switch to XlsxWriter, which is easier to use, has more features, has vastly better documentation, is actively maintained, and generates current .xlsx files instead of outdated .xls files.

Body:
import xlwt
import xlrd, xlutils

wb = xlwt.Workbook()
outsheet = wb.add_sheet('Page 1')

files = [r'c:\file1', r'C:c:\file2',]

outrow = 0

for f in files:

insheet = xlrd.open_workbook(f,formatting_info=True).sheets()[0]
for row in range(insheet.nrows):
    for col in range(insheet.ncols):
        outsheet.write(outrow, col,insheet.cell_value(row, col))
    outrow += 1
wb.save(r'C:\combined.xls')

i get output as

42753.61492

42753.61492

42753.61492

42753.61492

42753.61492

where i was looking something as this

                        2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-20 09:10:06 a


问:
How to get json object array from deep nested json array?
This is my json, I wanted to get 'products' arrays object.

```<code>{
       "Categories":[
          {
             "id":6,
             "status":"1",
             "parent_id":"0",
             "name":"Bottom Wear",
             "name_ar":"\u0623\u0633\u0641\u0644 \u0627\u0631\u062a\u062f\u0627\u0621",
             "picture":null,
             "description":"gents bottom wear",
             "slug":"bottom-wear",
             "created_at":"2017-06-05 21:08:28",
             "updated_at":"2017-06-05 21:08:28",
             "deleted_at":null,
             "product":[
                {
                   "id":2,
                   "status":"1",
                   "name":"Pants",
                   "name_ar":"\u0628\u0646\u0637\u0644\u0648\u0646",
                   "dryclean_price":"9",
                   "washing_price":"6",
                   "press":"4",
                   "sw_dryclean_price":"9",
                   "sw_washing_price":"6",
                   "sw_press":"4",
                   "picture":null,
                   "created_at":"2017-04-19 21:32:04",
                   "updated_at":"2017-06-05 21:18:04",
                   "deleted_at":null,
                   "pivot":{
                      "category_id":"6",
                      "product_id":"2"
                   }
                },
                {
                   "id":8,
                   "status":"1",
                   "parent_id":"0",
                   "name":"Undergarments",
                   "name_ar":"\u0623\u062b\u0648\u0627\u0628 \u062a\u062d\u062a\u0627\u0646\u064a\u0629",
                   "picture":null,
                   "description":"Undergarments",
                   "slug":"undergarments",
                   "created_at":"2017-06-05 21:22:09",
                   "updated_at":"2017-06-05 21:22:09",
                   "deleted_at":null,
                   "product":[
                      {
                         "id":23,
                         "status":"1",
                         "name":"Underwear",
                         "name_ar":"\u062b\u064a\u0627\u0628 \u062f\u0627\u062e\u0644\u064a\u0629",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-04-19 21:35:31",
                         "updated_at":"2017-06-05 21:23:42",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"23"
                         }
                      },
                      {
                         "id":34,
                         "status":"1",
                         "name":"Socks",
                         "name_ar":"\u062c\u0648\u0627\u0631\u0628",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-06-05 21:26:14",
                         "updated_at":"2017-06-05 21:26:14",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"34"
                         }
                      }
                   ]
                }
             ]
          }
       ]
    }
</code>```

I am able to save categories in my db like this.

```<code>  protected final String CategoryTable = "category_table";
    protected final String D_ID = "category_id";
    protected final String D_SERVER_ID = "categoryserver_id";
    protected final String D_JSON = "category_json";

 public boolean insertCategory(Category model) {
        ContentValues cv = new ContentValues();
        database = this.getWritableDatabase();
        cv.put(D_SERVER_ID, model.getId());
        cv.put(D_JSON, new Gson().toJson(model));
        int res = (int) database.insert(CategoryTable, null, cv);
        database.close();
        if (res > 0) {
            return true;
        } else {
            return false;
        }
    }

  public Collection<Category> getAllCategories() {
        database = this.getReadableDatabase();
        Gson gson = new Gson();
        ArrayList<Category> lst = new ArrayList<>();
        Cursor c = database.rawQuery("SELECT * FROM " + CategoryTable, null);
        if (c.moveToFirst()) {
            do {
                Category obj = gson.fromJson(c.getString(c.getColumnIndex(D_JSON)), Category.class);
                if (obj != null)
                    lst.add(obj);
            } while (c.moveToNext());
        }
        return lst;
    }
</code>```

Here is a Category Model class:

```<code>public class Category {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("parent_id")
    @Expose
    private String parentId;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("name_ar")
    @Expose
    private String nameAr;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("slug")
    @Expose
    private String slug;
    @SerializedName("created_at")
    @Expose
    private String createdAt;
    @SerializedName("updated_at")
    @Expose
    private String updatedAt;
    @SerializedName("deleted_at")
    @Expose
    private Object deletedAt;
    @SerializedName("product")
    @Expose
    private List<Product> product = null;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNameAr() {
        return nameAr;
    }

    public void setNameAr(String nameAr) {
        this.nameAr = nameAr;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getSlug() {
        return slug;
    }

    public void setSlug(String slug) {
        this.slug = slug;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Object getDeletedAt() {
        return deletedAt;
    }

    public void setDeletedAt(Object deletedAt) {
        this.deletedAt = deletedAt;
    }

    public List<Product> getProduct() {
        return product;
    }

    public void setProduct(List<Product> product) {
        this.product = product;
    }

}
</code>```

I am using retrofit library to get data. Here is the method I am using to save categories array in my db.

```<code>@Override
    public void onSuccess(Call call, Response response, int reqCode) {
        Loading.cancel();
        ProductsResponse productsResponse = (ProductsResponse) response.body();
        for (int i = 0; i < productsResponse.getCategories().size(); i++) {
            Category obj = productsResponse.getCategories().get(i);
            categories.add(obj);
            categoriesHandler.insertCategory(obj);
            categoriesHandler.insertLabel(obj.getName());
        }
        adapter.notifyDataSetChanged();
        loadSpinnerData();
}
</code>```

But how can I get product jsonArray from categories. Tried a lot but not able to find a method. Your help would be appreciated. Need to get products on the bases of categories. Kindly help. Thanks in advance.

Ashish I am using your method:

```<code> private void categorySelector(String str){
        Gson gson = new GsonBuilder().create();
        JSONArray mainData = (JSONArray) categoriesHandler.getAllCategories();
        ArrayList<Category> responseAsArrayList =
                gson.fromJson(mainData.toString(), new TypeToken<List<Category>>() {
                }.getType());
        for(int i =0;i<responseAsArrayList.size();i++)
        {
            for(int j = 0; j < responseAsArrayList.get(i).getProduct().size();j++)
            {
                Category category =  responseAsArrayList.get(i);
                Product product = category.getProduct().get(j);
                products.add(product);
            }

        }
</code>```

答:
1) If created and updated are String, make deleted a string too.

2) Assuming Person is well reflecting the json structure, and so does a class for Pivot, to get to products you can do this:

```<code>ArrayList<Category> categories = getAllCategories();
for(Category category : categories){
    for(Product product : category.getProduct()){
         <Do something with each product of the category >
    }
}
</code>```

3) In Category a better name to get the product's list is getPrducts() instead of getProduct().

EDIT 1

To search by product name:

The slow way:

This goes through all categories until it finds a product matching the productName. If there is more than one it returns the first one.

```<code>Product getProductByName(String productName){
        Product rtn = null;
        ArrayList<Category> categories = getAllCategories();
        for(Category category : categories){
            for(Product product : category.getProduct()){

                 if(product.getName().equals(productName){
                    rtn = product;
                    break;
                 }
            }
        }
        return rtn;
}
</code>```

Different approaches you can take to search more quickly:

1) Instead of storing the json string, unwrap the different objects and put the information in different tables: categoris, products, pivot.

2) Build some kind of index where you have for each product which is record that keeps the json string, the id of the category and the id of the product. When you need a product you look it up in the index and read the specific record you need to extract the product.

3) A caching strategy that combines the slow lookup with  the indexing in a hashmap.

There are probably more things you can do, this is to provide some ideas.

EDIT 2

Products by category name:

```<code>ArrayList<Product> getProductsByCategoryName(String categoryName){
    ArrayList<Product> rtn = new ArrayList<>();
    ArrayList<Category> categories = getAllCategories();
    for(Category category : categories){
        if(category.getName().equals(categoryName){
           rtn = category.getProduct();
        }
    }
    return rtn;
}
</code>```

Body:
This is my json, I wanted to get 'products' arrays object.

{
       "Categories":[
          {
             "id":6,
             "status":"1",
             "parent_id":"0",
             "name":"Bottom Wear",
             "name_ar":"\u0623\u0633\u0641\u0644 \u0627\u0631\u062a\u062f\u0627\u0621",
             "picture":null,
             "description":"gents bottom wear",
             "slug":"bottom-wear",
             "created_at":"2017-06-05 21:08:28",
             "updated_at":"2017-06-05 21:08:28",
             "deleted_at":null,
             "product":[
                {
                   "id":2,
                   "status":"1",
                   "name":"Pants",
                   "name_ar":"\u0628\u0646\u0637\u0644\u0648\u0646",
                   "dryclean_price":"9",
                   "washing_price":"6",
                   "press":"4",
                   "sw_dryclean_price":"9",
                   "sw_washing_price":"6",
                   "sw_press":"4",
                   "picture":null,
                   "created_at":"2017-04-19 21:32:04",
                   "updated_at":"2017-06-05 21:18:04",
                   "deleted_at":null,
                   "pivot":{
                      "category_id":"6",
                      "product_id":"2"
                   }
                },
                {
                   "id":8,
                   "status":"1",
                   "parent_id":"0",
                   "name":"Undergarments",
                   "name_ar":"\u0623\u062b\u0648\u0627\u0628 \u062a\u062d\u062a\u0627\u0646\u064a\u0629",
                   "picture":null,
                   "description":"Undergarments",
                   "slug":"undergarments",
                   "created_at":"2017-06-05 21:22:09",
                   "updated_at":"2017-06-05 21:22:09",
                   "deleted_at":null,
                   "product":[
                      {
                         "id":23,
                         "status":"1",
                         "name":"Underwear",
                         "name_ar":"\u062b\u064a\u0627\u0628 \u062f\u0627\u062e\u0644\u064a\u0629",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-04-19 21:35:31",
                         "updated_at":"2017-06-05 21:23:42",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"23"
                         }
                      },
                      {
                         "id":34,
                         "status":"1",
                         "name":"Socks",
                         "name_ar":"\u062c\u0648\u0627\u0631\u0628",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-06-05 21:26:14",
                         "updated_at":"2017-06-05 21:26:14",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"34"
                         }
                      }
                   ]
                }
             ]
          }
       ]
    }

I am able to save categories in my db like this.

  protected final String CategoryTable = "category_table";
    protected final String D_ID = "category_id";
    protected final String D_SERVER_ID = "categoryserver_id";
    protected final String D_JSON = "category_json";

 public boolean insertCategory(Category model) {
        ContentValues cv = new ContentValues();
        database = this.getWritableDatabase();
        cv.put(D_SERVER_ID, model.getId());
        cv.put(D_JSON, new Gson().toJson(model));
        int res = (int) database.insert(CategoryTable, null, cv);
        database.close();
        if (res > 0) {
            return true;
        } else {
            return false;
        }
    }

  public Collection<Category> getAllCategories() {
        database = this.getReadableDatabase();
        Gson gson = new Gson();
        ArrayList<Category> lst = new ArrayList<>();
        Cursor c = database.rawQuery("SELECT * FROM " + CategoryTable, null);
        if (c.moveToFirst()) {
            do {
                Category obj = gson.fromJson(c.getString(c.getColumnIndex(D_JSON)), Category.class);
                if (obj != null)
                    lst.add(obj);
            } while (c.moveToNext());
        }
        return lst;
    }

Here is a Category Model class:

public class Category {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("parent_id")
    @Expose
    private String parentId;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("name_ar")
    @Expose
    private String nameAr;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("slug")
    @Expose
    private String slug;
    @SerializedName("created_at")
    @Expose
    private String createdAt;
    @SerializedName("updated_at")
    @Expose
    private String updatedAt;
    @SerializedName("deleted_at")
    @Expose
    private Object deletedAt;
    @SerializedName("product")
    @Expose
    private List<Product> product = null;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNameAr() {
        return nameAr;
    }

    public void setNameAr(String nameAr) {
        this.nameAr = nameAr;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getSlug() {
        return slug;
    }

    public void setSlug(String slug) {
        this.slug = slug;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Object getDeletedAt() {
        return deletedAt;
    }

    public void setDeletedAt(Object deletedAt) {
        this.deletedAt = deletedAt;
    }

    public List<Product> getProduct() {
        return product;
    }

    public void setProduct(List<Product> product) {
        this.product = product;
    }

}

I am using retrofit library to get data. Here is the method I am using to save categories array in my db.

@Override
    public void onSuccess(Call call, Response response, int reqCode) {
        Loading.cancel();
        ProductsResponse productsResponse = (ProductsResponse) response.body();
        for (int i = 0; i < productsResponse.getCategories().size(); i++) {
            Category obj = productsResponse.getCategories().get(i);
            categories.add(obj);
            categoriesHandler.insertCategory(obj);
            categoriesHandler.insertLabel(obj.getName());
        }
        adapter.notifyDataSetChanged();
        loadSpinnerData();
}

But how can I get product jsonArray from categories. Tried a lot but not able to find a method. Your help would be appreciated. Need to get products on the bases of categories. Kindly help. Thanks in advance.

Ashish I am using your method:

 private void categorySelector(String str){
        Gson gson = new GsonBuilder().create();
        JSONArray mainData = (JSONArray) categoriesHandler.getAllCategories();
        ArrayList<Category> responseAsArrayList =
                gson.fromJson(mainData.toString(), new TypeToken<List<Category>>() {
                }.getType());
        for(int i =0;i<responseAsArrayList.size();i++)
        {
            for(int j = 0; j < responseAsArrayList.get(i).getProduct().size();j++)
            {
                Category category =  responseAsArrayList.get(i);
                Product product = category.getProduct().get(j);
                products.add(product);
            }

        }

Body:
1) If created and updated are String, make deleted a string too.

2) Assuming Person is well reflecting the json structure, and so does a class for Pivot, to get to products you can do this:

ArrayList<Category> categories = getAllCategories();
for(Category category : categories){
    for(Product product : category.getProduct()){
         <Do something with each product of the category >
    }
}

3) In Category a better name to get the product's list is getPrducts() instead of getProduct().

EDIT 1

To search by product name:

The slow way:

This goes through all categories until it finds a product matching the productName. If there is more than one it returns the first one.

Product getProductByName(String productName){
        Product rtn = null;
        ArrayList<Category> categories = getAllCategories();
        for(Category category : categories){
            for(Product product : category.getProduct()){

                 if(product.getName().equals(productName){
                    rtn = product;
                    break;
                 }
            }
        }
        return rtn;
}

Different approaches you can take to search more quickly:

1) Instead of storing the json string, unwrap the different objects and put the information in different tables: categoris, products, pivot.

2) Build some kind of index where you have for each product which is record that keeps the json string, the id of the category and the id of the product. When you need a product you look it up in the index and read the specific record you need to extract the product.

3) A caching strategy that combines the slow lookup with  the indexing in a hashmap.

There are probably more things you can do, this is to provide some ideas.

EDIT 2

Products by category name:

ArrayList<Product> getProductsByCategoryName(String categoryName){
    ArrayList<Product> rtn = new ArrayList<>();
    ArrayList<Category> categories = getAllCategories();
    for(Category category : categories){
        if(category.getName().equals(categoryName){
           rtn = category.getProduct();
        }
    }
    return rtn;
}


答:
One more option with dense_rank and max.

```<code>select t.*,
       max(rnk) over(partition by box_barcode) as distinct_count
from (select t.*,
      dense_rank() over(partition by box_barcode order by order_numbers) as rnk
      from t
     ) t
</code>```

The highest ranked row (using dense_rank) will be the distinct number of order numbers per box_barcode.

Title: A Column to count number of distinct values in column X based on column Y?

Body:
In SSMS 2016, I have a select statement with various joins which gives me the following data:

| box_barcode | order_number | order_shipment_id | item     | qty |
|-------------|--------------|-------------------|----------|-----|
|  3330000001 | 0000105      | FP001             | tshirt-S | 1   |
|  3330000001 | 0000105      | FP001             | tshirt-M | 2   |
|  3330000001 | 0000105      | FP001             | tshirt-L | 2   |
|  3330000005 | 0000108      | FP002             | shorts-S | 2   |
|  3330000005 | 0000108      | FP002             | shorts-M | 1   |
|  3330000005 | 0000120      | FP002             | shorts-S | 1   |
|  3330000010 | 0000120      | FP003             | shirts-M | 2   |
|  3330000010 | 0000120      | FP003             | shirts-L | 2   |
|  3330000010 | 0000121      | FP003             | shirts-S | 3   |
|  3330000010 | 0000121      | FP003             | shirts-M | 3   |
|  3330000010 | 0000122      | FP003             | shirts-S | 2   |

I'd like to add a column to count the number of distinct order_numbers for each box_barcode, for the desired result:

| box_barcode | order_number | order_shipment_id | item     | qty | count |
|-------------|--------------|-------------------|----------|-----|-------|
|  3330000001 | 0000105      | FP001             | tshirt-S | 1   | 1
|  3330000001 | 0000105      | FP001             | tshirt-M | 2   | 1
|  3330000001 | 0000105      | FP001             | tshirt-L | 2   | 1
|  3330000005 | 0000108      | FP002             | shorts-S | 2   | 2
|  3330000005 | 0000108      | FP002             | shorts-M | 1   | 2
|  3330000005 | 0000120      | FP002             | shorts-S | 1   | 2
|  3330000010 | 0000120      | FP003             | shirts-M | 2   | 3
|  3330000010 | 0000120      | FP003             | shirts-L | 2   | 3
|  3330000010 | 0000121      | FP003             | shirts-S | 3   | 3
|  3330000010 | 0000121      | FP003             | shirts-M | 3   | 3
|  3330000010 | 0000122      | FP003             | shirts-S | 2   | 3

I'm struggling to find out how best to achieve this. I know of count(distinct..), but would I have to put my current query into a subquery for the count to go against the results of that query first?

Body:
One more option with dense_rank and max.

select t.*,
       max(rnk) over(partition by box_barcode) as distinct_count
from (select t.*,
      dense_rank() over(partition by box_barcode order by order_numbers) as rnk
      from t
     ) t

The highest ranked row (using dense_rank) will be the distinct number of order numbers per box_barcode.


问:
how to change colours in Navigation Drawer
i'm trying to change my Navigation Drawer items to blue and background to white
i tried

```<code>app:itemTextColor="@color/blue"
android:background="#fff"
</code>```

and it give me this

and the original view is

i wan't to change all the items including the group title and make images appear when i change the background , any help?

Edit
my Navigation Drawer

```<code><android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    android:background="#fff"
    app:itemTextColor="@color/blue"
    app:menu="@menu/activity_main_drawer" />
</code>```

my Menu

```<code><group android:checkableBehavior="single">
    <item
        android:id="@+id/jazeera"
        android:icon="@drawable/jazeera"
        android:title="Al Jazeera English" />
    <item
        android:id="@+id/abc_news"
        android:icon="@drawable/ic_menu_gallery"
        android:title="ABC News (AU)" />
    <item
        android:id="@+id/bbc_news"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="BBC News" />
    <item
        android:id="@+id/cnn"
        android:icon="@drawable/ic_menu_manage"
        android:title="CNN" />
    <item
        android:id="@+id/daily_mail"
        android:icon="@drawable/ic_menu_manage"
        android:title="Daily Mail" />
    <item
        android:id="@+id/ny_times"
        android:icon="@drawable/ic_menu_manage"
        android:title="The New York Times" />
    <item
        android:id="@+id/usa_today"
        android:icon="@drawable/ic_menu_manage"
        android:title="USA Today" />

</group>

<item android:title="Sports">
    <menu>
        <item
            android:id="@+id/bbc_sport"
            android:icon="@drawable/ic_menu_share"
            android:title="BBC Sport" />
        <item
            android:id="@+id/fox_sports"
            android:icon="@drawable/ic_menu_send"
            android:title="Fox Sports" />
    </menu>
</item>`<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">

<group android:checkableBehavior="single">
    <item
        android:id="@+id/jazeera"
        android:icon="@drawable/jazeera"
        android:title="Al Jazeera English" />
    <item
        android:id="@+id/abc_news"
        android:icon="@drawable/ic_menu_gallery"
        android:title="ABC News (AU)" />
    <item
        android:id="@+id/bbc_news"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="BBC News" />
    <item
        android:id="@+id/cnn"
        android:icon="@drawable/ic_menu_manage"
        android:title="CNN" />
    <item
        android:id="@+id/daily_mail"
        android:icon="@drawable/ic_menu_manage"
        android:title="Daily Mail" />
    <item
        android:id="@+id/ny_times"
        android:icon="@drawable/ic_menu_manage"
        android:title="The New York Times" />
    <item
        android:id="@+id/usa_today"
        android:icon="@drawable/ic_menu_manage"
        android:title="USA Today" />

</group>

<item android:title="Sports">
    <menu>
        <item
            android:id="@+id/bbc_sport"
            android:icon="@drawable/ic_menu_share"
            android:title="BBC Sport" />
        <item
            android:id="@+id/fox_sports"
            android:icon="@drawable/ic_menu_send"
            android:title="Fox Sports" />
    </menu>
</item>
</code>```

答:
i finally figured out why it did all of this

i changed app theme it was a dark theme and headers title was default white so it didn't appear

i added a property app:itemIconTint="your desired color"in the NavigationView

final view

Body:
i'm trying to change my Navigation Drawer items to blue and background to white
i tried

app:itemTextColor="@color/blue"
android:background="#fff"

and it give me this

and the original view is

i wan't to change all the items including the group title and make images appear when i change the background , any help?

Edit
my Navigation Drawer

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    android:background="#fff"
    app:itemTextColor="@color/blue"
    app:menu="@menu/activity_main_drawer" />

my Menu

<group android:checkableBehavior="single">
    <item
        android:id="@+id/jazeera"
        android:icon="@drawable/jazeera"
        android:title="Al Jazeera English" />
    <item
        android:id="@+id/abc_news"
        android:icon="@drawable/ic_menu_gallery"
        android:title="ABC News (AU)" />
    <item
        android:id="@+id/bbc_news"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="BBC News" />
    <item
        android:id="@+id/cnn"
        android:icon="@drawable/ic_menu_manage"
        android:title="CNN" />
    <item
        android:id="@+id/daily_mail"
        android:icon="@drawable/ic_menu_manage"
        android:title="Daily Mail" />
    <item
        android:id="@+id/ny_times"
        android:icon="@drawable/ic_menu_manage"
        android:title="The New York Times" />
    <item
        android:id="@+id/usa_today"
        android:icon="@drawable/ic_menu_manage"
        android:title="USA Today" />

</group>

<item android:title="Sports">
    <menu>
        <item
            android:id="@+id/bbc_sport"
            android:icon="@drawable/ic_menu_share"
            android:title="BBC Sport" />
        <item
            android:id="@+id/fox_sports"
            android:icon="@drawable/ic_menu_send"
            android:title="Fox Sports" />
    </menu>
</item>`<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">

<group android:checkableBehavior="single">
    <item
        android:id="@+id/jazeera"
        android:icon="@drawable/jazeera"
        android:title="Al Jazeera English" />
    <item
        android:id="@+id/abc_news"
        android:icon="@drawable/ic_menu_gallery"
        android:title="ABC News (AU)" />
    <item
        android:id="@+id/bbc_news"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="BBC News" />
    <item
        android:id="@+id/cnn"
        android:icon="@drawable/ic_menu_manage"
        android:title="CNN" />
    <item
        android:id="@+id/daily_mail"
        android:icon="@drawable/ic_menu_manage"
        android:title="Daily Mail" />
    <item
        android:id="@+id/ny_times"
        android:icon="@drawable/ic_menu_manage"
        android:title="The New York Times" />
    <item
        android:id="@+id/usa_today"
        android:icon="@drawable/ic_menu_manage"
        android:title="USA Today" />

</group>

<item android:title="Sports">
    <menu>
        <item
            android:id="@+id/bbc_sport"
            android:icon="@drawable/ic_menu_share"
            android:title="BBC Sport" />
        <item
            android:id="@+id/fox_sports"
            android:icon="@drawable/ic_menu_send"
            android:title="Fox Sports" />
    </menu>
</item>


问:
Python Large list sorting and storage
I'm currently working with some very large lists (50 to 100 million entries) of information where each item in the list is in the form of [float,(string_1,string_2)]

I'm adding elements to the list in an unsorted manner, and would eventually like to have a list that is sorted by the float value. For example I would have a list that looks like this:

```<code>[ [0.5,(A,B)], [-0.15,(B,C)], [0.3,(A,C)], [-0.8,(A,D)] ]
</code>```

and then sort it  to get

```<code>[ [0.5,(A,B)], [0.3,(A,C)], [-0.15,(B,C)], [-0.8,(A,D)] ]
</code>```

Currently I'm using heapq to add items as I go along and then using sorted(heap) to ultimately give me the list I need. My question is: is there a better way to go about adding millions of items to a list and sorting them that won't crash my computer? Holding a list that long and then sorting it is causing some issues with my RAM.

答:
sorted() creates an entirely distinct list, so doubles the RAM needed for the massive list.  Use a list's .sort() method instead - that sorts the list in-place.

And unless there's something you haven't told us, leave heapq out of it entirely.  Putting the entries in a heap serves no purpose I can think of.  Just use a list's .append() method to add new entries, and apply .sort(reverse=True) to the list at end.

If you're still running out of RAM, then you simply can't solve this problem entirely in memory, and will need to craft an approach merging disk files.

LIVING WITH "TOO SMALL" RAM

In the worst case, even the list all by itself can't fit in available memory.  You can still create the sorted sequence, but it requires writing sorted chunks to disk and merging them later.  For the merging part, heapq is useful.  Here's an example:

```<code>import pickle
import heapq

MAXPERFILE = 100  # the array will never get bigger than this

def getfname(i):
    return "pickled%d.dat" % i

filenum = 0
def dumptofile(a):  # dump the array to file, as pickled data
    global filenum
    fname = getfname(filenum)
    with open(fname, "wb") as f:
        pickle.dump(len(a), f)
        for x in a:
            pickle.dump(x, f)
    filenum += 1

# generate some random data
import random
a = []
for _ in range(1012):  # 10 "full" files with some leftovers
    a.append(random.random())
    if len(a) == MAXPERFILE:
        a.sort(reverse=True)
        dumptofile(a)
        del a[:]
if a:
    a.sort(reverse=True)
    dumptofile(a)

print("number of files written:", filenum)

# now merge the files together; first a function
# to generate the file contents, one at a time
def feedfile(i):
    fname = getfname(i)
    with open(fname, "rb") as f:
        count = pickle.load(f)
        for _ in range(count):
            yield pickle.load(f)

for x in heapq.merge(*(feedfile(i) for i in range(filenum)),
                     reverse=True):
    print(x)
</code>```

Max memory use can be made smaller by decreasing MAXPERFILE, although performance will be better the larger MAXPERFILE.  Indeed, if MAXPERFILE is small enough and the total amount of data is large enough, the merging code may die with an OS "too many open files" error.

Title: Python Large list sorting and storage

Body:
I'm currently working with some very large lists (50 to 100 million entries) of information where each item in the list is in the form of [float,(string_1,string_2)]

I'm adding elements to the list in an unsorted manner, and would eventually like to have a list that is sorted by the float value. For example I would have a list that looks like this:

[ [0.5,(A,B)], [-0.15,(B,C)], [0.3,(A,C)], [-0.8,(A,D)] ]

and then sort it  to get

[ [0.5,(A,B)], [0.3,(A,C)], [-0.15,(B,C)], [-0.8,(A,D)] ]

Currently I'm using heapq to add items as I go along and then using sorted(heap) to ultimately give me the list I need. My question is: is there a better way to go about adding millions of items to a list and sorting them that won't crash my computer? Holding a list that long and then sorting it is causing some issues with my RAM.

Body:
sorted() creates an entirely distinct list, so doubles the RAM needed for the massive list.  Use a list's .sort() method instead - that sorts the list in-place.

And unless there's something you haven't told us, leave heapq out of it entirely.  Putting the entries in a heap serves no purpose I can think of.  Just use a list's .append() method to add new entries, and apply .sort(reverse=True) to the list at end.

If you're still running out of RAM, then you simply can't solve this problem entirely in memory, and will need to craft an approach merging disk files.

LIVING WITH "TOO SMALL" RAM

In the worst case, even the list all by itself can't fit in available memory.  You can still create the sorted sequence, but it requires writing sorted chunks to disk and merging them later.  For the merging part, heapq is useful.  Here's an example:

import pickle
import heapq

MAXPERFILE = 100  # the array will never get bigger than this

def getfname(i):
    return "pickled%d.dat" % i

filenum = 0
def dumptofile(a):  # dump the array to file, as pickled data
    global filenum
    fname = getfname(filenum)
    with open(fname, "wb") as f:
        pickle.dump(len(a), f)
        for x in a:
            pickle.dump(x, f)
    filenum += 1

# generate some random data
import random
a = []
for _ in range(1012):  # 10 "full" files with some leftovers
    a.append(random.random())
    if len(a) == MAXPERFILE:
        a.sort(reverse=True)
        dumptofile(a)
        del a[:]
if a:
    a.sort(reverse=True)
    dumptofile(a)

print("number of files written:", filenum)

# now merge the files together; first a function
# to generate the file contents, one at a time
def feedfile(i):
    fname = getfname(i)
    with open(fname, "rb") as f:
        count = pickle.load(f)
        for _ in range(count):
            yield pickle.load(f)

for x in heapq.merge(*(feedfile(i) for i in range(filenum)),
                     reverse=True):
    print(x)

Max memory use can be made smaller by decreasing MAXPERFILE, although performance will be better the larger MAXPERFILE.  Indeed, if MAXPERFILE is small enough and the total amount of data is large enough, the merging code may die with an OS "too many open files" error.


问:
Is there a cleaner way to get a hold of an ActiveRecord query interface?
I have this which works, but I thought there might be a specific method for it.

```<code>  @deals = Deal.where("1=1")
  if @dealFilter.min.to_i > 0
    @deals = @deals.where("size >= ?", @dealFilter.min)
  end
  if ...
</code>```

I tried Deal.select but it required parameters. I found Deal.none but that returns none always. I tried Deal.where but it gave undefined method ``where' for #<ActiveRecord::QueryMethods::WhereChain:0x0000001d2bfb20> when I tried to chain another where on.

I have many conditions chained together. If no conditions match, it should return Deal.all.

Reference: http://guides.rubyonrails.org/active_record_querying.html

答:
You could make use of ActiveRecord scopes, and move the logic into your model. For example:

```<code>class Deal < ActiveRecord::Base

  scope :filter_min, ->(min) {
    where("size >= ?", min) if min.to_i > 0
  }
  scope :filter_max, ->(max) {
    where("size <= ?", max) if max.to_i > 0
  }

end
</code>```

And then in your controller you can write:

```<code>Deal.filter_min(@dealFilter.min).filter_max(@dealFilter.max)
</code>```

Body:
I have this which works, but I thought there might be a specific method for it.

  @deals = Deal.where("1=1")
  if @dealFilter.min.to_i > 0
    @deals = @deals.where("size >= ?", @dealFilter.min)
  end
  if ...

I tried Deal.select but it required parameters. I found Deal.none but that returns none always. I tried Deal.where but it gave undefined method ``where' for #<ActiveRecord::QueryMethods::WhereChain:0x0000001d2bfb20> when I tried to chain another where on.

I have many conditions chained together. If no conditions match, it should return Deal.all.

Reference: http://guides.rubyonrails.org/active_record_querying.html

Body:
You could make use of ActiveRecord scopes, and move the logic into your model. For example:

class Deal < ActiveRecord::Base

  scope :filter_min, ->(min) {
    where("size >= ?", min) if min.to_i > 0
  }
  scope :filter_max, ->(max) {
    where("size <= ?", max) if max.to_i > 0
  }

end

And then in your controller you can write:

Deal.filter_min(@dealFilter.min).filter_max(@dealFilter.max)


问:
How can I redefine an operator as a function?
I've been thinking about a way to stop repeating myself when I create new code for a class, for instance, I need to sum all the values within a case class when the same class appears.

An example might better explain what I'm currently doing:

```<code>case class A(a: Double, b: Double) {
    def +(that: A): A {
        A(a + that.a, b + that.b)
    }
    def *(that: A): A {
        A(a * that.a, b * that.b)
    }
}
</code>```

which allows me to do:

```<code>val a = A(1, 2)
val b = A(3, 4)
val c = a + b
</code>```

where c = A(4, 6), right?

Well, what if I want to generalize the operation? For instance, let me give you an example of something that does not work but that I believe portrays my intention perfectly.

```<code>case class A(a: Double, b: Double) {
    def operation(op: (x: Double, y: Double) => Double)(that: => A) = {
        A(op(a, that.a), op(b, that.b))
    }
}
</code>```

Now, I know that doesn't work because I probably got some extremely important concepts mixed up which I haven't pinpointed yet, but I came up with this idea thinking of this possibility:

```<code>val a = A(1, 2)
val b = B(3, 4)
val + = (x: Double, y: Double) => (x + y)
val res = a + b
</code>```

I know that this can be done in different ways which will achieve the same result, but is there a way to portray generic operations like this?

答:
Not exactly sure what you're after, but maybe this comes close.

```<code>case class A(a: Double, b: Double) {
  def @@(that:A): ((Double, Double) => Double) => A =
    op => A(op(a, that.a), op(b, that.b))
}
</code>```

Usage:

```<code>val a = A(7, 2)
val b = A(3, 4)

(a @@ b)(_+_)      // res0: A = A(10.0,6.0)
(a @@ b)(_*_)      // res1: A = A(21.0,8.0)
(a @@ b)(Math.min) // res2: A = A(3.0,2.0)
</code>```

Body:
I've been thinking about a way to stop repeating myself when I create new code for a class, for instance, I need to sum all the values within a case class when the same class appears.

An example might better explain what I'm currently doing:

case class A(a: Double, b: Double) {
    def +(that: A): A {
        A(a + that.a, b + that.b)
    }
    def *(that: A): A {
        A(a * that.a, b * that.b)
    }
}

which allows me to do:

val a = A(1, 2)
val b = A(3, 4)
val c = a + b

where c = A(4, 6), right?

Well, what if I want to generalize the operation? For instance, let me give you an example of something that does not work but that I believe portrays my intention perfectly.

case class A(a: Double, b: Double) {
    def operation(op: (x: Double, y: Double) => Double)(that: => A) = {
        A(op(a, that.a), op(b, that.b))
    }
}

Now, I know that doesn't work because I probably got some extremely important concepts mixed up which I haven't pinpointed yet, but I came up with this idea thinking of this possibility:

val a = A(1, 2)
val b = B(3, 4)
val + = (x: Double, y: Double) => (x + y)
val res = a + b

I know that this can be done in different ways which will achieve the same result, but is there a way to portray generic operations like this?

Body:
Not exactly sure what you're after, but maybe this comes close.

case class A(a: Double, b: Double) {
  def @@(that:A): ((Double, Double) => Double) => A =
    op => A(op(a, that.a), op(b, that.b))
}

Usage:

val a = A(7, 2)
val b = A(3, 4)

(a @@ b)(_+_)      // res0: A = A(10.0,6.0)
(a @@ b)(_*_)      // res1: A = A(21.0,8.0)
(a @@ b)(Math.min) // res2: A = A(3.0,2.0)


问:
create igraph Graph from pandas dataframe
I have the following pandas dataframe contains an edgelist as following:

```<code>        name1              name2    weight
0  $hort, Too  Alexander, Khandi  0.083333
1  $hort, Too             B-Real  0.083333
</code>```

I want to create a igraph object from the pandas dataframe (not from files).
The graph is too large  so I cannot convert it to an adjacency matrix. How to do that?

答:
Just sketching/pseudocode, but what about:</p>

```<code>for i, row in df.iterrows():
    graph.add_edge(row.name1, row.name2, weight=row.weight)
</code>```

Body:
I have the following pandas dataframe contains an edgelist as following:

        name1              name2    weight
0  $hort, Too  Alexander, Khandi  0.083333
1  $hort, Too             B-Real  0.083333

I want to create a igraph object from the pandas dataframe (not from files).
The graph is too large  so I cannot convert it to an adjacency matrix. How to do that?

Body:
Just sketching/pseudocode, but what about:

for i, row in df.iterrows():
    graph.add_edge(row.name1, row.name2, weight=row.weight)


问:
string query in a function in kdb
```<code>func:{[query] value query};
</code>```

query is part of my function. I have add some like delete xxx, yyyy from (value query) and some manipulation. I am not sure why when I don't use value "query", the function doesn't work. It said it cannot find the table. So I have to use value query in the function and query is a parameter. I need to pass "select from tab" to the function.

My questions is: how do I send if the filter is a string too?

```<code>func["select from tab where a="abc""] <<< this does not work
</code>```

How can I make string inside a string work?

Also, not sure why if I do

```<code>func["select from tab where date = max date"]  it did not work due to length error
but func["100#select from tab where date = max date"] it works ?
</code>```

The whole function is

```<code>getTable:{[query]loadHDB[];.Q.view date where date < .z.D-30;tab:(delete xxxx,yyyyy,sub,ID,subID,tID,subTID,text,gID from((value query)));remove[];update {";"sv @[s;where (s:";"vs x) like "cId=*";:;enlist""]}each eData from (update {";"sv @[s;where (s:";"vs x) like "AId=*";:;enlist""]}each eData from tab)};

remove:{[]delete tab from `.};
loadHDB:{[]value "\\l /hdb};
</code>```

答:
I like using -3! and also -1 to print the result. If you know what your query should look like if executed from the console then after you construct your string, use -1 to print the string. It should print the query as how it would be executed by the console.</p>

```<code>    q)stst:-3!
    q)"select max age by user from tab where col1 like ",stst"Hello"
    "select max age by user from tab where col1 like \"Hello\""
    q)/then to view how it will be executed, use -1
    q)-1"select max age by user from tab where col1 like ",stst"Hello";
    select max age by user from tab where col1 like "Hello"
    q)/looks good
</code>```

Title: string query in a function in kdb

Body:
func:{[query] value query};

query is part of my function. I have add some like delete xxx, yyyy from (value query) and some manipulation. I am not sure why when I don't use value "query", the function doesn't work. It said it cannot find the table. So I have to use value query in the function and query is a parameter. I need to pass "select from tab" to the function.

My questions is: how do I send if the filter is a string too?

func["select from tab where a="abc""] <<< this does not work

How can I make string inside a string work?

Also, not sure why if I do

func["select from tab where date = max date"]  it did not work due to length error
but func["100#select from tab where date = max date"] it works ?

The whole function is

getTable:{[query]loadHDB[];.Q.view date where date < .z.D-30;tab:(delete xxxx,yyyyy,sub,ID,subID,tID,subTID,text,gID from((value query)));remove[];update {";"sv @[s;where (s:";"vs x) like "cId=*";:;enlist""]}each eData from (update {";"sv @[s;where (s:";"vs x) like "AId=*";:;enlist""]}each eData from tab)};

remove:{[]delete tab from `.};
loadHDB:{[]value "\\l /hdb};

Body:
I like using -3! and also -1 to print the result. If you know what your query should look like if executed from the console then after you construct your string, use -1 to print the string. It should print the query as how it would be executed by the console.

    q)stst:-3!
    q)"select max age by user from tab where col1 like ",stst"Hello"
    "select max age by user from tab where col1 like \"Hello\""
    q)/then to view how it will be executed, use -1
    q)-1"select max age by user from tab where col1 like ",stst"Hello";
    select max age by user from tab where col1 like "Hello"
    q)/looks good


问:
How to generate dynamic font awesome icon in php for loop
I want to generate all current available font awesome icons dynamically in my php code, so user can select it.  Do I need to hardcode all icons in an array or database? or is there any shortcut light weight way to do this? for example;

```<code><?php
foreach($fonticons as $icon){ // $fonticons is an abstract array, It have nothing
    echo '<i class="fa '.$icon.'"></i>';
}
?>
</code>```

so I should get;

```<code><i class="fa fa-adjust"></i>
<i class="fa fa-anchor"></i>
<i class="fa fa-archive"></i>
<i class="fa fa-area-chart"></i>
<i class="fa fa-arrows"></i>
<i class="fa fa-hand"></i>....
</code>```

is it possible?

I came to know that,

every font awesome icon has a unique unicode.

for example fa-adjust unicode is F042. you can see it in console css as . So what if set counter starts to F042 and loop and increment it in hex. and display this in html?

I can just copy paste this array and start using it. But I want it dynamic.

答:
You can use a yaml parser and process the icons.yml file provided by font awesome git repository:</p>

```<code><?php
use Symfony\Component\Yaml\Yaml;

$yaml = Yaml::parse(file_get_contents('FONT_AWESOME_PATH/src/icons.yml'));
$icons = $yaml['icons'];

foreach($icons as $icon) {
    if(empty($icon['unicode'])) {
        continue;
    }
    echo '<i class="fa fa-'.$icon['id'].'"></i>';
}
</code>```

Body:
I want to generate all current available font awesome icons dynamically in my php code, so user can select it.  Do I need to hardcode all icons in an array or database? or is there any shortcut light weight way to do this? for example;

<?php
foreach($fonticons as $icon){ // $fonticons is an abstract array, It have nothing
    echo '';
}
?>

so I should get;

....

is it possible?

I came to know that,

every font awesome icon has a unique unicode.

for example fa-adjust unicode is F042. you can see it in console css as . So what if set counter starts to F042 and loop and increment it in hex. and display this in html?

I can just copy paste this array and start using it. But I want it dynamic.

Body:
You can use a yaml parser and process the icons.yml file provided by font awesome git repository:

<?php
use Symfony\Component\Yaml\Yaml;

$yaml = Yaml::parse(file_get_contents('FONT_AWESOME_PATH/src/icons.yml'));
$icons = $yaml['icons'];

foreach($icons as $icon) {
    if(empty($icon['unicode'])) {
        continue;
    }
    echo '<i class="fa fa-'.$icon['id'].'"></i>';
}