问:
Automatically changes dictionary order/sort from HTTP response
My API returns the following dictionary:

```<code>"positions": {
    "31": 18,
    "25": 12,
    "23": 12,
    "22": 12,
    "19": 12,
    "26": 9,
    "21": 9,
    "29": 9,
    "20": 9,
    "30": 9,
    "24": 6,
    "27": 6,
    "28": 6,
    "17": 3
}
</code>```

When I receive this in Angular, it reorders the dictionary and sorts them by keys instead of by values. So I get something like this

```<code>"positions": {
    "17": 3,
    "19": 12,
    "20": 9,
    ...
}
</code>```

Why? Do I have to define a model for this KVP where I tell it that the keys are strings and not numbers? How would I do that?

I'd prefer not having to both sort my data on the backend and on the frontend.

答:
Why?

The problem is the way that the ECMAScript spec specifies this behavior (which is really just a reflection of how runtimes have implemented this.

Let keys be a new empty List.

For each own property key P of O that is an integer index, in ascending numeric index order, do

Add P as the last element of keys.

For each own property key P of O that is a String but is not an integer index, in ascending chronological order of property creation, do

Add P as the last element of keys.

For each own property key P of O that is a Symbol, in ascending chronological order of property creation, do

Add P as the last element of keys.

Return keys.

So basically, integral keys will always come first in ascending (increasing) order.

Like jonrsharpe mentioned, you should probably make positions an array, either of key/value pair objects, or of other arrays that can act as tuples.

Body:
My API returns the following dictionary:

"positions": {
    "31": 18,
    "25": 12,
    "23": 12,
    "22": 12,
    "19": 12,
    "26": 9,
    "21": 9,
    "29": 9,
    "20": 9,
    "30": 9,
    "24": 6,
    "27": 6,
    "28": 6,
    "17": 3
}

When I receive this in Angular, it reorders the dictionary and sorts them by keys instead of by values. So I get something like this

"positions": {
    "17": 3,
    "19": 12,
    "20": 9,
    ...
}

Why? Do I have to define a model for this KVP where I tell it that the keys are strings and not numbers? How would I do that?

I'd prefer not having to both sort my data on the backend and on the frontend.


来源: stackexchange

问:
Update Codeigniter's data on Table #2 based Table #1's id
I have 2 tables, reservation and is customer

```<code>table #1 : reservation
------------------------
- reservation_id
- reservation_status
- customer_id

table #2 : customer
------------------------
- customer_id
- customer_name
- customer_status
</code>```

I'm new in codeigniter but how I can update/change customer status (from 0 to 1 or 1 to somevalue) based on reservation id

is there using join and update or somewhat.
Thanks

答:
Try this query:

```<code>$sql = 'UPDATE customer AS C JOIN reservation AS R ON R.customer_id=C.customer_id
SET C.customer_status = (CASE C.customer_status WHEN 1 THEN 0 ELSE 1 END)
WHERE R.reservation_id="2"';
$result = $this->db->query($sql);
if($result) {
   echo "Success";
} else {
   echo "fail";
}
</code>```

And check your query by:

```<code>echo $this->db->last_query();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have 2 tables, reservation and is customer

table #1 : reservation
------------------------
- reservation_id
- reservation_status
- customer_id

table #2 : customer
------------------------
- customer_id
- customer_name
- customer_status

I'm new in codeigniter but how I can update/change customer status (from 0 to 1 or 1 to somevalue) based on reservation id

is there using join and update or somewhat.
Thanks

Body:
Try this query:

$sql = 'UPDATE customer AS C JOIN reservation AS R ON R.customer_id=C.customer_id
SET C.customer_status = (CASE C.customer_status WHEN 1 THEN 0 ELSE 1 END)
WHERE R.reservation_id="2"';
$result = $this->db->query($sql);
if($result) {
   echo "Success";
} else {
   echo "fail";
}

And check your query by:

echo $this->db->last_query();


问:
Getting closed implementation type inside Autofac's WithParameter
I'm trying to register generic repository to use specific context based on entity custom attribute. Below is what i have

Globax.asax

```<code>//data layer
foreach (var database in DatabaseManager.Databases)
{
    builder.Register<IDbContext>(c => new CodesObjectContext(database.ConnectionString))
        .As<IDbContext>()
        .Named<IDbContext>(database.Alias)
        .InstancePerLifetimeScope();
}

builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
    .WithParameter(new ResolvedParameter(
        (pi, ctx) => pi.ParameterType == typeof(IDbContext),
        (pi, ctx) => ctx.ResolveNamed<IDbContext>((
            { Generic Type Of EfRepository}.GetType()
                .GetCustomAttributes(typeof(DatabaseAttribute), true)[0]
                    as DatabaseAttribute).Name)))
    .InstancePerLifetimeScope();
</code>```

I cant seem to get here, { Generic Type Of EfRepository }. Is it possible for me to get the current generic type of EfRepository being registered?

答:
I manage to solve it using information from ParameterInfo. Here is my solution:</p>

```<code> //data layer
            foreach (var database in DatabaseManager.Databases)
            {
                builder.Register<IDbContext>(c => new CodesObjectContext(database.ConnectionString))
                    .As<IDbContext>()
                    .Named<IDbContext>(database.Alias)
                    .InstancePerLifetimeScope();
            }

        builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
            .WithParameter(new ResolvedParameter(
                   (pi, ctx) => pi.ParameterType == typeof(IDbContext),
                   (pi, ctx) => ctx.ResolveNamed<IDbContext>(
                       (pi.Member.DeclaringType.GetGenericArguments()[0] //get generic type
                       .GetCustomAttributes(typeof(DatabaseAttribute), true)[0] as DatabaseAttribute).Name))) //get attribute database name
       .InstancePerLifetimeScope();
</code>```

Body:
I'm trying to register generic repository to use specific context based on entity custom attribute. Below is what i have

Globax.asax

//data layer
foreach (var database in DatabaseManager.Databases)
{
    builder.Register<IDbContext>(c => new CodesObjectContext(database.ConnectionString))
        .As<IDbContext>()
        .Named<IDbContext>(database.Alias)
        .InstancePerLifetimeScope();
}

builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
    .WithParameter(new ResolvedParameter(
        (pi, ctx) => pi.ParameterType == typeof(IDbContext),
        (pi, ctx) => ctx.ResolveNamed<IDbContext>((
            { Generic Type Of EfRepository}.GetType()
                .GetCustomAttributes(typeof(DatabaseAttribute), true)[0]
                    as DatabaseAttribute).Name)))
    .InstancePerLifetimeScope();

I cant seem to get here, { Generic Type Of EfRepository }. Is it possible for me to get the current generic type of EfRepository being registered?

Body:
I manage to solve it using information from ParameterInfo. Here is my solution:

 //data layer
            foreach (var database in DatabaseManager.Databases)
            {
                builder.Register<IDbContext>(c => new CodesObjectContext(database.ConnectionString))
                    .As<IDbContext>()
                    .Named<IDbContext>(database.Alias)
                    .InstancePerLifetimeScope();
            }

        builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
            .WithParameter(new ResolvedParameter(
                   (pi, ctx) => pi.ParameterType == typeof(IDbContext),
                   (pi, ctx) => ctx.ResolveNamed<IDbContext>(
                       (pi.Member.DeclaringType.GetGenericArguments()[0] //get generic type
                       .GetCustomAttributes(typeof(DatabaseAttribute), true)[0] as DatabaseAttribute).Name))) //get attribute database name
       .InstancePerLifetimeScope();


问:
Convert date to UTC using moment.js
Probably and easy answer to this but I can't seem to find a way to get moment.js to return a UTC date time in milliseconds. Here is what I am doing:

```<code>var date = $("#txt-date").val(),
    expires = moment.utc(date);
</code>```

Any idea what I am doing wrong?

答:
```<code>moment.utc(date).format(...);
</code>```

is the way to go, since

```<code>moment().utc(date).format(...);
</code>```

does behave weird...

Title: Convert date to UTC using moment.js

Body:
Probably and easy answer to this but I can't seem to find a way to get moment.js to return a UTC date time in milliseconds. Here is what I am doing:

var date = $("#txt-date").val(),
    expires = moment.utc(date);

Any idea what I am doing wrong?

Body:
moment.utc(date).format(...);

is the way to go, since

moment().utc(date).format(...);

does behave weird...


问:
Threading issue with Dispatcher.Invoke and Dispatcher.BeginInvoke
Acording to my understanding Dispatcher.Invoke and Dispatcher.BeginInvoke executes on UI thread, The only difference is That Invoke is synchronous and BeginInvoke  is asynchronous.My problem is when i use this code

```<code> EDisc.App.Current.Dispatcher.
              Invoke(
                              DispatcherPriority.Normal, new Action(delegate
                              {
                                  context = NavigationManager.CurrentPage.DataContext;
                              }));
</code>```

Value of context is returned. However with the below code

```<code> EDisc.App.Current.Dispatcher.
              BeginInvoke(
                              DispatcherPriority.Normal, new Action(delegate
                              {
                                  context = NavigationManager.CurrentPage.DataContext;
                              }));
</code>```

Context is null and i get an InvalidOperation Exception saying "

The calling thread cannot access this object because a different thread owns it.I am calling this from a WCF service which is executing with UseSynchronizationContext = false .Can anybody explain this behaviour?

答:
Both BeginInvoke and Invoke will end up calling an internal method called BeginInvokeImpl to do the work. The difference is that Invoke then waits for the operation to complete before returning.

And there's one other difference: if you are already on the UI thread and you're using DispatcherPriority.Send Invoke will actually invoke the method directly without going via BeginInvokeImpl, meaning that the operation is processed without going via the message queue. (If you're not using Send then any other messages already queued up with higher property than your operation will get processed first.)

But since you're presumably not on the UI thread here - you're on some WCF callback - that special case won't apply. So Invoke ends up calling into the same underlying implementation as BeginInvoke.

From the information you've provided, I'd have to guess that there's a missing detail somewhere here. The code you've shown should work fine, unless perhaps you have multiple UI threads in your application, and the page that happens to be in CurrentPage belongs to different threads from time to time.

If you do have multiple UI threads, then the approach you're using - pushing everything through the current Application object's dispatcher - isn't going to work, because you'll have multiple dispatchers. You'd need to get the right dispatcher for whichever UI element you're planning to touch.

Incidentally, one way you might accidentally end up with multiple UI threads is if you construct a UI object (e.g. a Page) on some worker thread or callback. Is it possible that you've done that somewhere?

ContentLicense: CC BY-SA 2.5

Body:
Acording to my understanding Dispatcher.Invoke and Dispatcher.BeginInvoke executes on UI thread, The only difference is That Invoke is synchronous and BeginInvoke  is asynchronous.My problem is when i use this code

 EDisc.App.Current.Dispatcher.
              Invoke(
                              DispatcherPriority.Normal, new Action(delegate
                              {
                                  context = NavigationManager.CurrentPage.DataContext;
                              }));

Value of context is returned. However with the below code

 EDisc.App.Current.Dispatcher.
              BeginInvoke(
                              DispatcherPriority.Normal, new Action(delegate
                              {
                                  context = NavigationManager.CurrentPage.DataContext;
                              }));

Context is null and i get an InvalidOperation Exception saying "

The calling thread cannot access this object because a different thread owns it.I am calling this from a WCF service which is executing with UseSynchronizationContext = false .Can anybody explain this behaviour?


问:
What Could be the Cause of this: ** Command Error: SSL Error: error:14077410:SSL routines:SSL23_GET_SERVER_HEL LO:sslv3 alert handshake failure
Version: REBOL/View 2.7.8.3.1 1-Jan-2011

I have run a REBOL script weekly that fetches data for years. The last verified working of the script 21-Oct-2016.

As of today, 28-Oct-2016 the script fails with this error:

** Command Error: SSL Error:  error:14077410:SSL routines:SSL23_GET_SERVER_HEL
LO:sslv3 alert handshake failure

Someone suggests that during the SSL/TLS handshake, REBOL only offers ciphers that current servers no longer support. Subsequently, the server my script tried to contact is not willing to work with older ciphers of REBOL and thus the handshake fails.

Is this right? If this is so, REBOL 2.7.8 will become useless before long unless patched.

Incidentally, this fails with Saphirion's R3. In that case, it simply crashes and stops working without spewing an error message.

答:
Rebol2 only has support for TLS 1.0.  If you run the report from ssllabs on that server the report says that the only supported cipher suite for TLS 1.0 is TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA.

Now, Rebol3 and its forks aren't Rebol2, but if you look at the rebol3 source for prot-tls you'll see that the supported cipher suites do not include Elliptic Curve Diffie-Hellman Ephemeral or ECDHE.

We've updated the error message in the mean time so that it now says something more meaningful

read https://www.espacehifi.com/
** Error: Handshake failure - no supported cipher suite available on server

until we get ECDHE suites into rebol3.

ContentLicense: CC BY-SA 4.0


问:
How to specify device when running an iOS React Native project in IntelliJ IDEA
I have a basic React Native project setup in IntelliJ IDEA IDE. When I hit "Run" it runs on iOS Simulator without asking which device to run on, but I want to run it on a physical device.</p>

答:
Did this by adding a device argument in the run configuration.

Goto -> Run(on toolbar) -> Select the project -> add "--device [DEVICE_NAME]" to the  "Run arguments" field, click apply/Ok and you're good to go.

screenshot of the window

PS : To know or change the name of your physical iPhone, on the iPhone goto Settings -> General -> About, and the name should be there.

Also, if you want to check if your mac can see your plugged in device, run "instruments -s devices" in the terminal to see all devices connected including simulators.


问:
need someone to look at this javascript code i dont know how to solve this
I've created a Rock Paper scissors game using JavaScript, I want to show an image of element that won in the end.

For example:

If rock wins: show a image/jpg of a rock

If paper wins: show a image/jpg of a paper

Below is the code:

```<code>var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
}
else if (computerChoice <= 0.67) {
    computerChoice = "paper";
}
else {
    computerChoice = "scissors";
}
//console.log("Computer chooses: " + computerChoice);
var compare = function (choice1, choice2) {
    if (choice1 === choice2) {
        return "The result is a tie!" + " " + "Lets play again.";
    }
    else if (choice1 === "rock") {

        if (choice2 === "scissors") {
            return "rock wins" + "<br>" + "You beat the computer, nice job!";
        }
        else {
            return "paper wins" + "<br>" + "Your really smart computer beat you.";
        }
    }
    else if (choice1 === "paper") {

        if (choice2 === "rock") {
            return "paper wins" + "<br>" + "You beat the computer, nice job!";
        }
        else {
            return "scissors wins" + "<br>" + "Your really smart computer beat you.";
        }
    }

    else if (choice1 === "scissors") {

        if (choice2 === "rock") {
            return "rock wins" + "<br>" + "Your really smart computer beat you.";
        }
        else {
            return "scissors win" + "<br>" + "You beat the computer, nice job!";
        }
    }

} //closes compare function
document.write("Computer chose: " + computerChoice + "<br>");
document.write(compare(userChoice, computerChoice));
</code>```

答:
Basically you can just use the following selector / method to change the src image of an HTML img tag:

document.getElementById("your-img").src = 'rock.jpg';

Of course you have to set the image path and the id accordingly.

Body:
I've created a Rock Paper scissors game using JavaScript, I want to show an image of element that won in the end.

For example:

If rock wins: show a image/jpg of a rock

If paper wins: show a image/jpg of a paper

Below is the code:

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
}
else if (computerChoice <= 0.67) {
    computerChoice = "paper";
}
else {
    computerChoice = "scissors";
}
//console.log("Computer chooses: " + computerChoice);
var compare = function (choice1, choice2) {
    if (choice1 === choice2) {
        return "The result is a tie!" + " " + "Lets play again.";
    }
    else if (choice1 === "rock") {

        if (choice2 === "scissors") {
            return "rock wins" + "
" + "You beat the computer, nice job!";
        }
        else {
            return "paper wins" + "
" + "Your really smart computer beat you.";
        }
    }
    else if (choice1 === "paper") {

        if (choice2 === "rock") {
            return "paper wins" + "
" + "You beat the computer, nice job!";
        }
        else {
            return "scissors wins" + "
" + "Your really smart computer beat you.";
        }
    }

    else if (choice1 === "scissors") {

        if (choice2 === "rock") {
            return "rock wins" + "
" + "Your really smart computer beat you.";
        }
        else {
            return "scissors win" + "
" + "You beat the computer, nice job!";
        }
    }

} //closes compare function
document.write("Computer chose: " + computerChoice + "
");
document.write(compare(userChoice, computerChoice));


问:
Default value for Access-Control-Allow-Methods
I just learned about the Access-Control-Allow-Methods header, e.g.

```<code>Access-Control-Allow-Methods: OPTIONS, HEAD, GET
</code>```

I have never used this header (just Access-Control-Allow-Origin), but I have gotten CORS to work in the past.

Is the default to allow all methods, or have I gotten lucky with undefined behavior?

答:
The default of Access-Control-Allow-Methods is to allow through all simple methods, even on preflight requests. As the flow on https://www.w3.org/TR/cors/#preflight-request says (step 7 of successful preflight request):

If request method is not a case-sensitive match for any method in methods and is not a simple method, apply the cache and network error steps.

And the definition of simple method is:

A method is said to be a simple method if it is a case-sensitive match for one of the following: GET HEAD POST

So if you have a preflighted POST request (due to a custom HTTP header, say), and do not send a Access-Control-Allow-Methods response header, the request will still go ahead okay.

Body:
I just learned about the Access-Control-Allow-Methods header, e.g.

Access-Control-Allow-Methods: OPTIONS, HEAD, GET

I have never used this header (just Access-Control-Allow-Origin), but I have gotten CORS to work in the past.

Is the default to allow all methods, or have I gotten lucky with undefined behavior?


问:
Missing EXIF info in images selected from gallery using EXTERNAL_CONTENT_URI
I'm trying to gather EXIF info (date of picture taken, geotagging, orientation) from images selected from an EXTERNAL_CONTENT_URI intent, but it seems that if the pictures come from the internet (e.g. Google Photos) the EXIF data is somehow truncated.

For example if I download a picture from a web browser from photos.google.com on my PC, its size is 4.377.104 bytes, and all the EXIF data are there.
While if I download the same exact image using the command:

```<code>Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
</code>```

its size is 4.363.578 bytes (13526 bytes less than the original) and all the EXIF data are lost

Any idea on how to download the full original image?

PS: if I select a picture from the gallery which was taken from the phone and it is still resident on the phone's storage, the EXIF data are present

答:
I finally found out a solution. after getting the source image Uri in the onActivityResult method using

```<code>Uri selectedImage = data.getData();
</code>```

I use the following function to get the necessary data from the picture

```<code>public static ImageInfo getImageInfo(Context context, Uri photoUri) {

        Cursor cursor = context.getContentResolver().query(photoUri,
                new String[] {
                        MediaStore.Images.ImageColumns.ORIENTATION,
                        MediaStore.Images.ImageColumns.LATITUDE,
                        MediaStore.Images.ImageColumns.LONGITUDE,
                        MediaStore.Images.ImageColumns.DATE_TAKEN } , null, null, null);

        if (cursor.getCount() != 1) {
            return null;
        }

        cursor.moveToFirst();

        ImageInfo i = new ImageInfo();
        i.Orientation = cursor.getInt(0);
        i.Lat = cursor.getDouble(1);
        i.Lon = cursor.getDouble(2);
        i.DateTakenUTC = cursor.getLong(3)/1000;

        cursor.close();

        return i;
    }
</code>```

Body:
I'm trying to gather EXIF info (date of picture taken, geotagging, orientation) from images selected from an EXTERNAL_CONTENT_URI intent, but it seems that if the pictures come from the internet (e.g. Google Photos) the EXIF data is somehow truncated.

For example if I download a picture from a web browser from photos.google.com on my PC, its size is 4.377.104 bytes, and all the EXIF data are there.
While if I download the same exact image using the command:

Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

its size is 4.363.578 bytes (13526 bytes less than the original) and all the EXIF data are lost

Any idea on how to download the full original image?

PS: if I select a picture from the gallery which was taken from the phone and it is still resident on the phone's storage, the EXIF data are present

Body:
I finally found out a solution. after getting the source image Uri in the onActivityResult method using

Uri selectedImage = data.getData();

I use the following function to get the necessary data from the picture

public static ImageInfo getImageInfo(Context context, Uri photoUri) {

        Cursor cursor = context.getContentResolver().query(photoUri,
                new String[] {
                        MediaStore.Images.ImageColumns.ORIENTATION,
                        MediaStore.Images.ImageColumns.LATITUDE,
                        MediaStore.Images.ImageColumns.LONGITUDE,
                        MediaStore.Images.ImageColumns.DATE_TAKEN } , null, null, null);

        if (cursor.getCount() != 1) {
            return null;
        }

        cursor.moveToFirst();

        ImageInfo i = new ImageInfo();
        i.Orientation = cursor.getInt(0);
        i.Lat = cursor.getDouble(1);
        i.Lon = cursor.getDouble(2);
        i.DateTakenUTC = cursor.getLong(3)/1000;

        cursor.close();

        return i;
    }


问:
align histogram and scatter plot in R
I am trying to show two plots, one histogram and one scatter plot, and I wanted them to be aligned with respect to x-axis. I have created my histogram with hist() and my scatter plot with ggplot2. However, I found problems to create a multiplot mixing these two, so I decided to create the histogram with ggplot2. Please, find below the codes:

```<code>loadedimage <- readTIFF("my_data05.tiff")
rasterizedimage <- rasterGrob(loadedimage, interpolate = TRUE)
realmadrid_colors <-c("#00529f", "#8cc1f3", "blue")
data_test <- subset(full_data, Rival == "Barcelona")
data_kroos <- subset(data_test, Jugador == "Kroos")

myscatter <- ggplot(data_kroos, aes(x = x1, y = y1)) +
  annotation_custom(rasterizedimage, xmin = 0, xmax = 713, ymin = 0 , ymax = 497) +
  geom_point(aes(fill = factor(data_kroos$Resultado)),
         shape = 21,
         size = 5) +
  scale_fill_manual(values=realmadrid_colors) +
  guides(fill=guide_legend(title=NULL)) +
  coord_fixed() +
  theme_bw() +
  theme_no_axes(base.theme = theme_bw()) +
  theme(legend.position = c(0.5, 0.04),
    legend.box = "horizontal",
    legend.direction = "horizontal",
    legend.box.background = element_rect(fill = NA, colour = "transparent"),
    legend.text = element_text(family = "Courier", size = 14),
    axis.title = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    plot.margin=unit(c(-0.05,-0.05,-0.05,-0.1),"in")
    )

myhistogram <- qplot(data_barca[data_barca$Sección == "Passes_All",]$x1, breaks=seq(0, 660, by = 66), alpha = 0.5, geom = "histogram")
</code>```

If I try using grid.newpage() and grid.draw(), I get an error message: ncol(x) == ncol(y) is not TRUE

```<code>grid.newpage()
grid.draw(rbind(ggplotGrob(myscatter), ggplotGrob(myhistogram), size = "first"))
</code>```

I want to get something like in http://biokit.readthedocs.io/en/latest/auto_examples/plot_scatter.html
(indeed I am still in the first step, my target is to exactly as in the former link), or something like combine histogram with scatter plot in R, but in that case it is not used ggplot2, and I am not sure if I can play around like using that package.

Any help is welcome! If you need me to upload any file, please, let me know.

Thanks in advance!

答:
A further search maybe is the answer for me! The word I was looking for is marginal histograms!

Scatterplot with marginal histograms in ggplot2

Title: align histogram and scatter plot in R

Body:
I am trying to show two plots, one histogram and one scatter plot, and I wanted them to be aligned with respect to x-axis. I have created my histogram with hist() and my scatter plot with ggplot2. However, I found problems to create a multiplot mixing these two, so I decided to create the histogram with ggplot2. Please, find below the codes:

loadedimage <- readTIFF("my_data05.tiff")
rasterizedimage <- rasterGrob(loadedimage, interpolate = TRUE)
realmadrid_colors <-c("#00529f", "#8cc1f3", "blue")
data_test <- subset(full_data, Rival == "Barcelona")
data_kroos <- subset(data_test, Jugador == "Kroos")

myscatter <- ggplot(data_kroos, aes(x = x1, y = y1)) +
  annotation_custom(rasterizedimage, xmin = 0, xmax = 713, ymin = 0 , ymax = 497) +
  geom_point(aes(fill = factor(data_kroos$Resultado)),
         shape = 21,
         size = 5) +
  scale_fill_manual(values=realmadrid_colors) +
  guides(fill=guide_legend(title=NULL)) +
  coord_fixed() +
  theme_bw() +
  theme_no_axes(base.theme = theme_bw()) +
  theme(legend.position = c(0.5, 0.04),
    legend.box = "horizontal",
    legend.direction = "horizontal",
    legend.box.background = element_rect(fill = NA, colour = "transparent"),
    legend.text = element_text(family = "Courier", size = 14),
    axis.title = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    plot.margin=unit(c(-0.05,-0.05,-0.05,-0.1),"in")
    )

myhistogram <- qplot(data_barca[data_barca$Sección == "Passes_All",]$x1, breaks=seq(0, 660, by = 66), alpha = 0.5, geom = "histogram")

If I try using grid.newpage() and grid.draw(), I get an error message: ncol(x) == ncol(y) is not TRUE

grid.newpage()
grid.draw(rbind(ggplotGrob(myscatter), ggplotGrob(myhistogram), size = "first"))

I want to get something like in http://biokit.readthedocs.io/en/latest/auto_examples/plot_scatter.html
(indeed I am still in the first step, my target is to exactly as in the former link), or something like combine histogram with scatter plot in R, but in that case it is not used ggplot2, and I am not sure if I can play around like using that package.

Any help is welcome! If you need me to upload any file, please, let me know.

Thanks in advance!


问:
data union with tables
I have below query

```<code>SELECT Vehicle_ID,Total_Weight,date,bilty_No FROM harvesting
UNION
SELECT Vehicle_ID,Total_Weight,date,Bilty_No FROM Blade_Harvesting
</code>```

Now i want to show vehicle_name instead of vehicle_ID from vehicle table..
how can i add vehicle table and show name instead of ID?

答:
Try this query --</p>

```<code> SELECT Vehicle_Name
    ,Total_Weight
    ,DATE
    ,bilty_No
FROM harvesting H
INNER JOIN Vehicle V
ON H.Vehicle_ID = V.Vehicle_ID

UNION

SELECT Vehicle_Name
    ,Total_Weight
    ,DATE
    ,Bilty_No
FROM Blade_Harvesting BH
INNER JOIN Vehicle V
ON BH.Vehicle_ID = V.Vehicle_ID
</code>```

Title: data union with tables

Body:
I have below query

SELECT Vehicle_ID,Total_Weight,date,bilty_No FROM harvesting
UNION
SELECT Vehicle_ID,Total_Weight,date,Bilty_No FROM Blade_Harvesting

Now i want to show vehicle_name instead of vehicle_ID from vehicle table..
how can i add vehicle table and show name instead of ID?

Body:
Try this query --

 SELECT Vehicle_Name
    ,Total_Weight
    ,DATE
    ,bilty_No
FROM harvesting H
INNER JOIN Vehicle V
ON H.Vehicle_ID = V.Vehicle_ID

UNION

SELECT Vehicle_Name
    ,Total_Weight
    ,DATE
    ,Bilty_No
FROM Blade_Harvesting BH
INNER JOIN Vehicle V
ON BH.Vehicle_ID = V.Vehicle_ID


问:
How do pyplot functions (show, savefig, etc) work without "object" being passed in?
How do pyplot functions such as show() and savefig() not require a "plot object" to work?

For example, the following code works, but somehow I expect to use a file handler or pass a "plot object" into plt.show() and plot.savefig("venn3.pdf").

```<code>from matplotlib import pyplot as plt
from matplotlib_venn import venn3, venn3_circles

# Subset sizes
s = (2,3,4,3,1,0.5,4)

v = venn3(subsets=s, set_labels=('A', 'B', 'C'))

# Subset labels
v.get_label_by_id('100').set_text('Abc')
v.get_label_by_id('010').set_text('aBc')
v.get_label_by_id('110').set_text('ABc')
v.get_label_by_id('001').set_text('Abc')
v.get_label_by_id('101').set_text('aBc')
v.get_label_by_id('011').set_text('ABc')
v.get_label_by_id('111').set_text('ABC')

# Subset colors
v.get_patch_by_id('100').set_color('c')
v.get_patch_by_id('010').set_color('#993333')
v.get_patch_by_id('110').set_color('blue')

# Subset alphas
v.get_patch_by_id('101').set_alpha(0.4)
v.get_patch_by_id('011').set_alpha(1.0)
v.get_patch_by_id('111').set_alpha(0.7)

# Border styles
c = venn3_circles(subsets=s, linestyle='solid')
c[0].set_ls('dotted')  # Line style
c[1].set_ls('dashed')
c[2].set_lw(1.0)       # Line width

plt.show() # For show() to work without using variable v seems counter-intuitive to me.
plt.savefig("venn3.pdf") # For savefig() to work without using variable v seems counter-intuitive to me.
</code>```

2[]

答:
matplotlib.pyplot is often called "statemachine". This means that the function it provides do certain things depending on the internal state of pyplot.

In your code, you have created a figure and this is stored as an object; pyplot knows it has one figure.

If you then call other commands, it is assumend that they apply to that one figure which has been created previously, like plt.savefig.

plt.show() would work on all previously created figures (all of them would be shown).

Body:
How do pyplot functions such as show() and savefig() not require a "plot object" to work?

For example, the following code works, but somehow I expect to use a file handler or pass a "plot object" into plt.show() and plot.savefig("venn3.pdf").

from matplotlib import pyplot as plt
from matplotlib_venn import venn3, venn3_circles

# Subset sizes
s = (2,3,4,3,1,0.5,4)

v = venn3(subsets=s, set_labels=('A', 'B', 'C'))

# Subset labels
v.get_label_by_id('100').set_text('Abc')
v.get_label_by_id('010').set_text('aBc')
v.get_label_by_id('110').set_text('ABc')
v.get_label_by_id('001').set_text('Abc')
v.get_label_by_id('101').set_text('aBc')
v.get_label_by_id('011').set_text('ABc')
v.get_label_by_id('111').set_text('ABC')

# Subset colors
v.get_patch_by_id('100').set_color('c')
v.get_patch_by_id('010').set_color('#993333')
v.get_patch_by_id('110').set_color('blue')

# Subset alphas
v.get_patch_by_id('101').set_alpha(0.4)
v.get_patch_by_id('011').set_alpha(1.0)
v.get_patch_by_id('111').set_alpha(0.7)

# Border styles
c = venn3_circles(subsets=s, linestyle='solid')
c[0].set_ls('dotted')  # Line style
c[1].set_ls('dashed')
c[2].set_lw(1.0)       # Line width

plt.show() # For show() to work without using variable v seems counter-intuitive to me.
plt.savefig("venn3.pdf") # For savefig() to work without using variable v seems counter-intuitive to me.

2[]


问:
How does daylight saving work in php (difference between php and hhvm)?
I need to detect when a timestamp is in daylight saving or not.

I'm using this code to test the functionality:

```<code><?php
date_default_timezone_set('Europe/Berlin');

$timestamp = $baseTimestamp = 1509234900; // Sunday, 29 October of 2017 1:55:00 GMT+02:00 DST
$date = (new DateTime)->setTimestamp($baseTimestamp);

echo "DateTime\t\t| Is in summer \t| Minutes passed\n";

for($i = 0; $i < 70; $i++) {
    $date = (new DateTime)->setTimestamp($timestamp);
    echo $date->format("Y-m-d H:i:s \t|I") . "\t\t| " . ($timestamp - $baseTimestamp)/60 . "\n";
    $timestamp = $timestamp + 60;
}
</code>```

https://3v4l.org/dqNlK

Working with Europe/Berlin, I've seen that in March, when at 2.00 we pass from winter to summer, php solves it right, but then in October, when it is supposed to come back from summer to winter at 3.00, it doesn't work as expected.

In this case, we have two timestamps corresponding to the same hour (at 3 is 2 again), but the timestamp is unique, so for 2.00 there must be one timestamp in the summer time and another one in the winter time.

Using hhvm, it shows the right value, but normal php interpreters show that is not in summer for both 2.00 (the first one, which is 2am and the second one which is when at 3am is 2am again. This is the one that should say is not in summer anymore)

答:
```<code>function isSummer($timestamp) {
    $date = (new DateTime)->setTimestamp($timestamp);

    if ($date->format('I') == 1) {
        return true;
    }

   return ($date->getTimestamp() > $timestamp);
}
</code>```

I think this is going to do the trick

Body:
I need to detect when a timestamp is in daylight saving or not.

I'm using this code to test the functionality:

<?php
date_default_timezone_set('Europe/Berlin');

$timestamp = $baseTimestamp = 1509234900; // Sunday, 29 October of 2017 1:55:00 GMT+02:00 DST
$date = (new DateTime)->setTimestamp($baseTimestamp);

echo "DateTime\t\t| Is in summer \t| Minutes passed\n";

for($i = 0; $i < 70; $i++) {
    $date = (new DateTime)->setTimestamp($timestamp);
    echo $date->format("Y-m-d H:i:s \t|I") . "\t\t| " . ($timestamp - $baseTimestamp)/60 . "\n";
    $timestamp = $timestamp + 60;
}

https://3v4l.org/dqNlK

Working with Europe/Berlin, I've seen that in March, when at 2.00 we pass from winter to summer, php solves it right, but then in October, when it is supposed to come back from summer to winter at 3.00, it doesn't work as expected.

In this case, we have two timestamps corresponding to the same hour (at 3 is 2 again), but the timestamp is unique, so for 2.00 there must be one timestamp in the summer time and another one in the winter time.

Using hhvm, it shows the right value, but normal php interpreters show that is not in summer for both 2.00 (the first one, which is 2am and the second one which is when at 3am is 2am again. This is the one that should say is not in summer anymore)

Body:
function isSummer($timestamp) {
    $date = (new DateTime)->setTimestamp($timestamp);

    if ($date->format('I') == 1) {
        return true;
    }

   return ($date->getTimestamp() > $timestamp);
}

I think this is going to do the trick


问:
How to bind a read-only WPF control property (eg ActualWidth) so its value is accessible in the view model?
I want to bind a read-only property of a control to my view model so that the value is available in the view model.

What is the best way of doing this?

For example I'd like to bind ActualWidth to a property in my view model.  The width value is generated by WPF using its layout logic so I can't generate this value in my view model and push it to the control property, as would normally be the case.  Instead I need to have WPF generate the value and push it to the view model.

I would just use Mode=OneWayToSource, but this doesn't work for read-only properties:

```<code>  <Border
      ...
      ActualWidth="{Binding MyDataModelWidth, Mode=OneWayToSource}"
      >
      ... child controls ...
  </Border>
</code>```

The way I am doing it currently is to handle SizeChanged for the border and the code-behind plugs the value into the view model, but this doesn't feel quite right.

Has anyone already solved this problem?

UPDATE:
My question is effectively a duplicate of this one:
Pushing read-only GUI properties back into ViewModel

答:
The actual problem as to why this is not working is described here.

However, the given solution to create a throwing setter to pass the validation would not work in your case.

I think it's ok to call a method on the ViewModel. If that's the code behind part that bugs you, perhaps you can use interactivity to call a method based on an event trigger (SizeChanged).

Body:
I want to bind a read-only property of a control to my view model so that the value is available in the view model.

What is the best way of doing this?

For example I'd like to bind ActualWidth to a property in my view model.  The width value is generated by WPF using its layout logic so I can't generate this value in my view model and push it to the control property, as would normally be the case.  Instead I need to have WPF generate the value and push it to the view model.

I would just use Mode=OneWayToSource, but this doesn't work for read-only properties:

  <Border
      ...
      ActualWidth="{Binding MyDataModelWidth, Mode=OneWayToSource}"
      >
      ... child controls ...
  </Border>

The way I am doing it currently is to handle SizeChanged for the border and the code-behind plugs the value into the view model, but this doesn't feel quite right.

Has anyone already solved this problem?

UPDATE:
My question is effectively a duplicate of this one:
Pushing read-only GUI properties back into ViewModel


问:
How to show a carto map in an ionic 2 app?
Has anyone shown a carto map in an ionic 2 app? When I used ionic 1 there was no problem, because it is angular js and I could add the library in the index.html:

and then use it in a controller.js like that:

```<code>var mapa; mapa = new L.Map('mapa', { center: [39,-6], zoom: 9 })
</code>```

But the problem is that now I'm using ionic 2, so it's angular 2, typescript. After adding the libraries I try to do the same code above in the .ts file, but it can't find the name L.

Has anyone idea how to show my map? Or how to use a js library in typescript?

I'm not sure if I explained well the problem, so any doubt, ask me please.

Thanks!

答:
in index.html add this:

```<code><link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.15/themes/css/cartodb.css">
  <script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script>
</code>```

in page.ts file add this:

```<code>import L from 'leaflet';
</code>```

and alsodeclare L for avoiding from that error:

declare var L: any;

Body:
Has anyone shown a carto map in an ionic 2 app? When I used ionic 1 there was no problem, because it is angular js and I could add the library in the index.html:

and then use it in a controller.js like that:

var mapa; mapa = new L.Map('mapa', { center: [39,-6], zoom: 9 })

But the problem is that now I'm using ionic 2, so it's angular 2, typescript. After adding the libraries I try to do the same code above in the .ts file, but it can't find the name L.

Has anyone idea how to show my map? Or how to use a js library in typescript?

I'm not sure if I explained well the problem, so any doubt, ask me please.

Thanks!

Body:
in index.html add this:

<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.15/themes/css/cartodb.css">
  <script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script>

in page.ts file add this:

import L from 'leaflet';

and alsodeclare L for avoiding from that error:

declare var L: any;


问:
Submit form is not triggger in jquery
Here is the form:

```<code><form name="frmSelect" id="frmSelect" method="post" action="./abc.php">
  <input type="submit" value="To Confirm" name="To-Confirm" />
  <span>Click</span>
</form>
</code>```

Jquery:

```<code>span.onclick = function() {
  alert($('#frmSelect').length);

  $('#frmSelect').submit(function() {
    alert('abc');
    //var data = $("#frmSelect :input").serializeArray();
    //alert('Handler for .submit() called.');
    //OR
    //document.frmSelect.submit(); <-- Not Working Too
    //var x = document.getElementsByName("To-Confirm").value; <-- Always "undefined".
  });
}
</code>```

When I clicked on a  element, I am able to get the first alert with "1" (the length of form), but I am not able to get the second alert (which is abc).

p.s. there are many form elements but different name.

答:
You can use this

$("span").on("click",function() {
    console.log("clicked");
    $('#frmSelect').submit();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<form name="frmSelect" id="frmSelect" method="post" action="./abc.php">
      <input type="submit" value="To Confirm" name="To-Confirm" />
      <span>Click</span>
</form></code>```

Title: Submit form is not triggger in jquery

Body:
Here is the form:

<form name="frmSelect" id="frmSelect" method="post" action="./abc.php">
  <input type="submit" value="To Confirm" name="To-Confirm" />
  Click
</form>

Jquery:

span.onclick = function() {
  alert($('#frmSelect').length);

  $('#frmSelect').submit(function() {
    alert('abc');
    //var data = $("#frmSelect :input").serializeArray();
    //alert('Handler for .submit() called.');
    //OR
    //document.frmSelect.submit(); <-- Not Working Too
    //var x = document.getElementsByName("To-Confirm").value; <-- Always "undefined".
  });
}

When I clicked on a  element, I am able to get the first alert with "1" (the length of form), but I am not able to get the second alert (which is abc).

p.s. there are many form elements but different name.

Body:
You can use this

$("span").on("click",function() {
    console.log("clicked");
    $('#frmSelect').submit();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<form name="frmSelect" id="frmSelect" method="post" action="./abc.php">
      <input type="submit" value="To Confirm" name="To-Confirm" />
      <span>Click</span>
</form>


问:
Define Java POJO so Gson does not write value double quoted
Note is this example javascript

```<code><html>
<head>
<script type="text/javascript">
window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer",
    {
        title: {
            text: "Using labelFormatter function of axisY"
        },
        axisY:{
            labelFormatter: function(e){
                return  "Y: " + e.value;
            }
        },
        data: [
        {
            type: "spline",
            dataPoints: [
                { y: 5  },
                { y: 9  },
                { y: 17 },
                { y: 32 },
                { y: 22 },
                { y: 14 },
                { y: 25 },
                { y: 18 },
                { y: 20 }
            ]
        }
        ]
    });
    chart.render();
}
</script>
<script type="text/javascript" src="/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
</code>```

from http://canvasjs.com/docs/charts/chart-options/axisy/label-formatter/ that the value of labelFormatter field is not double quoted, and if I modify it to be double quoted then the code does not work.

I dont understand the Javascript rules for when it shoud/not be double quoted but it seems functions must not be.

I am trying to generate such code from Java using Gson, how do I create my POJO so that its value is not double quoted when output to json. Currently it is just defined as type String and therefore gets double quoted.

e.g

```<code>public class AxisY
{
    private boolean reversed;
    private int     labelMaxWidth;
    private boolean labelWrap;
    private String  title;
    private int     viewportMinimum = 0;
    private int     viewportMaximum;
    private int     interval;
    private String  labelFormatter;

    public boolean isReversed()
    {
        return reversed;
    }

    public void setReversed(boolean reversed)
    {
        this.reversed = reversed;
    }

    public int getLabelMaxWidth()
    {
        return labelMaxWidth;
    }

    public void setLabelMaxWidth(int labelMaxWidth)
    {
        this.labelMaxWidth = labelMaxWidth;
    }

    public boolean isLabelWrap()
    {
        return labelWrap;
    }

    public void setLabelWrap(boolean labelWrap)
    {
        this.labelWrap = labelWrap;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public int getViewportMinimum()
    {
        return viewportMinimum;
    }

    public void setViewportMinimum(int viewportMinimum)
    {
        this.viewportMinimum = viewportMinimum;
    }

    public int getViewportMaximum()
    {
        return viewportMaximum;
    }

    public void setViewportMaximum(int viewportMaximum)
    {
        this.viewportMaximum = viewportMaximum;
    }

    public int getInterval()
    {
        return interval;
    }

    public void setInterval(int interval)
    {
        this.interval = interval;
    }

    public String getLabelFormatter()
    {
        return labelFormatter;
    }

    public void setLabelFormatter(String labelFormatter)
    {
        this.labelFormatter = labelFormatter;
    }
}

  <!DOCTYPE HTML>
    <html>
    <head>
    <script type="text/javascript">
    window.onload = function () {
        var chart = new CanvasJS.Chart("chartContainer",
        {
            title: {
                text: "Using labelFormatter function of axisY"
            },
            axisY:{
                labelFormatter: function(e){
                    return  "Y: " + e.value;
                }
            },
            data: [
            {
                type: "spline",
                dataPoints: [
                    { y: 5  },
                    { y: 9  },
                    { y: 17 },
                    { y: 32 },
                    { y: 22 },
                    { y: 14 },
                    { y: 25 },
                    { y: 18 },
                    { y: 20 }
                ]
            }
            ]
        });
        chart.render();
    }
    </script>
    <script type="text/javascript" src="/assets/script/canvasjs.min.js"></script>
    </head>
    <body>
    <div id="chartContainer" style="height: 300px; width: 100%;"></div>
    </body>
    </html>
</code>```

答:
I dont understand the Javascript rules for when it shoud/not be double quoted but it seems functions must not be.

You're mixing JavaScript code and JavaScript Object Notation (JSON). Functions do not exist in JSON (see its grammar), the latter just serves data persistence/transfer responsibilities (exactly what jjones suggests as well). Therefore Gson treats all strings as string literals -- and that's why you're getting your function-containing string to be escaped. This is the way it's supposed to work.

Security concerns

Another thing I would not recommend is transferring JavaScript code directly  in JSON. This is a clear security concern. I would better pass labelFormatter value as a simple name to let the front-end code pick up a proper function by name (what if someone sends labelFormatter as function(){stealSessionCookies();}?). Say,

(from the server)

```<code>{
    "axisY": {
        "labelFormatterStyleName": "y-by-name"
    }
}
</code>```

(something like that at the client)

```<code>var labelFormatterStyles = {
    "y-by-name": function(e) {
        return "Y: " + e.value;
    }
}

var chartConfiguration = { // or something more JS-idiomatic to avoid field-by-field assignments
                           // I didn't write in JS for long time
    axisY: {
        labelFormatter: labelFormatterStyles[serverResponse.labelFormatterStyleName]
    }
};
new CanvasJS.Chart("chartContainer", chartConfiguration);
</code>```

If you're still convinced to do this with Gson

If for whatever solid reason you still need to generate such stuff at your server side, you can adapt your Gson to emit "more JavaScript-like" code.

final class ChartData {

    final Title title;
    final Axis axisY;
    final List<Datum> data;

    ChartData(final Title title, final Axis axisY, final List<Datum> data) {
        this.title = title;
        this.axisY = axisY;
        this.data = data;
    }

}
```

<pre class="lang-java prettyprint-override"><code>final class Title {

    final String text;

    Title(final String text) {
        this.text = text;
    }

}
</code>```

final class Axis {

    @JsonAdapter(RawStringTypeAdapter.class)
    final String labelFormatter;

    Axis(final String labelFormatter) {
        this.labelFormatter = labelFormatter;
    }

}
```

<pre class="lang-java prettyprint-override"><code>final class Datum {

    final String type;
    final List<DataPoint> dataPoints;

    Datum(final String type, final List<DataPoint> dataPoints) {
        this.type = type;
        this.dataPoints = dataPoints;
    }

}
</code>```

final class DataPoint {

    final double y;

    DataPoint(final double y) {
        this.y = y;
    }

}
```

<p>Note that the <code>Axis</code> class has a field annotated with <code>@JsonAdapter(RawStringTypeAdapter.class)</code>. This is a special directive to tell Gson apply a special (de)serialization strategy. We can bind one to emit a raw string value. For example:</p>

<pre class="lang-java prettyprint-override"><code>final class RawStringTypeAdapter
        extends TypeAdapter<String> {

    // Gson can do it itself
    private RawStringTypeAdapter() {
    }

    @Override
    public void write(final JsonWriter out, final String value)
            throws IOException {
        // not out.value(value)!
        out.jsonValue(value);
    }

    @Override
    public String read(final JsonReader in)
            throws IOException {
        return in.nextString();
    }

}
</code>```

Test:

final ChartData chartData = new ChartData(
        new Title("Using labelFormatter function of axisY"),
        new Axis(
                "function(e) { return \"Y: \" + e.value; }"
        ),
        ImmutableList.of(
                new Datum(
                        "spline",
                        ImmutableList.of(
                                new DataPoint(5),
                                new DataPoint(9),
                                new DataPoint(17),
                                new DataPoint(32),
                                new DataPoint(22),
                                new DataPoint(14),
                                new DataPoint(25),
                                new DataPoint(18),
                                new DataPoint(20)
                        )
                )
        )
);
gson.toJson(chartData, System.out);
```

<p>Output (partial minification mine):</p>

```{
  "title": {
    "text": "Using labelFormatter function of axisY"
  },
  "axisY": {
    "labelFormatter": function(e) { return "Y: " + e.value; }
  },
  "data": [
    {
      "type": "spline",
      "dataPoints": [
        {"y": 5.0},
        {"y": 9.0},
        {"y": 17.0},
        {"y": 32.0},
        {"y": 22.0},
        {"y": 14.0},
        {"y": 25.0},
        {"y": 18.0},
        {"y": 20.0}
      ]
    }
  ]
}
```

However, I wouldn't recommend you to generate JavaScript code at the back end: except of the security concerns, it's easier to change and redeploy JavaScript code.

Body:
Note is this example javascript

from http://canvasjs.com/docs/charts/chart-options/axisy/label-formatter/ that the value of labelFormatter field is not double quoted, and if I modify it to be double quoted then the code does not work.

I dont understand the Javascript rules for when it shoud/not be double quoted but it seems functions must not be.

I am trying to generate such code from Java using Gson, how do I create my POJO so that its value is not double quoted when output to json. Currently it is just defined as type String and therefore gets double quoted.

e.g

public class AxisY
{
    private boolean reversed;
    private int     labelMaxWidth;
    private boolean labelWrap;
    private String  title;
    private int     viewportMinimum = 0;
    private int     viewportMaximum;
    private int     interval;
    private String  labelFormatter;

    public boolean isReversed()
    {
        return reversed;
    }

    public void setReversed(boolean reversed)
    {
        this.reversed = reversed;
    }

    public int getLabelMaxWidth()
    {
        return labelMaxWidth;
    }

    public void setLabelMaxWidth(int labelMaxWidth)
    {
        this.labelMaxWidth = labelMaxWidth;
    }

    public boolean isLabelWrap()
    {
        return labelWrap;
    }

    public void setLabelWrap(boolean labelWrap)
    {
        this.labelWrap = labelWrap;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public int getViewportMinimum()
    {
        return viewportMinimum;
    }

    public void setViewportMinimum(int viewportMinimum)
    {
        this.viewportMinimum = viewportMinimum;
    }

    public int getViewportMaximum()
    {
        return viewportMaximum;
    }

    public void setViewportMaximum(int viewportMaximum)
    {
        this.viewportMaximum = viewportMaximum;
    }

    public int getInterval()
    {
        return interval;
    }

    public void setInterval(int interval)
    {
        this.interval = interval;
    }

    public String getLabelFormatter()
    {
        return labelFormatter;
    }

    public void setLabelFormatter(String labelFormatter)
    {
        this.labelFormatter = labelFormatter;
    }
}

  <!DOCTYPE HTML>

Body:
I dont understand the Javascript rules for when it shoud/not be double quoted but it seems functions must not be.

You're mixing JavaScript code and JavaScript Object Notation (JSON). Functions do not exist in JSON (see its grammar), the latter just serves data persistence/transfer responsibilities (exactly what jjones suggests as well). Therefore Gson treats all strings as string literals -- and that's why you're getting your function-containing string to be escaped. This is the way it's supposed to work.

Security concerns

Another thing I would not recommend is transferring JavaScript code directly  in JSON. This is a clear security concern. I would better pass labelFormatter value as a simple name to let the front-end code pick up a proper function by name (what if someone sends labelFormatter as function(){stealSessionCookies();}?). Say,

(from the server)

{
    "axisY": {
        "labelFormatterStyleName": "y-by-name"
    }
}

(something like that at the client)

var labelFormatterStyles = {
    "y-by-name": function(e) {
        return "Y: " + e.value;
    }
}

var chartConfiguration = { // or something more JS-idiomatic to avoid field-by-field assignments
                           // I didn't write in JS for long time
    axisY: {
        labelFormatter: labelFormatterStyles[serverResponse.labelFormatterStyleName]
    }
};
new CanvasJS.Chart("chartContainer", chartConfiguration);

If you're still convinced to do this with Gson

If for whatever solid reason you still need to generate such stuff at your server side, you can adapt your Gson to emit "more JavaScript-like" code.

final class ChartData {

    final Title title;
    final Axis axisY;
    final List<Datum> data;

    ChartData(final Title title, final Axis axisY, final List<Datum> data) {
        this.title = title;
        this.axisY = axisY;
        this.data = data;
    }

}

final class Title {

    final String text;

    Title(final String text) {
        this.text = text;
    }

}

final class Axis {

    @JsonAdapter(RawStringTypeAdapter.class)
    final String labelFormatter;

    Axis(final String labelFormatter) {
        this.labelFormatter = labelFormatter;
    }

}

final class Datum {

    final String type;
    final List<DataPoint> dataPoints;

    Datum(final String type, final List<DataPoint> dataPoints) {
        this.type = type;
        this.dataPoints = dataPoints;
    }

}

final class DataPoint {

    final double y;

    DataPoint(final double y) {
        this.y = y;
    }

}

Note that the Axis class has a field annotated with @JsonAdapter(RawStringTypeAdapter.class). This is a special directive to tell Gson apply a special (de)serialization strategy. We can bind one to emit a raw string value. For example:

final class RawStringTypeAdapter
        extends TypeAdapter<String> {

    // Gson can do it itself
    private RawStringTypeAdapter() {
    }

    @Override
    public void write(final JsonWriter out, final String value)
            throws IOException {
        // not out.value(value)!
        out.jsonValue(value);
    }

    @Override
    public String read(final JsonReader in)
            throws IOException {
        return in.nextString();
    }

}

Test:

final ChartData chartData = new ChartData(
        new Title("Using labelFormatter function of axisY"),
        new Axis(
                "function(e) { return \"Y: \" + e.value; }"
        ),
        ImmutableList.of(
                new Datum(
                        "spline",
                        ImmutableList.of(
                                new DataPoint(5),
                                new DataPoint(9),
                                new DataPoint(17),
                                new DataPoint(32),
                                new DataPoint(22),
                                new DataPoint(14),
                                new DataPoint(25),
                                new DataPoint(18),
                                new DataPoint(20)
                        )
                )
        )
);
gson.toJson(chartData, System.out);

Output (partial minification mine):

{
  "title": {
    "text": "Using labelFormatter function of axisY"
  },
  "axisY": {
    "labelFormatter": function(e) { return "Y: " + e.value; }
  },
  "data": [
    {
      "type": "spline",
      "dataPoints": [
        {"y": 5.0},
        {"y": 9.0},
        {"y": 17.0},
        {"y": 32.0},
        {"y": 22.0},
        {"y": 14.0},
        {"y": 25.0},
        {"y": 18.0},
        {"y": 20.0}
      ]
    }
  ]
}

However, I wouldn't recommend you to generate JavaScript code at the back end: except of the security concerns, it's easier to change and redeploy JavaScript code.


问:
rsync .git directory
This question probably is based on my lack of understanding of the role of .gits and git repositories in general but:

Can I rsync a dir with content that I created with git init between machines ?

I have a repository on my laptop, and the only way to get it away from there is scp/rsync to a remote host, from which I can download it again. Could I rsync the complete directory structure between these hosts?

答:
Using rsync to backup .git is possible, but with one catch ( at least to myself)
It can not be updated. The next time you try to rsync it again, you got massive object rename.. and you can not delete those..
Been not familiar with rsync or linux system, I purge the .git backup before I rsync it.

Which is:

```<code>> chmod -R 777 /path/of/your/backup/.git
> rm -fr /path/of/your/backup/.git
> rsync /path/of/your/origin/.git /path/of/your/backup/.git
</code>```

I know, this is very taxing and stupid.. Please let me know is there a better way to do this..

Title: rsync .git directory

Body:
Using rsync to backup .git is possible, but with one catch ( at least to myself)
It can not be updated. The next time you try to rsync it again, you got massive object rename.. and you can not delete those..
Been not familiar with rsync or linux system, I purge the .git backup before I rsync it.

Which is:

> chmod -R 777 /path/of/your/backup/.git
> rm -fr /path/of/your/backup/.git
> rsync /path/of/your/origin/.git /path/of/your/backup/.git

I know, this is very taxing and stupid.. Please let me know is there a better way to do this..


问:
@XmlElementWrapper not taken into account in XML/REST Spring webservice
I want to give custom names to the xml root element and to list elements.
But the annotations don't work.

```<code>@XmlRootElement(name = "test")
@XmlAccessorType(XmlAccessType.FIELD)
public class TestRsp {
    @XmlElementWrapper(name = "persons")
    @XmlElement(name = "pax")
    private List<Person> persons;
}

public class Person {
   private String name;
   private String age;
}
</code>```

Usage:

```<code>@RestController
public class MyServlet {
   @RequestMapping("/test")
   public TestRsp test() {
      //...
      return rsp;
   }
}
</code>```

Result:

```<code><TestRsp> <!-- should be named "test" -->
   <persons>
     <persons> <!-- should be named "pax" -->
       <name />
       <age />
     </persons>
     <persons>
        //...
     </persons>
   </persons>
</TestRsp>
</code>```

So my xml annotations are not picked up. But why?

答:
It turned out I have to use @JacksonXml* annotations instead:

```<code>@JacksonXmlRootElement(localName = "test")
public class TestRsp {
    @JacksonXmlElementWrapper(localName = "persons")
    @JacksonXmlProperty(localName = "pax")
    @JsonProperty(name = "persons")
    private List<Person> persons;
}
</code>```

Body:
I want to give custom names to the xml root element and to list elements.
But the annotations don't work.

@XmlRootElement(name = "test")
@XmlAccessorType(XmlAccessType.FIELD)
public class TestRsp {
    @XmlElementWrapper(name = "persons")
    @XmlElement(name = "pax")
    private List<Person> persons;
}

public class Person {
   private String name;
   private String age;
}

Usage:

@RestController
public class MyServlet {
   @RequestMapping("/test")
   public TestRsp test() {
      //...
      return rsp;
   }
}

Result:

<TestRsp>
   <persons>
     <persons>
       <name />
       <age />
     </persons>
     <persons>
        //...
     </persons>
   </persons>
</TestRsp>

So my xml annotations are not picked up. But why?

Body:
It turned out I have to use @JacksonXml* annotations instead:

@JacksonXmlRootElement(localName = "test")
public class TestRsp {
    @JacksonXmlElementWrapper(localName = "persons")
    @JacksonXmlProperty(localName = "pax")
    @JsonProperty(name = "persons")
    private List<Person> persons;
}


问:
Unable to generate POJO "Hibernate tools reverse engineering using Maven"
I am getting build success but still java files and not generated. I am using hibernate3-maven-plugin 2.2 for generating beans.

Database: Postgres 9.6

My pom.xml

```<code>    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>hibernate3-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <components>
                        <component>
                            <name>hbm2hbmxml</name>
                            <implementation>jdbcconfiguration</implementation>
                            <outputDirectory>target/generated-resources/hibernate3</outputDirectory>
                        </component>
                        <component>
                            <name>hbm2java</name>
                            <implementation>jdbcconfiguration</implementation>
                            <outputDirectory>target/generated-sources/hibernate3</outputDirectory>
                        </component>
                    </components>
                    <componentProperties>
                        <revengfile>src/main/resources/hibernate.reveng.xml</revengfile>
                        <propertyfile>src/main/resources/hibernate.properties</propertyfile>
                        <packagename>com.whatever.domain</packagename>
                        <jdk5>true</jdk5>
                        <ejb3>true</ejb3>
                    </componentProperties>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>cglib</groupId>
                        <artifactId>cglib-nodep</artifactId>
                        <version>2.2.2</version>
                    </dependency>
                    <dependency>
                        <groupId>org.postgresql</groupId>
                        <artifactId>postgresql</artifactId>
                        <version>9.4.1207.jre7</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</code>```

My hibernate.reveng.xml

```<code><hibernate-reverse-engineering>
</hibernate-reverse-engineering>
</code>```

I have not added anything in hibernate.reveng.xml.

Log:

```<code>▶ mvn hibernate3:hbm2java

[INFO] Scanning for projects...
[INFO]
[INFO]
------------------------------------------------------------------------ [INFO] Building demo 0.0.1-SNAPSHOT
[INFO]
------------------------------------------------------------------------ [INFO]
[INFO] >>> hibernate3-maven-plugin:2.2:hbm2java (default-cli) > process-resources @ demo >>>
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ demo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 3 resources
[INFO]
[INFO] <<< hibernate3-maven-plugin:2.2:hbm2java (default-cli) < process-resources @ demo <<<
[INFO]
[INFO] --- hibernate3-maven-plugin:2.2:hbm2java (default-cli) @ demo --- [INFO] using jdbcconfiguration task.
[INFO] Hibernate 3.3.1.GA
[INFO] loaded properties from resource hibernate.properties: {hibernate.connection.username=master, hibernate.default_schema=DBProd, hibernate.connection.password=****, hibernate.dialect=org.hibernate. dialect.PostgreSQLDialect, hibernate.connection.url=jdbc:postgresql://192.168.99.100:5432/DBProd, hibernate.bytecode.use_reflection_optimizer=false, hibernate.connection.driver_class=org.postgresql.Dri ver}
[INFO] Bytecode provider name : javassist
[INFO] using JDK 1.4 java.sql.Timestamp handling
[INFO] Configuration XML file loaded: file:/Users/admin/projects/manish/exp/hbmdemo/test1/src/main/resources/hibernate.cfg.xml [INFO] configuring from url: file:/Users/admin/projects/manish/exp/hbmdemo/test1/src/main/resources/hibernate.cfg.xml
[INFO] Configured SessionFactory: null
[INFO] Configuration Properties file loaded: /Users/admin/projects/manish/exp/hbmdemo/test1/src/main/resources/hibernate.properties [INFO] Override file: /Users/admin/projects/manish/exp/hbmdemo/test1/src/main/resources/hibernate.reveng.xml [INFO] Using Hibernate built-in connection pool (not for production use!) [INFO] Hibernate connection pool size: 20
[INFO] autocommit mode: false
[INFO] using driver: org.postgresql.Driver at URL: jdbc:postgresql://192.168.99.100:5432/DBProd
[INFO] connection properties: {user=master, password=****}
[INFO] RDBMS: PostgreSQL, version: 9.6.2
[INFO] JDBC driver: PostgreSQL Native Driver, version: PostgreSQL 9.4.1207.jre7
[INFO] Using dialect: org.hibernate.dialect.PostgreSQLDialect
[INFO] Using default transaction strategy (direct JDBC transactions)
[INFO] No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
[INFO] Automatic flush during beforeCompletion(): disabled
[INFO] Automatic session close at end of transaction: disabled
[INFO] JDBC batch size: 15
[INFO] JDBC batch updates for versioned data: disabled
[INFO] Scrollable result sets: enabled
[INFO] JDBC3 getGeneratedKeys(): enabled
[INFO] Connection release mode: auto
[INFO] Default schema: DBProd
[INFO] Default batch fetch size: 1
[INFO] Generate SQL with comments: disabled
[INFO] Order SQL updates by primary key: disabled
[INFO] Order SQL inserts for batching: disabled
[INFO] Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory [INFO] Using ASTQueryTranslatorFactory
[INFO] Query language substitutions: {}
[INFO] JPA-QL strict compliance: disabled
[INFO] Second-level cache: enabled
[INFO] Query cache: disabled
[INFO] Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
[INFO] Optimize cache for minimal puts: disabled
[INFO] Structured second-level cache entries: disabled
[INFO] Statistics: disabled
[INFO] Deleted entity synthetic identifier rollback: disabled
[INFO] Default entity-mode: pojo
[INFO] Named query checking : enabled
[INFO] cleaning up connection pool: jdbc:postgresql://192.168.99.100:5432/DBProd
[INFO] Hibernate Tools 3.2.2.GA
[INFO]
------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO]
------------------------------------------------------------------------ [INFO] Total time: 2.121 s
[INFO] Finished at: 2017-04-11T16:15:42+05:30
[INFO] Final Memory: 9M/140M [INFO]
------------------------------------------------------------------------ [INFO] cleaning up connection pool: jdbc:postgresql://192.168.99.100:5432/DBProd
</code>```

I could not found any error in the log. Don't know why it is not creating the POJOs? Any help will be appreciated.

答:
Try to define schema name in hibernate.reveng.xml

```<code><hibernate-reverse-engineering>
   <schema-selection match-schema="GEST_CORSI"/>
</hibernate-reverse-engineering>
</code>```

Body:
I am getting build success but still java files and not generated. I am using hibernate3-maven-plugin 2.2 for generating beans.

Database: Postgres 9.6

My pom.xml

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>hibernate3-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <components>
                        <component>
                            <name>hbm2hbmxml</name>
                            <implementation>jdbcconfiguration</implementation>
                            <outputDirectory>target/generated-resources/hibernate3</outputDirectory>
                        </component>
                        <component>
                            <name>hbm2java</name>
                            <implementation>jdbcconfiguration</implementation>
                            <outputDirectory>target/generated-sources/hibernate3</outputDirectory>
                        </component>
                    </components>
                    <componentProperties>
                        <revengfile>src/main/resources/hibernate.reveng.xml</revengfile>
                        <propertyfile>src/main/resources/hibernate.properties</propertyfile>
                        <packagename>com.whatever.domain</packagename>
                        <jdk5>true</jdk5>
                        <ejb3>true</ejb3>
                    </componentProperties>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>cglib</groupId>
                        <artifactId>cglib-nodep</artifactId>
                        <version>2.2.2</version>
                    </dependency>
                    <dependency>
                        <groupId>org.postgresql</groupId>
                        <artifactId>postgresql</artifactId>
                        <version>9.4.1207.jre7</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

My hibernate.reveng.xml

<hibernate-reverse-engineering>
</hibernate-reverse-engineering>

I have not added anything in hibernate.reveng.xml.

Log:

▶ mvn hibernate3:hbm2java

[INFO] Scanning for projects...
[INFO]
[INFO]
------------------------------------------------------------------------ [INFO] Building demo 0.0.1-SNAPSHOT
[INFO]
------------------------------------------------------------------------ [INFO]
[INFO] >>> hibernate3-maven-plugin:2.2:hbm2java (default-cli) > process-resources @ demo >>>
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ demo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 3 resources
[INFO]
[INFO] <<< hibernate3-maven-plugin:2.2:hbm2java (default-cli) < process-resources @ demo <<<
[INFO]
[INFO] --- hibernate3-maven-plugin:2.2:hbm2java (default-cli) @ demo --- [INFO] using jdbcconfiguration task.
[INFO] Hibernate 3.3.1.GA
[INFO] loaded properties from resource hibernate.properties: {hibernate.connection.username=master, hibernate.default_schema=DBProd, hibernate.connection.password=****, hibernate.dialect=org.hibernate. dialect.PostgreSQLDialect, hibernate.connection.url=jdbc:postgresql://192.168.99.100:5432/DBProd, hibernate.bytecode.use_reflection_optimizer=false, hibernate.connection.driver_class=org.postgresql.Dri ver}
[INFO] Bytecode provider name : javassist
[INFO] using JDK 1.4 java.sql.Timestamp handling
[INFO] Configuration XML file loaded: file:/Users/admin/projects/manish/exp/hbmdemo/test1/src/main/resources/hibernate.cfg.xml [INFO] configuring from url: file:/Users/admin/projects/manish/exp/hbmdemo/test1/src/main/resources/hibernate.cfg.xml
[INFO] Configured SessionFactory: null
[INFO] Configuration Properties file loaded: /Users/admin/projects/manish/exp/hbmdemo/test1/src/main/resources/hibernate.properties [INFO] Override file: /Users/admin/projects/manish/exp/hbmdemo/test1/src/main/resources/hibernate.reveng.xml [INFO] Using Hibernate built-in connection pool (not for production use!) [INFO] Hibernate connection pool size: 20
[INFO] autocommit mode: false
[INFO] using driver: org.postgresql.Driver at URL: jdbc:postgresql://192.168.99.100:5432/DBProd
[INFO] connection properties: {user=master, password=****}
[INFO] RDBMS: PostgreSQL, version: 9.6.2
[INFO] JDBC driver: PostgreSQL Native Driver, version: PostgreSQL 9.4.1207.jre7
[INFO] Using dialect: org.hibernate.dialect.PostgreSQLDialect
[INFO] Using default transaction strategy (direct JDBC transactions)
[INFO] No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
[INFO] Automatic flush during beforeCompletion(): disabled
[INFO] Automatic session close at end of transaction: disabled
[INFO] JDBC batch size: 15
[INFO] JDBC batch updates for versioned data: disabled
[INFO] Scrollable result sets: enabled
[INFO] JDBC3 getGeneratedKeys(): enabled
[INFO] Connection release mode: auto
[INFO] Default schema: DBProd
[INFO] Default batch fetch size: 1
[INFO] Generate SQL with comments: disabled
[INFO] Order SQL updates by primary key: disabled
[INFO] Order SQL inserts for batching: disabled
[INFO] Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory [INFO] Using ASTQueryTranslatorFactory
[INFO] Query language substitutions: {}
[INFO] JPA-QL strict compliance: disabled
[INFO] Second-level cache: enabled
[INFO] Query cache: disabled
[INFO] Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
[INFO] Optimize cache for minimal puts: disabled
[INFO] Structured second-level cache entries: disabled
[INFO] Statistics: disabled
[INFO] Deleted entity synthetic identifier rollback: disabled
[INFO] Default entity-mode: pojo
[INFO] Named query checking : enabled
[INFO] cleaning up connection pool: jdbc:postgresql://192.168.99.100:5432/DBProd
[INFO] Hibernate Tools 3.2.2.GA
[INFO]
------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO]
------------------------------------------------------------------------ [INFO] Total time: 2.121 s
[INFO] Finished at: 2017-04-11T16:15:42+05:30
[INFO] Final Memory: 9M/140M [INFO]
------------------------------------------------------------------------ [INFO] cleaning up connection pool: jdbc:postgresql://192.168.99.100:5432/DBProd

I could not found any error in the log. Don't know why it is not creating the POJOs? Any help will be appreciated.

Body:
Try to define schema name in hibernate.reveng.xml

<hibernate-reverse-engineering>
   <schema-selection match-schema="GEST_CORSI"/>
</hibernate-reverse-engineering>


问:
How to make library for linked-list functions
I want to create static or dynamic library for linked list functions, but when I try to compile function files with gcc to get object file it gives me error ‘struct node’ declared inside parameter list
 int GetNth(struct node* head, int index) & dereferencing pointer to incomplete type ‘struct node’ if(i == index) return head->data;. Not sure what's going on, may be because I haven't declared the structure in the file

```<code>#include <stdlib.h>
int count(struct node* head, int n) //counts the occurrence of n in the list
{
  int c = 0;
  while(head != NULL){
    if(head->data == n) c+=1;
    head = head->next;
  }
  return c;
}
</code>```

But if I'll declare it inside this file, I think it'll violate 1 definition rule. What to do?

structure is declared in the main function as

```<code>struct node{
  int data;
  struct node *next;
}
</code>```

答:
Prior to using objects (you use it, when have access to its members) you must completely define them. So, to use struct node, declare it before its first appearance in the source code. It's the rule of C programming language.

Put the declarations into header file and include the file into source files if you want to create useful libraries, e.g.:

```<code>...
struct node
{
    ...
};

int count(struct node *head, int n);
...
</code>```

Body:
I want to create static or dynamic library for linked list functions, but when I try to compile function files with gcc to get object file it gives me error ‘struct node’ declared inside parameter list
 int GetNth(struct node* head, int index) & dereferencing pointer to incomplete type ‘struct node’ if(i == index) return head->data;. Not sure what's going on, may be because I haven't declared the structure in the file

#include <stdlib.h>
int count(struct node* head, int n) //counts the occurrence of n in the list
{
  int c = 0;
  while(head != NULL){
    if(head->data == n) c+=1;
    head = head->next;
  }
  return c;
}

But if I'll declare it inside this file, I think it'll violate 1 definition rule. What to do?

structure is declared in the main function as

struct node{
  int data;
  struct node *next;
}

Body:
Prior to using objects (you use it, when have access to its members) you must completely define them. So, to use struct node, declare it before its first appearance in the source code. It's the rule of C programming language.

Put the declarations into header file and include the file into source files if you want to create useful libraries, e.g.:

...
struct node
{
    ...
};

int count(struct node *head, int n);
...


问:
PSR-2, Line Wrapping for long argument listsl and Netbeans
According to the PSR-2 Standard on long argument lists:

Argument lists MAY be split across multiple lines, where each subsequent >line is indented once. When doing so, the first item in the list MUST be >on the next line, and there MUST be only one argument per line.

And that would look like this:

```<code><?php
$foo->bar(
    $longArgument,
    $longerArgument,
    $muchLongerArgument
);
</code>```

However, in netbeans, while I have PSR-2 installed into the formatter, when I allow it to autoformat, I get:

```<code>$foo->bar($longArgument, $longerArgument, $muchLongerArgument);
</code>```

I can change it to look like this:

```<code>$foo->bar(
     $longArgument
     , $longerArgument
     , $muchLongerArgument
    );
</code>```

But this violates the standard.  I can also set it to always line-break with a method call, but then I get:

```<code>    $foo->bar($longArgument,
     $longerArgument,
     $muchLongerArgument);
</code>```

Which also does not conform to the standard.  It also automatically changes all method calls, while I want to only change method calls that I deem too long, and I want them to break as described above.

Is there a way to force netbeans to either break in the described way automatically when the line becomes too long ("Wrapping" set to "Too long" doesn't do it), and if not, is there a way I can prevent it from automatically putting my reformatted back onto one line without resorting to a different editor, or turning autoformat off?

答:
Netbeans hasn't good code formatting tools for PHP PSR standards and it's difficult to force it to do. Much more better options is use external tool.

That's look fine:
NetBeans PHP CS Fixer Plugin

You should just configure you setting and done.

Body:
According to the PSR-2 Standard on long argument lists:

Argument lists MAY be split across multiple lines, where each subsequent >line is indented once. When doing so, the first item in the list MUST be >on the next line, and there MUST be only one argument per line.

And that would look like this:

<?php
$foo->bar(
    $longArgument,
    $longerArgument,
    $muchLongerArgument
);

However, in netbeans, while I have PSR-2 installed into the formatter, when I allow it to autoformat, I get:

$foo->bar($longArgument, $longerArgument, $muchLongerArgument);

I can change it to look like this:

$foo->bar(
     $longArgument
     , $longerArgument
     , $muchLongerArgument
    );

But this violates the standard.  I can also set it to always line-break with a method call, but then I get:

    $foo->bar($longArgument,
     $longerArgument,
     $muchLongerArgument);

Which also does not conform to the standard.  It also automatically changes all method calls, while I want to only change method calls that I deem too long, and I want them to break as described above.

Is there a way to force netbeans to either break in the described way automatically when the line becomes too long ("Wrapping" set to "Too long" doesn't do it), and if not, is there a way I can prevent it from automatically putting my reformatted back onto one line without resorting to a different editor, or turning autoformat off?


问:
Android Firebase Google auth only working when run from single computer
I'll try to clarify the title a bit more. I have implemented Google signin with firebase for my Android application. When I tried it on my iMac everything is working fine. I can select the account and login with that account.

The problem occurs when I try to build/run the Android application from another laptop. When I try to login I can still select an account, but upon selecting an account it does not proceed to login and the signin activity reappears. The logs don't show anything.

Here's how I login/logout, but I don't think this is the problem.

```<code>public class AuthController {
private AuthListener authListener;
static final int RC_SIGN_IN = 9001;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

public AuthController(){
    mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(AUTHCONTROLLER_TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(AUTHCONTROLLER_TAG, "onAuthStateChanged:signed_out");
            }
            authListener.onUserAuthenticated(user);
        }
    };
}

public void startAuthStateListener() {
    mAuth.addAuthStateListener(mAuthListener);
}

public void stopAuthStateListener() {
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

public void firebaseAuthWithGoogle(GoogleSignInAccount acct, Activity activity) {
    Log.d(AUTHCONTROLLER_TAG, "firebaseAuthWithGoogle:" + acct.getId());
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(activity, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(AUTHCONTROLLER_TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state authListener will be notified and logic to handle the
                    // signed in user can be handled in the authListener.
                    if (!task.isSuccessful()) {
                        Log.w(AUTHCONTROLLER_TAG, "signInWithCredential", task.getException());
                    }
                }
            });
}

public void signOut() {
    mAuth.signOut();
}

void setAuthListener(AuthListener authListener) {
    this.authListener = authListener;
}

interface AuthListener {
    void onUserAuthenticated(FirebaseUser user);
}
</code>```

I'm guessing it has something to do with the configurations of the keys and/or google-services.json. But i'm not sure how to proceed. The json files are identical on both computers.

Any help would be appreciated.

答:
This is occurring just because your debug SHA key is related to your PC in your firebase console, If you want to access or build from another then also you need to add SHA key for your new PC in firebase console otherwise you can add release SHA key directly and build apk as release and you can access it anywhere,

Steps to add multiple SHA key in Firebase console:

Login in Firebase console,

Select your project

After selecting the project you find the list of apps and from that app, you need to select your app for which you want to add SHA,

Finally, after this, You will able to see add " Add Fingerprint " button bellow "SHA certificate fingerprints " section, Where you can add multiple SHA keys

Body:
I'll try to clarify the title a bit more. I have implemented Google signin with firebase for my Android application. When I tried it on my iMac everything is working fine. I can select the account and login with that account.

The problem occurs when I try to build/run the Android application from another laptop. When I try to login I can still select an account, but upon selecting an account it does not proceed to login and the signin activity reappears. The logs don't show anything.

Here's how I login/logout, but I don't think this is the problem.

public class AuthController {
private AuthListener authListener;
static final int RC_SIGN_IN = 9001;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

public AuthController(){
    mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(AUTHCONTROLLER_TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(AUTHCONTROLLER_TAG, "onAuthStateChanged:signed_out");
            }
            authListener.onUserAuthenticated(user);
        }
    };
}

public void startAuthStateListener() {
    mAuth.addAuthStateListener(mAuthListener);
}

public void stopAuthStateListener() {
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

public void firebaseAuthWithGoogle(GoogleSignInAccount acct, Activity activity) {
    Log.d(AUTHCONTROLLER_TAG, "firebaseAuthWithGoogle:" + acct.getId());
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(activity, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(AUTHCONTROLLER_TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state authListener will be notified and logic to handle the
                    // signed in user can be handled in the authListener.
                    if (!task.isSuccessful()) {
                        Log.w(AUTHCONTROLLER_TAG, "signInWithCredential", task.getException());
                    }
                }
            });
}

public void signOut() {
    mAuth.signOut();
}

void setAuthListener(AuthListener authListener) {
    this.authListener = authListener;
}

interface AuthListener {
    void onUserAuthenticated(FirebaseUser user);
}

I'm guessing it has something to do with the configurations of the keys and/or google-services.json. But i'm not sure how to proceed. The json files are identical on both computers.

Any help would be appreciated.