text:
Q: Best way to make duplicate copies of existing ASPX page in Visual Studio What is the best way to create a copy of an existing ASPX page in a web project in Visual Studio?
If I right click on the ASPX file in the Solution Explorer and select copy, then paste, it looks like what I was expecting. I get a new copy of the ASPX file and the code behind files. I can then rename the ASPX file and the code behind files get renamed as well.
Looking good, until I open the ASPX file. Then I see that it has the same "Inherits" tag that the original file had, and it points to the orginal class name.
Is there something that I am missing? I realize I can mannually edit this, and the code behind files (since they are declaring the same class name, which causes build errors). Is there a better way to do this, or should I just man up and start doing some manual work? :-)

A: I almost always create a brand new page, then just copy the "guts" (leaving page directive info, namespaces, etc) followed shortly by some find and replace if needed.

A: The following works in VS 2013

*

*Copy and paste the desired aspx page using VS right click copy\paste.

*Rename aspx page using right click 'rename'.

*Change Inherits tag at top of aspx page to the new name. (be aware - not all characters allowed).

*View Code.

*Change name of Class to match the Inherits tag in step 3.

A: I think Resharper has a 'Duplicate' refactoring that works on ASPX's as well. The default shortcut should be Ctrl-D

A: I figured it out - so no need for an answer, but I am leaving this here as I think others may find it useful.
What I did is to open one of the aspx page aspx.designer.vb files (they are all identical for my identical code-behind files) and copy the auto-generated WithEvents declarations for the controls.
I then turned the aspx.vb and aspx.designer.vb files into blank files (when I deleted them, the compiler complained that it couldn't find them - not sure yet how to fix that).  Magic!  All my aspx files now point to my new class (and file) and I no longer have the duplicated code.
By the way, this is not just a case of using multi-tier design.  I already had all the substantive code in one place, but I still had to duplicate the calls from Page_Load and various control click functions into that code.  Now I have nothing duplicated...
Brian

A: Similar to Brian's answer.
In VS2013.

*

*Highlight the .aspx you want to copy

*Click CTRL-C, then CTRL-V

You'll see a new aspx created with the same with " - Copy.aspx" at the end

*

*Highlight the new .aspx

*Right-mouse click and select "Rename..."

Type what you want the new .aspx called.  Inherits, etc. are updated automatically.

A: i allready try it and it faild.... so i copy every paragraph on the aspx page alone and paste it in the right place


text:
Q: Dictionary regex I have a function as follows:
HistolMacDescrip <- function(dataframe, MacroColumn) {
  dataframe <- data.frame(dataframe)

  # Column specific cleanup
  dataframe[, MacroColumn] <- str_replace(dataframe[, MacroColumn],
                                          "[Dd]ictated by.*", "")
  # Conversion of text numbers to allow number of biopsies to be extracted
  dataframe[, MacroColumn] <- str_replace(dataframe[, MacroColumn],
                                          "[Oo]ne", "1")
  dataframe[, MacroColumn] <- str_replace(dataframe[, MacroColumn],
                                          "[Ss]ingle", "1")
  dataframe[, MacroColumn] <- str_replace(dataframe[, MacroColumn],
                                          "[Tt]wo", "2")
  dataframe[, MacroColumn] <- str_replace(dataframe[, MacroColumn],
                                          "[Tt]hree", "3")
  dataframe[, MacroColumn] <- str_replace(dataframe[, MacroColumn],
                                          "[Ff]our", "4")
  dataframe[, MacroColumn] <- str_replace(dataframe[, MacroColumn],
                                          "[Ff]ive", "5")
  dataframe[, MacroColumn] <- str_replace(dataframe[, MacroColumn],
                                          "[Ss]ix", "6")
  dataframe[, MacroColumn] <- str_replace(dataframe[, MacroColumn],
                                          "[Ss]even", "7")
  dataframe[, MacroColumn] <- str_replace(dataframe[, MacroColumn],
                                          "[Ee]ight", "8")
  return(dataframe)
}

This strikes me as a bit inefficient. I have other functions that do a similar thing and I'd like to create one function instead that performs this kind of dictionary lookup, perhaps based on an external file that lists key values. Some of the keys will be regexes eg
key                                  value
bus|car|.*toy                     vehicle
\\d+\\s+mg                            dose

Is there a function that can do this kind of dictionary lookup function so that all I have to do is define the dictionary eg in a csv or something?

A: Here is a possible approach
# Function
my_transform <- function (string, lookup) {
  new_string <- string
  vapply(1:nrow(lookup),
         function (k) {
           new_string <<- gsub(lookup$key[k], lookup$value[k], new_string)
           0L
         }, integer(1))
  new_string
}

# Results
# lookup table
lookup <- structure(list(key = c("bus|car|.*toy", "\\d+\\s+mg"),
                         value = c("vehicle","dose")),
                    row.names = 1:2, class = "data.frame")

# string 1
string1 <- c('This car', '256 mg', '6536 \n mg')
my_transform(string1, lookup)
# [1] "This vehicle" "dose"         "dose"

# # string 2
string2 <- c('This car is no toy', '256 mg', '6536 \n mg')
my_transform(string2, lookup)
# [1] "vehicle" "dose"    "dose"

# data frame
df <- data.frame(string1, string2, stringsAsFactors = FALSE)
matrix(my_transform(unlist(df), lookup), nrow(df), ncol(df))
#      [,1]           [,2]
# [1,] "This vehicle" "vehicle"
# [2,] "dose"         "dose"
# [3,] "dose"         "dose"
# or
vapply(1:ncol(df),
       function (k) my_transform(.subset2(df, k), lookup),
       character(nrow(df)))
#      [,1]           [,2]
# [1,] "This vehicle" "vehicle"
# [2,] "dose"         "dose"
# [3,] "dose"         "dose"

So the idea is to store the substitutions in a table and then apply them. Using the above, it should be possible to obtain the desired output.
Note however issues can arise c.f. string2[1]: here you need to make sure what exactly is the desired output for such an instance.
Finally, two final points:

*

*gsub has other useful arguments such as perl (TRUE or FALSE) and fixed (TRUE or FALSE). These could be incorporated into the lookup table by for example adding columns labeled perl, fixed, etc.. This gives you more control.

*there a lot of useful regex functions (c.f. ?sub): depending on your needs, you can either use or combine other functions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does Jest/Vitest do ".not." attributes without using parentheses? How could I replicate it? Right now I'm required to do validate.not().empty(...) and it works fine to negate a "not empty" validation. But after looking at Vitest with the assertions of expect.not.toBe(...) that don't use parentheses, I'm left wondering how this would be coded. I tried a few things with proxies, getters and addProperty but haven't found a solution to replicate this setup.
Right now I just have this:
not() {
    this.is_not = true;
    return this;
}

Is there an easy way to do this or am I better of just using .not(). instead of .not.?

A: You can use Object.defineProperty:
Object.defineProperty(a, 'not', {
    get: function(){
        this.is_not=true;
        return this
    }
})

Note: It's really odd design to mutate this in a property getter. I'd strongly recommend to make a copy instead.

A: mousetail's answer works, but just to give the answer the ES6 way, this is what I ended up using since it compiles to Object.defineProperty:
class Validation {
  errors: ValidationErrorItem[] = [];
  is_not = false;

  get not() {
    this.is_not = true;
    return this;
  }
  . . .


text:
Q: componentWillUnmount is not getting invoked I have a backbone application, where i am trying to integrate React components.
React component is mounted using following code :
ReactDOM.render(
 <WrappedComponent />, node
);
where node is the DOM mode. This way React lifecycle events like componentWillMount and componentDidMount are getting called fine.
But when routing happen through Backbone routing, and React component getting removed from DOM,  componentWillUnmount is not invoked.
Any solutions ?

A: componentWillUnmount does not get called automatically when the container node gets removed. It only gets called:

*

*At the top level, when you call ReactDOM.unmountComponentAtNode

*As child components, when the parent unmounts the component


text:
Q: Как узнать количество знаков до точки и после? Как узнать сколько знаков имеет число до точки и после точки?
Допустим есть такие числа:
var num = 14;
var num2 = 14.54;
var num3 = 514.0587;
var num4 = 0;
var num5 = 0.00000008;

Нужно вывести так:
Первое число это сколько знаков до точки, второе сколько знаков после точки
var num = [2, 0];
var num2 = [2, 2];
var num3 = [3, 4];
var num4 = [1, 0];
var num5 = [1, 8];

A:

const num = 14;
const num2 = 14.54;
const num3 = 514.0587;
const num4 = 0;
const num5 = 0.00000008;

Number.prototype.numberOfCharactersBeforeAndAfter = function() {
 const str = this.toString();

 if (str.indexOf('e') === -1) {
  const result = str.split('.').map(i => i.length);
  return {
   before: result[0],
   after: result[1] || 0
  }
 }

 const exponent = parseInt(str.split('-')[1], 10);
 const result = this.toFixed(exponent).split('.').map(i => i.length);
 return {
  before: result[0],
  after: result[1] || 0
 }
}

console.log( num, num.numberOfCharactersBeforeAndAfter() );
console.log( num2, num2.numberOfCharactersBeforeAndAfter() );
console.log( num3, num3.numberOfCharactersBeforeAndAfter() );
console.log( num4, num4.numberOfCharactersBeforeAndAfter() );
console.log( num5, num5.numberOfCharactersBeforeAndAfter() );


text:
Q: condition on hql statements I have som hql statements running every day like
drop table if exists table1;
create table table1 as
select ....
from A;

But some times create table fails and then my original table is¨deleted without a new one is created
I would like to do this a smarter way
like this pseudo code
if ( create table table1_tmp as
     select ....
     from A; )
then (    drop table table1 ;
          rename table1_tmp to table1 ;
     )

Is it possible to do that in hql or do i have to at
pig, spark, python etc.

A: INSERT OVERWRITE is the best fit for what you are trying to do.
You might want to keep an eye on your HDFS Trash folder because I think the underlying files always move to /user/<username>/.Trash when you perform an INSERT OVERWRITE


text:
Q: I've added things into my ArrayList but still not working for loop, and function So I have to create a movie kiosk rental system for one of my assignments, and I have to add five films into the database. I have done that properly (I believe) but when I implement the removeMovie() function it is returning null, especially. I'm not sure what I'm doing wrong.
Here is my code:
import java.util.*;

public class Catalogue {

private Kiosk kiosk;
private List<Movie> moviesAvailable = new ArrayList<Movie>();
private List<Movie> moviesRented = new ArrayList<Movie>();
private List<Genre> genres = new ArrayList<>();

public Catalogue(Kiosk kiosk) {
    this.kiosk = kiosk;
    genres.add(new Genre ("SciFi"));
    genres.add(new Genre("Drama"));
    genres.add(new Genre("Crime"));
    moviesAvailable.add(new Movie("Matrix", 1999, genres.get(0), 3));
    moviesAvailable.add(new Movie("Titanic", 1997, genres.get(1), 4));
    moviesAvailable.add(new Movie("The Silence of the Lambs", 1991, genres.get(2), 3));
    moviesAvailable.add(new Movie("Jurassic Park", 1993, genres.get(0), 4));
    moviesAvailable.add(new Movie("Terminator 2", 1991, genres.get(0), 3));
}

/**
 *
 */
public void use() {
    char choice;
    while ((choice = readChoice()) != 'R') {
        switch (choice){
            case '1': dispMovies(); break;
            case '2': dispAvail(); break;
            case '3': dispGenres(); break;
            case '4': dispMoviegen(); break;
            case '5': dispMovieyear(); break;
            case '6': rentMovie(); break;
            case '7': returnMovie(); break;
        }
    }
}

private char readChoice() {
    System.out.println("Welcome to the Catalogue! Please make a selection from the menu:");
    System.out.println("1. Display all movies.");
    System.out.println("2. Display all available movies.");
    System.out.println("3. Display all genres.");
    System.out.println("4. Display movies in a genre.");
    System.out.println("5. Display all movies by year.");
    System.out.println("6. Rent a movie.");
    System.out.println("7. Return a movie.");
    System.out.println("R. Return to previous menu.");
    System.out.print("Enter a choice: ");
    return In.nextChar();
}

 private void dispMovies(){

}

private void dispAvail(){
}

private void dispGenres(){
}

private void dispMoviegen(){
}

private void dispMovieyear(){
}

private void rentMovie() {
}

private void returnMovie() {
}

private String readTitle() {
    System.out.print("Enter the title of the movie: ");
    return In.nextLine();
}

private int readYear() {
    System.out.print("Enter the year: ");
    return In.nextInt();
}

/**
 *
 */
public void useAdmin() {
    char choice;
    while((choice = readChoiceadmin()) != 'R') {
        switch (choice) {
            case '1': listCustomers(); break;
            case '2': addCustomer(); break;
            case '3': removeCustomer(); break;
            case '4': listMovies(); break;
            case '5': addMovie(); break;
            case '6': removeMovie(); break;
        }
    }
}

private char readChoiceadmin(){
    System.out.println("Welcome to the administration menu:");
    System.out.println("1. List all customers.");
    System.out.println("2. Add a customer.");
    System.out.println("3. Remove a customer.");
    System.out.println("4. List all movies.");
    System.out.println("5. Add a movie to the catalogue.");
    System.out.println("6. Remove a movie from the catalogue.");
    System.out.println("R. Return to the previous menu.");
    System.out.print("Enter a choice: ");
    return In.nextChar();
}

private void listCustomers(){
}

private void addCustomer(){
}

private void removeCustomer(){
}

private void listMovies(){
    System.out.println("");
    System.out.println("The Kiosk has the following movies:");
    System.out.println(moviesAvailable);
    System.out.println("");
}

private void addMovie(){
}

private void removeMovie(){
    System.out.println("");
    System.out.println("Removing a movie.");
    String title = readTitle();
    int year = readYear();
    Movie movie = movie(title, year);
    if(movie != null) {
        moviesAvailable.remove(movie);
   System.out.println(movie + " removed from catalogue.");
    }
   else
    System.out.println("No such movie.");

}

    private Movie movie(String title, int year) {

        for (Movie movie : moviesAvailable)
            if(movie.hasTitle(title) && movie.hasYear(year))
                return movie;
        return null;
    }

 Catalogue() {
     //To change body of generated methods, choose Tools | Templates.
}

}

A: Movie movie = movie(title, year);
I don't really understand this.  It looks like a constructor but apparently isn't???
Regardless it smells to me like you are creating a new movie object and then trying to remove that object from your collection.  Which of course it isn't in your collection.  It may be another object with the exact same attributes.  But that doesn't make it the same object that is stored in the collection.
I suggest you read up on Object.equals.  Then use forEach to loop over your collection.  Probably something like
String title = readTitle();
int year = readYear();
Movie searchMovie = new Movie(title, year);
for (Movie movie : moviesAvailable) {
    if (movie.equals(searchMovie) {
       moviesAvailable.remove(movie)
    }
}


text:
Q: Grouping GeoDataFrame by column while comparing feature area and adding values to new column with GeoPandas I have these columns: "index", "area_of_poly", "cad_admin" in  my GeoDataFrame, the dataset is available here: http://www.mediafire.com/file/x4q5k7xuztq6o3w/p.zip.
Now, I have to group by column called "index" in order to take the rows that have the same value, e.g. all the ones, all the twos, etc.
Some of them (rows) are unique though.
About the ones that are not unique I have to check with a groupby() which of the groups have the largest area and give its respected "CAD_ADMIN" value to the others in its group in a new column called "CAD_ADMIN1".
The unique values are going to still have the same value they had in "CAD_ADMIN" in the now "CAD_ADMIN1" column.
import geopandas as gpd

inte = gpd.read_file('in.shp')

print(inte['index'].value_counts()[inte['index'].value_counts()>1])

359    9
391    8
376    7
374    6
354    5
446    4
403    4
348    4
422    4
424    4
451    4
364    3
315    3
100    3
245    3

inte["rank_gr"] = inte.groupby("index")["area_of_poly"].rank(ascending=False, method="first")

inte["key1_temp"] = inte.apply(lambda row: str(row[""]) if row["rank_gr"] == 1.0 else "", axis = 1)

inte["CAD_ADMIN_FINAL"] = inte.groupby("index")["key1_temp"].transform("sum")

print(inte[["area_of_poly", "index", "CAD_ADMIN", "CAD_ADMIN_FINAL"]])

This code as you will see produces some errors like:

TypeError: 'str' object cannot be interpreted as an integer

During handling of the above exception, another exception occurred:

KeyError: ('', 'occurred at index 0')

A: With such a question you will probably find more luck on the Stack Overflow. However, I may try to resolve it.
There are several hints regarding your code:

*

*there are more columns than just "index", "area_of_poly", "cad_admin", so for more easier computation one can create a subset of the original GeoDataFrame with: inte_mini = inte[["index", "area_of_po", "index", "CAD_ADMIN"]].

*when working with a shapefile keep in mind that the maximum length of field names is 10 characters, so your column "area_of_poly" will be "area_of_po" etc.

*when creating the "rank_gr" field, one can use the .astype(int) method to convert floats to integers.

*this str(row[""]) will cause the KeyError: '', because this index "" is meaningless for the pandas.core.series.Series class. Moreover, I do not really understand what are you trying to implement with this statement inte["key1_temp"] = inte.apply(lambda row: str(row[""]) if row["rank_gr"] == 1.0 else "", axis = 1).

*also it is not clear what is the purpose of this inte['index'].value_counts()[inte['index'].value_counts() > 1] statement. Is it just for visual understanding?

From what I understood in your question, this may be your final code:
import geopandas as gpd

absolute_path_to_shapefile = 'C:/Users/taras/Documents/p/in.shp'

inte = gpd.read_file(absolute_path_to_shapefile)

inte_mini = inte[["index", "area_of_po", "CAD_ADMIN"]]

inte_mini["rank_gr"] = inte_mini.groupby("index")["area_of_po"].rank(ascending=False, method="first").astype(int)

inte_mini_unique = inte_mini[inte_mini["rank_gr"] == 1]

inte_mini = inte_mini.merge(inte_mini_unique[["index", "CAD_ADMIN"]].add_suffix('1'), left_on="index", right_on="index1", how='left')
inte_mini.drop(["index1"], inplace=True, axis=1)

inte_mini["CAD_ADMIN_FINAL"] = inte_mini.groupby("index")["CAD_ADMIN1"].transform("count")

print(inte_mini[["index", "area_of_po", "CAD_ADMIN", "CAD_ADMIN_FINAL"]])

     index     area_of_po CAD_ADMIN  CAD_ADMIN_FINAL
0        2   28047.706672   0113922                1
1       18   78070.668553   0113921                1
2       15  176470.060863   0113921                1
3       27   18303.173073   0113921                1
4       44  149722.831771   0113921                1
..     ...            ...       ...              ...
558    270    1889.449872   0113904                1
559    269    3852.816088   0113904                1
560    272    3796.918474   0113904                1
561    271    7128.637880   0113904                1
562    479   52836.928028   0113927                1

[563 rows x 4 columns]

References:

*

*wikipedia | Shapefile

*wikipedia | .dbf


text:
Q: Solr re ranking of results is not working as expected Dear solr community members,
I have a question related to re-ranking of my results from solr.
Problem:
I have a set of filters in a multifield like below in each document along with other fields.
{filters_multi_string :["A:H", "B:H", "C:N"]},
{filters_multi_string :["A:N", "B:H", "C:N"]},
{filters_multi_string :["A:H", "B:N", "C:H"]},
{filters_multi_string :["A:H", "B:H", "C:H"]},
{filters_multi_string :["A:N", "B:N", "C:N"]}

on the page user will be presented with filters A, B, and C. A:H means it's high-quality product where as A:N means a secondary quality product, the same applies to
other filters B and C. So now when selecting a filter we should show the quality products first and then secondary quality products.
I tried the following:
I want to achieve this by using the ReRank query parser (Query re-ranking in solr). Currently, we are having big complex
query which gives us results by applying different other filters and combinations, now on top of this query I want to re-rank the results using the re-rank query parser.
But somehow the results are not as expected.
Below is my example query when user selects filter A: (my complex query)&rq={!rerank reRankQuery=$rqq reRankDocs=100 reRankWeight=20}&rqq={!lucene df=filters_multi_string v=$v1}&v1=A:H^20
With the above query, I expect all my results from the first query to be boosted with high-quality products and show on top of the result set, but it did not work as expected and there is no change in the results at all.
Can someone help me with this? and please let me know if there is any other approach than this.


text:
Q: call function in angular ui tooltip Have used this code which invokes the user defined function : getTooltipText

....

//function definition

$scope.getTooltipText = function(arg1){
console.log(arg1); // prints undefined
....
return text;
}

But it is not working. Have even tried trinary operator, but no luck!! Any suggestion?

A: instead of {{ getTooltipText(arg1) }} ,may be you can use ngMouseenter and ngMouseleave directive.

In your controller:
$scope.getTooltipText = function(arg1){
   $scope.tooltip = "Your tooltip here";
}

link
(I am not sure about usage of arg1)
I took code from angular site and modified it a little just to demonstrate working of it:

   <button ng-mouseenter="mouseOvver()" ng-mouseleave="mouseLeave()">
   when mouse enters
 </button>
 count: {{msg}}


text:
Q: How to pass parameters in cucumber scenario outline example based on environment? I am using Scenario Outline for my API testing. My need is very simple, give multiple input and verify the output.(Negative & Positive inputs).
So for that  I want to parameterized input data depends on my environment.
Dependency - cucumber-java : 2.4.0
 @sanity @regression @test
  Scenario Outline: Verify user details
    Given Client is API Client
    When I make the GET request for <userId> to get details
    Then I should get success status as <success status>
    And Verify Json schema

    Examples:
      | userId        |   success status        |
      | 11903         |   true                  |
      | vjndv         |   false                 |
      | @!#$#         |   false                 |

Here I want to use userId depends on my environment. I have multiple features in which I am using things which can be vary based on environment.
Any suggestion will be helpful.

A: I would suggest using different feature files per environment.
The basic premise of cucumber gherkin scenarios is "specifications by example". Adding variables/ tokens to the scenarios will likely make the scenarios unreadable.

A: I believe you'd have to do something like this, if you have different inputs per env.
Scenario Outline: Verify user details
 Given Client is API Client
 When I make the GET request for <userId> to get details
 Then I should get success status as <success status>
 And Verify Json schema

@env1 @sanity @regression @test
Examples: Environment 1
  | userId        |   success status        |
  | 11903         |   true                  |

@env2 @sanity @regression @test
Examples: Environment 2
  | userId        |   success status        |
  | vjndv         |   false                 |

@env3 @sanity @regression @test
Examples: Environment 3
  | userId        |   success status        |
  | @!#$#         |   false                 |

You'd control each example with a different tag to denote which env you want to run.


text:
Q: How to pre-process BigQuery data coming from Stackdriver I am currently exporting logs from Stackdriver to BigQuery using sinks. But i am only interessted in the jsonPayload. I would like to ignore pretty much everything else.
But since the table creation and data insertion happens automatically, i could not do this.
Is there a way to preprocess data coming from sink to store only what matters?
If the answer is no, is there a way to run a cron job each day to copy yesterday data into a seperate table and then remove it? (knowing that the tables are named using timestamps which makes it possible to query them by day)

A: As far as I know both options mentioned are currently not possible in the GCP platform. On my end I've also tried to create an internal reproduction of your request and noticed that there isn't a way to solely filter the jsonPayload.
I would therefore suggest creating a feature request in regards to your ask on the following public issue tracker link. Note that feature requests do not have an ETA as to when they'll processed or if they'll be implemented.


text:
Q: When will this execute? I have a C code:
...
void caller() {
    #define YES 1
    #define NO 0
}
...

Will the both #define lines execute when caller is called/executed, or will they execute at compile-time only.

A: The prerpcessor macros don't execute, they are just named fragments of the code which will be replaced by the preprocessor to theirs content if you use them. Read more about preprocessor macros here.
So, after preprocessing, your code will be:
void caller() {
}

Let assume you use the YES macro after you #define it:
#define YES 1
#define NO 0

void caller() {
    printf("My answer is: %d", YES);
}

After preprocessing the code above will be the following:
void caller() {
    printf("My answer is: %d", 1);
}


text:
Q: What does a variable named using ampersand followed by an underscore means? I'm studying C++ and I found this weird syntax.
What does &_ mean and why the author could use the variable as _1st?
std::sort(open_list.begin(), open_list.end(), [] (const auto &_1st, const auto &_2st) {
  return _1st->h_value + _1st->g_value < _2st->h_value + _2st->g_value
});

EDIT 1
I thought that in order to create a reference of a variable it was necessary to use ampersand operator followed by the name, like: & _1st(notice the blank space between them).
Is underscore a special way to declare name variables in C++?

A: & is used for declaring references; so const auto &_1st is declaring a parameter named _1st, whose type is lvalue-reference (to const). It's same as const auto & _1st, and the spaces are superfluous; you can even write it as const auto&_1st, this is not special for underscores.
And note that underscores could be used for identifiers.

An identifier is an arbitrarily long sequence of digits, underscores, lowercase and uppercase Latin letters, and most Unicode characters (see below for details). A valid identifier must begin with a non-digit character (Latin letter, underscore, or Unicode non-digit character).

A: const auto &_1st
That declares a parameter with the name _1st.  The & means that it's passed by reference to the function.

A: Variables can be used only according to particular rules. It cannot directly start with a number, so the author has used _(underscore).
Look into this : https://www.sitesbay.com/cpp/cpp-variable-declaration
Ampersand symbol is used for representing pass by reference.

A: The operation is & + variable_name, rather than &_ + variable_name.
In this context, & followed by a variable means passing the pointer of this variable as one of the function arguments. You will probably notice that in the code you pasted, the third very long argument of std::sort is actually a lambda expression( a function ):
[] (const auto &_1st, const auto &_2st) {
  return _1st->h_value + _1st->g_value < _2st->h_value + _2st->g_value
}

It corresponds to the third argument of sort from according to HERE, and below is a short quote:

comp
Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
  The function shall not modify any of its arguments.
  This can either be a function pointer or a function object.

So basically when you want to sort a type of variable with your specifically defined rule or c++ does not know how to compare the target you are trying to sort, you have to define a function tells c++ how to perform sorting.
For details, you may also want to take a look at THIS.
There are few reasons to pass variables as reference pointers instead of passing by value. In many cases you just do not wanted to create additional memory consumption and save time, passing by reference allows you access values without make a copy. For details, please refer to HERE

A: This is just a naming convention to declare the variable which was written by someone in that code snippet.
So, _1st and _2nd just a reference variable of auto type.
Below code will also work fine:
std::sort(open_list.begin(), open_list.end(), [] (const auto &first, const auto &second) {
return first->h_value + first->g_value < second->h_value + second->g_value
});


text:
Q: How to adjust Kibana Dashboard link in ElastAlert I have written the following rule
type: frequency

filter:
- query:
    query_string:
      query: "category:foo.bar AND msg._:*Failure*"

alert_text: "Total number of errors cross threshold..... Kibana link"
alert_text_args:
  - kibana_link
alert_text_type: alert_text_only

my config.yaml is
# Kibana Dashboard
use_kibana4_dashboard: http://mykibana.com/

When an alert is raised and I click on the hyperlink which I am putting in the message. It takes me to my dashboard.
But what I want is that instead of a dashboard it takes to the data discovery screen and there it issues the very same query that it had issued when the alert was raised.
This way I want to see exactly the query results which the elastalert had seen when the alert was raised.

A: Actually, I was able to solve this myself. I am writing my solution here.
So basically, I did the exact same search as my criteria above in kibana and saved that search. Next I created a dashboard and pulled the saved query into the dashboard.
Next I pointed the rule to the new dashboard which contains the saved query.
When the link is generated, the elastalert will create the link in a way the time period is injected into the hyperlink. When you click on the link you will see exactly what the alert saw.


text:
Q: How to get the same effect with pure javascript Hi everyone how to do this effect with Pure Javascript by placing a button on the top of the box and on click add or remove the class to get the same effect as provided in this slide on hover here is my code

.wrap {
  position: relative;
  width: 200px;
}

.mainclass {
  height: 200px;
  background: #ccc;
  ;
}

.overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #237aba;
  overflow: hidden;
  width: 100%;
  height: 0;
  transition: .5s ease;
}

.wrap:hover .overlay {
  height: 100%;
}

A: As far as I understand you just want to replace the use of the pseudo-class (:hover) in your css with pure javascript code.
In that case, maybe the following code is a solution.
I hope this helps :-)

var overlay = 0;
function overlayColor(){
  var element = document.getElementsByClassName("overlay")[0];
  var btn = document.getElementById("btnOverlay");
  if ( overlay ){
    element.style.height="0%";
    btn.innerText = "add overlay";
    overlay = 0;
  }
  else {
    element.style.height="100%";
    btn.innerText = "remove overlay";
    overlay = 1;
  }
}
.wrap {
  position: relative;
  width: 200px;
}

.mainclass {
  height: 200px;
  background: #ccc;
  ;
}

.overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #237aba;
  overflow: hidden;
  width: 100%;
  height: 0;
  transition: .5s ease;
}
<button id="btnOverlay" onclick="overlayColor()">
  add overlay
</button>


text:
Q: Deserialize XML to ObservableCollection Using VS 2012 and .NET 4.0, I have the following code which correctly deserializes an XML file:
XML File:
<?xml version="1.0"?>
<Codes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema" >

    <AccpacCode>CA9998</AccpacCode>
    <LAC>90699999999999999</LAC>
    <SCSCode>SDI</SCSCode>

    <AccpacCode>ORWC</AccpacCode>
    <LAC>94199999999999999</LAC>
    <SCSCode>WC</SCSCode>

    <AccpacCode>AK9999</AccpacCode>
    <LAC>90299999999999999</LAC>
    <SCSCode>UI</SCSCode>
    <ParentEmployerAccpacCode>AKSUTA</ParentEmployerAccpacCode>

<Codes>

XSD File:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Codes" xmlns="SerializeObservableCollection" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="Codes" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Code">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="AccpacCode" type="xs:string" minOccurs="0" />
              <xs:element name="LAC" type="xs:string" minOccurs="0" />
              <xs:element name="SCSCode" type="xs:string" minOccurs="0" />
              <xs:element name="ParentEmployerAccpacCode" type="xs:string" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

C# Code:
try
{
    XmlSerializer _serializer = new XmlSerializer(typeof(Codes));

    // A file stream is used to read the XML file into the ObservableCollection
    using (StreamReader _reader = new StreamReader(@"LocalCodes.xml"))
    {
        var codes = _serializer.Deserialize(_reader) as Codes;

    }
}
catch (Exception ex)
{
    // Catch exceptions here
}

I would like to put the results of the deserialization into an ObservableCollection and have found examples that say the following should work:
ObservableCollection<Codes> CodeCollection;

...
try
{
    XmlSerializer _serializer = new XmlSerializer(typeof(ObservableCollection<Codes>));

    // A file stream is used to read the XML file into the ObservableCollection
    using (StreamReader _reader = new StreamReader(@"LocalCodes.xml"))
    {
        CodeCollection = _serializer.Deserialize(_reader) as ObservableCollection<Codes>;

    }
}

When I run this code I get an error message of "There is an error in XML document (2, 2)." and an inner exception of "<Codes xmlns=''> was not expected."  I have seen mention of needing a default constructor to make this work and the Codes.cs class does have one (it is the file generated by VS 2012 by the XSD file).  here is a snippet of the Codes.cs file:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18051
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

#pragma warning disable 1591

namespace SerializeObservableCollection {

    ///
    ///Represents a strongly typed in-memory cache of data.
    ///
    [global::System.Serializable()]
    [global::System.ComponentModel.DesignerCategoryAttribute("code")]
    [global::System.ComponentModel.ToolboxItem(true)]
    [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema")]
    [global::System.Xml.Serialization.XmlRootAttribute("Codes")]
    [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")]
    public partial class Codes : global::System.Data.DataSet {

        private CodeDataTable tableCode;

        private global::System.Data.SchemaSerializationMode _schemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema;

        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
        public Codes() {
            this.BeginInit();
            this.InitClass();
            global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
            base.Tables.CollectionChanged += schemaChangedHandler;
            base.Relations.CollectionChanged += schemaChangedHandler;
            this.EndInit();
        }

What do I need to change/fix to get this to work and populate the ObservableCollection?

A: @BrianKE I doubt very much this will still be of use to you, but maybe it will be of use to someone else. I had the same problem as you today. Took me half the day to figure it out.
First, the message you are seeing is because the type you are specifying...
XmlSerializer _serializer = new XmlSerializer(typeof(ObservableCollection<Codes>));

..is not an ObservableCollection. If the type is wrong you get this error. Codes needs to be an observable collection for your statement to work.
What you need is root element, currently Codes is your root element, so you need a Class just for the root and then you have a number of Code elements under this. e.g.
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class MIGRATION : object, INotifyPropertyChanged, INotifyPropertyChanging
{

    private string projectNameField;

    private ObservableCollection<FileDescriptions> fileDescriptionsField;

    //private FileDescriptions[] fileDescriptionsField;

    /// <remarks/>
    //[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [XmlElement("ProjectName")]
    public string ProjectName
    {
        get
        {
            return this.projectNameField;
        }
        set
        {
            this.RaisePropertyChanging("ProjectName");
            this.projectNameField = value;
            this.RaisePropertyChanged("ProjectName");
        }
    }

    /// <remarks/>
    [XmlElement("FileDescriptions")]
    public ObservableCollection<FileDescriptions> FileDescriptions
    {
        get
        {
            return this.fileDescriptionsField;
        }
        set
        {
            this.fileDescriptionsField = value;
            this.RaisePropertyChanged("FileDescriptions");
        }
    }

    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName)
    {
        System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
        if ((propertyChanged != null))
        {
            propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }
    }

    public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;

    protected void RaisePropertyChanging(string propertyName)
    {
        System.ComponentModel.PropertyChangingEventHandler propertyChanging = this.PropertyChanging;
        if ((propertyChanging != null))
        {
            propertyChanging(this, new System.ComponentModel.PropertyChangingEventArgs(propertyName));
        }
    }
}

So the Observable collection(s) is on the elements inside the deserialized Class. I know what you are talking about though, I have seen examples like you are describing, but I don't know what that is about. As far as I can tell the deserialize had nothing to do with observable collection. Unless maybe they have more than one root element? Or perhaps it is when you are not deserializing a whole XML, but just a part of one, would make sense.

A: Deserialize should be used only with content that was previously serialized using Serialize. Otherwise, you are just playing with fire.
You can easily open and iterate through an XML document using XDocument.
XDocument xml = XDocument.Load(filename);
var collection = new ObservableCollection();
foreach (XElement e in xml.Elements("code"))
{
   collection.Add(new Code() { AccpacCode = e.Element("AccpacCode").Value,
                               LAC = e.Element("LAC").Value });
}

You can easily iterate in all xml.Elements and intiatiate a code object which you add to an ObservableCollection. The interface may flickr a bit though during the loading.


text:
Q: How to convert a single object or a set into a set? There's a method as follows:
def send_message(
    content: str,
    slack_conn_ids: Union[SlackConnection, Set[SlackConnection]],
    send_only_in_production: bool = True,
):
   ...
   if isinstance(slack_conn_ids, set):
      set_slack_conn_ids = slack_conn_ids
   elif isinstance(slack_conn_ids, SlackConnection):
      set_slack_conn_ids = {slack_conn_ids}
   else:
      raise ValueError("`slack_conn_ids` should be of type `SlackConnection` or `Set[SlackConnection]`"
        )
   ...

Can this code be simplified, implemented more idiomatically?

A: You can use pattern matching.
match slack_conn_ids:
    case set():
        set_slack_conn_ids = slack_conn_ids
    case SlackConnection():
        set_slack_conn_ids = { slack_conn_ids }
    case _:
        raise ValueError("`slack_conn_ids` should be of type `SlackConnection` or `Set[SlackConnection]`")

A: Don't. Let the caller be responsible for providing a set, even if that set only contains one connection.
def send_message(
    content: str,
    slack_conn_ids: Set[SlackConnection],
    send_only_in_production: bool = True,
):

   ...

s = SlackConnection(...)
send_message("hi", {s})

A: Your code is already very simplified, it is impossible to come out with something worth the difference.
Here is how I would design that code:
if isinstance(slack_conn_ids, SlackConnection) or isinstance(slack_conn_ids, set):
    try:
        slack_conn_ids = {slack_conn_ids}
    except TypeError:
        pass
else:
    raise ValueError("`slack_conn_ids` should be of type `SlackConnection` or `Set[SlackConnection]`")

Explanation:

*

*Check in one-line if input is approved.

*Change variable slack_conn_ids to set if object. If already set, everything okay. No need to waste memory creating new variables and assigning more than needed.


text:
Q: Have some queries about Fourier Transform I have some queries about the Fourier transform

*

*In most of the cases, the Fourier transform of a signal is symmetric with respect to positive and negative frequency. I think the computational complexity increases because only half of the symmetric spectrum (i.e. spectrum for only positive frequencies) is useful. Also, while working in the frequency domain we could get wrong value of energy or power due to the spectrum on negative axis.

*In the Fourier transform formula the limits of integration are from $-\infty$ to $\infty$. However, for a signal which is continuously or exponentially increasing with time, one can't compute it's Fourier transform.

*After computation of Fourier transform of a signal, we get phase and frequency spectrum of the whole signal which is localized in frequency domain only. But from both of these spectrum, we don't get any spatial component features like which frequency component is present at which time (and same with the phase value).

*After computation of Fourier transform of signal, with dc and positive frequencies we also get unnecessary negative frequency components. I think concept of negative frequency doesn't exists practically.
I feel that these are the "shortcomings" of Fourier transform but don't know whether they really are or not.
So can anybody give explanation on any of above doubts?

A: 1) For real signals you can skip the computations of the negative part if you want, and the energy on it will always be the same as in the positive part
2) Fourier analysis is not aimed at this kind of signals. See Laplace Transforms for that
3) You can get information from both time and frequency domains by windowing the signal in many frames and computing the FT for each of them. Take a look into spectrograms and how people do it
4) In most cases you will only work with real signals so we do ignore the negative part because it is redundant. Telecommunications and electronics engineers sometimes make use of complex signals as a shortcut even if these don't exist in reality


text:
Q: Trim unreachable code from Assembly
Possible Duplicate:
How does the number of classes in an assembly impact performance?

I have a fairly large .Net assembly containing common controls and components.  This the VS project file is used in several different VS solutions.  Any given application may only require a small subset of the code within the common assembly.  Is there any way to customise the build for each application to exclude code which is not required in order to reduce the assembly size.  I have looked at ILMerge but can not tell if it is capable of merging then trimming unreachable IL?


text:
Q: UnicodeDecodeError when trying to open file I tried to open a file but kept getting an error (decoding error). I finally came across a topic on stackoverflow and got one step further. However, now I don't get any results when I try to loop through my file. The file is the setting file for uTorrent. I fairly new to Python and programming so I thought I could try to read and extract some parameters from that file.
getDir = r'{0}/{1}/{2}/AppData/Roaming/uTorrent/settings.dat'.format(partition,
"Users", user)

data = []
try:
    with codecs.open(getDir, "r") as f:
        for lines in f:
            data.append(lines)
except UnicodeEncodeError:
    pass

I get an error when I use UnicodeEncodeError but not with other exceptions. I have tried with/without codecs.open and to specify the decoding type in the open function, I have used ignore as well. The code goes through but the list remains empty.
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 1962: character maps to <undefined>

The code works fine with other files in the same directory. I have checked the file and there are some weird characters. Example below.
RÉ"  tÝï:Q'æІ•

Really appreciate the help and thanks for a awesome site!

A: Summary
You would need to specify the encoding when you open the file.  It would look like this if the encoding is 'utf-16', though from the example you gave, it might not be.
with codecs.open(getDir, "r", encoding="utf-16") as f:

Error Handling
You can also specify how you want to handle the errors by putting in the argument 'errors'.  This allows you to replace unknown characters or ignore them.  See here for more detail: http://docs.python.org/2/library/codecs.html#codec-base-classes
Additional Reading
You're probably wondering how can you determine the encoding?  In summary, you need to be told what the encoding is.  Here's a link that describes encoding and decoding in a concise and understandable way: http://www.joelonsoftware.com/articles/Unicode.html


text:
Q: MVVM: Thin ViewModels and Rich Models I'm continuing to struggle with the MVVM pattern and, in attempting to create a practical design for a small/medium project, have run into a number of challenges.  One of these challenges is figuring out how to get the benefits of decoupling with this pattern without creating a lot of repetitive, hard-to-maintain code.
My current strategy has been to create 'rich' Model classes.  They are fully aware that they will be consumed by an MVVM pattern and implement INotifyPropertyChanged, allow their collections to be observed and remain cognizant that they may always be under observation.  My ViewModel classes tend to be thin, only exposing properties when data actually needs to be transformed, with the bulk of their code being RelayCommand handlers.  Views happily bind to either ViewModels or Models directly, depending on whether any data transformation is required.  I use AOP (via Postsharp) to ease the pain of INotifyPropertyChanged, making it easy to make all of my Model classes 'rich' in this way.
Are there significant disadvantages to using this approach?  Can I assume that the ViewModel and View are so tightly coupled that if I need new data transformation for the View, I can simply add it to the ViewModel as needed?

A: I think INotifyPropertyChanged on your model is only useful when you're expecting it to be operated on by your VM and external "forces" simultaneously.
I'm personally a supporter of POCO models. Putting any framework-specific scaffolding into my model would make me worry. When you put an event into your model class you have to consider carefully possible issues with your model's life-cycle, serialization, storage etc. For example what happens if you recreate your object from data source and old INotifyPropertyChanged subscriptions are now invalid?
Similarily better place for ObservableCollection is in the VM, which can consume an IEnumerable datasource, and present to the view only selected or ad hoc filtered items.

A: I consider this to be the pragmatic approach - we have followed this pattern successfully in the past.
The basic premis was to bind directly to a model that implements INotifyPropertyChanged for most read-only data, and then add extra properties to the viewmodel for view specific stuff that needs to be transformed (as you suggested).  For non read-only properties, we found it easiest the create viewmodel entries (generally of type string) as this allows client-side validation to be added easily in the viewmodel.

A: Disclaimer - I am not an expert -
I do not put INotifyChanged on my Models. I had done this at first but came to the simple realization that INotifyChanged is really only practical for notifying the UI so I only put INotifyChanged on my ViewModels now. This has made it easier to control the number of "RaisePropertyChanged"... My views never reference a Model directly.
I'm working on my first MVVM project yet on my 3rd major refactor :P

A: I agree that there will be tight coupling between the View and ViewModel. But this can be alleviated to some extent by using IValueConverters whenever possible to do transformations.
I try to keep my business logic in my ViewModel. Also, I use the Viewmodel to change the shape of my Model to fit that which the View might expect.


text:
Q: How to remove required action "Configure OTP" from Keycloak Admin Client user registration I'm using spring to create users with keycloak admin client. In my UserService I'm only specifying 2 required actions: Verify Email & Update Password
    public String create(UserRequest request) {
        UserRepresentation userRepresentation = new UserRepresentation();
        userRepresentation.setEnabled(true);
        userRepresentation.setUsername(request.getUsername());
        userRepresentation.setFirstName(request.getFirstName());
        userRepresentation.setLastName(request.getLastName());
        userRepresentation.setEmail(request.getEmail());

        CredentialRepresentation credentialRepresentation = new CredentialRepresentation();
        credentialRepresentation.setTemporary(true);
        credentialRepresentation.setType(CredentialRepresentation.PASSWORD);
        credentialRepresentation.setValue(request.getCode());

        userRepresentation.setCredentials(List.of(credentialRepresentation));
        userRepresentation.setRequiredActions(
            List.of(
                UserModel.RequiredAction.VERIFY_EMAIL.name(),
                UserModel.RequiredAction.UPDATE_PASSWORD.name()
            ));

        Response response = keycloak.realm(this.realm).users().create(userRepresentation);
        if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL)
            return CreatedResponseUtil.getCreatedId(response);
        return null;
    }

Yet, after creation, I'm getting 3 required actions in admin console: Configure OTP, Verify Email & UpdatePassword.
I've seen some articles talking about flows but the newer Version of Admin Console looks almost nothing like the one in the tutorials

A: If your user has unexpected Required Actions on creation, you should check if that action is configured as a "default action" in the realm.
For this, navigate to your realm in the admin console, click "Authentication" on the left sidebar, and then click the "Required Actions" Tab.
There you should see a list of all required actions that are available. The first switch for each means that the required action is enabled for that realm. The second switch means that the required action will be automatically set for all new users created in that realm.


text:
Q: Target .NET 4.0 from Windows 10? I need to target .NET 4.0 from my current Windows 10 development machine.
I can't find any offline installations of .NET 4.0 SDK. Right now I'm having 4.6.1 and 4.5.1 SDK installed, I've manually set 4.0 version in my csproj.
MSBuild gives me a warning that I need to install .NET 4.0 SDK and the compiler generates calls to System.Array.Empty (this call is generated by the compiler I don't use it directly) which doesn't exist on .NET prior to 4.6.
How do I make sure that I compile executables that would run on .NET 4.0 version (without System.Array.Empty and other stuff that doesn't exist in .NET 4.0)? Where do I get offline installer for .NET 4.0 SDK?
PS: I'm using JetBrains Rider and MSBuild 14.0 currently.  Alternatively. is there a way to make Roslyn not omitting System.Array.Empty calls for every empty array instantiation in my code?

A: I've eventually ended up installing Visual Studio 2013 along side with JetBrains Rider and it installed .NET 4.0 SDK as well as tone other stuff that I don't use. But now everything works as it should.


text:
Q: SlimDX, understanding how the window works Okay i am trying to begin learning SlimDX, as i need probably need it for my application.
And as i don´t know DirectX, i am stuck very early with how a thing works.
And that is creating a render window, here is how the example shows, and i pretty much copy paste it.
            MessagePump.Run(form, () =>
        {
            // clear the render target to a soothing blue
            context.ClearRenderTargetView(renderTarget, new Color4(0.5f, 0.5f, 1.0f));

            // draw the triangle
            context.Draw(3, 0);
            swapChain.Present(0, PresentFlags.None);
        });

Now i do understand it somehow, but what i don´t get, is "MessagePump.Run". This causes everything in the code to Pause.
And what i am trying to do, which is loading pictures constantly, won´t work if the code pauses when i open a window.

A: Think i solved it myself, it creates it´s own loop, so i have to use it in a thread.


text:
Q: Sending Fetch Request from Client to Server results in 404 Next.js Express Im trying to figure out some routing issues with express, im using next.js as well but i dont think that is the issues.
Originally, i have my clientside POST request pointing to /server, the same with my server.js, which works out fine. If i switch it to /api/submit on both client and server, this results in a 404 error. I'm sure there is a misconfiguration with my routing in express but i cant seem to figure it out. below is my code:
clientside:
const submitFormData = e => {
e.preventDefault();
const { formDataOne, formDataTwo } = props;
const formData = {
  formDataOne,
  formDataTwo,
};
fetch('/api/submit', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    data: formData,
  }),
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));
};

server.js:
const express = require('express');
const bodyParser = require('body-parser');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    const server = express();
    server.use(bodyParser.urlencoded({ extended: true }));
    server.use(bodyParser.json());

    server.post('/api/submit', (req, res) => {
      console.log(req.body);
    });

    server.get('*', (req, res) => {
      return handle(req, res);
    });

    server.listen(3000, err => {
      if (err) throw err;
      console.log('> Ready on http://localhost:3000');
    });
  })
  .catch(ex => {
    console.error(ex.stack);
    process.exit(1);
  });

A: You are missing a leading / in your route path:
server.post('/api/submit', (req, res) => {
  console.log(req.body);
});


text:
Q: Calculate month's days based on Year & Month selected I am trying to get days number based on Year (Years are numbers) & Month (are text) selected from combo box.
Year Combo box name: cmbYear
Month Combo box name: cmbMonth
Code trigger event:
    private void cmbMonth_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cmbYear.SelectedIndex > -1)
        {
                {
                    var a = cmbDay;
                        a.Enabled = true;
                        a.BackColor = Color.LightCoral;
                }

                cmbMonth.BackColor = Color.Empty;
                MethodLibrary.Fill_cmbDay(cmbYear,cmbMonth, cmbDay);

Method:
static class MethodLibrary //Method does not return something
{
    public static void Fill_cmbDay(ComboBox strYear, ComboBox strMonth, ComboBox  cmbTarget) //Void used does not return something
    {
        //Find how many days month has based on selected year & month. Convert month name to month number.
        int days = DateTime.DaysInMonth(Convert.ToInt32(strYear.SelectedItem), Convert.ToInt32(strMonth.SelectedItem));

        //Clear Combo box
        cmbTarget.Items.Clear();

        //Loop from 1 to number of days & add items to combo box
        for (int i = 1; i <= days; i++)
        {
            cmbTarget.Items.Add(i);
        }
    }
}

UserForm:

Error on line:
int days = DateTime.DaysInMonth(Convert.ToInt32(strYear.SelectedItem), Convert.ToInt32(strMonth.SelectedItem));

I believe that error occurs during the conversion of strMonth.SelectedItem to int32.
An help will appreciate.

A: The very reason of the exception is that your try to convert "January" string into integer value. Try
 int days = DateTime.DaysInMonth(
   Convert.ToInt32(strYear.SelectedItem), // "2019" can be converted into 2019
   strMonth.SelectedIndex + 1);           // "January" can't; let's take Index then

A: What i have manage and it works for me:
Code trigger:
    private void cmbMonth_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cmbYear.SelectedIndex > -1)
        {
                {
                    var a = cmbDay;
                        a.Enabled = true;
                        a.BackColor = Color.LightCoral;
                }

                cmbMonth.BackColor = Color.Empty;
                int monthInDigit = DateTime.ParseExact(cmbMonth.SelectedItem.ToString(), "MMMM", CultureInfo.InvariantCulture).Month;
                MethodLibrary.Fill_cmbDay(cmbYear, monthInDigit, cmbDay);
        }
    }

Method:
static class MethodLibrary //Method does not return something
{
    public static void Fill_cmbDay(ComboBox strYear, int Month, ComboBox  cmbTarget) //Void used does not return something
    {
        //Find how many days month has based on selected year & month. Convert month name to month number.
        int days = DateTime.DaysInMonth(Convert.ToInt32(strYear.SelectedItem),Month);

    //Clear Combo box
    cmbTarget.Items.Clear();

        //Loop from 1 to number of days & add items to combo box
        for (int i = 1; i <= days; i++)
        {
            cmbTarget.Items.Add(i);
        }
    }
}


text:
Q: How to copy object array from ngfor to other div I would like to click on a specific div, and then click on the div with the data of the object, so that this data will be copied to the new div. I want the object to be copied in the new div, not just the string from the data object.
html.file:

paste here

paste here

paste here

    copy here
    name:{{sub.name}}
    w(h): {{sub.wh}}
   c(h): {{sub.ch}}
    l(h): {{sub.lh}}


text:
Q: No cyrillic letters in Qt 4.8.6 / Linux Mint I can't read or write any Russian text in a program written on Qt. All labels on Russian are blank, typing Cyrillic letters in QLineEdit has no effect.
Note all other programs works with Russian fine, even Qt Creator itself. In form design mode all labels are OK, but they disappear when I run a program.
Also Qt Linguist doesn't show Russian text
Image below shows a test program: Second line label contains Russian text, and QLineEdit at end too.

I tried qtconfig. It works, font changes, but no Russian letters appeared
Configuration:
resu@resu-desktop ~ $ cat /proc/version
Linux version 3.13.0-24-generic (buildd@batsu) (gcc version 4.8.2 (Ubuntu
4.8.2-19ubuntu1) ) #47-Ubuntu SMP Fri May 2 23:30:00 UTC 2014

/etc/lsb-release:
DISTRIB_ID=LinuxMint
DISTRIB_RELEASE=17
DISTRIB_CODENAME=qiana
DISTRIB_DESCRIPTION="Linux Mint 17 Qiana"

Qt: 4.8.6
.qmake.cache:
CONFIG +=  debug largefile stl precompile_header mmx 3dnow sse sse2
sse3 ssse3 sse4_1 sse4_2 avx dylib create_prl link_prl depend_includepath
fix_output_dirs QTDIR_build

A: I added QFontDialog and found that Qt has only ten ugly raster fonts, with Bitstream Character as default. This topic said I need rebuild Qt with -fontconfig option. Also I installed other recommended Qt for X11 requirements.
First ./configure attempt reported a problem
QTextCodec: using KOI8-R, probe failed (e0 ce ru)

and this topic helped me:
$ localedef --no-archive -c -f KOI8-R -i ru_RU ru_RU.KOI8-R

My final script to build is:
sudo apt-get install  libfontconfig1-dev libfreetype6-dev\
libx11-dev libxcursor-dev libxext-dev libxfixes-dev libxft-dev\
libxi-dev libxrandr-dev libxrender-dev

localedef --no-archive -c -f KOI8-R -i ru_RU ru_RU.KOI8-R

./configure -debug -opensource -shared -qt-sql-psql -nomake demos\
-nomake examples -gtkstyle -xrender -xrandr -xcursor -xfixes -fontconfig

make

sudo make install


text:
Q: Pull the Report Title into the JavaScript used in a Custom Control Page Module I am working on adding the Google Analytics code, to my Cognos reports, to help track usage from our website.  I have created a page module custom control that does work correctly when the report page loads.  The code currently sets the report name manually in the code. I want to have the control dynamically get the report name.  The code for the page module is:
define( ["https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"], function() {

function PageModule()
{};

PageModule.prototype.load = function( oPage )
{
 window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-XXXXXXXXXX', {
  'page_title' : 'Cognos Report Name'
});
};

I know Cognos has a function that will get the report name when added in a query item. I am trying to get the same report name pulled into the custom control without having to add a unique query item in the report. Is it possible to get the report name using JavaScript, and if so, what code do I need to insert in place of Cognos Report Name?  Any suggestions would be greatly appreciated.

A: I received a reply from dougp to my posting, on cognoise, that resolved my problem. Here is the final code which is based on Google Analytics 4.
define( ["https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"], function() {

function PageModule()
{};

PageModule.prototype.load = function( oPage )
{

window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-XXXXXXXXXX',
  { 'page_title': (new DOMParser()).parseFromString(oPage.application.Document.reportXML, "text/xml").getElementsByTagName("reportName")[0].childNodes[0].nodeValue }
  );


text:
Q: Docker volume, source file is being copied as a directory in container, why? I'm trying to pass the amazon credentials folder (.aws) to to the container's root folder.
docker run -it -v ~/.aws:/root/.aws -p 8000:8000 collection
Inside the .aws folder there is a file named 'credentials' (no extension).
The problem is, when I inspect the root/.aws folder inside the container, the 'credentials' file is a directory, not a file.
cd /root/.aws
~/.aws # ls -l
total 8
drwxr-xr-x    3 root     root          4096 Jan  9 23:17 credentials

cat credentials
cat: read error: Is a directory

Does anybody know what I need to do? Even if I include a text file, eg: test.txt, it is copied as a directory.
Thank you!


text:
Q: Consulta com vários SELECT's MySQL SELECT prefixo FROM getVeiculosLinha AS V JOIN getLinhas AS L ON V.cod_linha = L.cod_linha JOIN tab_garagens AS G ON V.prefixo = G.onibus_prefixo

SELECT c.local FROM status AS s JOIN cadastro_pontos AS c ON c.onibus_ponto = s.onibus_ponto JOIN tab_garagens AS t ON t.onibus_prefixo = c.local WHERE data > (NOW() - INTERVAL 10 MINUTE) GROUP BY s.onibus_ponto

As duas consultas são consultas distintas em que eu gostaria de gerar uma terceira consulta com os dados que NÃO estão duplicados; lembrando que ambas possuem uma coluna em comum (c.local e prefixo) que trazem a mesma informação porém de lugares diferentes.

A: Como o MySQL não implementa FULL OUTER JOIN simule com UNION de LEFT JOIN e RIGHT JOIN e usando CTE para simplificar:
WITH
  cte1 AS (SELECT prefixo FROM getVeiculosLinha AS V JOIN getLinhas AS L ON V.cod_linha = L.cod_linha JOIN tab_garagens AS G ON V.prefixo = G.onibus_prefixo),
  cte2 AS (SELECT c.local FROM status AS s JOIN cadastro_pontos AS c ON c.onibus_ponto = s.onibus_ponto JOIN tab_garagens AS t ON t.onibus_prefixo = c.local WHERE data > (NOW() - INTERVAL 10 MINUTE) GROUP BY s.onibus_ponto)

SELECT prefixo, local FROM cte1 LEFT JOIN cte2 ON (prefixo = local) WHERE local IS NULL
UNION
SELECT prefixo, local FROM cte1 RIGHT JOIN cte2 ON (prefixo = local) WHERE prefixo IS NULL;


text:
Q: How to start service after reboot device in Android I want start my Service after reboot device, I write below codes but when reboot device not start Service.
Manifest:
<activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".alarm1.alarm1"></activity>

        <receiver android:name=".alarm1.AlarmReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

        <!-- Will not be called unless the application explicitly enables it -->
        <receiver android:name=".alarm1.DeviceBootReceiver"
            android:enabled="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

Activity code:
public class alarm1 extends AppCompatActivity {

    private PendingIntent pendingIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm1);

            /* Retrieve a PendingIntent that will perform a broadcast */
        Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, 0);

        findViewById(R.id.startAlarm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                start();
            }
        });

        findViewById(R.id.stopAlarm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancel();
            }
        });

        findViewById(R.id.stopAlarmAt10).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAt10();
            }
        });
    }

    public void start() {
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        int interval = 8000;

        manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
        Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
    }

    public void cancel() {
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        manager.cancel(pendingIntent);
        Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
    }

    public void startAt10() {
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        int interval = 1000 * 60 * 20;

        /* Set the alarm to start at 10:30 AM */
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 17);
        calendar.set(Calendar.MINUTE, 15);

        Toast.makeText(alarm1.this, "Start at 17:11", Toast.LENGTH_SHORT).show();

        /* Repeating on every 20 minutes interval */
        manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                1000 * 60 * 3, pendingIntent);
    }
}

AlarmReceiver codes:
public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // For our recurring task, we'll just display a message
        Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
    }
}

DeviceBootReceiver codes:
public class DeviceBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
            /* Setting the alarm here */
            Intent alarmIntent = new Intent(context, AlarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);

            AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            int interval = 8000;
            manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);

            Toast.makeText(context, "Alarm Set", Toast.LENGTH_SHORT).show();
        }
    }
}

How can I fix this and when reboot device start Service?

A: Add permissions in Manifest.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Add receiver entry in Manifest.
 <receiver android:enabled="true" android:name=".alarm1.DeviceBootReceiver"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

A: You just need to

*

*Request a permission

and

*Explicitly enable the receiver.

The permission goes in the manifest file:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

Then when the user sets an alarm (for example your start method), enable the boot receiver:
ComponentName receiver = new ComponentName(context, DeviceBootReceiver.class);
getPackageManager().setComponentEnabledSetting(receiver,
    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
    PackageManager.DONT_KILL_APP);

When the user cancels all alarms, you should disable the boot receiver using a similar piece of code.


text:
Q: Macbook Pro in 2-screen setup Is it possible to use a Macbook Pro 15" (latest) in a setup where an external LCD is connected and used as the primary screen while at the same time the Macbook's own screen is used as the secondary screen (= extends the primary screen to the right)?
(I'd like to work on a big monitor and use the Macbook screen for auxiliary stuff like Terminal windows.)

A: If You have Mavericks installed it's not a problem at all to quickly switch between the primary/secondary screen, because the menubar is present on both screens.
To move the Dock You only need to move your mouse cursor to the bottom of the second screen and then move the mouse down again.

EDIT:
On previous OSs you can also change the primary screen in Preferences -> Displays -> Arrangements and move the Menubar (white stripe) to secondary screen. Here you can also change the position of secondary monitor.


text:
Q: ternary operator within .filter() A simple example.
var evens= true;
var numbers = [1,2,3,4,5]
var result = [];

if(evens){
  result = numbers.filter(num => num%2 === 0)
} else {
  result = numbers.filter(num => num%2 !== 0)
}

Is there a way to get something like  result = numbers.filter(num => num%2 (evens) ? === : !==  0) where depending on 'evens' to use equals or not equals to 0 within the .filter function? Is there a way to reuse same function to not have replication?

A: How about just
result = numbers.filter(num => !(num % 2) === evens)

A: In general, I think your code is fine and readable.
To better understand how to write higher-order functions for cases where they might be more appropriate, I'll answer your question as written:
In this case, !== 0 is the same as === 1, which is much easier to generalize alongside === 0. We can write a function that returns a function output of the form num => num%2 === SOMETHING:
composeMod2Equals = target => num => num%2 === target

Then we can use it to build the necessary functions:
if(evens){
    result = numbers.filter(composeMod2Equals(0))
} else {
    result = numbers.filter(composeMod2Equals(1))
}

Or, since booleans will coerce to a 0/1 number, use !evens instead of the if:
result = numbers.filter(composeMod2Equals(+!evens))

This is much more generalized but vastly less readable! I'd suggest keeping what you have already.

A: You can do something like this:
result = numbers.filter(num =>{
    let condition = evens ? num % 2 ===0 : num % 2 !== 0;
    return condition;
})

A: No. You cannot use ternaries on operators, only on expressions. But that aside, you should not try stuff like this.
Ternaries serve a specific purpose, and this is not it.
Code should be readable, understandable and expandable. Your current code is just about okay but could be better.
For example:
function filterByModulo(numbers, divisor, mod) {
    return numbers.filter(num => num % divisor === mod);
}
function filterEvens(numbers) {
    return filterByModulo(numbers, 2, 0);
}
function filterOdds(numbers) {
    return filterByModulo(numbers, 2, 1);
}

Now you can use filterEvens() or filterOdds() as appropriate, and this can be extended to any future modulo-based filtering you may need.


text:
Q: Need explanation of this program in java I'm trying to understand, how the compareTo method is called in this program.
class Student implements Comparable {
    String dept, name;

    public Student(String dept, String name) {
        this.dept = dept;
        this.name = name;
    }

    public String getDepartment() {
        return dept;
    }

    public String getName() {
        return name;
    }

    public String toString() {
        return "[dept=" + dept + ",name=" + name + "]";
    }

    public int compareTo(Object obj) {
        Student emp = (Student) obj;
        System.out.println("Compare to : " +dept.compareTo(emp.getDepartment()));
        int deptComp = dept.compareTo(emp.getDepartment());

        return ((deptComp == 0) ? name.compareTo(emp.getName()) : deptComp);
    }

    public boolean equals(Object obj) {
        if (!(obj instanceof Student)) {
            return false;
        }
        Student emp = (Student) obj;
        boolean ii = dept.equals(emp.getDepartment()) && name.equals(emp.getName());
        System.out.println("Boolean equal :" +ii);
        return ii ;

    }

    public int hashCode() {
        int i2 = 31 * dept.hashCode() + name.hashCode();
        System.out.println("HashCode :" + i2);
        return i2;

    }
}

public class CompareClass {
    public static void main(String args[]) {
        Student st[] = { new Student("Finance", "A"),
                new Student("Finance", "B"), new Student("Finance", "C"),
                new Student("Engineering", "D"),
                new Student("Engineering", "E"),
                new Student("Engineering", "F"), new Student("Sales", "G"),
                new Student("Sales", "H"), new Student("Support", "I"), };
        Set set = new TreeSet(Arrays.asList(st));
        System.out.println(Arrays.asList(st));
        System.out.println(set);
    }
}

*

*Why is Arrays.asList(st) used?

*What is use of equals() and hashcode()?

A:
Why Arrays.asList(st) is used ?

Because the TreeSet constructor TreeSet(Collection c) accepts a Collection and not a String[] , hence you convert the String[] to a List which is a Collection using the method List asList(T... a). Note here , the array is same as varargs in this case.

What is use of equals() and hashcode() ?

Object class provides two methods hashcode() and equals() to represent the identity of an object.
You are using a TreeSet in your code . As per the documentation:

the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal.

Hence in your case , implementing Comparable and overriding compareTo() is enough .

Suggested Reading:

*

*Overriding equals and hashCode in Java.

*Hashset vs Treeset

*What is the difference between compare() and compareTo()?

A: .equals() is used because you are comparing two Objects.

A:
I m trying to understand ,how the compareTo method is called in this program.

Because what you use here is a TreeSet, which implements SortedSet, and for which uniqueness is calculated by comparing elements using their natural ordering, and not equality.
Classes implementing Comparable of themselves, or a superclass of themselves, can be compared to one another. For classes which do not, you can supply a Comparator instead.
When you add an element to a SortedSet, the set will first compare it to elements already present in the set, and only add it if no comparison gives 0. See below for a demonstration.
See also Collections.sort().

1.Why Arrays.asList(st) is used ?

because this is Java 1.4 code. In Java 5, you'd use Arrays.asList(s1, s2, etc) (ie, a varargs method).

2.What is use of equals() and hashcode() ?

In this case, none.

Sample program (with generics this time) illustrating the difference between a SortedSet and a HashSet, using BigDecimal:
final BigDecimal one = BigDecimal.ONE;
final BigDecimal oneDotZero = new BigDecimal("1.0");

one.equals(oneDotZero); // false
one.compareTo(oneDotZero); // 0

// HashSet: uses .equals() and .hashCode();

final Set<BigDecimal> hashset = new HashSet<>();
hashset.add(one); hashset.add(oneDotZero);
hashset.size(); // 2

// TreeSet: uses Comparable

final Set<BigDecimal> treeset = new TreeSet<>();
treeset.add(one); treeset.add(oneDotZero);
treeset.size(); // 1

A: There is a very good explanation of the Comparable interface in the Oracle documentation: http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html
In this code, Arrays.asList(st) is used basically because the author thought it was simpler to instantiate an Array in Java and convert it to a List than it is to create an ArrayList and call .add for each item.  It's really not critical to what is going on, though.  Another thing that happens on that same line is where the magic is.
Set set = new TreeSet(Arrays.asList(st));

This creates a TreeSet from the list.  It is worth taking a look at this post: What is the difference between Set and List? briefly.  In a Set, all elements are unique, so when you create a Set from a List that contains duplicates the Set constructor will throw the extra items away.  How does it determine what elements are duplicates?  It uses the methods of the Comparable interface.  Similarly, a List is sorted but a Set is not so the implementation can choose to store the items in the Set in whatever order is most efficient.  In the case of a TreeSet it handily explains how it does it right at the top of the Oracle documentation:

Note that the ordering maintained by a set (whether or not an explicit
  comparator is provided) must be consistent with equals if it is to
  correctly implement the Set interface. (See Comparable or Comparator
  for a precise definition of consistent with equals.) This is so
  because the Set interface is defined in terms of the equals operation,
  but a TreeSet instance performs all element comparisons using its
  compareTo (or compare) method, so two elements that are deemed equal
  by this method are, from the standpoint of the set, equal. The
  behavior of a set is well-defined even if its ordering is inconsistent
  with equals; it just fails to obey the general contract of the Set
  interface.

A: Some of the Java API was built around arrays and some of it was built around collections. asList is basically an adapter that lets your array be accessed like a collection.
Some data structures and algorithms operate on what's called the "hash" of a piece of data. This is done largely for performance reasons. In most cases the hash is a single number representing a particular object. You can see how this might be useful for sorting a collection quickly or checking equivalence.
equals exists of course to test if two objects represent the same thing.

A: .equals and .hashcode are methods inherited from the Object class in java by every class.
When creating your own class you would usually override these two default implementations because the default Object function generally does not lead to the desired behavior.
They are there for good measure really, but as it is they are not being used.


text:
Q: How can I programatically open the "compose" Box in GMail using Javascript I am creating a script for Gmail, which open Single compose Box in the Gmail page like when click on compose button. I have tried the following code but sometimes it opens multiple compose Boxes.
But I want to open only one compose box when script will run. Is there any other way to open Compose Box.
        var down = new MouseEvent('mousedown');
        var up = new MouseEvent('mouseup');
        var elem = document.getElementsByClassName("T-I-KE")[0];
        elem.dispatchEvent(down);
        elem.dispatchEvent(up);

Compose Box

A: You could be more robust and only dispatch the mouse events if the compose frame is not showing. The following seems to work for me.
var composeButton = document.getElementsByClassName("T-I-KE")[0];
var down = new MouseEvent('mousedown');
var up = new MouseEvent('mouseup');

function openCompose() {
    if (document.querySelectorAll('.dw.np').length) {
        composeButton.dispatchEvent(down);
        composeButton.dispatchEvent(up);
    }
}

openCompose();


text:
Q: SQL Select data with condition from result data Table Structure :
|Category_id |Parent_id|
|     193    |   185   |
|     200    |   193   |
|     11     |   193   |
|     150    |   193   |
|     145    |   185   |
|     165    |   145   |
|     123    |   11    |

First query = select * from table where parent_id = 185, result :
|Category_id |Parent_id|
|     193    |   185   |
|     145    |   185   |

Then repeated with same table, second query = select * from table where parent_id = 193 result:
|Category_id |Parent_id|
|     200    |   193   |
|     11     |   193   |
|     150    |   193   |

What I want to do is count (category_id from second query) with single query like
select *,(count(select * from table where parent_id = ..... )) AS count from table where parent_id = 185 order by count ASC with result like this :
|Category_id |Parent_id| Count |
|     193    |   185   |   3   |
|     145    |   185   |   1   |

I know I can do it, if do it 1 by 1 but it's waste loading so much.
it's possible build like that?
Thanks Advance.

A: SELECT
TT1.*,
  (
    SELECT COUNT(TT2.Category_id)
    FROM table TT2
    WHERE TT2.Parent_id = TT1.Category_id
  ) count
FROM table TT1
WHERE TT1.Parent_id = 185;

SQL Fiddle

A: Another option, avoiding using a sub query is to use a self join:-
SELECT t1.parent_id,
        t1.category_id,
        COUNT(t2.category_id)
FROM table t1
LEFT OUTER JOIN table t2 ON t1.category_id = t2.parent_id
WHERE t1.parent_id = 185
GROUP BY t1.parent_id,
        t1.category_id

This will count parent recodss who have 0 or more child records. If you only want those with 1 or more child records then change the LEFT OUTER JOIN to an INNER JOIN.


text:
Q: XPath Evaluation over not well-formed XML? I need to pass some not strictly well-formatted XML through an XPath evaluator. The XML is in fact mostly html, which could like the following:

So, the noticeable problems are that it: has no root element; Also  is not terminated. While it is easy to wrap with a root element, when I pass through the XPath evaluator, I get an exception something like:
[Fatal Error] :7:196: The element type "img" must be terminated by the matching end-tag "".

Btw, the code for the XPath Evaluator in Java looks like:
XPath xPath = XPathFactory.newInstance().newXPath();
Object result = xPath.evaluate(xpath,
    new InputSource(new StringReader(xmlString)), XPathConstants.NODESET);

So, I would like to know, what is the best way to deal with this, so that I could successfully evaluate the XML? It seems I have at least two options: (a) try to get the XPath evaluator to be more smart; or (b) try having a way to automatically repair the poorly formatted XML. A solution to this problem would be appreciated!

A: You could parse the HTML using an HTML parser such as NekoHTML, then run XPath queries over the resulting DOM tree
import org.cyberneko.html.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

DOMParser parser = new DOMParser();
parser.parse(new InputSource(new StringReader(xmlString)));
XPath xPath = XPathFactory.newInstance().newXPath();
Object result = xPath.evaluate(xpath, parser.getDocument(),
      XPathConstants.NODESET);

Note that NekoHTML produces the specific HTML DOM nodes by default, and these report their node names in upper case regardless of the case of the original input tags.  Therefore if you want an XPath that will extract all
 elements then you need //P rather than //p.

A: There are several utilities that will convert HTML or generally anything with angle-brackets into well-formed XML (which might or might not be the XML that you expected, but it will be well-formed). JTidy and TagSoup are often used in this role. You don't have to materialize the XML, you can pump it straight into the next step in your processing pipeline, e.g. an XSLT transformation or schema validation.


text:
Q: Cannot start Tensorboard when tensorflow is running I cannot start a tensorboard instance when tensorflow is already running and using the GPU. The error is below. Apparently Tensorflow blocks all GPU memory on start independent of what it actually requires. Is there a way to start tensorboard while a tensorflow process is running or does it always have be started first?
totalMemory: 5,93GiB freeMemory: 41,56MiB
2018-06-02 15:28:11.053634: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1435] Adding visible gpu devices: 0
2018-06-02 15:28:11.321850: E tensorflow/core/common_runtime/direct_session.cc:154] Internal: CUDA runtime implicit initialization on GPU:0 failed. Status: out of memory
Traceback (most recent call last):
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/bin/tensorboard", line 11, in <module>
    sys.exit(run_main())
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/lib/python3.6/site-packages/tensorboard/main.py", line 36, in run_main
    tf.app.run(main)
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 126, in run
    _sys.exit(main(argv))
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/lib/python3.6/site-packages/tensorboard/main.py", line 45, in main
    default.get_assets_zip_provider())
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/lib/python3.6/site-packages/tensorboard/program.py", line 166, in main
    tb = create_tb_app(plugins, assets_zip_provider)
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/lib/python3.6/site-packages/tensorboard/program.py", line 201, in create_tb_app
    flags=FLAGS)
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/lib/python3.6/site-packages/tensorboard/backend/application.py", line 126, in standard_tensorboard_wsgi
    plugin_instances = [constructor(context) for constructor in plugins]
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/lib/python3.6/site-packages/tensorboard/backend/application.py", line 126, in <listcomp>
    plugin_instances = [constructor(context) for constructor in plugins]
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/lib/python3.6/site-packages/tensorboard/plugins/beholder/beholder_plugin.py", line 47, in __init__
    self.most_recent_frame = im_util.get_image_relative_to_script('no-data.png')
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/lib/python3.6/site-packages/tensorboard/plugins/beholder/im_util.py", line 254, in get_image_relative_to_script
    return read_image(filename)
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/lib/python3.6/site-packages/tensorboard/plugins/beholder/im_util.py", line 242, in read_image
    return np.array(decode_png(image_file.read()))
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/lib/python3.6/site-packages/tensorboard/plugins/beholder/im_util.py", line 159, in __call__
    self._lazily_initialize()
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/lib/python3.6/site-packages/tensorboard/plugins/beholder/im_util.py", line 137, in _lazily_initialize
    self._session = tf.Session(graph=graph, config=config)
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1560, in __init__
    super(Session, self).__init__(target, graph, config=config)
  File "/home/pascalwhoop/Documents/Code/University/powerTAC/python-agent/venv/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 633, in __init__
    self._session = tf_session.TF_NewSession(self._graph._c_graph, opts)
tensorflow.python.framework.errors_impl.InternalError: Failed to create session.

A:
Tensorboard 1.7.0 seems to occupy about 150MB on the GPU. See this open Tensorboard issue. Looks like it's in the process of being resolved.
An option in the interim is to limit the percentage of memory Tensorflow is allowed to allocate per process upfront as detailed in this answer. This way you can ensure a certain percentage of memory is reserved for other tasks on the GPU that you might want to run during training.
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.8)

sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))


text:
Q: Concerning the nonlinear functional equation $f(x)f(x) =x+1+f(x+1)$ There's a problem I've been working on for awhile that involves some hefty functional equations. For example, I may have something along the lines of
$$
f(x)f(x) =x+1+f(x+1)
$$
I've tried several different methods of attack (the farthest I ever got was probably with a power series which didn't yield a recurrence relation)  but it never amounts to much. As if that wasn't bad enough, I don't actually know any values of $f(x)$, other than that $\lim_{x\to\infty}f(x)=\infty$. The thing is, I don't actually care about $f(x)$, I only want to know $f(0)$ (analytically) but I can never seem to get two equations for a given point.
I was wondering if anyone had any ideas on how to solve this, or even just some insight into whether or not it can be solved. Thanks!
Edit: Additional facts

*

*It can be required that $1<f(0)<2$

*$f(x)$ is strictly increasing

*$f(x)$ is non-negative

A: Your constraints are not strong enough to impose a unique value to $f(0)$.  In fact, I show below that there for every value $a$ between $1.8$ and $2$ there is a solution with $f(0)=a$ (in fact  for a given $a$ there are uncoutably many such solutions, as our construction will show).
Given a function $\phi : [0,1[ \to {\mathbb R}$, there is a unique solution $f: [0,+\infty[ \to {\mathbb R}$ to the functional equation that coincides with $\phi$ on $[0,1[$.  Indeed, we will have
$$
\begin{array}{lcl}
f(x)&=&\phi(x-1)^2-x=\phi_1(x) \ \ (\text{for }\ x\in[1,2[) \\
f(x)&=&\phi_1(x-1)^2-x=\phi_2(x) \ \ (\text{for }\ x\in[2,3[) \\
\end{array}\tag{1}
$$
and so on.
Now, let $a \in [1.8,2]$ and let $\phi : [0,1] \to {\mathbb R}$ be a continuous, strictly increasing map satisfying the boundary conditions $\phi(0)=a, \phi(1)=a^2-1$ (so for example you could take $\phi$ affine, or trigonometric, etc).
Then the $f$ uniquely defined by (1) will also be continuous and strictly increasing (in particular, $f$ will be positive).
So all we need to show is that $f \to +\infty$ at $+\infty$ ; since $f$ is strictly increasing, it suffices to show that $f(n) \to +\infty$ when $n$ is an integer.
We have
$$
\begin{array}{lcl}
f(1)&=&f(0)^2-1 \geq 1.8^2-1=2.24 \\
f(2)&=&f(1)^2-2 \geq 2.24^2-2=3.0176 \geq 3 \\
f(3)&=&f(2)^2-3 \geq 3^2-2=6 \\
\end{array}\tag{1}
$$
We can then use mathematical induction : let us show that $f(k) \geq k$, for every $k\geq 3$.
The $k=3$ case has just been checked. Suppose that the hypothesis is true for some $k\geq 3$.
  We have
$$f(k+1)=f(k)^2-(k+1) \geq k^2-(k+1)=k-2+(k-1)^2 \geq k-2+4=k+2 \geq k+1 $$
So the hypothesis holds on the next level. This shows that $\lim_{+\infty}(f)=+\infty$ as wished.