问:
in ASP.NET MVC3 how can I see the request?
I'm using a simple route as

```<code>routes.MapRoute(
    "Default2", // Route name
    "{cliurl}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{cliurl}/{controller}/{action}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);
</code>```

and when I debug the website (VS2010 SP1), I have a breakpoint in my ABook Controller, inside the Index action method witch contains only:

```<code>//
// GET: /ABook/
public ActionResult Index()
{
    if (currentClient == null)
        return RedirectToAction("Empty");

    return View();
}

//
// GET: /Empty/
public ActionResult Empty()
{
    return View();
}
</code>```

The thing is that, when I insert this in the browser:

```<code>http://localhost:14951/client_name/hashed_id
</code>```

I get 3 breaks in that breakpoint.

How can I see what in the world is going on? why 3 times when I just requested 1, what is exactly the browser requesting?

I can only get the Route Parameters and I do get the first correct, but 2nd and 3rd are using the default values, and I tried to navigate through the RequestContext and I can't see anything useful :(

Just want to know if there is a way to really see what's been requested.

答:
In every Controller there exists a property called Request. It is actually defined in System.Web.Mvc.Controller which is the superclass of all controllers. The property returns the acutal Request object as HttpRequestBase and exposes fields like InputStream, Headers, HttpMethod so on and so forth.

As for why you are hitting the index method 3 times, I'm sure that other requests made by the browser, say for example for images and javascript and other existing files, also are handled by your route defined. In short your route defenition is too generic and handles unexpected requests. You can correct this by using Route.IgnoreRoute("Path/to/Existing/Files") or by making your route more specific by adding RouteConstraints. Leave a comment if you want to know how to do that.

Body:
I'm using a simple route as

routes.MapRoute(
    "Default2", // Route name
    "{cliurl}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{cliurl}/{controller}/{action}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

and when I debug the website (VS2010 SP1), I have a breakpoint in my ABook Controller, inside the Index action method witch contains only:

//
// GET: /ABook/
public ActionResult Index()
{
    if (currentClient == null)
        return RedirectToAction("Empty");

    return View();
}

//
// GET: /Empty/
public ActionResult Empty()
{
    return View();
}

The thing is that, when I insert this in the browser:

http://localhost:14951/client_name/hashed_id

I get 3 breaks in that breakpoint.

How can I see what in the world is going on? why 3 times when I just requested 1, what is exactly the browser requesting?

I can only get the Route Parameters and I do get the first correct, but 2nd and 3rd are using the default values, and I tried to navigate through the RequestContext and I can't see anything useful :(

Just want to know if there is a way to really see what's been requested.


来源: stackexchange

问:
How do I POST JSON data with cURL?
I use Ubuntu and installed cURL on it. I want to test my Spring REST application with cURL. I wrote my POST code at the Java side. However, I want to test it with cURL. I am trying to post a JSON data. Example data is like this:

```<code>{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}
</code>```

I use this command:

curl -i \
    -H "Accept: application/json" \
    -H "X-HTTP-Method-Override: PUT" \
    -X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true \
    http://localhost:8080/xx/xxx/xxxx
```
<p>It returns this error:</p>
<pre class="lang-none prettyprint-override"><code>HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT
</code>```

The error description is this:

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().

Tomcat log:
"POST /ui/webapp/conf/clear HTTP/1.1" 415 1051

What is the right format of the cURL command?

This is my Java side PUT code (I have tested GET and DELETE and they work):

```<code>@RequestMapping(method = RequestMethod.PUT)
public Configuration updateConfiguration(HttpServletResponse response, @RequestBody Configuration configuration) { //consider @Valid tag
    configuration.setName("PUT worked");
    //todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return configuration;
}
</code>```

答:
I made a tool called fetcher for this. It can send requests and format curl snippets:

Here's an example:

Example output:

```<code>curl -XGET -H "Accept: application/json" -d "{\"value\":\"30\",\"type\":\"Tip 3\",\"targetModule\":\"Target 3\",\"configurationGroup\":null,\"name\":\"Configuration Deneme 3\",\"description\":null,\"identity\":\"Configuration Deneme 3\",\"version\":0,\"systemId\":3,\"active\":true}" "http://localhost:8080/xx/xxx/xxxx"
</code>```

ContentLicense: CC BY-SA 4.0

Title: How do I POST JSON data with cURL?

Body:
I use Ubuntu and installed cURL on it. I want to test my Spring REST application with cURL. I wrote my POST code at the Java side. However, I want to test it with cURL. I am trying to post a JSON data. Example data is like this:

{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}

I use this command:

curl -i \
    -H "Accept: application/json" \
    -H "X-HTTP-Method-Override: PUT" \
    -X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true \
    http://localhost:8080/xx/xxx/xxxx

It returns this error:

HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT

The error description is this:

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().

Tomcat log:
"POST /ui/webapp/conf/clear HTTP/1.1" 415 1051

What is the right format of the cURL command?

This is my Java side PUT code (I have tested GET and DELETE and they work):

@RequestMapping(method = RequestMethod.PUT)
public Configuration updateConfiguration(HttpServletResponse response, @RequestBody Configuration configuration) { //consider @Valid tag
    configuration.setName("PUT worked");
    //todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return configuration;
}

Body:
I made a tool called fetcher for this. It can send requests and format curl snippets:

Here's an example:

Example output:

curl -XGET -H "Accept: application/json" -d "{\"value\":\"30\",\"type\":\"Tip 3\",\"targetModule\":\"Target 3\",\"configurationGroup\":null,\"name\":\"Configuration Deneme 3\",\"description\":null,\"identity\":\"Configuration Deneme 3\",\"version\":0,\"systemId\":3,\"active\":true}" "http://localhost:8080/xx/xxx/xxxx"


问:
Uses of T extends U?
Lately I encountered a method defined similar to this and I don't exactly understand its usage:

```<code>public static <T, U extends T> T foo(U u) { ... }
</code>```

A sample use could be like this:

```<code>// Baz is just the containing class of foo()
Number n = Baz.foo(1);
</code>```

Where T is inferred to Number and U (probably) to Integer. But I can't wrap my head around when this is superior to e.g. this method definition:

```<code>public static <T> T bar(T t) { ... }
</code>```

If I call it like this:

```<code>Number n = Baz.bar(2);
</code>```

The code still works. T is inferred to either Number or Integer (Don't know if the argument type, in this example Integer is preferred over the call site return type Number)

I've read these questions: 1, 2 but I still don't know if the first method with 2 parameters has any advantage over the second method with only one generic.

答:
I think that, in fact, this only makes sense when the type parameter of the method appears as the type parameter of a parameterized type that is part of the method signature.

(At least, I couldn't quickly come up with an example where it would really makes sense otherwise)

This is also the case in the question that you linked to, where the method type parameters are used as type parameters in the AutoBean class.

A small update:

Based on the discussion in the question and other answers, the core of this question was likely a misinterpretation of the way of how the type parameters are used. As such, this question could be considered as a duplicate of Meaning of <T, U extends T> in java function declaration , but hopefully someone will consider this answer helpful nevertheless.

In the end, the reason for using the pattern of <T, U extends T> can be seen in the inheritance relationships of parameterized types, which in detail may be fairly complicated. As an example, to illustrate the most relevant point: A List<Integer> is not a subtype of a List<Number>.

An example showing where it can make a difference is below. It contains a "trivial" implementation that always works (and does not make sense, as far as I can tell). But the type bound becomes relevant when the type parameters T and U are also the type parameters of the method parameters and return type. Whith the T extends U, you can return a type that has a supertype as the type parameter. Otherwise, you couldn't, as shown with the example that // Does not work:

```<code>import java.util.ArrayList;
import java.util.List;

public class SupertypeMethod {
    public static void main(String[] args) {

        Integer integer = null;
        Number number = null;

        List<Number> numberList = null;
        List<Integer> integerList = null;

        // Always works:
        integer = fooTrivial(integer);
        number = fooTrivial(number);
        number = fooTrivial(integer);

        numberList = withList(numberList);
        //numberList = withList(integerList); // Does not work

        // Both work:
        numberList = withListAndBound(numberList);
        numberList = withListAndBound(integerList);
    }

    public static <T, U extends T> T fooTrivial(U u) {
        return u;
    }

    public static <T, U extends T> List<T> withListAndBound(List<U> u) {
        List<T> result = new ArrayList<T>();
        result.add(u.get(0));
        return result;
    }

    public static <T> List<T> withList(List<T> u) {
        List<T> result = new ArrayList<T>();
        result.add(u.get(0));
        return result;
    }

}
</code>```

(This looks a bit contrived, of course, but I think that one could imagine scenarios where this actually makes sense)

Title: Uses of T extends U?

Body:
Lately I encountered a method defined similar to this and I don't exactly understand its usage:

public static <T, U extends T> T foo(U u) { ... }

A sample use could be like this:

// Baz is just the containing class of foo()
Number n = Baz.foo(1);

Where T is inferred to Number and U (probably) to Integer. But I can't wrap my head around when this is superior to e.g. this method definition:

public static <T> T bar(T t) { ... }

If I call it like this:

Number n = Baz.bar(2);

The code still works. T is inferred to either Number or Integer (Don't know if the argument type, in this example Integer is preferred over the call site return type Number)

I've read these questions: 1, 2 but I still don't know if the first method with 2 parameters has any advantage over the second method with only one generic.

Body:
I think that, in fact, this only makes sense when the type parameter of the method appears as the type parameter of a parameterized type that is part of the method signature.

(At least, I couldn't quickly come up with an example where it would really makes sense otherwise)

This is also the case in the question that you linked to, where the method type parameters are used as type parameters in the AutoBean class.

A small update:

Based on the discussion in the question and other answers, the core of this question was likely a misinterpretation of the way of how the type parameters are used. As such, this question could be considered as a duplicate of Meaning of <T, U extends T> in java function declaration , but hopefully someone will consider this answer helpful nevertheless.

In the end, the reason for using the pattern of <T, U extends T> can be seen in the inheritance relationships of parameterized types, which in detail may be fairly complicated. As an example, to illustrate the most relevant point: A List<Integer> is not a subtype of a List<Number>.

An example showing where it can make a difference is below. It contains a "trivial" implementation that always works (and does not make sense, as far as I can tell). But the type bound becomes relevant when the type parameters T and U are also the type parameters of the method parameters and return type. Whith the T extends U, you can return a type that has a supertype as the type parameter. Otherwise, you couldn't, as shown with the example that // Does not work:

import java.util.ArrayList;
import java.util.List;

public class SupertypeMethod {
    public static void main(String[] args) {

        Integer integer = null;
        Number number = null;

        List<Number> numberList = null;
        List<Integer> integerList = null;

        // Always works:
        integer = fooTrivial(integer);
        number = fooTrivial(number);
        number = fooTrivial(integer);

        numberList = withList(numberList);
        //numberList = withList(integerList); // Does not work

        // Both work:
        numberList = withListAndBound(numberList);
        numberList = withListAndBound(integerList);
    }

    public static <T, U extends T> T fooTrivial(U u) {
        return u;
    }

    public static <T, U extends T> List<T> withListAndBound(List<U> u) {
        List<T> result = new ArrayList<T>();
        result.add(u.get(0));
        return result;
    }

    public static <T> List<T> withList(List<T> u) {
        List<T> result = new ArrayList<T>();
        result.add(u.get(0));
        return result;
    }

}

(This looks a bit contrived, of course, but I think that one could imagine scenarios where this actually makes sense)


问:
R: Looping over two variables with RDCOMClient
I have a data frame of names and mails, and I would i like to create a loop where R sends a mail to all of these people but with their respective names using the RDCOMClient library.
The data frame is

df <- data.frame("Name" = c("Name1", "Name2"), "Mail" = c("mail1@mail.com", "mail2@mail.com"))
```

<p>As I have just used Python in an exam project, I created loops several times with mulitple variables, such as:</p>

<pre class="lang-py prettyprint-override"><code>for i,j in zip(df[1], df[2])
</code>```

My code would ideally be something like

for (mail in df$Mail, name in df$Name) {

  outApp <- COMCreate("Outlook.Application")
  outMail = outApp$CreateItem(0)

  outMail[["To"]] = mail
  outMail[["subject"]] = "Subject"
  outMail[["body"]] = paste(" Dear", name, "\n \n bla bla bla.")

  outMail$Send()

  Sys.sleep(0.5)

  if (mail == df$Mail[-1]) cat("Done!")
}
```

This, however, gives an error.

The reason I would like to use a loop is for two reasons:

I would like R to make a pause before starting the next iteration (I don't know if this is really necessary but if my data frame has over a hundred mails it would propably be better - I could be wrong here).

I would like R to print the message "Done!" when it is done.

If you have other suggestions (I have seen several recommendations on the lapply, sapply, etc. packages) they are very welcom!

I hope there's someone out there who knows just what to do.

Thanks in advance,

Emil

答:
I cannot reproduce your question cause I am not on windows but here is an example using the package mailR.

```<code>library(mailR)
library(purrr)
df <- tibble("Name" = c("Name1", "Name2"), "Mail" = c("mail1@mail.com", "mail2@mail.com"))

mail_fun <- function(name, mail){
send.mail(from = "sender@gmail.com",
          to = mail,
          subject = "Subject of the email",
          body = paste(" Dear", name, "\n \n bla bla bla."),
          smtp = list(host.name = "aspmx.l.google.com", port = 25),
          authenticate = FALSE,
          send = TRUE)

  Sys.sleep(0.5)

  print("Done!")

}

mail_fun("filip", "filip.wastberg@ferrologic.se")

map2(df$Name, df$Mail, ~mail_fun(name = .x, mail = .y))
</code>```

This should get you an overall idea how to put your code in a function and then use purrr to iterate over a data.frame.

Body:
I have a data frame of names and mails, and I would i like to create a loop where R sends a mail to all of these people but with their respective names using the RDCOMClient library.
The data frame is

df <- data.frame("Name" = c("Name1", "Name2"), "Mail" = c("mail1@mail.com", "mail2@mail.com"))

As I have just used Python in an exam project, I created loops several times with mulitple variables, such as:

for i,j in zip(df[1], df[2])

My code would ideally be something like

for (mail in df$Mail, name in df$Name) {

  outApp <- COMCreate("Outlook.Application")
  outMail = outApp$CreateItem(0)

  outMail[["To"]] = mail
  outMail[["subject"]] = "Subject"
  outMail[["body"]] = paste(" Dear", name, "\n \n bla bla bla.")

  outMail$Send()

  Sys.sleep(0.5)

  if (mail == df$Mail[-1]) cat("Done!")
}

This, however, gives an error.

The reason I would like to use a loop is for two reasons:

I would like R to make a pause before starting the next iteration (I don't know if this is really necessary but if my data frame has over a hundred mails it would propably be better - I could be wrong here).

I would like R to print the message "Done!" when it is done.

If you have other suggestions (I have seen several recommendations on the lapply, sapply, etc. packages) they are very welcom!

I hope there's someone out there who knows just what to do.

Thanks in advance,

Emil

Body:
I cannot reproduce your question cause I am not on windows but here is an example using the package mailR.

library(mailR)
library(purrr)
df <- tibble("Name" = c("Name1", "Name2"), "Mail" = c("mail1@mail.com", "mail2@mail.com"))

mail_fun <- function(name, mail){
send.mail(from = "sender@gmail.com",
          to = mail,
          subject = "Subject of the email",
          body = paste(" Dear", name, "\n \n bla bla bla."),
          smtp = list(host.name = "aspmx.l.google.com", port = 25),
          authenticate = FALSE,
          send = TRUE)

  Sys.sleep(0.5)

  print("Done!")

}

mail_fun("filip", "filip.wastberg@ferrologic.se")

map2(df$Name, df$Mail, ~mail_fun(name = .x, mail = .y))

This should get you an overall idea how to put your code in a function and then use purrr to iterate over a data.frame.


问:
Getting Data from server using rest Api how to set the Data in a Text in react native
I am getting the data from server successfully i am not under standing how to set that data in a Text tag in React native here is my code please help.

```<code> state = {
    data: []
  };

  componentWillMount() {
    this.fetchFreelancerData();
  }
  fetchFreelancerData = async () => {
    const { params } = this.props.navigation.state;
    const response = await fetch(
      BaseUrl + "listing/get_freelancers?listing_type=single&profile_id=" + params.profile_id
    );
    const json = await response.json();
    console.log(json[0].name);
    this.setState({ fetchFreelancer: json });
  };
</code>```

Here i am getting the response in json const successfully. i have also console the log as well and terminal is showing the name properly.But i am not understanding how to display the name in the Text tag.

this line  console.log(json[0].name); is getting the name properly.

```<code><View style={styles.viewStyle}>
                        <Text style = {styles.nameStyle}>

                        </Text>
</View>
</code>```

I have to set the name in the text as shown up here.

this is the response i am getting form server.

```<code>[
  Object {
    "_address": "",
    "_awards": Array [],
    "_educations": Array [],
    "_english_level": "",
    "_experience": Array [],
    "_featured_timestamp": "wt-featured",
    "_gender": "male",
    "_is_verified": "no",
    "_latitude": "",
    "_longitude": "",
    "_perhour_rate": "$125.00",
    "_projects": Array [],
    "_tag_line": "The Future Of Memory",
    "badge": Object {
      "badget_color": "#e67e22",
      "badget_url": "https://amentotech.com/projects/api_workreap/wp-content/uploads/2019/03/featured.png",
    },
    "banner_img": "https://amentotech.com/projects/api_workreap/wp-content/themes/workreap/images/frbanner-350x172.jpg",
    "cancelled_jobs": 0,
    "completed_jobs": 1,
    "content": "",
    "favorit": "",
    "freelancer_link": "https://amentotech.com/projects/api_workreap/freelancer/wezalono-alone/",
    "location": Object {
      "_country": "Turkey",
      "flag": "https://amentotech.com/projects/api_workreap/wp-content/uploads/2019/03/img-01-4.png",
    },
    "member_since": "April 13, 2019",
    "name": "wezalono Alone",
    "ongoning_jobs": 0,
    "profile_id": 604,
    "profile_img": "https://amentotech.com/projects/api_workreap/wp-content/uploads/2019/03/29-1-100x100.jpg",
    "rating_filter": "5",
    "reviews": Array [
      Object {
        "_is_verified": "no",
        "employer_image": "https://amentotech.com/projects/api_workreap/wp-content/uploads/2019/04/img-01__2_-2.jpg",
        "employer_name": "pozev Jon",
        "level_sign": 1,
        "level_title": "Basic Level",
        "post_date": "April 13, 2019",
        "project_location": "australia",
        "project_rating": "5.00",
        "project_title": "Ecology Professor",
        "review_content": "Excepteur sint occaecat cupidatat non proident, saeunt in culpa qui officia deserunt mollit anim laborum. ",
      },
    ],
    "skills": Array [],
    "total_earnings": "$0.00",
    "user_id": 63,
    "wt_average_rating": "5",
    "wt_total_percentage": "25",
    "wt_total_rating": "1",
  },
]
</code>```

答:
try this</p>

```<code>{this.state.fetchFreelancer &&
<Text style = {styles.nameStyle}>{this.state.fetchFreelancer[0].name} .
</Text>}
</code>```

Body:
I am getting the data from server successfully i am not under standing how to set that data in a Text tag in React native here is my code please help.

 state = {
    data: []
  };

  componentWillMount() {
    this.fetchFreelancerData();
  }
  fetchFreelancerData = async () => {
    const { params } = this.props.navigation.state;
    const response = await fetch(
      BaseUrl + "listing/get_freelancers?listing_type=single&profile_id=" + params.profile_id
    );
    const json = await response.json();
    console.log(json[0].name);
    this.setState({ fetchFreelancer: json });
  };

Here i am getting the response in json const successfully. i have also console the log as well and terminal is showing the name properly.But i am not understanding how to display the name in the Text tag.

this line  console.log(json[0].name); is getting the name properly.

<View style={styles.viewStyle}>
                        <Text style = {styles.nameStyle}>

                        </Text>
</View>

I have to set the name in the text as shown up here.

this is the response i am getting form server.

[
  Object {
    "_address": "",
    "_awards": Array [],
    "_educations": Array [],
    "_english_level": "",
    "_experience": Array [],
    "_featured_timestamp": "wt-featured",
    "_gender": "male",
    "_is_verified": "no",
    "_latitude": "",
    "_longitude": "",
    "_perhour_rate": "$125.00",
    "_projects": Array [],
    "_tag_line": "The Future Of Memory",
    "badge": Object {
      "badget_color": "#e67e22",
      "badget_url": "https://amentotech.com/projects/api_workreap/wp-content/uploads/2019/03/featured.png",
    },
    "banner_img": "https://amentotech.com/projects/api_workreap/wp-content/themes/workreap/images/frbanner-350x172.jpg",
    "cancelled_jobs": 0,
    "completed_jobs": 1,
    "content": "",
    "favorit": "",
    "freelancer_link": "https://amentotech.com/projects/api_workreap/freelancer/wezalono-alone/",
    "location": Object {
      "_country": "Turkey",
      "flag": "https://amentotech.com/projects/api_workreap/wp-content/uploads/2019/03/img-01-4.png",
    },
    "member_since": "April 13, 2019",
    "name": "wezalono Alone",
    "ongoning_jobs": 0,
    "profile_id": 604,
    "profile_img": "https://amentotech.com/projects/api_workreap/wp-content/uploads/2019/03/29-1-100x100.jpg",
    "rating_filter": "5",
    "reviews": Array [
      Object {
        "_is_verified": "no",
        "employer_image": "https://amentotech.com/projects/api_workreap/wp-content/uploads/2019/04/img-01__2_-2.jpg",
        "employer_name": "pozev Jon",
        "level_sign": 1,
        "level_title": "Basic Level",
        "post_date": "April 13, 2019",
        "project_location": "australia",
        "project_rating": "5.00",
        "project_title": "Ecology Professor",
        "review_content": "Excepteur sint occaecat cupidatat non proident, saeunt in culpa qui officia deserunt mollit anim laborum. ",
      },
    ],
    "skills": Array [],
    "total_earnings": "$0.00",
    "user_id": 63,
    "wt_average_rating": "5",
    "wt_total_percentage": "25",
    "wt_total_rating": "1",
  },
]

Body:
try this

{this.state.fetchFreelancer &&
<Text style = {styles.nameStyle}>{this.state.fetchFreelancer[0].name} .
</Text>}


问:
Grouping Elements with Muenchian Method
I am trying to group all the same AsstTp together, according to the first element in their node. So all Scty elements go under one AsstTp element and all Csh elements go under another AsstTp element. As below:

```<code><RpTrad>
<AsstTp>
  <Scty>
    <Id>
      <Id>GB00B3KJDQ49</Id>
      <ClssfctnTp>DBADGC</ClssfctnTp>
      <QtyOrNmnlVal>
        <NmnlVal Ccy="EUR">1000000</NmnlVal>
      </QtyOrNmnlVal>
    </Id>
  </Scty>
</AsstTp>
<AsstTp>
  <Scty>
    <Id>
      <Id>GB00B3KJDP50</Id>
      <ClssfctnTp>DBADGC</ClssfctnTp>
      <QtyOrNmnlVal>
        <NmnlVal Ccy="GBP">1100000</NmnlVal>
      </QtyOrNmnlVal>
    </Id>
  </Scty>
</AsstTp>
<AsstTp>
  <Scty>
    <Id>
      <Id>GB00B3KJDR51</Id>
      <ClssfctnTp>DBADGC</ClssfctnTp>
      <QtyOrNmnlVal>
        <NmnlVal Ccy="CHF">1200000</NmnlVal>
      </QtyOrNmnlVal>
    </Id>
  </Scty>
</AsstTp>
<AsstTp>
  <Csh>
    <Id>
      <Id>US1234567890</Id>
      <ClssfctnTp>EABCDE</ClssfctnTp>
      <QtyOrNmnlVal>
        <Qty>10000</Qty>
      </QtyOrNmnlVal>
    </Id>
  </Csh>
</AsstTp>
</RpTrad>
</code>```

Should become...

```<code><RpTrad>
<AsstTp>
  <Scty>
    <Id>
      <Id>GB00B3KJDQ49</Id>
      <ClssfctnTp>DBADGC</ClssfctnTp>
      <QtyOrNmnlVal>
        <NmnlVal Ccy="EUR">1000000</NmnlVal>
      </QtyOrNmnlVal>
    </Id>
  </Scty>
  <Scty>
    <Id>
      <Id>GB00B3KJDP50</Id>
      <ClssfctnTp>DBADGC</ClssfctnTp>
      <QtyOrNmnlVal>
        <NmnlVal Ccy="GBP">1100000</NmnlVal>
      </QtyOrNmnlVal>
    </Id>
  </Scty>
  <Scty>
    <Id>
      <Id>GB00B3KJDR51</Id>
      <ClssfctnTp>DBADGC</ClssfctnTp>
      <QtyOrNmnlVal>
        <NmnlVal Ccy="CHF">1200000</NmnlVal>
      </QtyOrNmnlVal>
    </Id>
  </Scty>
</AsstTp>
<AsstTp>
  <Csh>
    <Id>
      <Id>US1234567890</Id>
      <ClssfctnTp>EABCDE</ClssfctnTp>
      <QtyOrNmnlVal>
        <Qty>10000</Qty>
      </QtyOrNmnlVal>
    </Id>
  </Csh>
</AsstTp>
</RpTrad>
</code>```

I am currently trying to use the following XSLT, but it seems to just repeat what I have 4 times:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ext="http://exslt.org/common">

<xsl:key name="Coll-by-AsstTp" match="AsstTp" use="local-name()" />
<xsl:template match="RpTrad">
    <xsl:for-each select="AsstTp[count(. | key('Coll-by-AsstTp', local-name())[1]) = 1]">
        <xsl:for-each select="key('Coll-by-AsstTp', local-name())">
            <xsl:copy-of select="/node()" />
        </xsl:for-each>
    </xsl:for-each>
</xsl:template>
</code>```

So I believe there is something wrong with creating my key and using the local-name() function not picking up the correct element value it needs to. Thus causing the for loop to run to many times and not going the level deeper to only copy the inner node of each AsstTp.

Thanks in advance,
Saul

答:
You want to group AsstTp elements by the name of their child element - so your key should be defined as:

```<code><xsl:key name="asstTp-by-child" match="AsstTp" use="local-name(*)" />
</code>```

Then:

XSLT 1.0

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

<xsl:key name="asstTp-by-child" match="AsstTp" use="local-name(*)" />

<xsl:template match="/RpTrad">
    <xsl:copy>
        <xsl:for-each select="AsstTp[count(. | key('asstTp-by-child', local-name(*))[1]) = 1]">
            <xsl:copy>
                <xsl:copy-of select="key('asstTp-by-child', local-name(*))/*"/>
            </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

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

will return the result you want.

Note:

The instruction:

```<code><xsl:copy-of select="/node()" />
</code>```

will copy the entire XML document, starting at the root node, regardless of the current context.

Title: Grouping Elements with Muenchian Method

Body:
I am trying to group all the same AsstTp together, according to the first element in their node. So all Scty elements go under one AsstTp element and all Csh elements go under another AsstTp element. As below:

<RpTrad>
<AsstTp>
  <Scty>
    <Id>
      <Id>GB00B3KJDQ49</Id>
      <ClssfctnTp>DBADGC</ClssfctnTp>
      <QtyOrNmnlVal>
        <NmnlVal Ccy="EUR">1000000</NmnlVal>
      </QtyOrNmnlVal>
    </Id>
  </Scty>
</AsstTp>
<AsstTp>
  <Scty>
    <Id>
      <Id>GB00B3KJDP50</Id>
      <ClssfctnTp>DBADGC</ClssfctnTp>
      <QtyOrNmnlVal>
        <NmnlVal Ccy="GBP">1100000</NmnlVal>
      </QtyOrNmnlVal>
    </Id>
  </Scty>
</AsstTp>
<AsstTp>
  <Scty>
    <Id>
      <Id>GB00B3KJDR51</Id>
      <ClssfctnTp>DBADGC</ClssfctnTp>
      <QtyOrNmnlVal>
        <NmnlVal Ccy="CHF">1200000</NmnlVal>
      </QtyOrNmnlVal>
    </Id>
  </Scty>
</AsstTp>
<AsstTp>
  <Csh>
    <Id>
      <Id>US1234567890</Id>
      <ClssfctnTp>EABCDE</ClssfctnTp>
      <QtyOrNmnlVal>
        <Qty>10000</Qty>
      </QtyOrNmnlVal>
    </Id>
  </Csh>
</AsstTp>
</RpTrad>

Should become...

<RpTrad>
<AsstTp>
  <Scty>
    <Id>
      <Id>GB00B3KJDQ49</Id>
      <ClssfctnTp>DBADGC</ClssfctnTp>
      <QtyOrNmnlVal>
        <NmnlVal Ccy="EUR">1000000</NmnlVal>
      </QtyOrNmnlVal>
    </Id>
  </Scty>
  <Scty>
    <Id>
      <Id>GB00B3KJDP50</Id>
      <ClssfctnTp>DBADGC</ClssfctnTp>
      <QtyOrNmnlVal>
        <NmnlVal Ccy="GBP">1100000</NmnlVal>
      </QtyOrNmnlVal>
    </Id>
  </Scty>
  <Scty>
    <Id>
      <Id>GB00B3KJDR51</Id>
      <ClssfctnTp>DBADGC</ClssfctnTp>
      <QtyOrNmnlVal>
        <NmnlVal Ccy="CHF">1200000</NmnlVal>
      </QtyOrNmnlVal>
    </Id>
  </Scty>
</AsstTp>
<AsstTp>
  <Csh>
    <Id>
      <Id>US1234567890</Id>
      <ClssfctnTp>EABCDE</ClssfctnTp>
      <QtyOrNmnlVal>
        <Qty>10000</Qty>
      </QtyOrNmnlVal>
    </Id>
  </Csh>
</AsstTp>
</RpTrad>

I am currently trying to use the following XSLT, but it seems to just repeat what I have 4 times:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ext="http://exslt.org/common">

<xsl:key name="Coll-by-AsstTp" match="AsstTp" use="local-name()" />
<xsl:template match="RpTrad">
    <xsl:for-each select="AsstTp[count(. | key('Coll-by-AsstTp', local-name())[1]) = 1]">
        <xsl:for-each select="key('Coll-by-AsstTp', local-name())">
            <xsl:copy-of select="/node()" />
        </xsl:for-each>
    </xsl:for-each>
</xsl:template>

So I believe there is something wrong with creating my key and using the local-name() function not picking up the correct element value it needs to. Thus causing the for loop to run to many times and not going the level deeper to only copy the inner node of each AsstTp.

Thanks in advance,
Saul

Body:
You want to group AsstTp elements by the name of their child element - so your key should be defined as:

<xsl:key name="asstTp-by-child" match="AsstTp" use="local-name(*)" />

Then:

XSLT 1.0

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

<xsl:key name="asstTp-by-child" match="AsstTp" use="local-name(*)" />

<xsl:template match="/RpTrad">
    <xsl:copy>
        <xsl:for-each select="AsstTp[count(. | key('asstTp-by-child', local-name(*))[1]) = 1]">
            <xsl:copy>
                <xsl:copy-of select="key('asstTp-by-child', local-name(*))/*"/>
            </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

will return the result you want.

Note:

The instruction:

<xsl:copy-of select="/node()" />

will copy the entire XML document, starting at the root node, regardless of the current context.


问:
Splitting scalac plugin into multiple files
I'd like to split my scalac plugin into multiple files. This sounds easy but I haven't managed to pull it off due to path-dependent type issues stemming from the import global._ line.

Here's Lex Spoon's sample plugin:

```<code>package localhost

import scala.tools.nsc
import nsc.Global
import nsc.Phase
import nsc.plugins.Plugin
import nsc.plugins.PluginComponent

class DivByZero(val global: Global) extends Plugin {
  import global._

  val name = "divbyzero"
  val description = "checks for division by zero"
  val components = List[PluginComponent](Component)

  private object Component extends PluginComponent {
    val global: DivByZero.this.global.type = DivByZero.this.global
    val runsAfter = "refchecks"
    // Using the Scala Compiler 2.8.x the runsAfter should be written as below
    // val runsAfter = List[String]("refchecks");
    val phaseName = DivByZero.this.name
    def newPhase(_prev: Phase) = new DivByZeroPhase(_prev)

    class DivByZeroPhase(prev: Phase) extends StdPhase(prev) {
      override def name = DivByZero.this.name
      def apply(unit: CompilationUnit) {
        for ( tree @ Apply(Select(rcvr, nme.DIV), List(Literal(Constant(0)))) <- unit.body;
             if rcvr.tpe <:< definitions.IntClass.tpe)
          {
            unit.error(tree.pos, "definitely division by zero")
          }
      }
    }
  }
}
</code>```

How can I put Component and DivByZeroPhase in their own files without having the import global._ in scope?

答:
In the Scala Refactoring library, I solved it by having a trait CompilerAccess:

```<code>trait CompilerAccess {
  val global: tools.nsc.Global
}
</code>```

Now all the other traits that need to access global just declare CompilerAccess as a dependency:

```<code>trait TreeTraverser {
  this: CompilerAccess =>
  import global._

  ...
}
</code>```

and then there's a class that mixes in all these traits and provides an instance of global:

```<code>trait SomeRefactoring extends TreeTraverser with OtherTrait with MoreTraits {
  val global = //wherever you get your global from
}
</code>```

This scheme worked quite well for me.

ContentLicense: CC BY-SA 3.0

Body:
I'd like to split my scalac plugin into multiple files. This sounds easy but I haven't managed to pull it off due to path-dependent type issues stemming from the import global._ line.

Here's Lex Spoon's sample plugin:

package localhost

import scala.tools.nsc
import nsc.Global
import nsc.Phase
import nsc.plugins.Plugin
import nsc.plugins.PluginComponent

class DivByZero(val global: Global) extends Plugin {
  import global._

  val name = "divbyzero"
  val description = "checks for division by zero"
  val components = List[PluginComponent](Component)

  private object Component extends PluginComponent {
    val global: DivByZero.this.global.type = DivByZero.this.global
    val runsAfter = "refchecks"
    // Using the Scala Compiler 2.8.x the runsAfter should be written as below
    // val runsAfter = List[String]("refchecks");
    val phaseName = DivByZero.this.name
    def newPhase(_prev: Phase) = new DivByZeroPhase(_prev)

    class DivByZeroPhase(prev: Phase) extends StdPhase(prev) {
      override def name = DivByZero.this.name
      def apply(unit: CompilationUnit) {
        for ( tree @ Apply(Select(rcvr, nme.DIV), List(Literal(Constant(0)))) <- unit.body;
             if rcvr.tpe <:< definitions.IntClass.tpe)
          {
            unit.error(tree.pos, "definitely division by zero")
          }
      }
    }
  }
}

How can I put Component and DivByZeroPhase in their own files without having the import global._ in scope?

Body:
In the Scala Refactoring library, I solved it by having a trait CompilerAccess:

trait CompilerAccess {
  val global: tools.nsc.Global
}

Now all the other traits that need to access global just declare CompilerAccess as a dependency:

trait TreeTraverser {
  this: CompilerAccess =>
  import global._

  ...
}

and then there's a class that mixes in all these traits and provides an instance of global:

trait SomeRefactoring extends TreeTraverser with OtherTrait with MoreTraits {
  val global = //wherever you get your global from
}

This scheme worked quite well for me.


问:
Position imageView between two views and dynamically resize it to fit?
I have a simple layout with two buttons and a image view contained in a ConstraintLayout. The image view shows a vector graphic and is position between the two buttons horizontally.

```<code>____________
| Button    |
------------
____________
| ImageView |
------------
____________
| Button    |
------------
</code>```

The problem is that I cant seem to figure out how to properly constrain the image view vertically between the two buttons.

As long as I have layout_width and layout_height for the image view set to wrap_content the result will vary depending on the aspect ratio of the device display. I could set hardcoded height and width values but that also seems like a bad idea.

Isnt there some way to dynamically resize the ImageView based on the constraints?

```<code><ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/image"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/buttonTop"
    app:layout_constraintBottom_toTopOf="@id/buttonBottom"/>
</code>```

This works on tall aspect ratio devices but on small ones the bottom and/or top buttons overlap the imageView.

答:
You should set the ImageView layout size to match_constraint.
Just set the layout_width and layout_height to 0dp. In this way the layout size will be as big as the set constraints allows it to be.

```<code><ImageView
    android:id="@+id/imageView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:src="@drawable/image"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/buttonTop"
    app:layout_constraintBottom_toTopOf="@id/buttonBottom"/>
</code>```

Body:
I have a simple layout with two buttons and a image view contained in a ConstraintLayout. The image view shows a vector graphic and is position between the two buttons horizontally.

____________
| Button    |
------------
____________
| ImageView |
------------
____________
| Button    |
------------

The problem is that I cant seem to figure out how to properly constrain the image view vertically between the two buttons.

As long as I have layout_width and layout_height for the image view set to wrap_content the result will vary depending on the aspect ratio of the device display. I could set hardcoded height and width values but that also seems like a bad idea.

Isnt there some way to dynamically resize the ImageView based on the constraints?

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/image"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/buttonTop"
    app:layout_constraintBottom_toTopOf="@id/buttonBottom"/>

This works on tall aspect ratio devices but on small ones the bottom and/or top buttons overlap the imageView.

Body:
You should set the ImageView layout size to match_constraint.
Just set the layout_width and layout_height to 0dp. In this way the layout size will be as big as the set constraints allows it to be.

<ImageView
    android:id="@+id/imageView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:src="@drawable/image"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/buttonTop"
    app:layout_constraintBottom_toTopOf="@id/buttonBottom"/>


问:
jQuery How to change class for each table data row?
I have table, with data, and i need for td:eq(4) change class, and box for baghround.

I have this code:

```<code> $('tr').each(function () {
        var rowCol = $(this);
        rowCol.find('td:eq(4)').each(function () {
            var rowValue = parseFloat($(this).text());
            console.log(rowValue === 0)
            if (rowValue > 1) {
                $('.defects').addClass('def').removeClass('defects');
            } else {
                $('.def').addClass('defects').removeClass('def');
            }
        });
    });

.defects {
    background: #e74c3c;
    color: #fff;
    padding: 3px;
    border-radius: 6px;
}
</code>```

And if at this td i have value more then 1, i add bg red box.

But nox, something went wrong.

答:
Without seeing your html, I can only guess about how it looks based on your code, but try this:

```<code>$('tr').each(function() {
  var rowCol = $(this);
  rowCol.find('td:eq(4)').each(function() {
    var mytd = $(this);
    var rowValue = parseFloat($(this).text());
    console.log(rowValue === 0)
    if (rowValue > 1) {
      mytd.addClass('def').removeClass('defects');
    } else {
      mytd.addClass('defects').removeClass('def');
    }
  });
});
</code>```

first of, I'm assigning your td:eq(4) to a variable var mytd = $(this);.

 then I'm replacing $('.defects') with mytd

Code

$('tr').each(function() {
  var rowCol = $(this);
  rowCol.find('td:eq(4)').each(function() {
    var mytd = $(this);
    var rowValue = parseFloat($(this).text());
    console.log(rowValue === 0)
    if (rowValue > 1) {
      mytd.addClass('def').removeClass('defects');
    } else {
      mytd.addClass('defects').removeClass('def');
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.defects {
  background: #e74c3c;
  color: #fff;
  padding: 3px;
  border-radius: 6px;
}</code>```

    1
    2
    3
    4
    0
    6

    1
    2
    3
    4
    5
    6

```

You can run the demo above and see the result.

Body:
I have table, with data, and i need for td:eq(4) change class, and box for baghround.

I have this code:

 $('tr').each(function () {
        var rowCol = $(this);
        rowCol.find('td:eq(4)').each(function () {
            var rowValue = parseFloat($(this).text());
            console.log(rowValue === 0)
            if (rowValue > 1) {
                $('.defects').addClass('def').removeClass('defects');
            } else {
                $('.def').addClass('defects').removeClass('def');
            }
        });
    });

.defects {
    background: #e74c3c;
    color: #fff;
    padding: 3px;
    border-radius: 6px;
}

And if at this td i have value more then 1, i add bg red box.

But nox, something went wrong.

Body:
Without seeing your html, I can only guess about how it looks based on your code, but try this:

$('tr').each(function() {
  var rowCol = $(this);
  rowCol.find('td:eq(4)').each(function() {
    var mytd = $(this);
    var rowValue = parseFloat($(this).text());
    console.log(rowValue === 0)
    if (rowValue > 1) {
      mytd.addClass('def').removeClass('defects');
    } else {
      mytd.addClass('defects').removeClass('def');
    }
  });
});

first of, I'm assigning your td:eq(4) to a variable var mytd = $(this);.

 then I'm replacing $('.defects') with mytd

Code

$('tr').each(function() {
  var rowCol = $(this);
  rowCol.find('td:eq(4)').each(function() {
    var mytd = $(this);
    var rowValue = parseFloat($(this).text());
    console.log(rowValue === 0)
    if (rowValue > 1) {
      mytd.addClass('def').removeClass('defects');
    } else {
      mytd.addClass('defects').removeClass('def');
    }
  });
});

.defects {
  background: #e74c3c;
  color: #fff;
  padding: 3px;
  border-radius: 6px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>0</td>
    <td>6</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
</table>

You can run the demo above and see the result.


问:
Common pre-C89 compiler/stdlib idioms (1985-1988)
I'm writing a C compiler for the fictional DCPU-16 CPU (which will be used in the 0x10C game).  In this game world any original software written for the system has been developed before (or during) 1988: so I'm trying to write my compiler like it was coded between 1985-1988.  I've got a copy of the C89 standard, but would like to know how common compilers preceding this differed from the standard and the common coding styles of the period.

So far this is what I'm assuming:

I need to use preprocessor support to define both old and new style function definitions/prototypes.

Coding style generally uses "something_with_an_underscore" for types, functions and variables (is this true? how prevelant was Hungarian notation during the period? what about camel case?)

Other things I would like to know:

How did common c compilers/stdlibs differ from the later C89 standard?

What common code patterns were in vogue?

How were common variables named at the time (i, n, foo, bar?)

Do you have any example code from the time?

Etc...

答:
The ANSI X3J11 committee that was responsible for standardizing the C language was formed in 1983, and in April 1985 they published a first draft.  According to Eric S. Raymond, "[the C language] has been essentially stable since copies of the X3J11 committee's working papers on the Draft Proposed Standard signaled the committee's intentions to compiler implementers in 1985-1986".  [1]

Studying a compiler manual from the '85-'86 timeframe, such as Lattice C [2] or Microsoft C 4.0 [3], shows that these compilers had already begun to support most of ANSI C89.  The most glaring omissions are the lack of const and volatile support (although Microsoft C had already added these to the list of reserved keywords) and the continued use of "K&R"-style function definitions.

So by 1988, it wouldn't be unreasonable to see ANSI C89 code in the wild, even though the standard itself had not yet been published -- simply because the compiler writers had already been incorporating parts of the standard into their compilers for several years.

[1]  http://www.catb.org/~esr/writings/taoup/html/c_evolution.html

[2]  https://archive.org/details/Lattice_C_AmigaDOS_Compiler_Version_3_Programmers_Reference_Guide_1986-09-12_Lattice_Inc.

[3]  http://www.os2museum.com/wp/dos/dos-library/


问:
Index column size too large. The maximum column size is 767 bytes. on import existing database in Laravel (Read carefully not duplicate)
Please read carefully. This is not a duplicate on the topic:
#1071 - Specified key was too long; max key length is 767 bytes and  How to fix 1709 - Index column size too large. The maximum column size is 767 bytes. in mysql in XAMPP

I already have an existing base. And I get this error. My question is how to correct it and I tried everything.

First I set in my database.php this code

```<code>        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
</code>```

After I set:

```<code>         Schema::defaultStringLength(191);
</code>```

Always i got error message:

Index column size too large. The maximum column size is 767 bytes.

The first time my import burst here:

```<code> CREATE TABLE `admins` (
   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
   `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `email` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `password` varchar(60) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `created_at` timestamp NULL DEFAULT NULL,
   `updated_at` timestamp NULL DEFAULT NULL,
   PRIMARY KEY (`id`),
   UNIQUE KEY `admins_email_unique` (`email`)
 ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4
 COLLATE=utf8mb4_unicode_ci
</code>```

This is 5 tables in a row, I have 40 more. For that reason I can't change existing table.

The question, how to fix this? I use mariaDB and xampp.
The difference between my question and those above is that I import an existing table and I can not change the data. I also work in Laravel

答:
This is an XY problem

Why? Because the issue is not the amount of data not fitting the index, that's the symptom.

Real problem

Real problem is how to stop duplicate email entries.

Attempted solution

Attempted solution is to create a UNIQUE index on the email column. It's a great attempt at solving the issue except - emails can be unusually large, your index length will vary. Sometimes it might be a 10 bytes, sometimes 30, sometimes 50.. and sometimes 255 - that's not good.

Back to the drawing board

What if all emails had fixed length? That's a much easier problem to tackle. You don't have to worry about index size limitation, all you need to make sure is that it's below the default limit of 767 bytes.

Better solution

Let's not index the email field. Let's create another column, email_unique and let's store the hash of the email there. Then, make the hash a UNIQUE index.

Benefits:
- always fixed with
- always falls within default index length of 767 bytes
- no worrying about utf8

How to do it to waste as little space as possible

choose a hashing algorithm. sha1 is completely fine, although you can go for sha256. I'll use 256-bit version of SHA-2 algorithm

create a binary(32 field). It will hold the raw value of our hashing function. It will always be fixed with for any kind of email

I'll use triggers, before create and before update to maintain the value of the hash so I don't have to worry about it in my language's logic.

Add the binary column

```<code>ALTER TABLE admins ADD email_hash BINARY(32) AFTER email;
</code>```

Add the before insert trigger

```<code>DELIMITER $$

CREATE TRIGGER `admins_before_insert` BEFORE INSERT
ON admins
FOR EACH ROW BEGIN
    SET NEW.email_hash = UNHEX(SHA2(NEW.email, 256)); -- this creates a binary representation of a sha-256 hashed email column

END$$

DELIMITER ;
</code>```

Add before update trigger

```<code>DELIMITER $$

CREATE TRIGGER `admins_before_insert` BEFORE UPDATE
ON admins
FOR EACH ROW BEGIN
    SET NEW.email_hash = UNHEX(SHA2(NEW.email, 256)); -- this creates a binary representation of a sha-256 hashed email column

END$$

DELIMITER ;
</code>```

Final words

I added trigger example code but I didn't test it. The idea is to be able to add and update emails and have MySQL tell you if there's a duplicate. Some people don't like using triggers. That's why the step with triggers is optional and an example how to achieve the effect if you prefer that route.

You can, of course, increase the amount of bytes MySQL will accept for indexing. However, that's not the optimal solution as you can quickly fill up your memory and basically waste resources. Down the line, you might exceed newly set limit.

Body:
Please read carefully. This is not a duplicate on the topic:
#1071 - Specified key was too long; max key length is 767 bytes and  How to fix 1709 - Index column size too large. The maximum column size is 767 bytes. in mysql in XAMPP

I already have an existing base. And I get this error. My question is how to correct it and I tried everything.

First I set in my database.php this code

        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',

After I set:

         Schema::defaultStringLength(191);

Always i got error message:

Index column size too large. The maximum column size is 767 bytes.

The first time my import burst here:

 CREATE TABLE `admins` (
   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
   `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `email` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `password` varchar(60) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `created_at` timestamp NULL DEFAULT NULL,
   `updated_at` timestamp NULL DEFAULT NULL,
   PRIMARY KEY (`id`),
   UNIQUE KEY `admins_email_unique` (`email`)
 ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4
 COLLATE=utf8mb4_unicode_ci

This is 5 tables in a row, I have 40 more. For that reason I can't change existing table.

The question, how to fix this? I use mariaDB and xampp.
The difference between my question and those above is that I import an existing table and I can not change the data. I also work in Laravel

Body:
This is an XY problem

Why? Because the issue is not the amount of data not fitting the index, that's the symptom.

Real problem

Real problem is how to stop duplicate email entries.

Attempted solution

Attempted solution is to create a UNIQUE index on the email column. It's a great attempt at solving the issue except - emails can be unusually large, your index length will vary. Sometimes it might be a 10 bytes, sometimes 30, sometimes 50.. and sometimes 255 - that's not good.

Back to the drawing board

What if all emails had fixed length? That's a much easier problem to tackle. You don't have to worry about index size limitation, all you need to make sure is that it's below the default limit of 767 bytes.

Better solution

Let's not index the email field. Let's create another column, email_unique and let's store the hash of the email there. Then, make the hash a UNIQUE index.

Benefits:
- always fixed with
- always falls within default index length of 767 bytes
- no worrying about utf8

How to do it to waste as little space as possible

choose a hashing algorithm. sha1 is completely fine, although you can go for sha256. I'll use 256-bit version of SHA-2 algorithm

create a binary(32 field). It will hold the raw value of our hashing function. It will always be fixed with for any kind of email

I'll use triggers, before create and before update to maintain the value of the hash so I don't have to worry about it in my language's logic.

Add the binary column

ALTER TABLE admins ADD email_hash BINARY(32) AFTER email;

Add the before insert trigger

DELIMITER $$

CREATE TRIGGER `admins_before_insert` BEFORE INSERT
ON admins
FOR EACH ROW BEGIN
    SET NEW.email_hash = UNHEX(SHA2(NEW.email, 256)); -- this creates a binary representation of a sha-256 hashed email column

END$$

DELIMITER ;

Add before update trigger

DELIMITER $$

CREATE TRIGGER `admins_before_insert` BEFORE UPDATE
ON admins
FOR EACH ROW BEGIN
    SET NEW.email_hash = UNHEX(SHA2(NEW.email, 256)); -- this creates a binary representation of a sha-256 hashed email column

END$$

DELIMITER ;

Final words

I added trigger example code but I didn't test it. The idea is to be able to add and update emails and have MySQL tell you if there's a duplicate. Some people don't like using triggers. That's why the step with triggers is optional and an example how to achieve the effect if you prefer that route.

You can, of course, increase the amount of bytes MySQL will accept for indexing. However, that's not the optimal solution as you can quickly fill up your memory and basically waste resources. Down the line, you might exceed newly set limit.


问:
Refresh Excel 2007 Web Service Reference
I have consumed a web service (WSDL) within Excel 2007, using the Web Service References Tool 2.0.  I am able to call the web service and make successful requests.

The WSDL has changed (a new service has been added/parameters changed).  How do I refresh the web service reference in Excel to take account of the changes?  The only way I can see at the moment is removing and adding back in again?

答:
You can change your webservice url using its url property. try below code.

```<code>Dim CallWebService As New WebRef.WMS_WS
CallWebService.Url = myNewURL
</code>```

Thanks

Body:
You can change your webservice url using its url property. try below code.

Dim CallWebService As New WebRef.WMS_WS
CallWebService.Url = myNewURL

Thanks


问:
Using agent parameters from main to different agent?
For a project I'm trying to select the right output if a parameter of the created agent is true. The agent is created in the main but goes into a different agent for the selection of the output. If I use a select in the main and use the statement for the parameter as condition it works fine. Whenever it enters the agent and I use the same statement it gives an error (Description: product1 cannot be resolved or is not a field. Location: testCase5/Transport/selectOutput - SelectOutput).

I tried using different conditions like main.agent.product1 . Can't seem to solve the issue. I know that it has to do something with declaration probably but I'm clueless at the moment.

//for the condition that works if I put the selectOutput in the main

agent.product1

//for the condition in the agent I tried the same but didn't work. also tried

main.agent.product1 // Gives the same error but for (Description: agentcannot be resolved or is not a field.)

(Main)agent.product1
//And a few more

答:
In AnyLogic each block of a project flow (regardless if from the process modeling library, the pedestrian library or another) has the type of Agent that is flowing through it defined in its properties. You can find this setting as Agent type in the block's properties under Advanced.

If you fail to set this correctly (meaning this setting equals the type of Agents you let flow through it), it will still flow through, BUT: you cannot access the specific properties of the Agent type.

That said, usually you do not even have to think about, because AnyLogic has an automatism there: The first block of your process flow, typically a Source-block or a Enter-block is the only block where you have to make the correct setting, all attached blocks get it then automatically!

However this does not work when:

You have separate flows (eg. you leave one flow through an Exit-block and enter another by an Enter). You'll manually have to put the correct setting also for the first block of the second process flow.

Your process flow is continued inside of another Agent/Custom Block, as in your example. AnyLogic doesnt realize the process flow inside your custom block is logically connected to the outside process flow in main. You have to specifiy manually again the Agent type flowing through in the first block of your process inside your Custom Block.


问:
How to get the last folder's name where the file is stored (without using macro)
I need to extract - in a cell - the last folder name where the active excel file is stored.

E.g. C:/Documents/Users/Accounting/May 2019/Expenses.xls

I want to extract/output the text "May 2019" in a specific cell by using a formula (not a macro).

Thank you in advance.

答:
So, I went with using the CELL() function to get the full path and then cut out the last folder name.

See:

```<code>=TRIM(MID(SUBSTITUTE(CELL("filename",A1),"/",REPT(" ",999)),4*999-998,999))
</code>```

Edit, As Ron pointed out that was fixed for the number of folders... This works around that:

See:

```<code>=TRIM(MID(SUBSTITUTE(CELL("filename",A1),"/",REPT(" ",999)),SUM(IF(CELL("filename",A1)<>"",LEN(CELL("filename",A1))-LEN(SUBSTITUTE(CELL("filename",A1),"/","")),0))*999-998,999))
</code>```

Note:

Localization can mean ";" instead of "," and "\" instead of "/", so take care...

Body:
So, I went with using the CELL() function to get the full path and then cut out the last folder name.

See:

=TRIM(MID(SUBSTITUTE(CELL("filename",A1),"/",REPT(" ",999)),4*999-998,999))

Edit, As Ron pointed out that was fixed for the number of folders... This works around that:

See:

=TRIM(MID(SUBSTITUTE(CELL("filename",A1),"/",REPT(" ",999)),SUM(IF(CELL("filename",A1)<>"",LEN(CELL("filename",A1))-LEN(SUBSTITUTE(CELL("filename",A1),"/","")),0))*999-998,999))

Note:

Localization can mean ";" instead of "," and "\" instead of "/", so take care...


问:
Unity-Android-App Crashes when Run First Time but From Second Time it Works Fine
I have implemented Firebase Analytics and Firebase Messaging after download the plugin from Google we site and successfully running the Resolvers.
The problem is after build when App is Run FIRST TIME it crashes with the following error but from 2nd time onwards the app does not crash
Here is the log

```<code>FATAL EXCEPTION: main
    Process: com.lemontart.flying.robot.car.transformation, PID: 27861
    java.lang.RuntimeException: Unable to instantiate service com.google.firebase.messaging.cpp.ListenerService: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.messaging.cpp.ListenerService" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk"],nativeLibraryDirectories=[/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/lib/arm, /data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk!/lib/armeabi-v7a, /system/lib]]
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3654)
        at android.app.ActivityThread.access$1500(ActivityThread.java:207)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6863)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.messaging.cpp.ListenerService" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk"],nativeLibraryDirectories=[/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/lib/arm, /data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk!/lib/armeabi-v7a, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:169)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.AppComponentFactory.instantiateService(AppComponentFactory.java:103)
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3649)
        at android.app.ActivityThread.access$1500(ActivityThread.java:207)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6863)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
        Suppressed: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/messaging/FirebaseMessagingService;
        at java.lang.VMClassLoader.findLoadedClass(Native Method)
        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
                ... 11 more
     Caused by: java.lang.ClassNotFoundException: com.google.firebase.messaging.FirebaseMessagingService
        at java.lang.VMClassLoader.findLoadedClass(Native Method)
        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                ... 14 more
     Caused by: java.lang.IllegalAccessError: Class com.google.firebase.iid.zzb extended by class com.google.firebase.messaging.FirebaseMessagingService is inaccessible (declaration of 'com.google.firebase.messaging.FirebaseMessagingService' appears in base.apk)
                ... 14 more
2019-05-17 12:55:18.960 27861-27861/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.lemontart.flying.robot.car.transformation, PID: 27861
    java.lang.Error: FATAL EXCEPTION [main]
    Unity version     : 2018.3.14f1
    Device model      : OnePlus ONEPLUS A5000
    Device fingerprint: OnePlus/OnePlus5/OnePlus5:9/PKQ1.180716.001/1904191514:user/release-keys

    Caused by: java.lang.RuntimeException: Unable to instantiate service com.google.firebase.messaging.cpp.ListenerService: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.messaging.cpp.ListenerService" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk"],nativeLibraryDirectories=[/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/lib/arm, /data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk!/lib/armeabi-v7a, /system/lib]]
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3654)
        at android.app.ActivityThread.access$1500(ActivityThread.java:207)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6863)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.messaging.cpp.ListenerService" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk"],nativeLibraryDirectories=[/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/lib/arm, /data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk!/lib/armeabi-v7a, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:169)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.AppComponentFactory.instantiateService(AppComponentFactory.java:103)
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3649)
        at android.app.ActivityThread.access$1500(ActivityThread.java:207)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6863)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
        Suppressed: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/messaging/FirebaseMessagingService;
        at java.lang.VMClassLoader.findLoadedClass(Native Method)
        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
</code>```

I an see there are all the jars and aars present it the project, still I am not able to figure our the problem.
Here is my gradle file

```<code>// GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN

buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
**BUILD_SCRIPT_DEPS**}
}

allprojects {
    repositories {
        google()
        jcenter()
        flatDir {
            dirs 'libs'
        }
    }
}

// Android Resolver Repos Start
allprojects {
    repositories {
        maven {
            url "https://maven.google.com"
        }
        maven {
            url "https://maven.google.com/" // Assets/Consoliads/Editor/ConsoliAdsDependencies.xml:7
        }
        maven {
            url "file:////Volumes/JawadData/Unity%20Projects/Consoli%204.6.2%20Unity%202018/Assets/Firebase/m2repository" // Assets/Firebase/Editor/AnalyticsDependencies.xml:22, Assets/Firebase/Editor/AppDependencies.xml:22
        }
        mavenLocal()
        jcenter()
        mavenCentral()
    }
}
// Android Resolver Repos End
apply plugin: 'com.android.application'
**APPLY_PLUGINS**

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:multidex:1.0.1'

**DEPS**}

android {
    compileSdkVersion **APIVERSION**
    buildToolsVersion '**BUILDTOOLS**'

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        multiDexEnabled true
        minSdkVersion **MINSDKVERSION**
        targetSdkVersion **TARGETSDKVERSION**
        applicationId '**APPLICATIONID**'
        ndk {
            abiFilters **ABIFILTERS**
        }
        versionCode **VERSIONCODE**
        versionName '**VERSIONNAME**'
    }

    lintOptions {
        abortOnError false
    }

    aaptOptions {
        noCompress = ['.unity3d', '.ress', '.resource', '.obb'**STREAMING_ASSETS**]
    }**SIGN**

    buildTypes {
        debug {
            minifyEnabled **MINIFY_DEBUG**
            useProguard **PROGUARD_DEBUG**
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'**USER_PROGUARD**
            jniDebuggable true
        }
        release {
            minifyEnabled **MINIFY_RELEASE**
            useProguard **PROGUARD_RELEASE**
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'**USER_PROGUARD****SIGNCONFIG**
        }
    }**PACKAGING_OPTIONS****SPLITS**
**BUILT_APK_LOCATION**
    bundle {
        language {
            enableSplit = false
        }
        density {
            enableSplit = false
        }
        abi {
            enableSplit = true
        }
    }
}**SPLITS_VERSION_CODE****REPOSITORIES****SOURCE_BUILD_SETUP**
</code>```

I need to fix this issue, please help it will be highly appreciated.
Thanks

答:
Few days ago I faced the same issue, And it was resolved by just updating The all firebase libraries to their latest version. It seems that their could be version conflict between the dependencies.
You can find the latest versions list of the Firebase libraries here</p>

Body:
I have implemented Firebase Analytics and Firebase Messaging after download the plugin from Google we site and successfully running the Resolvers.
The problem is after build when App is Run FIRST TIME it crashes with the following error but from 2nd time onwards the app does not crash
Here is the log

FATAL EXCEPTION: main
    Process: com.lemontart.flying.robot.car.transformation, PID: 27861
    java.lang.RuntimeException: Unable to instantiate service com.google.firebase.messaging.cpp.ListenerService: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.messaging.cpp.ListenerService" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk"],nativeLibraryDirectories=[/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/lib/arm, /data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk!/lib/armeabi-v7a, /system/lib]]
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3654)
        at android.app.ActivityThread.access$1500(ActivityThread.java:207)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6863)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.messaging.cpp.ListenerService" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk"],nativeLibraryDirectories=[/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/lib/arm, /data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk!/lib/armeabi-v7a, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:169)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.AppComponentFactory.instantiateService(AppComponentFactory.java:103)
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3649)
        at android.app.ActivityThread.access$1500(ActivityThread.java:207)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6863)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
        Suppressed: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/messaging/FirebaseMessagingService;
        at java.lang.VMClassLoader.findLoadedClass(Native Method)
        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
                ... 11 more
     Caused by: java.lang.ClassNotFoundException: com.google.firebase.messaging.FirebaseMessagingService
        at java.lang.VMClassLoader.findLoadedClass(Native Method)
        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                ... 14 more
     Caused by: java.lang.IllegalAccessError: Class com.google.firebase.iid.zzb extended by class com.google.firebase.messaging.FirebaseMessagingService is inaccessible (declaration of 'com.google.firebase.messaging.FirebaseMessagingService' appears in base.apk)
                ... 14 more
2019-05-17 12:55:18.960 27861-27861/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.lemontart.flying.robot.car.transformation, PID: 27861
    java.lang.Error: FATAL EXCEPTION [main]
    Unity version     : 2018.3.14f1
    Device model      : OnePlus ONEPLUS A5000
    Device fingerprint: OnePlus/OnePlus5/OnePlus5:9/PKQ1.180716.001/1904191514:user/release-keys

    Caused by: java.lang.RuntimeException: Unable to instantiate service com.google.firebase.messaging.cpp.ListenerService: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.messaging.cpp.ListenerService" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk"],nativeLibraryDirectories=[/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/lib/arm, /data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk!/lib/armeabi-v7a, /system/lib]]
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3654)
        at android.app.ActivityThread.access$1500(ActivityThread.java:207)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6863)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.messaging.cpp.ListenerService" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk"],nativeLibraryDirectories=[/data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/lib/arm, /data/app/com.lemontart.flying.robot.car.transformation-EVwlnR7Mxf4TO-7_HvK44w==/base.apk!/lib/armeabi-v7a, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:169)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.AppComponentFactory.instantiateService(AppComponentFactory.java:103)
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3649)
        at android.app.ActivityThread.access$1500(ActivityThread.java:207)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6863)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
        Suppressed: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/messaging/FirebaseMessagingService;
        at java.lang.VMClassLoader.findLoadedClass(Native Method)
        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)

I an see there are all the jars and aars present it the project, still I am not able to figure our the problem.
Here is my gradle file

// GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN

buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
**BUILD_SCRIPT_DEPS**}
}

allprojects {
    repositories {
        google()
        jcenter()
        flatDir {
            dirs 'libs'
        }
    }
}

// Android Resolver Repos Start
allprojects {
    repositories {
        maven {
            url "https://maven.google.com"
        }
        maven {
            url "https://maven.google.com/" // Assets/Consoliads/Editor/ConsoliAdsDependencies.xml:7
        }
        maven {
            url "file:////Volumes/JawadData/Unity%20Projects/Consoli%204.6.2%20Unity%202018/Assets/Firebase/m2repository" // Assets/Firebase/Editor/AnalyticsDependencies.xml:22, Assets/Firebase/Editor/AppDependencies.xml:22
        }
        mavenLocal()
        jcenter()
        mavenCentral()
    }
}
// Android Resolver Repos End
apply plugin: 'com.android.application'
**APPLY_PLUGINS**

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:multidex:1.0.1'

**DEPS**}

android {
    compileSdkVersion **APIVERSION**
    buildToolsVersion '**BUILDTOOLS**'

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        multiDexEnabled true
        minSdkVersion **MINSDKVERSION**
        targetSdkVersion **TARGETSDKVERSION**
        applicationId '**APPLICATIONID**'
        ndk {
            abiFilters **ABIFILTERS**
        }
        versionCode **VERSIONCODE**
        versionName '**VERSIONNAME**'
    }

    lintOptions {
        abortOnError false
    }

    aaptOptions {
        noCompress = ['.unity3d', '.ress', '.resource', '.obb'**STREAMING_ASSETS**]
    }**SIGN**

    buildTypes {
        debug {
            minifyEnabled **MINIFY_DEBUG**
            useProguard **PROGUARD_DEBUG**
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'**USER_PROGUARD**
            jniDebuggable true
        }
        release {
            minifyEnabled **MINIFY_RELEASE**
            useProguard **PROGUARD_RELEASE**
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'**USER_PROGUARD****SIGNCONFIG**
        }
    }**PACKAGING_OPTIONS****SPLITS**
**BUILT_APK_LOCATION**
    bundle {
        language {
            enableSplit = false
        }
        density {
            enableSplit = false
        }
        abi {
            enableSplit = true
        }
    }
}**SPLITS_VERSION_CODE****REPOSITORIES****SOURCE_BUILD_SETUP**

I need to fix this issue, please help it will be highly appreciated.
Thanks


问:
Beginner : Not understanding shape [,1] on Tensorflow.js
I want to make a model to convert Celsius to Fahrenheit with Tensorflow.js (with Node.js).

However, I am not understanding what shapes to use.

I have tried different input_shape such as [1], [1,20] and finally set it to[20]
I also have tried different tensor shape for the Celsius & Fahrenheit arrays such as tensor(celsius), tensor([celsius]).

Here is the code

```<code>
var model = tf.sequential()
model.add(tf.layers.dense({inputShape:[20], units: 1}))

async function trainModel(model, inputs, labels) {
    // Prepare the model for training.
    model.compile({
      optimizer: tf.train.adam(),
      loss: tf.losses.meanSquaredError,
      metrics: ['mse'],
    });

    const batchSize = 28;
    const epochs = 500;

    return await model.fit(inputs, labels, {
      epochs,
      shuffle: true,
    //   callbacks: tfvis.show.fitCallbacks(
    //     { name: 'Training Performance' },
    //     ['loss', 'mse'],
    //     { height: 200, callbacks: ['onEpochEnd'] }
    //   )
    });
  }

c = tf.tensor([celsius]) // celsius = [1,2,3,4,...]
console.log(c.shape) // ==> [1,20]

f = tf.tensor([fahrenheit])
console.log(f.shape) // ==> [1,20]

trainModel(model, c, f)
</code>```

Moreover, in the Python tutorial input_shape is [1] . With Node.js, only [20] seems to work.

The shape of inputs is [1,20] and it is correct.

Shape of labels is [1,20] as well but triggers following error :

Debugger says :

```<code>Error when checking target: expected dense_Dense1 to have shape [,1], but got array with shape [1,20].
</code>```

-
EDIT

Furthermore, when i try input_shape: [1,20], it gives me :

```<code>expected dense_Dense1_input to have 3 dimension(s). but got array with shape 1,20
</code>```

-

I expect the model to train by associating C° values to F° values.

Thank you

答:
The error is clear:

```<code>{inputShape:[20], units: 1}
</code>```

The model contains a single layer. inputShape:[20] which means batchInputShape that is [null, 20] will be the shape of the first layer. Likewise, units: 1 indicates that the last layer will have the shape [null, 1].

The features used have the shape [1, 20] matching therefore the batchInputShape of the model. However, that's not the case for the labels that have the shape [1, 20]. It has to have the shape [1, 1] therefore throwing the error:

expected dense_Dense1 to have shape [,1], but got array with shape [1,20]

The units size of the model has to be changed to reflect the labels shape.

```<code>{inputShape:[20], units: 20}
</code>```

Body:
I want to make a model to convert Celsius to Fahrenheit with Tensorflow.js (with Node.js).

However, I am not understanding what shapes to use.

I have tried different input_shape such as [1], [1,20] and finally set it to[20]
I also have tried different tensor shape for the Celsius & Fahrenheit arrays such as tensor(celsius), tensor([celsius]).

Here is the code

var model = tf.sequential()
model.add(tf.layers.dense({inputShape:[20], units: 1}))

async function trainModel(model, inputs, labels) {
    // Prepare the model for training.
    model.compile({
      optimizer: tf.train.adam(),
      loss: tf.losses.meanSquaredError,
      metrics: ['mse'],
    });

    const batchSize = 28;
    const epochs = 500;

    return await model.fit(inputs, labels, {
      epochs,
      shuffle: true,
    //   callbacks: tfvis.show.fitCallbacks(
    //     { name: 'Training Performance' },
    //     ['loss', 'mse'],
    //     { height: 200, callbacks: ['onEpochEnd'] }
    //   )
    });
  }

c = tf.tensor([celsius]) // celsius = [1,2,3,4,...]
console.log(c.shape) // ==> [1,20]

f = tf.tensor([fahrenheit])
console.log(f.shape) // ==> [1,20]

trainModel(model, c, f)

Moreover, in the Python tutorial input_shape is [1] . With Node.js, only [20] seems to work.

The shape of inputs is [1,20] and it is correct.

Shape of labels is [1,20] as well but triggers following error :

Debugger says :

Error when checking target: expected dense_Dense1 to have shape [,1], but got array with shape [1,20].

-
EDIT

Furthermore, when i try input_shape: [1,20], it gives me :

expected dense_Dense1_input to have 3 dimension(s). but got array with shape 1,20

-

I expect the model to train by associating C° values to F° values.

Thank you

Body:
The error is clear:

{inputShape:[20], units: 1}

The model contains a single layer. inputShape:[20] which means batchInputShape that is [null, 20] will be the shape of the first layer. Likewise, units: 1 indicates that the last layer will have the shape [null, 1].

The features used have the shape [1, 20] matching therefore the batchInputShape of the model. However, that's not the case for the labels that have the shape [1, 20]. It has to have the shape [1, 1] therefore throwing the error:

expected dense_Dense1 to have shape [,1], but got array with shape [1,20]

The units size of the model has to be changed to reflect the labels shape.

{inputShape:[20], units: 20}


问:
Detecting when an object gets added to a movieclip
Alright, so I'm trying to figure out when a child is added to a movieclip "x", and handling/detouring this operation from within this "x" movieclip.

I tried overriding addChild and addChildAt at with no prevail. The movieclips that are placed on the stage via flash still don't trigger addChild or addChildAt. However, tracing this.numChildren shows '2' correctly.

Any hints?

答:
You can override the default methods of a movieclip by doing the following:

Create a class to extend a movieclip:

```<code>package  {
    import flash.display.*;

    public class SuperMovieClip extends MovieClip {

        public function SuperMovieClip() {
            // constructor code
            super();
        }

        override public function addChild(child:DisplayObject):DisplayObject {
            trace("Hello, I am overriding add child");
                    // still perform the default behavior but you can do what ever you want.
            return super.addChild(child);
        }

    }

}
</code>```

Then in Flash create a new movieclip, and make sure it is marked as Enable for ActionScript. The Class should be any name you want, but the base class needs to be SuperMovieClip (or the name you chose for your extended class) See image:

Now when any stage clip is created of this base type (regardless if it's in the IDE or through code) it will be of type SuperMovieClip and anytime addChild is called it will override the original function.

For example, I placed an instance of this mc from library onto the stage at design time and compiled it using the following code on the timeline:

```<code>import flash.display.Sprite;

stage_mc.addChild(new Sprite());
</code>```

And it output Hello, I am overriding add child

Body:
You can override the default methods of a movieclip by doing the following:

Create a class to extend a movieclip:

package  {
    import flash.display.*;

    public class SuperMovieClip extends MovieClip {

        public function SuperMovieClip() {
            // constructor code
            super();
        }

        override public function addChild(child:DisplayObject):DisplayObject {
            trace("Hello, I am overriding add child");
                    // still perform the default behavior but you can do what ever you want.
            return super.addChild(child);
        }

    }

}

Then in Flash create a new movieclip, and make sure it is marked as Enable for ActionScript. The Class should be any name you want, but the base class needs to be SuperMovieClip (or the name you chose for your extended class) See image:

Now when any stage clip is created of this base type (regardless if it's in the IDE or through code) it will be of type SuperMovieClip and anytime addChild is called it will override the original function.

For example, I placed an instance of this mc from library onto the stage at design time and compiled it using the following code on the timeline:

import flash.display.Sprite;

stage_mc.addChild(new Sprite());

And it output Hello, I am overriding add child


问:
symfony 4 form translate variable in twig include
I am currently trying to translate a string in Symfony/Twig inside an include Statement for a twig Template.
This is the non-translated Code is use for it currenty:

{{ include('@BluelineUser/user/_form.html.twig', {
    'back_link': path('user_index'),
    'title' : 'Edit User: ' ~ user.username,
    'button_caption': 'Save'
}) }}
```

<p>And in my form I output it like this: </p>

```{{ form_start(form) }}

{{ title|trans }}

{{ form_end(form) }}
```

<p>Now if I use the include with a diffrent title (without a variable in it) it works fine.</p>

<p>Adding this to my translation file just doesn't pick up the 'Edit User: '</p>

```<trans-unit id="edit.name2">
    <source>Edit User: </source>
    <target>Benutzer bearbeiten: </target>
</trans-unit>
```

Any idea on how to get they 'Edit User: ' in the title translated? I think it's breaking because of the variable.
So far couldn't find any example on how to get this working in an include statement.

答:
Try to translate it before like this:</p>

```<code>{{ include('@BluelineUser/user/_form.html.twig', {
    'back_link': path('user_index'),
    'title' : ('Edit User: '|trans) ~ user.username,
    'button_caption': 'Save'
}) }}
</code>```

Body:
I am currently trying to translate a string in Symfony/Twig inside an include Statement for a twig Template.
This is the non-translated Code is use for it currenty:

{{ include('@BluelineUser/user/_form.html.twig', {
    'back_link': path('user_index'),
    'title' : 'Edit User: ' ~ user.username,
    'button_caption': 'Save'
}) }}

And in my form I output it like this:

{{ form_start(form) }}

{{ title|trans }}

{{ form_end(form) }}

Now if I use the include with a diffrent title (without a variable in it) it works fine.

Adding this to my translation file just doesn't pick up the 'Edit User: '

<trans-unit id="edit.name2">
    <source>Edit User: </source>
    <target>Benutzer bearbeiten: </target>
</trans-unit>

Any idea on how to get they 'Edit User: ' in the title translated? I think it's breaking because of the variable.
So far couldn't find any example on how to get this working in an include statement.

Body:
Try to translate it before like this:

{{ include('@BluelineUser/user/_form.html.twig', {
    'back_link': path('user_index'),
    'title' : ('Edit User: '|trans) ~ user.username,
    'button_caption': 'Save'
}) }}


问:
I need help centering text in the center of CSS Grid
I am unable to align text in the center of the grid, both vertical and horizontally, because nothing that I tried seems to work, so I wanted to know what is the problem with my code or how should I do it.

I tried using justify-items: center, align-items: center and even place-items: center center;

This is a my full, hopefully, you can give it a try and see what is wrong with it.

```<code><title> Learning Grid </title>

<style>

    body {
        color: #fff;
        font-family: sans-serif;
        text-align: center;
    }

    #content {
        display: grid;
        grid-template-columns: repeat(12, 1fr);
        grid-auto-rows: minmax(100px, auto);
        grid-gap: 10px;
        max-width: 960px;
        margin: 0 auto;
    }

    #content > * {
        padding: 30px;
        font-size: 30px;

    }

    header {
        grid-column: 1/13;
        text-align: center;
        background-color: hotpink;
    }

     main {
        grid-column: 4/13;
        grid-row: 2/4;
         background-color: darksalmon;
    }

      aside {
        grid-column: 1/4;
        grid-row: 2/3;
          background-color: cadetblue;
    }

     nav {
        grid-column: 1/4;
        grid-row: 3/4;
         text-align: center;
         font-size: 30px;
         background-color: aquamarine;
    }

     section {
        grid-column: 1/13;
        grid-row: 4/6;
         background-color: coral;
    }

    footer {
        grid-column: 1/13;
        grid-row: 6/7;
        background-color: cornflowerblue;
    }

</style>

</head>

<body>

    <div id="content">

        <header> Header </header>

        <main> Main </main>

        <section>Section </section>

        <aside>Aside </aside>

        <nav> Nav </nav>

        <footer> Footer</footer>

    </div>

</body>
</code>```

答:
You can use Bootstrap classes for example :

 Main

Or aligning text over CSS

```<code>main {
    display: flex;
    justify-content: center;
    align-items: center;
}
</code>```

Body:
I am unable to align text in the center of the grid, both vertical and horizontally, because nothing that I tried seems to work, so I wanted to know what is the problem with my code or how should I do it.

I tried using justify-items: center, align-items: center and even place-items: center center;

This is a my full, hopefully, you can give it a try and see what is wrong with it.

<title> Learning Grid </title>

         Header

         Main

Section

        Aside

         Nav

         Footer

Body:
You can use Bootstrap classes for example :

<main class="text-center justify-content-center align-items-center"> Main </main>

Or aligning text over CSS

main {
    display: flex;
    justify-content: center;
    align-items: center;
}


问:
How to get information about identified point and exclude it in next plot in R
i've got problem with identify().

I have something like this

```<code>library (UsingR)
df=data.frame(emissions)
plot (df)
getPoint=identify(df)
</code>```

And I have to exclude the point  that is too far away from correct observation group.

How can I take this uncorrect point save it, exclude it, and get the correct frame in next plotting without saved point?

答:
First off I tried using identify on a data frame plot- it doesn't seem to work so instead I did one comparison- GDP vs perCapita:

```<code>plot(df$GDP,df$perCapita)
getPoint=identify(df$GDP,df$perCapita)
</code>```

I then picked a few points on the plot and then pressed 'ESC'

getPoint returns the number of the row of the points that I picked. I can then omit or select these points:

```<code>df[getPoint,] #select picked data points
df[-getPoint,] #exclude picked data points
</code>```

Body:
i've got problem with identify().

I have something like this

library (UsingR)
df=data.frame(emissions)
plot (df)
getPoint=identify(df)

And I have to exclude the point  that is too far away from correct observation group.

How can I take this uncorrect point save it, exclude it, and get the correct frame in next plotting without saved point?

Body:
First off I tried using identify on a data frame plot- it doesn't seem to work so instead I did one comparison- GDP vs perCapita:

plot(df$GDP,df$perCapita)
getPoint=identify(df$GDP,df$perCapita)

I then picked a few points on the plot and then pressed 'ESC'

getPoint returns the number of the row of the points that I picked. I can then omit or select these points:

df[getPoint,] #select picked data points
df[-getPoint,] #exclude picked data points