问:
Failed to load libmysql.dll file using Ruby on Rails 3
I am making one application using RoR with mysql.I followed the below steps for making app with mysql.

1-rails new projectname -d mysql

2-rails generate scaffold Post title:string body:text

After running the 2nd step  I got the following error.

Error:

```<code>Failed to load libmysql.dll from C:\Ruby193\lib\ruby\gems\1.9.1\gems\mysql2-0.3.
18-x86-mingw32\vendor\libmysql.dll
</code>```

I have installed mysql in my system and copied the libmysql.dll file from mysql-connector-c-noinstall-6.0.2-win32\lib\libmysql.dll to C:\Ruby193\bin still i am getting the above error.Please try to help me to resolve this error and i am also interested to know if my mysql DB is present in some other instance instead of my local system how can i connect it using Rails.

I am using Rails version-3.2.19 and win-xp in my system.

答: This happened to me after I upgraded to mysql2 0.4.7+.  Versions after 0.4.6 use MySQL Connector C 6.1.10+.  The release notes mention that in order to compile MySQL Connector C, you will need Visual C++ Redistributable for Visual Studio 2015 installed.  After installing that and reinstalling mysql2, the error went away. </p>

Body:
I am making one application using RoR with mysql.I followed the below steps for making app with mysql.

1-rails new projectname -d mysql

2-rails generate scaffold Post title:string body:text

After running the 2nd step  I got the following error.

Error:

Failed to load libmysql.dll from C:\Ruby193\lib\ruby\gems\1.9.1\gems\mysql2-0.3.
18-x86-mingw32\vendor\libmysql.dll

I have installed mysql in my system and copied the libmysql.dll file from mysql-connector-c-noinstall-6.0.2-win32\lib\libmysql.dll to C:\Ruby193\bin still i am getting the above error.Please try to help me to resolve this error and i am also interested to know if my mysql DB is present in some other instance instead of my local system how can i connect it using Rails.

I am using Rails version-3.2.19 and win-xp in my system.


来源: stackexchange

问:
Multithreading in c++
I want to run one function with different parameters on different threads:

```<code>int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i<threads; i++){
  //new_thread function(par1[i], par2[i]);
}
</code>```

I know nothing about threads. I tried to do something the windows API (can't use other libraries), but it doesn't work. How should I implement this? And it is possible to start an unknown number of threads of the time of programming (dynamically creating threads)?

答:
I know nothing about threads.

This is a problem. Threads is one of the area where experimenting without at least some theoretical background usually ends in a catastrophe. There’s so much that can go wrong with threading, but that doesn’t occur until much, much later.

I would suggest either getting a book about multithreading or reading a few articles online before starting.

If you are interested in using multithreading for for efficiency then Herb Sutter’s column may be for you. And then there’s the excellent Introduction to Parallel Computing by Blaise Barney.

ContentLicense: CC BY-SA 3.0

Title: Multithreading in c++

Body:
I want to run one function with different parameters on different threads:

int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i<threads; i++){
  //new_thread function(par1[i], par2[i]);
}

I know nothing about threads. I tried to do something the windows API (can't use other libraries), but it doesn't work. How should I implement this? And it is possible to start an unknown number of threads of the time of programming (dynamically creating threads)?

ContentLicense: CC BY-SA 2.5


问:
Printing textdata from toString - Java
I am working on a personal Java project and learning how to print out data from a text file. My code (as you can see below) prints out the userNameGenerator and personName data perfectly fine but I want it to be printed out from the toString in my Java Class. How can I change my code to print it out from there?

This is how my toString looks like:

```<code>@Override
public String toString() {
    return userNameGenerator + " -> " + "[" + personName + "]" ;
}
</code>```

Full code:

```<code>import java.util.*;
import java.io.*;

public class Codes {
    public static void main(String[] args) {
        List<Codes2> personFile = new ArrayList<>();

        try {
            BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
            String fileRead = br.readLine();
            while (fileRead != null) {
                String[] personData = fileRead.split(":");
                String personName = personData[0];
                String userNameGenerator = personData[1];
                Codes2 personObj = new Codes2(personName, userNameGenerator);
                personFile.add(personObj);
                fileRead = br.readLine();
            }
            br.close();
        }

        catch (FileNotFoundException ex) {
            System.out.println("File not found!");
        }

        catch (IOException ex) {
            System.out.println("An error has occured: " + ex.getMessage());
        }

        Set<String> newStrSet = new HashSet<>();
        for(int i = 0; i < personFile.size(); i++){
            String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
            for(int j = 0; j < regionSplit.length; j++){
                newStrSet.add(regionSplit[j]);
            }
        }

        for (String p: newStrSet) {
            System.out.printf("%s -> ", p);
            for (Codes2 s: personFile) {
                if (s.getUserNameGenerator().contains(p)) {
                    System.out.printf("%s, ", s.getPersonName());
                }
            }
            System.out.println();
        }
    }
}
</code>```

Java Class:

```<code>public class Codes2 implements Comparable<Codes2> {

    private String personName;
    private String userNameGenerator;

    public Codes2(String personName, String userNameGenerator) {
        this.personName = personName;
        this.userNameGenerator = userNameGenerator;
    }

    public String getPersonName() {
        return personName;
    }

    public String getUserNameGenerator() {
        return userNameGenerator;
    }

    @Override
    public int compareTo(Codes2 o) {
        return getUserNameGenerator().compareTo(o.getUserNameGenerator());
    }

    public int compare(Object lOCR1, Object lOCR2) {
        return ((Codes2)lOCR1).userNameGenerator
                .compareTo(((Codes2)lOCR2).userNameGenerator);
    }

    @Override
    public String toString() {
        return userNameGenerator + " -> " + "[" + personName + "]" ;
    }
}
</code>```

答:
Try:</p>

```<code>@Override
public String toString() {
    return String.format("%s -> [%s]",this.userNameGenerator,this.personName);
}
</code>```

Title: Printing textdata from toString - Java

Body:
I am working on a personal Java project and learning how to print out data from a text file. My code (as you can see below) prints out the userNameGenerator and personName data perfectly fine but I want it to be printed out from the toString in my Java Class. How can I change my code to print it out from there?

This is how my toString looks like:

@Override
public String toString() {
    return userNameGenerator + " -> " + "[" + personName + "]" ;
}

Full code:

import java.util.*;
import java.io.*;

public class Codes {
    public static void main(String[] args) {
        List<Codes2> personFile = new ArrayList<>();

        try {
            BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
            String fileRead = br.readLine();
            while (fileRead != null) {
                String[] personData = fileRead.split(":");
                String personName = personData[0];
                String userNameGenerator = personData[1];
                Codes2 personObj = new Codes2(personName, userNameGenerator);
                personFile.add(personObj);
                fileRead = br.readLine();
            }
            br.close();
        }

        catch (FileNotFoundException ex) {
            System.out.println("File not found!");
        }

        catch (IOException ex) {
            System.out.println("An error has occured: " + ex.getMessage());
        }

        Set<String> newStrSet = new HashSet<>();
        for(int i = 0; i < personFile.size(); i++){
            String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
            for(int j = 0; j < regionSplit.length; j++){
                newStrSet.add(regionSplit[j]);
            }
        }

        for (String p: newStrSet) {
            System.out.printf("%s -> ", p);
            for (Codes2 s: personFile) {
                if (s.getUserNameGenerator().contains(p)) {
                    System.out.printf("%s, ", s.getPersonName());
                }
            }
            System.out.println();
        }
    }
}

Java Class:

public class Codes2 implements Comparable<Codes2> {

    private String personName;
    private String userNameGenerator;

    public Codes2(String personName, String userNameGenerator) {
        this.personName = personName;
        this.userNameGenerator = userNameGenerator;
    }

    public String getPersonName() {
        return personName;
    }

    public String getUserNameGenerator() {
        return userNameGenerator;
    }

    @Override
    public int compareTo(Codes2 o) {
        return getUserNameGenerator().compareTo(o.getUserNameGenerator());
    }

    public int compare(Object lOCR1, Object lOCR2) {
        return ((Codes2)lOCR1).userNameGenerator
                .compareTo(((Codes2)lOCR2).userNameGenerator);
    }

    @Override
    public String toString() {
        return userNameGenerator + " -> " + "[" + personName + "]" ;
    }
}

Body:
Try:

@Override
public String toString() {
    return String.format("%s -> [%s]",this.userNameGenerator,this.personName);
}


问:
Why do I need std::get_temporary_buffer?
For what purpose I should use std::get_temporary_buffer? Standard says the following:

Obtains a pointer to storage sufficient to store up to n adjacent T objects.

I thought that the buffer will be allocated on the stack, but that is not true. According to the C++ Standard this buffer is actually not temporary. What advantages does this function have over the global function ::operator new, which doesn't construct the objects either. Am I right that the following statements are equivalent?

```<code>int* x;
x = std::get_temporary_buffer<int>( 10 ).first;
x = static_cast<int*>( ::operator new( 10*sizeof(int) ) );
</code>```

Does this function only exist for syntax sugar? Why is there temporary in its name?

One use case was suggested in the Dr. Dobb's Journal, July 01, 1996 for implementing algorithms:

If no buffer can be allocated, or if it is smaller than requested, the algorithm still works correctly, It merely slows down.

答:
For what purpose I should use std::get_temporary_buffer?

The function is deprecated in C++17, so the correct answer is now "for no purpose, do not use it".

Body:
For what purpose I should use std::get_temporary_buffer? Standard says the following:

Obtains a pointer to storage sufficient to store up to n adjacent T objects.

I thought that the buffer will be allocated on the stack, but that is not true. According to the C++ Standard this buffer is actually not temporary. What advantages does this function have over the global function ::operator new, which doesn't construct the objects either. Am I right that the following statements are equivalent?

int* x;
x = std::get_temporary_buffer<int>( 10 ).first;
x = static_cast<int*>( ::operator new( 10*sizeof(int) ) );

Does this function only exist for syntax sugar? Why is there temporary in its name?

One use case was suggested in the Dr. Dobb's Journal, July 01, 1996 for implementing algorithms:

If no buffer can be allocated, or if it is smaller than requested, the algorithm still works correctly, It merely slows down.


问:
Decrease the increase of value in database
My starting value is 18, for every +1 increase in that number the increase of value should decrease. Basically so it gets harder to inrease this value if you have more of it. The increase should be of 2% less that the previous increase as shown below.

Right now i only got a steady increase of 2 for every run.

```<code>$Strengthvalue = 2 + $row['strength'];
</code>```

18 = +2 (increase)

19 = +1.96 (increase)

20 = +1.92 (increase)

答:
Your starting strength is static, so you can calculate the increase based on the difference of the current strength and the start point.</p>

```<code>$currentStrength = $row["strength"];
$increment = (1 - ($currentStrength - 18) * 0.02) * 2;
$StrengthValue = $increment + $currentStrength;
</code>```

Body:
My starting value is 18, for every +1 increase in that number the increase of value should decrease. Basically so it gets harder to inrease this value if you have more of it. The increase should be of 2% less that the previous increase as shown below.

Right now i only got a steady increase of 2 for every run.

$Strengthvalue = 2 + $row['strength'];

18 = +2 (increase)

19 = +1.96 (increase)

20 = +1.92 (increase)

Body:
Your starting strength is static, so you can calculate the increase based on the difference of the current strength and the start point.

$currentStrength = $row["strength"];
$increment = (1 - ($currentStrength - 18) * 0.02) * 2;
$StrengthValue = $increment + $currentStrength;


问:
How to enable back and forward buttons when using history.pushState functionality?
I have use the following code to update a seccion in a WebSite. I decided to implement the window.history.pushState functionality. Apparently it is working properly but if I press the back button the address bar will be updated with the correct value but the navegator does not update the page's content.

How can I enable the proper back a forward functionality of the web browser when using pushState?

```<code>  ajaxPost("/URLSite", idData, function (data) { //Success
         div.innerHTML = data.Html;
             if (data.Url.length > 0 && window.history.pushState)
                 window.history.pushState({ "html": data.Html, "pageTitle": ' my site: ' + data.Url }, '', '/' + data.Url);

         }, function (cod, Error) { //Error
            var lblMsj = document.getElementById("lblMsj");
             lblMsj.innerHTML =" <br/> " +  Error + " <br/>";
         },null);
</code>```

答:
@SLaks is right.  I reviewed some documentation about onpopState and the following code solved the problem. </p>

```<code>window.onpopstate = function (event) {
     if (event.state)
     {
        var divMain = document.getElementById("divMain");
        divMain.innerHTML = event.state.html;
        document.title = event.state.pageTitle;
     }
}
</code>```

Body:
I have use the following code to update a seccion in a WebSite. I decided to implement the window.history.pushState functionality. Apparently it is working properly but if I press the back button the address bar will be updated with the correct value but the navegator does not update the page's content.

How can I enable the proper back a forward functionality of the web browser when using pushState?

  ajaxPost("/URLSite", idData, function (data) { //Success
         div.innerHTML = data.Html;
             if (data.Url.length > 0 && window.history.pushState)
                 window.history.pushState({ "html": data.Html, "pageTitle": ' my site: ' + data.Url }, '', '/' + data.Url);

         }, function (cod, Error) { //Error
            var lblMsj = document.getElementById("lblMsj");
             lblMsj.innerHTML ="
 " +  Error + "
";
         },null);

Body:
@SLaks is right.  I reviewed some documentation about onpopState and the following code solved the problem.

window.onpopstate = function (event) {
     if (event.state)
     {
        var divMain = document.getElementById("divMain");
        divMain.innerHTML = event.state.html;
        document.title = event.state.pageTitle;
     }
}


问:
Varying glyph spacing with fixed width glyphs
I am trying to create a clock using a particular font (https://www.fontsquirrel.com/fonts/play) where it is desired that the digits not move at all horizontally as time changes.  The font is not a fixed width font, but all the digits are identical widths.

The problem is that the date digits are not aligned as time changes (they are rendering with varying spaces as the digits change) when rendered by osgPango.    A fixed width font, Liberation Mono, does work as expected.

Looking at the font in Fontforge, the digit glyphs vary in physical width, but when the left and right bearing is added these are all identical width.  In other programs like Inkscape this renders as expected with a fixed width.

Is there some setting in osgPango or Pango that is overriding the font left and right bearings that can be disabled?  Or what am I missing?

答: I was finally able to fix the issue by completely turning off hinting (CAIRO_HINT_STYLE_NONE).  This can be set on the osgPango context init method.</p>


问:
JAX-WS server-side SOAPHandler that returns fault gets "Internal Error" on WebSphere v8
I have a server-side JAX-WS SOAPHandler (on WebSphere v8) that in certain cases needs to respond to the client with a SOAP response that it has in a String variable (let's call it responseXml).

When responseXml contains a successful (i.e., non-fault) SOAP message, JAX-WS sends the response to the client correctly.  However, when responseXml contains a SOAP fault message, an "Internal Error" occurs, and the client gets a different fault response than the one in responseXml, as shown here:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <soapenv:Fault xmlns:axis2ns1="http://schemas.xmlsoap.org/soap/envelope/">
         <faultcode>axis2ns1:Server</faultcode>
         <faultstring>Internal Error</faultstring>
         <detail/>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

The following error is written to the console:

```<code>[10/9/12 12:21:04:177 EDT] 00000025 AxisEngine    E org.apache.axis2.engine.AxisEngine receive An error was detected during JAXWS processing
                             org.apache.axis2.AxisFault: An error was detected during JAXWS processing
at org.apache.axis2.jaxws.server.JAXWSMessageReceiver.receive(JAXWSMessageReceiver.java:208)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:198)
at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:172)
at com.ibm.ws.websvcs.transport.http.WASAxis2Servlet.doPost(WASAxis2Servlet.java:1466)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:595)
...
</code>```

Here is a simplified SOAPHandler that illustrates this problem.  (Note that the value of responseXml shown here is just an example. In my actual SOAPHandler, the responses are not hard-coded but are read from a database. I'm just trying to show the simplest sample code possible.)

```<code>package simplified.demo;

import java.io.ByteArrayInputStream;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

public class FaultyHandler implements SOAPHandler<SOAPMessageContext> {

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

        if (!outbound) {
            String responseXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Header></soapenv:Header><soapenv:Body><soapenv:Fault><faultcode>soapenv:Server</faultcode><faultstring>ORA-01031: insufficient privileges</faultstring><detail/></soapenv:Fault></soapenv:Body></soapenv:Envelope>";
            try {
                SOAPMessage newMsg = createSOAPMessage(responseXml);
                context.setMessage(newMsg);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return (outbound);
    }

    private SOAPMessage createSOAPMessage(String responseXml) {
        try {
            ByteArrayInputStream in = new ByteArrayInputStream(responseXml.getBytes());
            MessageFactory messageFactory = MessageFactory.newInstance();
            return messageFactory.createMessage(null, in);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        return true;
    }

    @Override
    public Set<QName> getHeaders() {
        return null;
    }

    @Override
    public void close(MessageContext context) {
    }
}
</code>```

I get the exact same error when I code the SOAPHandler to create a SOAPFault object (using a SOAPFactory) and throw it in a SOAPFaultException.

Based on the stack trace, I looked at the source code for JAXWSMessageReceiver, and it looks like under the covers, Axis2 is looking for a causedByException, but of course in this case there isn't one.

Does anyone know why this is happening or how it can be fixed?  Thanks!

答:
I had the same issue after upgrading the WAS FP 8.5.5.10 to 8.5.5.12. We had two Services with exactly same method name but different targetNameSpace,like DomainService1 has 'get' method and DomainService2 also has 'get' method, but WAS 8.5.5.12 throws this exception and doesn't give any clue to find the root cause. Apparently WAS is more strict in recent version with the naming of the methods.

This was the exception:
org.apache.axis2.jaxws.wrapper.impl.JAXBWrapperException: An internal assertion error occurred. The com.xxx.web.myapp.services.jaxws.GetResponse JAXB object does not have a xxxxxStatus xml

After changing the name of the method specific to each service 'getABC' and 'getPQR' it worked!!!

hope this works!

Body:
I have a server-side JAX-WS SOAPHandler (on WebSphere v8) that in certain cases needs to respond to the client with a SOAP response that it has in a String variable (let's call it responseXml).

When responseXml contains a successful (i.e., non-fault) SOAP message, JAX-WS sends the response to the client correctly.  However, when responseXml contains a SOAP fault message, an "Internal Error" occurs, and the client gets a different fault response than the one in responseXml, as shown here:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <soapenv:Fault xmlns:axis2ns1="http://schemas.xmlsoap.org/soap/envelope/">
         <faultcode>axis2ns1:Server</faultcode>
         <faultstring>Internal Error</faultstring>
         <detail/>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>

The following error is written to the console:

[10/9/12 12:21:04:177 EDT] 00000025 AxisEngine    E org.apache.axis2.engine.AxisEngine receive An error was detected during JAXWS processing
                             org.apache.axis2.AxisFault: An error was detected during JAXWS processing
at org.apache.axis2.jaxws.server.JAXWSMessageReceiver.receive(JAXWSMessageReceiver.java:208)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:198)
at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:172)
at com.ibm.ws.websvcs.transport.http.WASAxis2Servlet.doPost(WASAxis2Servlet.java:1466)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:595)
...

Here is a simplified SOAPHandler that illustrates this problem.  (Note that the value of responseXml shown here is just an example. In my actual SOAPHandler, the responses are not hard-coded but are read from a database. I'm just trying to show the simplest sample code possible.)

package simplified.demo;

import java.io.ByteArrayInputStream;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

public class FaultyHandler implements SOAPHandler<SOAPMessageContext> {

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

        if (!outbound) {
            String responseXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Header></soapenv:Header><soapenv:Body><soapenv:Fault><faultcode>soapenv:Server</faultcode><faultstring>ORA-01031: insufficient privileges</faultstring><detail/></soapenv:Fault></soapenv:Body></soapenv:Envelope>";
            try {
                SOAPMessage newMsg = createSOAPMessage(responseXml);
                context.setMessage(newMsg);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return (outbound);
    }

    private SOAPMessage createSOAPMessage(String responseXml) {
        try {
            ByteArrayInputStream in = new ByteArrayInputStream(responseXml.getBytes());
            MessageFactory messageFactory = MessageFactory.newInstance();
            return messageFactory.createMessage(null, in);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        return true;
    }

    @Override
    public Set<QName> getHeaders() {
        return null;
    }

    @Override
    public void close(MessageContext context) {
    }
}

I get the exact same error when I code the SOAPHandler to create a SOAPFault object (using a SOAPFactory) and throw it in a SOAPFaultException.

Based on the stack trace, I looked at the source code for JAXWSMessageReceiver, and it looks like under the covers, Axis2 is looking for a causedByException, but of course in this case there isn't one.

Does anyone know why this is happening or how it can be fixed?  Thanks!


问:
Set a Property in a ViewModel from Another ViewModel
I am trying to pass a value to a view model from another view model before navigating to the page attached to that view model.
I was previously passing it to the view, then passing it to the view model. This seems like a clumsy way of doing things.
I am not using any kind of framework so that is not an option.
At the moment the property is set as static and this works but im not sure if this is good practice.
The code:

View model 1:

This command opens the new page:

```<code>public void OpenRouteDetails()
{
   RouteStopPopOverViewModel.RouteName = "TestRoute";
   App.Page.Navigation.PushAsync(new RouteStopPopOverView());
}
</code>```

View model 2: (RouteStopPopOverViewModel)

```<code>public static string RouteName { get; set; }
</code>```

This does work but I would prefer not to use static as a way to achieve this.
Is there some way to set the RouteName property without using static or passing it through view-> view model.
I have seen some answers about this but they don't seem to answer to question clearly.

答:
As you are using the MVVM pattern, you can use one of the many MVVM Frameworks to achieve this.

I use FreshMvvm and it allow me to pass parameters between view models like this

```<code>await CoreMethods.PushPageModel<SecondPageModel>(myParameter, false);
</code>```

Then in SecondPageModel I can see access the parameters in the Init method

```<code>private MyParamType _myParameter;

public override void Init(object initData)
{
    base.Init(initData);

    var param = initData as MyParamType;
    if (param != null)
    {
        _myParameter = param;
    }
}
</code>```

You can find more details about FreshMvvm here although most MVVM frameworks have similar functionality.

Body:
I am trying to pass a value to a view model from another view model before navigating to the page attached to that view model.
I was previously passing it to the view, then passing it to the view model. This seems like a clumsy way of doing things.
I am not using any kind of framework so that is not an option.
At the moment the property is set as static and this works but im not sure if this is good practice.
The code:

View model 1:

This command opens the new page:

public void OpenRouteDetails()
{
   RouteStopPopOverViewModel.RouteName = "TestRoute";
   App.Page.Navigation.PushAsync(new RouteStopPopOverView());
}

View model 2: (RouteStopPopOverViewModel)

public static string RouteName { get; set; }

This does work but I would prefer not to use static as a way to achieve this.
Is there some way to set the RouteName property without using static or passing it through view-> view model.
I have seen some answers about this but they don't seem to answer to question clearly.

Body:
As you are using the MVVM pattern, you can use one of the many MVVM Frameworks to achieve this.

I use FreshMvvm and it allow me to pass parameters between view models like this

await CoreMethods.PushPageModel<SecondPageModel>(myParameter, false);

Then in SecondPageModel I can see access the parameters in the Init method

private MyParamType _myParameter;

public override void Init(object initData)
{
    base.Init(initData);

    var param = initData as MyParamType;
    if (param != null)
    {
        _myParameter = param;
    }
}

You can find more details about FreshMvvm here although most MVVM frameworks have similar functionality.


问:
CRNA/Expo and iOS - how do i create a build signed with a Developer certificate?
We're looking to run UI Automation on our app generated with CRNA using Appium.  I am able to generate an Enterprise Distribution build via the CRNA CLI but not a Developer build.  Is there a way to do this with the built-in CLI or a custom script?  If not, do I need to eject the app just to generate a Developer build?</p>

答:
Its possible and thats how actually mobile device clouds are able to run tests on different iOS apps (not having their provision profiles):

More or less its like this:

You have MyApp.ipa

unzip MyApp.ipa

rm -rf Payload/MyApp.app/_CodeSignature/

cp ~/ Payload/MyApp.app/

codesign -f -s "iPhone Distribution: Company Certificate" Payload/MyApp.app

zip -qr resigned.ipa Payload/

What you need to know is that after resign you push notifications (if there are any) will be broken.


问:
E-R Diagram and Relational Tables

I need to use this description to make an E-R Diagram and then reduce it to relational tables. Later a creation of the tables is needed in SQL, but first I want to get these correct.

Consider the following set of requirements for a FAST FOOD CHAIN application.
This fast food chain can have several restaurants. Each restaurant has a manager and an
assistant manager (different from the manager), and several other employees like
cashiers, and cleaning personnel. We know the name, address, phone and salary of all
employees. Each restaurant keeps track of its inventory, so it knows how many items of each
item there are at the store. Each item has a provider with a name, and an address.
Customers visit restaurants to get food (items). There are two types of customers: regulars and VIP
customers. The fast food chain keeps track of the name, address, phone of each customer. For
VIP customers, however, the store also keeps track of the customer’s birthdate. The store keeps
track of each purchase made by a customer, by recording the date of purchase, the total
amount paid for the visit, and listing all the items purchased by the customer. Each purchase is made by a customer, and associated with the cashier.

My first attempt at the E-R Diagram is this:

My attempt at the tables look like:

```<code>Restaurant(manager, assistant_manager)

Employees(id, name, address, phone, salary)

Items(item_id, provider, address)

Customer(customer_id, type, name, address, phone, VIP)

Purchases(customer_id, cashier_id, total_paid, date_bought, items_bought)
</code>```

Any help is appreciated! Thank you

答:
You have many mistakes in you ER.

First of all: It's better to read a Data Modeling Book in-depth.

see: How to become a good database designer?

I list some important mistakes:

Manager and Assistant Manager can not be attributes. They are types of Employees. You can have one-to-one relationship (with the name of Manager or Assistant_Manager) between Restaurant and Employees (For each of them : manager and assistant manager).

Based on your explains, it's better to have a Employee Type entity.

Provider of Items can turn into an Entity.

You should put purchases_id into Items.

Relationship between Purchases and Employees should be many-to-one (each Employee can handle many Purchases and each Purchase handled by one Employee).

Absolutely, each Employee can handle only one Purchase at the time. But when we designing ER, we should consider period of time instead of at the time. (for example: each Employee handles many Purchases in one day)

Title: E-R Diagram and Relational Tables

Body:
I need to use this description to make an E-R Diagram and then reduce it to relational tables. Later a creation of the tables is needed in SQL, but first I want to get these correct.

Consider the following set of requirements for a FAST FOOD CHAIN application.
This fast food chain can have several restaurants. Each restaurant has a manager and an
assistant manager (different from the manager), and several other employees like
cashiers, and cleaning personnel. We know the name, address, phone and salary of all
employees. Each restaurant keeps track of its inventory, so it knows how many items of each
item there are at the store. Each item has a provider with a name, and an address.
Customers visit restaurants to get food (items). There are two types of customers: regulars and VIP
customers. The fast food chain keeps track of the name, address, phone of each customer. For
VIP customers, however, the store also keeps track of the customer’s birthdate. The store keeps
track of each purchase made by a customer, by recording the date of purchase, the total
amount paid for the visit, and listing all the items purchased by the customer. Each purchase is made by a customer, and associated with the cashier.

My first attempt at the E-R Diagram is this:

My attempt at the tables look like:

Restaurant(manager, assistant_manager)

Employees(id, name, address, phone, salary)

Items(item_id, provider, address)

Customer(customer_id, type, name, address, phone, VIP)

Purchases(customer_id, cashier_id, total_paid, date_bought, items_bought)

Any help is appreciated! Thank you


问:
Returning frequencies of words in a dictionary
I think I have the right idea on how to solve this function, but I'm not sure
why I don't get the desired results shown in the docstring. Can anyone please help me fix this?</p>

```<code>def list_to_dict(word_list):
'''(list of str) -> dict
Given a list of str (a list of English words) return a dictionary that keeps
track of word length and frequency of length. Each key is a word length and
the corresponding value is the number of words in the given list of that
length.
>>> d = list_to_dict(['This', 'is', 'some', 'text'])
>>> d == {2:1, 4:3}
True
>>> d = list_to_dict(['A', 'little', 'sentence', 'to', 'create', 'a',
'dictionary'])
>>> d == {1:2, 6:2, 8:1, 2:1, 10:1}
True
'''
d = {}
count = 0
for i in range(len(word_list)):
length = len(i)
if length not in d:
    count = count + length
    d[length] = {count}
    count += 1
return d
</code>```

答:
Simply do a loop for any word in the list. In each iteration create new key with value 1 if the length is not in the dict as a key yet, otherwise increase the previous value for the key:

```<code>def list_to_dict(word_list):
   d = dict()
   for any_word in word_list:
      length = len(any_word)
      if length not in d:
          d[length] = 1
      else:
          d[length] += 1
   return d
</code>```

Body:
I think I have the right idea on how to solve this function, but I'm not sure
why I don't get the desired results shown in the docstring. Can anyone please help me fix this?

def list_to_dict(word_list):
'''(list of str) -> dict
Given a list of str (a list of English words) return a dictionary that keeps
track of word length and frequency of length. Each key is a word length and
the corresponding value is the number of words in the given list of that
length.
>>> d = list_to_dict(['This', 'is', 'some', 'text'])
>>> d == {2:1, 4:3}
True
>>> d = list_to_dict(['A', 'little', 'sentence', 'to', 'create', 'a',
'dictionary'])
>>> d == {1:2, 6:2, 8:1, 2:1, 10:1}
True
'''
d = {}
count = 0
for i in range(len(word_list)):
length = len(i)
if length not in d:
    count = count + length
    d[length] = {count}
    count += 1
return d

Body:
Simply do a loop for any word in the list. In each iteration create new key with value 1 if the length is not in the dict as a key yet, otherwise increase the previous value for the key:

def list_to_dict(word_list):
   d = dict()
   for any_word in word_list:
      length = len(any_word)
      if length not in d:
          d[length] = 1
      else:
          d[length] += 1
   return d


问:
Why is the complexity of computing the Fibonacci series 2^n and not n^2?
I am trying to find complexity of Fibonacci series using a recursion tree and concluded height of tree = O(n) worst case, cost of each level = cn, hence complexity = n*n=n^2

How come it is O(2^n)?

答: I cannot resist the temptation of connecting a linear time iterative algorithm for Fib to the exponential time recursive one: if one reads Jon Bentley's wonderful little book on "Writing Efficient Algorithms" I believe it is a simple case of "caching": whenever Fib(k) is calculated, store it in array FibCached[k]. Whenever Fib(j) is called, first check if it is cached in FibCached[j]; if yes, return the value; if not use recursion. (Look at the tree of calls now ...)</p>


问:
Using a static class as an input parameter on another class
I have no idea if this is possible but it feels like it should be from using C# up to this point.

I want to have a bunch of static classes that contain 'set values' for users of the library to send into another class as parameter.

So this is where I was headed but I can't figure it out.  This below is just an example of what I was thinking so don't try and work out 'why' :-)

First - The Class that will be called

```<code>public class myClass
    {
        public bool isError { private set; get; }

        public DataTable output { private set; get; }

        public String filename { set; private get; }

        public settingModule settings { set; private get; }

        public static void execute()
        {

            //Call Private 'getTheData'
            //set isError accordingly
            //Load output

        }

        private static DataTable getTheData()
        {
            //Open and read file for 'fileName'

            //Use settings.startingRow
            //Use settings.fileType
            //User settings.skipEmpty

            //Do some stuff

            return Datatable from workings

        }

    }
</code>```

Second - The Class I want to user to pass

```<code>public static class settingMobule
    {
        public static class fileTypeA
        {
            public static int startingRow = 1;
            public static String fileType = "txt";
            public static bool skipEmpty = true;
        }

        public static class fileTypeB
        {
            public static int startingRow = 10;
            public static String fileType = "csv";
            public static bool skipEmpty = false;
        }

        public static class fileTypeC
        {
            public static int startingRow = 3;
            public static String fileType = "hex";
            public static bool skipEmpty = true;
        }

    }
</code>```

Lastly the way I want to be able to call it

```<code>myClass test = new myClass();

test.filename = "c:\\temp\\test.txt;

test.settings = settingModule.fileTypeA;

test.execute();

if(test.isError == false

{
DataTable myTable = test.output;
test.dispose()
}
</code>```

Thanks in advance... and yes, "your nuts there is a much better way" is a perfectly valid answer :-)

I would also LOVE to know how to add a .dispose() to my code, it's not something i have got to yet but while I am here... :-D

答:
No, basically; but you could do this:

```<code>public sealed class SettingMobule
{
    public int StartingRow {get; private set;}
    public string FileType {get; private set;}
    public bool SkipEmpty {get; private set;}

    private SettingMobule(int startingRow, string fileType, bool skipEmpty)
    {
        StartingRow = startingRow;
        FileType = fileType;
        SkipEmpty = skipEmpty;
    }
    public static SettingMobule FileTypeA {get;}
          = new SettingMobule(1, "txt", true);

    public static SettingMobule FileTypeB {get;}
          = new SettingMobule(10, "csv", false);

    public static SettingMobule FileTypeC {get;}
          = new SettingMobule(3, "hex", true);

}
</code>```

and pass SettingMobule.FileTypeA as an instance, etc.

Body:
I have no idea if this is possible but it feels like it should be from using C# up to this point.

I want to have a bunch of static classes that contain 'set values' for users of the library to send into another class as parameter.

So this is where I was headed but I can't figure it out.  This below is just an example of what I was thinking so don't try and work out 'why' :-)

First - The Class that will be called

public class myClass
    {
        public bool isError { private set; get; }

        public DataTable output { private set; get; }

        public String filename { set; private get; }

        public settingModule settings { set; private get; }

        public static void execute()
        {

            //Call Private 'getTheData'
            //set isError accordingly
            //Load output

        }

        private static DataTable getTheData()
        {
            //Open and read file for 'fileName'

            //Use settings.startingRow
            //Use settings.fileType
            //User settings.skipEmpty

            //Do some stuff

            return Datatable from workings

        }

    }

Second - The Class I want to user to pass

public static class settingMobule
    {
        public static class fileTypeA
        {
            public static int startingRow = 1;
            public static String fileType = "txt";
            public static bool skipEmpty = true;
        }

        public static class fileTypeB
        {
            public static int startingRow = 10;
            public static String fileType = "csv";
            public static bool skipEmpty = false;
        }

        public static class fileTypeC
        {
            public static int startingRow = 3;
            public static String fileType = "hex";
            public static bool skipEmpty = true;
        }

    }

Lastly the way I want to be able to call it

myClass test = new myClass();

test.filename = "c:\\temp\\test.txt;

test.settings = settingModule.fileTypeA;

test.execute();

if(test.isError == false

{
DataTable myTable = test.output;
test.dispose()
}

Thanks in advance... and yes, "your nuts there is a much better way" is a perfectly valid answer :-)

I would also LOVE to know how to add a .dispose() to my code, it's not something i have got to yet but while I am here... :-D

Body:
No, basically; but you could do this:

public sealed class SettingMobule
{
    public int StartingRow {get; private set;}
    public string FileType {get; private set;}
    public bool SkipEmpty {get; private set;}

    private SettingMobule(int startingRow, string fileType, bool skipEmpty)
    {
        StartingRow = startingRow;
        FileType = fileType;
        SkipEmpty = skipEmpty;
    }
    public static SettingMobule FileTypeA {get;}
          = new SettingMobule(1, "txt", true);

    public static SettingMobule FileTypeB {get;}
          = new SettingMobule(10, "csv", false);

    public static SettingMobule FileTypeC {get;}
          = new SettingMobule(3, "hex", true);

}

and pass SettingMobule.FileTypeA as an instance, etc.


问:
Trying to prevent multiple form entries with identical field data (only allow first user to take timeslot)
I am trying to have users enter data in a django form and only allow ONE entry into the database per each time slot and day slot.

Example: User fills out form to "sign up" to speak during 8:00am - 9:00am on Day 1 for schedule id 2.

If a database entry already exists with the same TIMESLOT and DAYSLOT, I want to raise an error and prevent entry.

Here is what I have so far, but the filter is spanning across the entire table rather than just filtering per schedule ID...

```<code>models.py

from django.db import models
import datetime

class Schedule(models.Model):
    title = models.CharField(max_length=250)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

class Agenda(models.Model):

    dayChoice = (
     ('d1', "Day 1"),
     ('d2', "Day 2"),
     ('d3', "Day 3"),
     ('d4', "Day 4")
    )

    fullName = models.CharField(max_length=250)
    startTime = models.TimeField(auto_now=False, blank=True, null=True)
    endTime = models.TimeField(auto_now=False, blank=True, null=True)
    approved = models.BooleanField(blank=True)
    daySlot = models.CharField(max_length=2, choices=dayChoice)
    sub_date = models.DateTimeField(auto_now=True)
    scheduler = models.ForeignKey(Schedule, on_delete=models.CASCADE)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.fullName
</code>```

```<code>   views.py
   from django.shortcuts import render, redirect

    from django.utils import timezone
    from django.shortcuts import render, get_object_or_404
    from .models import Schedule, Agenda
    from .forms import AgendaForm
    # Create your views here.

    def schedule_list(request):
        schedules = Schedule.objects.all()
        return render(request, 'adjenda/schedule_list.html', {'schedules': schedules})

    def agenda_detail(request, pk):
        schedules = get_object_or_404(Schedule, pk=pk)
        agenda = Agenda.objects.filter(scheduler_id=pk).order_by('startTime')
        form = AgendaForm(request.POST)
        if request.method == "POST":
            form = AgendaForm(request.POST)
            if form.is_valid():
                post = form.save(commit=False)
                post.author = request.user
                post.published_date = timezone.now()
                post.save()
                return redirect("/schedule/" + pk)
        else:
            form = AgendaForm()

        return render(request, 'adjenda/schedule_detail.html', {'agenda': agenda, 'schedules': schedules, 'form': form})

forms.py

from django import forms
from .models import Agenda, Schedule

class AgendaForm(forms.ModelForm):

    class Meta:
        model = Agenda
        fields = '__all__'

    def clean_startTime(self):
        startTime = self.cleaned_data['startTime']
        if Agenda.objects.filter(startTime=startTime).exists():
            raise forms.ValidationError("Time/Day already taken")
        return startTime
</code>```

Thanks for any help!

答:
Maybe unique_together is what you're looking for:</p>

```<code>class Agenda(models.Model):
    # field definiton

    class Meta:
        unique_together = ("startTime", "endTime", "daySlot")
</code>```

Body:
I am trying to have users enter data in a django form and only allow ONE entry into the database per each time slot and day slot.

Example: User fills out form to "sign up" to speak during 8:00am - 9:00am on Day 1 for schedule id 2.

If a database entry already exists with the same TIMESLOT and DAYSLOT, I want to raise an error and prevent entry.

Here is what I have so far, but the filter is spanning across the entire table rather than just filtering per schedule ID...

models.py

from django.db import models
import datetime

class Schedule(models.Model):
    title = models.CharField(max_length=250)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

class Agenda(models.Model):

    dayChoice = (
     ('d1', "Day 1"),
     ('d2', "Day 2"),
     ('d3', "Day 3"),
     ('d4', "Day 4")
    )

    fullName = models.CharField(max_length=250)
    startTime = models.TimeField(auto_now=False, blank=True, null=True)
    endTime = models.TimeField(auto_now=False, blank=True, null=True)
    approved = models.BooleanField(blank=True)
    daySlot = models.CharField(max_length=2, choices=dayChoice)
    sub_date = models.DateTimeField(auto_now=True)
    scheduler = models.ForeignKey(Schedule, on_delete=models.CASCADE)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.fullName

   views.py
   from django.shortcuts import render, redirect

    from django.utils import timezone
    from django.shortcuts import render, get_object_or_404
    from .models import Schedule, Agenda
    from .forms import AgendaForm
    # Create your views here.

    def schedule_list(request):
        schedules = Schedule.objects.all()
        return render(request, 'adjenda/schedule_list.html', {'schedules': schedules})

    def agenda_detail(request, pk):
        schedules = get_object_or_404(Schedule, pk=pk)
        agenda = Agenda.objects.filter(scheduler_id=pk).order_by('startTime')
        form = AgendaForm(request.POST)
        if request.method == "POST":
            form = AgendaForm(request.POST)
            if form.is_valid():
                post = form.save(commit=False)
                post.author = request.user
                post.published_date = timezone.now()
                post.save()
                return redirect("/schedule/" + pk)
        else:
            form = AgendaForm()

        return render(request, 'adjenda/schedule_detail.html', {'agenda': agenda, 'schedules': schedules, 'form': form})

forms.py

from django import forms
from .models import Agenda, Schedule

class AgendaForm(forms.ModelForm):

    class Meta:
        model = Agenda
        fields = '__all__'

    def clean_startTime(self):
        startTime = self.cleaned_data['startTime']
        if Agenda.objects.filter(startTime=startTime).exists():
            raise forms.ValidationError("Time/Day already taken")
        return startTime

Thanks for any help!

Body:
Maybe unique_together is what you're looking for:

class Agenda(models.Model):
    # field definiton

    class Meta:
        unique_together = ("startTime", "endTime", "daySlot")


问:
Referring to a generic type of a generic type in C# XML documentation?
Writing some XML documentation for a predicate helper class. But I can't figure out I can refer to an Expression<Func<T, bool>> without getting a syntax error. Is it even possible? I have tried this:

```<code><see cref="Expression{Func{T, bool}}"/>
</code>```

But I get a red squiggly line under {T, bool}}. This works though:

```<code><see cref="Expression{TDelegate}"/>
</code>```

Anyone have a clue?

Update:

The answer that was given (and I accepted) seemingly did work. But now I have started to get a lot of warnings about stuff not being able to resolve. I have a class called ExpressionBuilder<T> which works with Expression<Func<T, bool>> a lot. So I of course want to refer to that in my XML comments.

I have tried both versions that I know about:

```<code><see cref="Expression<Func<T, Boolean>>"/>
<see cref="Expression{Func{T, Boolean}}"/>
</code>```

But neither work. (And on the last one, ReSharper puts a blue squiggly under {T,Boolean}} I get two warnings under compilation everywhere I have used it which says that:

XML comment on 'blah blah' has cref attribute 'Expression>' that could not be resolved

Type parameter declaration must be an identifier not a type. See also error CS0081.

Have the same issue somewhere I tried to refer to Range<Nullable<DateTime>> (Range<DateTime?> didnt work either. Both with { } and with < >)

Am I not supposed to refer to these kinds of generics?

答:
Don't use an empty see element (<see cref="..." />). Instead, put text inside the see element

```<code><see cref="IEnumerable{T}">IEnumerable</see><<see cref="..."/>>
</code>```

OwnerDisplayName: Svish

Body:
Writing some XML documentation for a predicate helper class. But I can't figure out I can refer to an Expression<Func<T, bool>> without getting a syntax error. Is it even possible? I have tried this:

<see cref="Expression{Func{T, bool}}"/>

But I get a red squiggly line under {T, bool}}. This works though:

<see cref="Expression{TDelegate}"/>

Anyone have a clue?

Update:

The answer that was given (and I accepted) seemingly did work. But now I have started to get a lot of warnings about stuff not being able to resolve. I have a class called ExpressionBuilder<T> which works with Expression<Func<T, bool>> a lot. So I of course want to refer to that in my XML comments.

I have tried both versions that I know about:

<see cref="Expression<Func<T, Boolean>>"/>
<see cref="Expression{Func{T, Boolean}}"/>

But neither work. (And on the last one, ReSharper puts a blue squiggly under {T,Boolean}} I get two warnings under compilation everywhere I have used it which says that:

XML comment on 'blah blah' has cref attribute 'Expression>' that could not be resolved

Type parameter declaration must be an identifier not a type. See also error CS0081.

Have the same issue somewhere I tried to refer to Range<Nullable<DateTime>> (Range<DateTime?> didnt work either. Both with { } and with < >)

Am I not supposed to refer to these kinds of generics?

LastEditorDisplayName: moocha

Body:
Don't use an empty see element (<see cref="..." />). Instead, put text inside the see element

<see cref="IEnumerable{T}">IEnumerable</see>&lt;<see cref="..."/>&gt;

ContentLicense: CC BY-SA 4.0


问:
How to filter objects full of arrays based on the value of its property
I am trying to get a value from an array of objects based on the value of another property.

Sample array of objects:

```<code>objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];
</code>```

I am trying to get "1" based on filtering "2". I do not know the position of "bar: 2" and as the data is changing every day, the objArray may look like this next day:

```<code>objArray = [ { foo: 3, bar: 4}, { foo: 1, bar: 2}, { foo: 5, bar: 6} ];
</code>```

I thought about filtering:

but I am getting nowhere...

答:
You need array.filter without strict equality:

    var objArray = [ { foo: 3, bar: 4}, { foo: 1, bar: 2}, { foo: 5, bar: 6} ];

    var result = objArray.filter(function(e) {
      return e.bar == '2'
    })

    console.log(result)```

Body:
I am trying to get a value from an array of objects based on the value of another property.

Sample array of objects:

objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];

I am trying to get "1" based on filtering "2". I do not know the position of "bar: 2" and as the data is changing every day, the objArray may look like this next day:

objArray = [ { foo: 3, bar: 4}, { foo: 1, bar: 2}, { foo: 5, bar: 6} ];

I thought about filtering:

but I am getting nowhere...


问:
Iterating over a dict made from a .CSV
I have a .CSV file that looks like this:

```<code>NAME            ES  VALUE FILE_LOC                                     NOTES
android_female  HAPPY   25  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_happy_25.obj   Slightly happy
android_female  HAPPY   50  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_happy_50.obj   happy
android_female  HAPPY   75  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_happy_75.obj   Joyful or glee, eyes squinty
android_female  SAD 25  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_sad_25.obj Morose
android_female  SAD 75  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_sad_75.obj Very Sad
android_female  CONFUSED    50  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_confused_50.obj    Bewildered
android_female  SCARED  50  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_scared_50.obj  Frightened
android_female  TIRED   25  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_tired_25.obj   Slightly run down
android_female  TIRED   75  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_tired_75.obj   Very tired
android_female  SURPRISED   50  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_surprised_50.obj   Semi shocked
android_female  EMBARRASSED 50  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_embarrassed_50.obj Reddened cheeks
android_female  KISS    50  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_kiss_50.obj    Kissy face, eyes closed
android_female  MISCHIEVOUS 50  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_mischievous_50.obj Smirking and shifty eyes
 android_female PAIN    25  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_pain_25.obj    Slight pain, grimace
android_female  PAIN    75  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_pain_75.obj    Severe pain, eyes closed
android_female  ANGRY   25  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_angry_25.obj   Upset, brow furrowed
android_female  ANGRY   75  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_angry_75.obj   Very angry, brows down
</code>```

Fairly simple.  To get it from .CSV into a dict, I have the following code:

```<code>layouts_schema_file_name ='C:\\Users\\jason\\Documents\\RAY\\char_es_schemas\\ANIBOT_CHAR_ES_SCHEMA.csv'
full_path_to_file = layouts_schema_file_name
print('============ Importing LAYOUTS schema from: ', full_path_to_file , ' ==============')
openfile = open(full_path_to_file)
reader = csv.DictReader(openfile)

print('Printing Character Emotional States reader file:')
print(reader)

char_es_schema = {}

for group1, records1 in itertools.groupby(reader, key=operator.itemgetter("NAME")):
    char_es_schema[group1] = {}
    for group2, records2 in itertools.groupby(records1, key=operator.itemgetter("ES")):
        char_es_schema[group1][group2] = list(records2)
        #for group3, records3 in itertools.groupby(records2, key=operator.itemgetter("VALUE")):
        #   char_es_schema[group2][group3] = list(records3)
</code>```

This results in the following (probably too complicated) dict, which is intended to store the keys and values in a structured way:

```<code>{'android_female': {'ANGRY': [{'ES': 'ANGRY',
                           'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_angry_25.obj',
                           'NAME': 'android_female',
                           'NOTES': 'Upset, brow furrowed',
                           'VALUE': '25'},
                          {'ES': 'ANGRY',
                           'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_angry_75.obj',
                           'NAME': 'android_female',
                           'NOTES': 'Very angry, brows down',
                           'VALUE': '75'}],
                'CONFUSED': [{'ES': 'CONFUSED',
                              'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_confused_50.obj',
                              'NAME': 'android_female',
                              'NOTES': 'Bewildered',
                              'VALUE': '50'}],
                'EMBARRASSED': [{'ES': 'EMBARRASSED',
                                 'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_embarrassed_50.obj',
                                 'NAME': 'android_female',
                                 'NOTES': 'Reddened cheeks',
                                 'VALUE': '50'}],
                'HAPPY': [{'ES': 'HAPPY',
                           'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_happy_25.obj',
                           'NAME': 'android_female',
                           'NOTES': 'Slightly happy',
                           'VALUE': '25'},
                          {'ES': 'HAPPY',
                           'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_happy_50.obj',
                           'NAME': 'android_female',
                           'NOTES': 'happy',
                           'VALUE': '50'},
                          {'ES': 'HAPPY',
                           'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_happy_75.obj',
                           'NAME': 'android_female',
                           'NOTES': 'Joyful or glee, eyes squinty',
                           'VALUE': '75'}],
                'KISS': [{'ES': 'KISS',
                          'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_kiss_50.obj',
                          'NAME': 'android_female',
                          'NOTES': 'Kissy face, eyes closed',
                          'VALUE': '50'}],
                'MISCHIEVOUS': [{'ES': 'MISCHIEVOUS',
                                 'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_mischievous_50.obj',
                                 'NAME': 'android_female',
                                 'NOTES': 'Smirking and shifty eyes',
                                 'VALUE': '50'}],
                'PAIN': [{'ES': 'PAIN',
                          'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_pain_25.obj',
                          'NAME': 'android_female',
                          'NOTES': 'Slight pain, grimace',
                          'VALUE': '25'},
                         {'ES': 'PAIN',
                          'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_pain_75.obj',
                          'NAME': 'android_female',
                          'NOTES': 'Severe pain, eyes closed',
                          'VALUE': '75'}],
                'SAD': [{'ES': 'SAD',
                         'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_sad_25.obj',
                         'NAME': 'android_female',
                         'NOTES': 'Morose',
                         'VALUE': '25'},
                        {'ES': 'SAD',
                         'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_sad_75.obj',
                         'NAME': 'android_female',
                         'NOTES': 'Very Sad',
                         'VALUE': '75'}],
                'SCARED': [{'ES': 'SCARED',
                            'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_scared_50.obj',
                            'NAME': 'android_female',
                            'NOTES': 'Frightened',
                            'VALUE': '50'}],
                'SURPRISED': [{'ES': 'SURPRISED',
                               'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_surprised_50.obj',
                               'NAME': 'android_female',
                               'NOTES': 'Semi shocked',
                               'VALUE': '50'}],
                'TIRED': [{'ES': 'TIRED',
                           'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_tired_25.obj',
                           'NAME': 'android_female',
                           'NOTES': 'Slightly run down',
                           'VALUE': '25'},
                          {'ES': 'TIRED',
                           'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_tired_75.obj',
                           'NAME': 'android_female',
                           'NOTES': 'Very tired',
                           'VALUE': '75'}]}}
</code>```

I'm trying to iterate over this nested dict in order to match up the NAME and ES levels and the VALUE in the last level (it's actually a list with a dict in it).  The intention is to simple pull the file_loc for use later, using NAME, ES and VALUE to pull it.  It's supposed to be a 3 key concatenated field.

Having a hard time doing this multiple ways.  I suspect my dict is overly complicated, would appreciate any thoughts.

Here is my code to iterate which doesn't work now:

```<code>for actors in char_es_schema.keys():
        if found_it == True:
            print('Found character emotional state...')
            continue
        for emotions in actors:
            for poses in emotions:
                print('Current ES state and value we are searching is: ',char_es_schema[actor_name][curr_es][0]['ES'] ,char_es_schema[actor_name][curr_es][0]['VALUE'])
                if char_es_schema[actor_name][curr_es][0]['VALUE'] == curr_es_level:
                    file_loc = char_es_schema[actor_name][curr_es][0]['FILE_LOC']#!!!!!! what code goes here JMR 12/4
                    print('Found file location for emotional state:', curr_es, curr_es_level, ' - : ', file_loc)
                    found_it = True
            if found_it == True:
               -do some stuff-
</code>```

Any ideas?  I think I made my dict too complicate and hard to iterate over, but would appreciate any ideas.

答:
How 'bout this?

```<code>def select(schema, name, es, value):
    emotionGrp = schema[name][es]
    return [x for x in emotionGrp if x['VALUE']==value];

print(select(data, 'android_female', 'PAIN', '75'))
</code>```

Where data is the data structure you've supplied in your question.

Running this code with your sample data returns:

```<code>[{'NOTES': 'Severe pain, eyes closed', 'VALUE': '75', 'NAME': 'android_female', 'ES': 'PAIN', 'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_pain_75.obj'}]
</code>```

Could be further simplified to just:

```<code>selectedAndroids = [x for x in schema[name][es] if x['VALUE']==value];
</code>```

What's conspicuously missing is any kind of checking for keys which don't exist in the data model. Hm...

```<code>selectedAndroids = [x for x in schema.get(name, {}).get(es, {}) if x.get('VALUE', None)==value]
</code>```

Title: Iterating over a dict made from a .CSV

Body:
I have a .CSV file that looks like this:

NAME            ES  VALUE FILE_LOC                                     NOTES
android_female  HAPPY   25  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_happy_25.obj   Slightly happy
android_female  HAPPY   50  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_happy_50.obj   happy
android_female  HAPPY   75  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_happy_75.obj   Joyful or glee, eyes squinty
android_female  SAD 25  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_sad_25.obj Morose
android_female  SAD 75  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_sad_75.obj Very Sad
android_female  CONFUSED    50  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_confused_50.obj    Bewildered
android_female  SCARED  50  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_scared_50.obj  Frightened
android_female  TIRED   25  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_tired_25.obj   Slightly run down
android_female  TIRED   75  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_tired_75.obj   Very tired
android_female  SURPRISED   50  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_surprised_50.obj   Semi shocked
android_female  EMBARRASSED 50  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_embarrassed_50.obj Reddened cheeks
android_female  KISS    50  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_kiss_50.obj    Kissy face, eyes closed
android_female  MISCHIEVOUS 50  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_mischievous_50.obj Smirking and shifty eyes
 android_female PAIN    25  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_pain_25.obj    Slight pain, grimace
android_female  PAIN    75  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_pain_75.obj    Severe pain, eyes closed
android_female  ANGRY   25  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_angry_25.obj   Upset, brow furrowed
android_female  ANGRY   75  C:\Users\jason\Documents\3Dobjects\poses\androidfemale\androidfemale_angry_75.obj   Very angry, brows down

Fairly simple.  To get it from .CSV into a dict, I have the following code:

layouts_schema_file_name ='C:\\Users\\jason\\Documents\\RAY\\char_es_schemas\\ANIBOT_CHAR_ES_SCHEMA.csv'
full_path_to_file = layouts_schema_file_name
print('============ Importing LAYOUTS schema from: ', full_path_to_file , ' ==============')
openfile = open(full_path_to_file)
reader = csv.DictReader(openfile)

print('Printing Character Emotional States reader file:')
print(reader)

char_es_schema = {}

for group1, records1 in itertools.groupby(reader, key=operator.itemgetter("NAME")):
    char_es_schema[group1] = {}
    for group2, records2 in itertools.groupby(records1, key=operator.itemgetter("ES")):
        char_es_schema[group1][group2] = list(records2)
        #for group3, records3 in itertools.groupby(records2, key=operator.itemgetter("VALUE")):
        #   char_es_schema[group2][group3] = list(records3)

This results in the following (probably too complicated) dict, which is intended to store the keys and values in a structured way:

{'android_female': {'ANGRY': [{'ES': 'ANGRY',
                           'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_angry_25.obj',
                           'NAME': 'android_female',
                           'NOTES': 'Upset, brow furrowed',
                           'VALUE': '25'},
                          {'ES': 'ANGRY',
                           'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_angry_75.obj',
                           'NAME': 'android_female',
                           'NOTES': 'Very angry, brows down',
                           'VALUE': '75'}],
                'CONFUSED': [{'ES': 'CONFUSED',
                              'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_confused_50.obj',
                              'NAME': 'android_female',
                              'NOTES': 'Bewildered',
                              'VALUE': '50'}],
                'EMBARRASSED': [{'ES': 'EMBARRASSED',
                                 'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_embarrassed_50.obj',
                                 'NAME': 'android_female',
                                 'NOTES': 'Reddened cheeks',
                                 'VALUE': '50'}],
                'HAPPY': [{'ES': 'HAPPY',
                           'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_happy_25.obj',
                           'NAME': 'android_female',
                           'NOTES': 'Slightly happy',
                           'VALUE': '25'},
                          {'ES': 'HAPPY',
                           'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_happy_50.obj',
                           'NAME': 'android_female',
                           'NOTES': 'happy',
                           'VALUE': '50'},
                          {'ES': 'HAPPY',
                           'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_happy_75.obj',
                           'NAME': 'android_female',
                           'NOTES': 'Joyful or glee, eyes squinty',
                           'VALUE': '75'}],
                'KISS': [{'ES': 'KISS',
                          'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_kiss_50.obj',
                          'NAME': 'android_female',
                          'NOTES': 'Kissy face, eyes closed',
                          'VALUE': '50'}],
                'MISCHIEVOUS': [{'ES': 'MISCHIEVOUS',
                                 'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_mischievous_50.obj',
                                 'NAME': 'android_female',
                                 'NOTES': 'Smirking and shifty eyes',
                                 'VALUE': '50'}],
                'PAIN': [{'ES': 'PAIN',
                          'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_pain_25.obj',
                          'NAME': 'android_female',
                          'NOTES': 'Slight pain, grimace',
                          'VALUE': '25'},
                         {'ES': 'PAIN',
                          'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_pain_75.obj',
                          'NAME': 'android_female',
                          'NOTES': 'Severe pain, eyes closed',
                          'VALUE': '75'}],
                'SAD': [{'ES': 'SAD',
                         'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_sad_25.obj',
                         'NAME': 'android_female',
                         'NOTES': 'Morose',
                         'VALUE': '25'},
                        {'ES': 'SAD',
                         'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_sad_75.obj',
                         'NAME': 'android_female',
                         'NOTES': 'Very Sad',
                         'VALUE': '75'}],
                'SCARED': [{'ES': 'SCARED',
                            'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_scared_50.obj',
                            'NAME': 'android_female',
                            'NOTES': 'Frightened',
                            'VALUE': '50'}],
                'SURPRISED': [{'ES': 'SURPRISED',
                               'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_surprised_50.obj',
                               'NAME': 'android_female',
                               'NOTES': 'Semi shocked',
                               'VALUE': '50'}],
                'TIRED': [{'ES': 'TIRED',
                           'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_tired_25.obj',
                           'NAME': 'android_female',
                           'NOTES': 'Slightly run down',
                           'VALUE': '25'},
                          {'ES': 'TIRED',
                           'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_tired_75.obj',
                           'NAME': 'android_female',
                           'NOTES': 'Very tired',
                           'VALUE': '75'}]}}

I'm trying to iterate over this nested dict in order to match up the NAME and ES levels and the VALUE in the last level (it's actually a list with a dict in it).  The intention is to simple pull the file_loc for use later, using NAME, ES and VALUE to pull it.  It's supposed to be a 3 key concatenated field.

Having a hard time doing this multiple ways.  I suspect my dict is overly complicated, would appreciate any thoughts.

Here is my code to iterate which doesn't work now:

for actors in char_es_schema.keys():
        if found_it == True:
            print('Found character emotional state...')
            continue
        for emotions in actors:
            for poses in emotions:
                print('Current ES state and value we are searching is: ',char_es_schema[actor_name][curr_es][0]['ES'] ,char_es_schema[actor_name][curr_es][0]['VALUE'])
                if char_es_schema[actor_name][curr_es][0]['VALUE'] == curr_es_level:
                    file_loc = char_es_schema[actor_name][curr_es][0]['FILE_LOC']#!!!!!! what code goes here JMR 12/4
                    print('Found file location for emotional state:', curr_es, curr_es_level, ' - : ', file_loc)
                    found_it = True
            if found_it == True:
               -do some stuff-

Any ideas?  I think I made my dict too complicate and hard to iterate over, but would appreciate any ideas.

Body:
How 'bout this?

def select(schema, name, es, value):
    emotionGrp = schema[name][es]
    return [x for x in emotionGrp if x['VALUE']==value];

print(select(data, 'android_female', 'PAIN', '75'))

Where data is the data structure you've supplied in your question.

Running this code with your sample data returns:

[{'NOTES': 'Severe pain, eyes closed', 'VALUE': '75', 'NAME': 'android_female', 'ES': 'PAIN', 'FILE_LOC': 'C:\\Users\\jason\\Documents\\3Dobjects\\poses\\androidfemale\\androidfemale_pain_75.obj'}]

Could be further simplified to just:

selectedAndroids = [x for x in schema[name][es] if x['VALUE']==value];

What's conspicuously missing is any kind of checking for keys which don't exist in the data model. Hm...

selectedAndroids = [x for x in schema.get(name, {}).get(es, {}) if x.get('VALUE', None)==value]


问:
scrollTo class not working
need your help on scrollTo function, which is not working currently (doesn't do anything on click)

Js:

```<code>$('#Sb').click(function(e) {
  e.preventDefault();
  document.querySelector('.screen_3').scrollIntoView();
});
</code>```

HTML (nav):

```<code><ul>
    <li><a id="Sb" href="">Services</a></li>
    <li><a href="">About Us</a></li>
    <li><a href="">Contact Us</a></li>
    <li><a href="">Our works</a></li>
</ul>
</code>```

HTML (body):

```<code><section id="container" class="screen_3">
      <p class="text_1">Our Services</p>
      ...
</section>
</code>```

nothing happens when you click the link snippet

答:
Use This:

```<code>$('#Sb>a').on('click', function(e) {
    e.preventDefault();
    window.scrollTo(0,document.querySelector(".screen_3").offsetTop);
});
</code>```

if you want to add id in your a tag instead li use code below:

```<code>$('#Sb').on('click', function(e) {
    e.preventDefault();
    window.scrollTo(0,document.querySelector(".screen_3").offsetTop);
});
</code>```

and read this please
Jquery API

jsfiddle

Title: scrollTo class not working

Body:
need your help on scrollTo function, which is not working currently (doesn't do anything on click)

Js:

$('#Sb').click(function(e) {
  e.preventDefault();
  document.querySelector('.screen_3').scrollIntoView();
});

HTML (nav):

Services

About Us

Contact Us

Our works

HTML (body):

Our Services

      ...

nothing happens when you click the link snippet

Body:
Use This:

$('#Sb>a').on('click', function(e) {
    e.preventDefault();
    window.scrollTo(0,document.querySelector(".screen_3").offsetTop);
});

if you want to add id in your a tag instead li use code below:

$('#Sb').on('click', function(e) {
    e.preventDefault();
    window.scrollTo(0,document.querySelector(".screen_3").offsetTop);
});

and read this please
Jquery API

jsfiddle


问:
Use same .gs script for many Spreadsheet files
I need some consultation

I'm working woth Google Sheets. I have a lot of SpreadSheets. And I need an additional functionality for them, I need addition menu that will show me Hello everyone alert. Good I can write a .gs script for that and I did it. But now I need to copy this script to all of my Spreadsheets one by one. And If I want to modify the script - I had to do this in every document :(

Is there any wway to use same .gs script in multiple google document?

答:
You need to publish it as Sheets add-on.

Then you can install in in all of your sheets.  Any updates you publish thereafter will propagate out to the installed instances.


问:
Magmi don't update products
I'm using magmi to import in magento several product. My first import work ok, and all products were created and are visible. Now I need to update some information, like title, description and association beewtween them. I've modified my first import csv, the one that was working in the first time, then I lauch the update via ssh with the command "create" and my products are not updated. I control in frontend, backend and DB. Still old information. Do you have some ideas? </p>

答: I was using an old version of magmi with a new magento update. I've updated the last magmi version and now all work fine! Thank you!</p>

Title: Magmi don't update products


问:
Prevent duplicate posts within foreach

Hello all, I'm currently working on a foreach loop that pulls images from a gallery from the backend of Wordpress. The gallery is working fine and as expected, however, I would like to prevent duplicate photos from appearing.

```<code><?php if () $query->have_posts() ):
  $thumbs = [];
?>
<?php
    foreach( $query->posts as $gallery ):
      $images = get_field('gallery_images', $gallery->ID);
      if( $images ):
        foreach( $images as $image ):
          $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
          $img_id[] = $image['ID'];
          $thumbs[] = $cropped_img;
?>
</code>```

Unrelated HTML to the Problem

```<code><?php endforeach; endif; endforeach; ?>
<?php foreach($thumbs as $thumbnail): ?>
  <div class="gallery__thumb"><img src="<?= $thumbnail; ?>"></div>
<?php endforeach; ?>
</code>```

Here is essentially what I'm trying to work out. I've thought to add two variables for the image ID so that they aren't duplicated in the first block of code. So that first if/foreach state looks like:

```<code><?php if( $images ):
  foreach( $images as $image ):
    $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
    $img_id[] = $image['ID'];
    $do_not_duplicate[] = $image['ID'];
    $thumbs[] = $cropped_img;
?>
</code>```

Followed by the followed foreach for the thumbnails

```<code><?php foreach($thumbs as $thumbnail): ?>
    <?php foreach($img_id as $img): ?>
      <?php if ($img == $do_not_duplicate) : ?>
      //do nothing
      <?php else : ?>
      <div class="gallery__thumb"><img src="<?= $thumbnail; ?>"></div>
      <?php endif; ?>
<?php endforeach; endforeach; ?>
</code>```

The problem I'm experiencing with this is I'm getting 22 images outputed 23 times because there are 22 images being pulled(with 1 duplicate). Essentially I'm trying to accomplish 22 images with no duplicates.

Any insight would be greatly appreciated, thank you in advance.

答:
Based on your code, it should be:

```<code><?php if( $images ):
  foreach( $images as $image ):
    $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
    $img_id[] = $image['ID'];
    $thumbs['url'][] = $cropped_img;
    $thumbs['id'][] = $image['ID']
?>
</code>```

then

```<code><?php foreach($thumbs as $thumbnail): ?>
    <?php if (!in_array($thumbnail['do_not_duplicate'], $img_id)): ?>
      <div class="gallery__thumb"><img src="<?= $thumbnail['url']; ?>"></div>
    <?php endif; ?>
<?php endforeach; ?>
</code>```

Title: Prevent duplicate posts within foreach

Body:
Hello all, I'm currently working on a foreach loop that pulls images from a gallery from the backend of Wordpress. The gallery is working fine and as expected, however, I would like to prevent duplicate photos from appearing.

<?php if () $query->have_posts() ):
  $thumbs = [];
?>
<?php
    foreach( $query->posts as $gallery ):
      $images = get_field('gallery_images', $gallery->ID);
      if( $images ):
        foreach( $images as $image ):
          $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
          $img_id[] = $image['ID'];
          $thumbs[] = $cropped_img;
?>

Unrelated HTML to the Problem

<?php endforeach; endif; endforeach; ?>
<?php foreach($thumbs as $thumbnail): ?>

<img src="<?= $thumbnail; ?>">

<?php endforeach; ?>

Here is essentially what I'm trying to work out. I've thought to add two variables for the image ID so that they aren't duplicated in the first block of code. So that first if/foreach state looks like:

<?php if( $images ):
  foreach( $images as $image ):
    $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
    $img_id[] = $image['ID'];
    $do_not_duplicate[] = $image['ID'];
    $thumbs[] = $cropped_img;
?>

Followed by the followed foreach for the thumbnails

<?php foreach($thumbs as $thumbnail): ?>
    <?php foreach($img_id as $img): ?>
      <?php if ($img == $do_not_duplicate) : ?>
      //do nothing
      <?php else : ?>

<img src="<?= $thumbnail; ?>">

      <?php endif; ?>
<?php endforeach; endforeach; ?>

The problem I'm experiencing with this is I'm getting 22 images outputed 23 times because there are 22 images being pulled(with 1 duplicate). Essentially I'm trying to accomplish 22 images with no duplicates.

Any insight would be greatly appreciated, thank you in advance.

Body:
Based on your code, it should be:

<?php if( $images ):
  foreach( $images as $image ):
    $cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
    $img_id[] = $image['ID'];
    $thumbs['url'][] = $cropped_img;
    $thumbs['id'][] = $image['ID']
?>

then

<?php foreach($thumbs as $thumbnail): ?>
    <?php if (!in_array($thumbnail['do_not_duplicate'], $img_id)): ?>
      <div class="gallery__thumb"><img src="<?= $thumbnail['url']; ?>"></div>
    <?php endif; ?>
<?php endforeach; ?>


问:
How to convert SQL Server datetime to UTC Json format?
I have column which is datetime in SQL Server, how can I get its Json based datetime format: "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"?

By the way, I am using SQL Server 2014

答:
use:

```<code>SELECT FORMAT(GETUTCDATE(),'yyyy-MM-ddTHH:mm:ssZ')
</code>```

Output:
2017-12-06T23:13:34Z

SELECT FORMAT(GETUTCDATE(),'yyyy-MM-ddTHH:mm:ss.fffZ')

Output:
2017-12-07T09:43:03.153Z

Body:
use:

SELECT FORMAT(GETUTCDATE(),'yyyy-MM-ddTHH:mm:ssZ')

Output:
2017-12-06T23:13:34Z

SELECT FORMAT(GETUTCDATE(),'yyyy-MM-ddTHH:mm:ss.fffZ')

Output:
2017-12-07T09:43:03.153Z


问:
What is the alternative for the depricated tref?
I have been reading into to svg spec a bit. I read about the tref-element https://www.w3.org/TR/SVG/single-page.html#text-TRefElement. Most of you will probably know that tref will be / is depricated. That led me to wonder how to do the same thing now. It shouldn't be too hard, but I can't really find anything on the topic. I am also curious about the reasoning behind depricating the tref. But that would just be a 'fun fact'. So in short:

What is the alternative for tref?

Why has tref been depricated?

svg

```<code><svg>
  <defs>
    <text id="ReferencedText">
      Referenced character data
    </text>
  </defs>
  <text x="100" y="200" font-size="45" fill="red" >
    <tref href="#ReferencedText"/>
  </text>
</svg>
</code>```

答:
I had the same situation and upon further reading I tested the following and it worked as tref used to work:</p>

```<code><svg>
    <defs>
        <text id="Text1">The text to be shown</text>
    </defs>

    <use xlink:href="#Text1" x="560" y="850" style="font-family: Arial;fill:#000000; font-size:28px;">
</svg>
</code>```

Body:
I have been reading into to svg spec a bit. I read about the tref-element https://www.w3.org/TR/SVG/single-page.html#text-TRefElement. Most of you will probably know that tref will be / is depricated. That led me to wonder how to do the same thing now. It shouldn't be too hard, but I can't really find anything on the topic. I am also curious about the reasoning behind depricating the tref. But that would just be a 'fun fact'. So in short:

What is the alternative for tref?

Why has tref been depricated?

svg

<svg>
  <defs>
    <text id="ReferencedText">
      Referenced character data
    </text>
  </defs>
  <text x="100" y="200" font-size="45" fill="red" >
    <tref href="#ReferencedText"/>
  </text>
</svg>

Body:
I had the same situation and upon further reading I tested the following and it worked as tref used to work:

<svg>
    <defs>
        <text id="Text1">The text to be shown</text>
    </defs>

    <use xlink:href="#Text1" x="560" y="850" style="font-family: Arial;fill:#000000; font-size:28px;">
</svg>


问:
Regular expression to match all digits of unknown length except the last 4 digits
There is a number with unknown length and the idea is to build a regular expression which matches all digits except last 4 digits.

I have tried a lot to achieve this but no luck yet.

Currently I have this regex: "^(\d*)\d{0}\d{0}\d{0}\d{0}.*$"

Input: 123456789089775

Expected output: XXXXXXXXXXX9775

which I am using as follows(and this doesn't work):

```<code>String accountNumber ="123456789089775";
String pattern = "^(\\d*)\\d{1}\\d{1}\\d{1}\\d{1}.*$";
String result = accountNumber.replaceAll(pattern, "X");
</code>```

Please suggest how I should approach this problem or give me the solution.
In this case my whole point is to negate the regex : "\d{4}$"

答:
Try:

```<code>String pattern = "^(.*)[0-9]{4}$";
</code>```

Addendum after comment:  A refactor to only match full numerics could look like this:

```<code>String pattern = "^([0-9]+)[0-9]{4}$";
</code>```

Body:
There is a number with unknown length and the idea is to build a regular expression which matches all digits except last 4 digits.

I have tried a lot to achieve this but no luck yet.

Currently I have this regex: "^(\d*)\d{0}\d{0}\d{0}\d{0}.*$"

Input: 123456789089775

Expected output: XXXXXXXXXXX9775

which I am using as follows(and this doesn't work):

String accountNumber ="123456789089775";
String pattern = "^(\\d*)\\d{1}\\d{1}\\d{1}\\d{1}.*$";
String result = accountNumber.replaceAll(pattern, "X");

Please suggest how I should approach this problem or give me the solution.
In this case my whole point is to negate the regex : "\d{4}$"

Body:
Try:

String pattern = "^(.*)[0-9]{4}$";

Addendum after comment:  A refactor to only match full numerics could look like this:

String pattern = "^([0-9]+)[0-9]{4}$";