text:
Q: decoding a json to generic array or class in swift How do you decode json to a generic model in swift?
In java for decoding json I use GSON and in general it does not matter I use <T<E>> or ArrayList<E>.In swift Array is a struct and can't be inheritance and it has not implemented Decodable.
I'm looking for a generic elegant class to use in all my web service.
My scenario:
I have json response
{
"status": true,
"message": "",
"code": 200,
"response": [{
    "id": 43
}]
}

and a generic reponse model like this from web services:
class GeneralResponse< T : Decodable >:NSObject,Decodable{

    var status = false
    var message = ""
    var code = -1
    var response : T?

    private enum CodingKeys: String, CodingKey {
        case status
        case message
        case code
        case response
    }

    required public init(from decoder: Decoder) throws{
        let container = try decoder.container(keyedBy: CodingKeys.self)
        status = try container.decode(Bool.self, forKey: .status)
        message = try container.decode(String.self, forKey: .message)
        code = try container.decode(Int.self, forKey: .code)
        response = try container.decode(T.self, forKey: .response)
    }

}
class ItemDemoModel:Decodable {
     var id = -1
    private enum ItemDemModelCodingKeys : String, CodingKey {
        case id
    }
     required init(from decoder:Decoder) throws {
        let container = try decoder.container(keyedBy: ItemDemModelCodingKeys.self)
        id = try container.decode(Int.self, forKey: .id)
    }
}

response variable can be ItemDemoModel or an array of ItemDemoModel.
For example:
It can be GeneralResponse<Array<ItemDemoModel>>>
or GeneralResponse<ItemDemoModel>>
thanks.

A: If you declare a Decodable properties with same name as the key in json then you don't really need an enum to define Coding keys and an initializer to manually map every property with the key.
Also, there is no need to inherit from NSObject in Swift until you have a specific use case for that. Looking at the declaration, it seems unnecessary so your GeneralResponse can be redeclared as simple as this,
class GeneralResponse<T: Decodable>: Decodable {

    var code: Int
    var status: Bool
    var message: String?
    var response : T?
}

Similarly, ItemDemoModel can be declared as this,
class ItemDemoModel: Decodable {
     var id: Int
}

Now you can setup your service as below to get the GeneralResponse<T> for any request,
struct RequestObject {
    var method: String
    var path: String
    var params: [String: Any]
}

class WebService {

    private let decoder: JSONDecoder

    public init(_ decoder: JSONDecoder = JSONDecoder()) {
        self.decoder = decoder
    }

    public func decoded<T: Decodable>(_ objectType: T.Type,
                                      with request: RequestObject,
                                      completion: @escaping  (GeneralResponse<T>?, Error?) -> Void)  {
        // Here you should get data from the network call.
        // For compilation, we can create an empty object.
        let data = Data()

        // Now parsing
        do {
            let response  = try self.decoder.decode(GeneralResponse<T>.self, from: data)
            completion(response, nil)
        } catch {
            completion(nil, error)
        }
    }
}

Usage
let request = RequestObject(method: "GET", path: "https://url.com", params: [:])
WebService().decoded([ItemDemoModel].self, with: request) { (response, error) in
    if let items = response?.response {
        print(items)
    }
}

P.S; You must be used to declare arrays and dictionaries as below,
let array: Array<SomeType>
let dictionary: Dictionary<String: SomeType>
let arrayOfDictionary: Array<Dictionary<String: SomeType>>

But with Swift's type inference, you can declare an array and a dictionary as simple as below,
let array: [SomeType]
let dictionary: [String: SomeType]
let arrayOfDictionary: [[String: SomeType]]

A: Here you have a function you may want to use in order to decode your JSON:
func decode<T: Decodable>(_ data: Data, completion: @escaping ((T) -> Void)) {
    do {
        let model = try JSONDecoder().decode(T.self, from: data)
        completion(model)
    } catch {
        log(error.localizedDescription, level: .error)
    }
}

So you can just call your function like:
decode(data, completion: { (user: User) in
            // Do something with your parsed user struct or whatever you wanna parse
        })

I hope this helps :D

A: Array<T> conforms to Decodable if T conforms to Decodable, so GeneralResponse<[ItemDemoModel]> won't produce any errors.
As shown here:

You can simply do this:
let decoder = JSONDecoder()
let obj = try decoder.decode(type, from: json.data(using: .utf8)!)


text:
Q: Can I "stack" !important;? I googled a little bit and I couldn't find the answer.
My question is: does stacking !important works in some way? Or can I achieve the same functionality in another way? I'm aware that it's not a good practice
Example, say I have:
.myOuterDiv
{
   margin-left: 5px !important;
}

.myInnerDiv
{
   margin-left: 10px !important;
}

It's obvious that the content of the inner div will have a margin of 10px, but can I add another important such as
.myOuterDiv
{
   margin-left: 5px !important !important;
}

I wanna do exactly that, override the inner important so I can have a margin-left of 10. Can I do it like this or in some other way?

A: No, you cannot stack !important.. it doesn't work that way.
!important can be avoided a majority of the time, there are usually alternatives.

A: You can always override a CSS property by using a more specific selector.
If you have a rule being applied as .myOutterDiv { some-property: some-value !important; }, all you need to do is actually make yours have more weight. You can do that by doing, for example, div.myOutterDiv { some-property: some-other-value !important; }
Edit: You can read more details on CSS Specificity Value

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setting up MySQL cross-listing query I have a table Classes, which stores data on different college classes (a unique Class_ID and Department, Course, etc.).
Some Classes are cross-listed with multiple names.  For example, the same class might be cross listed as HIST-204 (History) and AAST-103 (African American Studies).  There can be more than 2 cross-listings for a class.
I'd like to store cross-listings properly, so that when students search for a class's textbooks (stored in Class_Books table) using any of its possible cross-listings, they are shown the required books.  It is not important whether students know about other cross-listings when they make a search, only that they get the books for that course.
I'm thinking of doing this by storing a Cross_List_ID in Classes, which would indicate that a given class is just a cross listing of an existing one, whose Class_ID would be stored in that field.  Then I would only need to store the required book (in Class_Books) for the Class_ID that was cross listed.  Then when students enter a class in the search, I'd make sure to include all books required for the Cross_List_ID.  If you agree that this is the way to go, I'd be interested in how you'd set up that query (to get the class-books for the class_id entered, as well as its cross-listing).
One other option would seem to be storing Class_Books data for every cross listing..  I don't want to do this method because the raw Class and Class-Book data which I upload to the database doesn't lend itself to this, because there are separate files for each, and only one of the cross-listings is linked to a Book in the Class-Book file.  Also, even if this method were easily feasible, it would use up more database space.
I'm open to other options if you disagree with my Cross_Listing_ID approach.  Like I said, if you agree with that approach then help me make a query!
Note: Structure of Class-Books is just Class_ID, Book_ID

A: If you have to pick between the two go with the first option. You don't want to have ostensibly duplicate entries in class books. That can cause all sorts of problems for you.
Update  Since you want Class ID to be in the where clause I've updated it.
As for the query this is how I would search for books
SELECT DISTINCT books.*
FROM
    classes main
    LEFT JOIN classes crosslinked
    ON main.Class_id = crosslinked.cross_link_class_id
    LEFT JOIN class_books books
    ON main.class_id =  books.class_id
WHERE
    main.class_id= 252
    OR
    crossLinked.class_id= 252

But you should take ijw's point. It would be much better to just have a class_names table that's associated with the class. It would be a bit cleaner. Then you don't have to do logic like : if cross_link_class_id is not null then don't allow students to register for it, a professor can't teach a class that has a null for cross_link_class_id.., after all you wouldn't want to accidentally overbook a class or double the number of classes a professor was being recorded as  teaching
Here's how it would be done with a separate class names table.
SELECT DISTINCT books.*
FROM
    classes
    --LEFT JOIN class_names names
    --ON main.Class_id = names.Class_id
    LEFT JOIN class_books books
    ON main.class_id =  books.class_id
WHERE
   clases.class_id  = 252

Notice the OR statement is gone and no funny self join (which can confuse people) and the aforementioned logic on empty cross_link_class_id is gone.
Note: I've taken some liberties with the query e.g the literal string would be replaced with a parameter. You wouldn't select * but use the actual field names.


text:
Q: Nativescript core OCR plugin I'm trying to develop an ocr app with the Nativescript plugin:
https://market.nativescript.org/plugins/nativescript-ocr
https://github.com/EddyVerbruggen/nativescript-ocr
and it seems that the example doesn't works or I'm doing something wrong. I read something about Firebase ML kit but I have no idea about that and if it works offline (Offline work is a must for me).
https://github.com/EddyVerbruggen/nativescript-plugin-firebase/blob/master/docs/ML_KIT.md
Could be deprecated the first plugin?
might I use firebase?
could it use with nativescript core (only js)?
It works offline?
Any idea about how to start?

A: Yes, the OCR plugin is kind of deprecated, not actively maintained anymore.
Firebase ML-Kit is recommended and it has different methods you could use for text recognition, one works on device and another on cloud. Refer the same read me you have linked in your question.


text:
Q: How to manage Tycho / EAP versioning correctly I have an Eclipse 4 project that is built using Tycho (0.19.0) and Maven (3.0-5)
During development of a version, say 1.0.0, the artifacts are configured with version 1.0.0-SNAPSHOT, and 1.0.0.qualifier depending on the files. When I want to release the version, I use the tycho-versions:set-version goal to change from 1.0.0-SNAPSHOT to 1.0.0.
I then build and copy the product to a remote share that publishes an update site so that older versions can be upgraded automatically at launch time.
Since I have some beta testers, I use more that one update site. One contains the stable versions, and my beta testers have one more update site to check at startup. The other one is actually an update site for snapshots that I have published, so those are not released versions of the product.
What I am experiencing seems strange: When the 1.0.0 application starts, it finds the previous snapshot (versioned 1.0.0.201312191455), thinks that those artifacts are more recent and updates itself back to an older version.
I'm guessing that Eclipse's version conventions state that x.y.z is older than x.y.z.u. Is that correct?
If so, then why does the tycho versions plugin remove the qualifier when a versions changes from snapshot to "release"? Doing so seems to make the artifacts look older than any of the snapshots. What's the correct way to handle this situation?

A: The answer was given in the tycho mailing list some time ago:
http://dev.eclipse.org/mhonarc/lists/tycho-user/msg01001.html
The details:

OSGi does not have a notion of "snapshot" versions, all versions are
  treated the same and 1.0.0.qualifier is indeed considered to be newer
  than 1.0.0.
There are two versioning schemes that result is reasonable behaviour
  both for OSGi and Maven.
Use the same four part version (eg., 1.0.0.20111112-0735) for both Maven
  and OSGi. This results in slightly odd version jump when going from
  snapshots to releases on the maven side, i.e. 1.0.0-SNAPSHOT goes to
  1.0.0.20111112-0735, but everything works otherwise.
Use even/odd convention to version snapshots and releases, i.e.
  1.0.1-SNAPSHOT/1.0.1.qualifier is released as 1.0.2/1.0.2.
I think it is also possible to decouple maven and osgi versions of
  released artifacts, i.e. use 1.0.0 for maven and 1.0.0.20111112-0735 for
  OSGi, but personally I find this confusing and would not recommend. And
  I am not sure if Tycho will allow this in the future.
--
  Regards,
  Igor


text:
Q: Sound quality problem on Dell Vostro 14 3000 We have purchased this brand new Dell Vostro 14 3000 laptop which comes with 8GB RAM and SSD drives.
Tried installing latest Ubutnu 20.04.3 LTS on this machine, but it has problem with the sound quality. When any kind of sound is played there is a weird buzz in the back ground.
Have tried searching for any updated drives on Dell website, but could not find any.
Is anyone else facing similar problem ? Any help will be appreciated.
Thanks
Regards,
Sam


text:
Q: How to parse a variable into firebase.database().ref().set({...}) i am trying to add firebase into my react-native application, and have the following code:
_saveFile(fileName){
    var userPath = "/Users/Johnny/files/";
    var storageString = ("Johnny Johnson\n"+ date + "\n" +
            this.state.text);
    var name = fileName;

    firebase.database().ref(userPath).set({
        name : storageString
    })

}

But as you can probably guess, this isn't getting the name variable and storing it as the key. It is simply storing it in the database as..
Users -> Johnny -> files -> {name: "whatever the string was i saved"}
and then simply overriding it every time i try and make a new file. Just wondering how i go about parsing in this fileName variable? It is getting the child value correctly - which is why i am confused.
Any help would be appreciated, i'm pretty new to this.

A: If you put brackets around name it will use the name variable instead of creating a key called name.
firebase.database().ref(userPath).set({
    [name] : storageString
})


text:
Q: Comparison method violates its general contract, how to make it transitive? I dont see how it is not transitive, please someone suggest me the right way.
if both values are null
I return 0, the two other statements are pretty obvious.
Why i got IllegalArgumentException with:
Comparison method violates its general contract
My compare method: (I compare doubles)
@Override
public int compare(HashMap<String, String> lhs, HashMap<String, String> rhs) {

    double dist1 = 0;
    double dist2 = 0;

    int compInt1 = 0;
    int compInt2 = 0;

    if (lhs.get("dist") != null && rhs.get("dist") != null && !lhs.get("dist").equals("") && !rhs.get("dist").equals("")) {

        dist1 = Double.parseDouble(lhs.get("dist").substring(0, lhs.get("dist").length() - 3));
        dist2 = Double.parseDouble(rhs.get("dist").substring(0, rhs.get("dist").length() - 3));

        dist1 = dist1 * 100;
        dist2 = dist2 * 100;

        compInt1 = (int) dist1;
        compInt2 = (int) dist2;

    }

    if (compInt1 < compInt2) {
        return -1;
    } else if (compInt1 >= compInt2) {
        return 1;
    } else {
        return 0;
    }

}

A: Look at this code:
if (compInt1 < compInt2) {
    return -1;
} else if (compInt1 >= compInt2) {
    return 1;
} else {
    return 0;
}

How do you expect that ever to return 0? What values of compInt1 and compInt2 would make both if conditions fail?
This violates symmetry too - it means that compare(x, y) and compare(y, x) can both return 1...
Assuming you're really just trying to compare compInt1 and compInt2 in the obvious way at this point, just replace the whole block with:
// As of Java 7...
return Integer.compare(compInt1, compInt2);

If you're using Java 6 (or earlier) you could use:
return Integer.valueOf(compInt1).compareTo(compInt2);

That's a little inefficient, but it's at least worth using to start with, just to get everything working.
Additionally, I'd strongly recommend extracting the lhs.get("dist") and rhs.get("dist") expressions from your first part - it's horribly repetitive at the moment. And just declare dist1 and dist2 within the block - they're not used elsewhere.

A: The condition  else if (compInt1 >= compInt2) is ambiguous as it would return a value of 1 even if both values are equal. Replace your comparison logic of ints as follows :
 return compInt1  - compInt2;

A: Transitivity defines as :
compare(a, b) == -compare(b, a)

Which implies compare(a, a) == -compare(a, a) == 0
Now, considering your code,
compare(a, a) == 1


text:
Q: Better way to insert excel range as row and copy formats using c# I have to insert row of range which has many merged cells,styling and number format many times before writing data to them.
When I insert a row its not copying maerged cells ,style or number formats etc.
Hence I selecting range as a row and insert the same,and copying the previous row to newly inserted row.
This process taking more and more time as i had to do this many times .
This is how I'm doing
Range rangeToInsert = Worksheet1.get_Range("a" + Convert.ToString(20), "z" + Convert.ToString(20));
Range rangeToInsertRow= rangeToInsert.EntireRow;

rangeToInsertRow.Insert(app.XlInsertShiftDirection.xlShiftDown, false);
Range InsertedRowRange= Worksheet1.get_Range("a" + Convert.ToString(newrowNum), "z" + Convert.ToString(newrowNum));
rangeToInsert.copy(InsertedRowRange);

Please suggest if there is any optimization to my code to do Row insert/copying style faster.

A: Maybe try like this
Range rngToCopy = ws.get_Range("A" + 20, "Z" + 20);
rngToCopy.Copy();
rngToCopy.Offset[1, 0].Insert(XlInsertShiftDirection.xlShiftDown, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);

also you could wrap the entire copy-paste snippet with (before any work on cells)
xlApp.ScreenUpdating = false;

and (after you've done modifying cells)
xlApp.ScreenUpdating = true;


text:
Q: Some tabular problems Would someone mind helping me out with some tabular problems that I am having ? Basically, my table is going off the page (I am not that good at defining tables with text) and if anyone has any other good ideas to make this table more clean, I would greatly appreciate it. Here is the code I am working with:
\documentclass[a4paper]{article}
\usepackage{amsmath}
\usepackage[english]{babel}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\usepackage[margin=1.25in,top=1in,bottom=1in]{geometry}
\makeatletter
\setlength\parindent{0pt}
\usepackage{ amssymb }
\usepackage{booktabs}% http://ctan.org/pkg/booktabs
\newcommand{\tabitem}{~~\llap{\textbullet}~~}
\begin{document}
    \begin{tabular}{llll}
        \toprule
        Topics & General $(n \times n)$ matrix & Hermitian & Real Symmetric \\
        \midrule
        Eigenvalues & Always have $n$ eigenvalues, \\

        & some may be repeated or c.c & All real eigenvalues & Real symmetric  \\[.5\normalbaselineskip]
        Eigenvectors & \\ \tabitem eigenvectors are l.i \\ for distinct eigenvalues \\
                       \tabitem If there are $n$ distinct \\ eigenvalues, then the eigenvectors forms \\ a basis for $C^n$ \\ & Orthogonal for distinct eigenvalues \\ &  They always form an orthonormal matrix \\

        \bottomrule
    \end{tabular}
\end{document}

And here is a picture of the problem I am having:
I am not that familiar with adding longer text in tables as I have mainly been using it for displaying numbers but if someone could give some advice, I would greatly appreciate it.
Thank you

A: I think the following might be what you are looking for, but i am not sure.

\documentclass[a4paper]{article}
\usepackage{amsmath}
\usepackage[english]{babel}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\usepackage[margin=1.25in,top=1in,bottom=1in]{geometry}
\usepackage{amssymb}
\usepackage{tabularx}
\usepackage{booktabs}% http://ctan.org/pkg/booktabs
\newcommand{\tabitem}{~~\llap{\textbullet}~~}
\begin{document}
\begin{tabularx}{\linewidth}{l>{\raggedright\arraybackslash}X>{\raggedright\arraybackslash}Xl}
    \toprule
    Topics & General $(n \times n)$ matrix & Hermitian & Real Symmetric \\
    \midrule
    Eigenvalues  & Always have $n$ eigenvalues, some may be repeated or c.c    & All real eigenvalues & Real symmetric  \\
    Eigenvectors & \tabitem eigenvectors are l.i for distinct eigenvalues \par
    \tabitem If there are $n$ distinct eigenvalues, then the eigenvectors forms a basis for $C^n$             & Orthogonal for distinct eigenvalues They always form an orthonormal matrix \\
    \bottomrule
\end{tabularx}
\end{document}


text:
Q: How to fetch top 10 scores from a specific gamecenter leaderboard with swift (iOS) How to fetch top 10 scores from a specific gamecenter leaderboard in swift (iOS)?
I'd like to fetch top 10 scores and players from leaderbaord and build a custom "HALL OF FAMES" in game.
How to fetch datas from leaderbaord?

A: Meanwhile i found an answer:
    let leaderBoardRequest = GKLeaderboard()
    leaderBoardRequest.identifier = kGcIdHighScore // my GC Leaderboard ID
    leaderBoardRequest.playerScope = GKLeaderboardPlayerScope.Global
    leaderBoardRequest.timeScope = GKLeaderboardTimeScope.AllTime
    leaderBoardRequest.range = NSMakeRange(1,10) // top 10

    leaderBoardRequest.loadScoresWithCompletionHandler
        { (scores, error) -> Void in
            if (error != nil)
                {
                    print("Error: \(error!.localizedDescription)")
                } else if (scores != nil)
                  {

                  print("got top \(scores?.count) scores"  )

                    var ii = 0
                    while (ii < scores?.count)
                    {
                        NSLog("%i ....... %@ %i %i", Int(ii+1), scores![ii].player.alias! , scores![ii].rank , scores![ii].value )
                        ii = ii + 1
                    }

                  }
        } // end leaderBoardRequest.loadScoresWithCompletionHandler

A: I have used the above and tweaked it to work with Swift 4
I have created a function to get scores inside it I am appending the results into an array of Tuples where:
0-element is the place achieved
1-element is the GameCenter player name
2-element is the score
I have used that to populate everything into a tableView. Tweak it to your needs
import GameKit
import UIKit

class HighScoresViewController: UIViewController, GKGameCenterControllerDelegate, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var scoreTableView: UITableView!

var highScores = [(String,String,String)]()
let LEADERBOARD_ID = "com.yourLeaderboard"

override func viewDidLoad() {
    super.viewDidLoad()
    scoreTableView.delegate = self
    scoreTableView.dataSource = self
    getScores()
}

func getScores(){
     let leaderBoardRequest = GKLeaderboard()
     leaderBoardRequest.identifier = LEADERBOARD_ID // my GC Leaderboard ID
     leaderBoardRequest.playerScope = GKLeaderboardPlayerScope.global
     leaderBoardRequest.timeScope = GKLeaderboardTimeScope.allTime
     leaderBoardRequest.range = NSMakeRange(1,10) // top 10

     leaderBoardRequest.loadScores
        { (scores, error) -> Void in
            if (error != nil)
            {
                print("Error: \(error!.localizedDescription)")
            } else if (scores != nil)
            {
                print("Top \(scores?.count ?? 0) scores"  )

                var ii = 0
                while (ii < scores?.count ?? 0)
                {
                    self.highScores.append(("\(scores![ii].rank)" , "\(scores![ii].player?.alias! ?? "Player")" , "\(scores![ii].value)"))
                    print(Int(ii+1) , scores![ii].rank , scores![ii].player?.alias! ?? "Player" , scores![ii].value )
                    ii = ii + 1
                }
                self.refreshTableData()                }
    } // end leaderBoardRequest.loadScoresWithCompletionHandler
}

func refreshTableData(){

    print("refreshed")
    self.scoreTableView.reloadData()
  }
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "scoreCell", for: indexPath) as! ScoreTableViewCell
    cell.placeAchieved.text = highScores[indexPath.row].0
    cell.playerName.text = highScores[indexPath.row].1
    cell.playerScore.text = highScores[indexPath.row].2
    return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return highScores.count
  }
}

And here is my TableViewCell file consisting of labels
import UIKit

class ScoreTableViewCell: UITableViewCell {
   @IBOutlet weak var placeAchieved: UILabel!
   @IBOutlet weak var playerName: UILabel!
   @IBOutlet weak var playerScore: UILabel!

}


text:
Q: Usage examples of binary search I just realized that in my 4+ years of Java programming (mostly desktop apps) I never used the binary search methods in the Arrays class for anything practical. Not even once. Some reasons I can think of:

*

*100% of the time you can get away with linear search, maps or something else that isn't binary search.

*The incoming data is almost never sorted, and making it sorted requires an extra sorting step.

So I wonder if it's just me, or do a lot of people never use binary search? And what are some good, practical usage examples of binary search?

A: On the desktop, you're probably just dealing with the user's data, which might not be all that big. If you are querying over very large datasets, shared by many users, then it can be a different matter. A lot of people don't necessarily deal with binary search directly, but anyone using a database is probably using it implicitly. If you use AppEngine, for example, datastore queries almost certainly use binary search.

A: I would say it boils down to this:
If we are going to do a binary search, we're going to have a key to search by. If we have a key, we're probably using a map instead of an array.
There's another very important thing to keep in mind:
Binary search is a clear-cut example of how thinking like a good programmer is very different than thinking like a normal person. It's one of those cognitive leaps that makes you really think about taking operations that are traditionally done (when done by humans) in order-n time and taking it down to order-lg-n time. And that makes it very, very useful even if it's never used in production code.

A: I hardly ever, if ever use a binary search.
But I would if:

*

*I needed to search the same list multiple times

*the list was long enough to have a performance problem (although I'm often guilty of micro-optimization)
However, I often use hash tables / dictionaries for fast lookups.

A: For production code on my day job, a Set or Map is always good enough so far.
For algorithmic problems that a I solve for fun, binary search is a very useful technique. For starters, if the set of elements never changes (i.e. you are never going to insert or delete elements in the set being queried) a Map/Set has no advantage over binary search - and a binary search over a simple array avoids a lot of the overhead associated with querying a more complex data structure. In many cases I have seen it to be actually faster than a HashMap.
Binary search is also a more general technique than just querying for membership in a set. Binary search can be performed on any monotone function to find a value for which the function satisfies a certain criteria. You can find a more detailed explanation here. But as I said, my line of work does not bring up enough computationally involved problems for this to be applicable.

A: Assume you have to search an element in a list.
You could use linear search, you'll get O(n).
Alternatively, you could sort it by fastest algorithm (O(log n)*n), and binary search(O(log n)). You'll get O((log n)*n + log n).
That means when searching large size of list, binary search is better. Also, it depends data structure of list. If list is a link based list, binary search is bad practice.


text:
Q: Passing arguments to pmap in mutate I have a problem with passing arguments to purrr::pmap when using with mutate.
I don't understand why some things work and some don't.
My example data:
sdf <- tibble(
  col_id  = c("id1",  "id2", "id3", "id4", "id5", "id6",  "id7",  "id8", "id9", "id10"),
  col_a  = c(0.7,  0.3, 1.4, 0.7, 0.5, 1.1,  0.1,  0.6, 1.7, 0.5),
  col_b  = c(NA, 0.6, 0.2, 0.2, 0.7, 0.2, 0.7,  3.7, 0.7, 0.7),
  col_c  = c(0.3, 0.4,  1.0,  NA,  3.1,  0.2, 0.4,  1.0, 0.1, 0.5))

params = c("col_a", "col_b", "col_c")

Then I want to execute some functions in rows using pmap_dbl.
First code (below) evaluates as intended.
# code 1
sdf_2 <- sdf %>%
  select(all_of(params)) %>%
  mutate(sum_p = pmap_dbl(., sum, na.rm = TRUE))

But the same syntax doesn't work with a different function:
sdf_2 <- sdf %>%
  select(all_of(params)) %>%
  mutate(mean_p = pmap_dbl(., mean, na.rm = TRUE))

Error in mutate(., mean_p = pmap_dbl(., mean, na.rm = TRUE)) :
Caused by error in mean.default():
! argument "x" is missing, with no default

Also, when I try to pass parameters to sum function directly - not by ... it does not work
sdf_2 <- sdf %>%
  select(all_of(params)) %>%
  mutate(sum_p = pmap_dbl(., sum(na.rm = TRUE)))

Error in mutate(., sum_p = pmap_dbl(., sum(na.rm = TRUE))) :
Caused by error in pluck():
! argument "x" is missing, with no default

What is the correct way to pass parameters to functions inside pmap when working on whole dataframe horizontally?
Next question:
Is there any way to pas column names stored in params to perform function in pmap only on them?
select(all_of(params)) works but result dataframe has no id column. It's easy to recreate, but would be nice to not remove it at all.

A: Why can't I parse mean to pmap?
Try:
mean(0.7, NA, 0.3, na.rm = TRUE)
sum(0.7, NA, 0.3, na.rm = TRUE)

mean take argument x,sum takes ... directly (check documentation). You'll need:
mean(c(0.7, NA, 0.3), na.rm = TRUE)

I.e.
library(dplyr)
library(purrr)

sdf |>
  mutate(mean_p = pmap_dbl(across(params), ~ mean(c(...), na.rm = TRUE)))

Output:
# A tibble: 10 × 5
   col_id col_a col_b col_c mean_p
   <chr>  <dbl> <dbl> <dbl>  <dbl>
 1 id1      0.7  NA     0.3  0.5
 2 id2      0.3   0.6   0.4  0.433
 3 id3      1.4   0.2   1    0.867
 4 id4      0.7   0.2  NA    0.45
 5 id5      0.5   0.7   3.1  1.43
 6 id6      1.1   0.2   0.2  0.5
 7 id7      0.1   0.7   0.4  0.4
 8 id8      0.6   3.7   1    1.77
 9 id9      1.7   0.7   0.1  0.833
10 id10     0.5   0.7   0.5  0.567

How to to specify variables in pmap?

*

*With cur_data()
library(dplyr)
library(purrr)

sdf |>
  mutate(sum_p = pmap_dbl(select(cur_data(), all_of(params)), sum, na.rm = TRUE))

*With across
library(dplyr)
library(purrr)

sdf |>
  mutate(sum_p = pmap_dbl(across(params), sum, na.rm = TRUE))

*Manual list

library(dplyr)
library(purrr)

sdf |>
  mutate(sum_p = pmap_dbl(list(col_a, col_b, col_c), sum, na.rm = TRUE))

*With unquote-splicing:

library(dplyr)
library(purrr)
library(rlang)

sdf |>
  mutate(sum_p = pmap_dbl(list(!!!syms(params)), sum, na.rm = TRUE))

Output:
# A tibble: 10 × 5
   col_id col_a col_b col_c sum_p
   <chr>  <dbl> <dbl> <dbl> <dbl>
 1 id1      0.7  NA     0.3   1
 2 id2      0.3   0.6   0.4   1.3
 3 id3      1.4   0.2   1     2.6
 4 id4      0.7   0.2  NA     0.9
 5 id5      0.5   0.7   3.1   4.3
 6 id6      1.1   0.2   0.2   1.5
 7 id7      0.1   0.7   0.4   1.2
 8 id8      0.6   3.7   1     5.3
 9 id9      1.7   0.7   0.1   2.5
10 id10     0.5   0.7   0.5   1.7

The fast way: Using rowMeans and rowSums with across:
library(dplyr)

sdf |> mutate(mean_p = rowMeans(across(params), na.rm = TRUE))
sdf |> mutate(sum_p = rowSums(across(params), na.rm = TRUE))

Update: Add fourth way

A: When passed a dataframe and function, pmap() expects the column names of the dataframe to correspond to the arguments of the function. For instance,
fx <- function(a, b, c) (a + b)^c

dat <- data.frame(a = 1:3, b = 4:6, c = 3:1)

dat %>%
  mutate(d = pmap_dbl(., fx))

  a b c   d
1 1 4 3 125
2 2 5 2  49
3 3 6 1   9

mean() expects an argument called x, but there's no column x in your data - hence the error.
However, if a function takes ... as its first arg, pmap() just passes all columns to .... This is the case for sum(), which is why your code works with sum().


text:
Q: How to find scala api documentation for string class How to find the API for the String class in Scala. Specifically I need to read the exists method.

A: You can't find documentation for the String class itself in Scala API docs because it isn't a Scala class, it's from the Java standard library, so you can find its documentation at https://docs.oracle.com/javase/8/docs/api/java/lang/String.html. Scala-specific methods like exists are added to it using implicit conversions in scala.Predef, which has this to say about String:

The String type in Scala has methods that come either from the underlying Java String (see the documentation corresponding to your Java version, for example http://docs.oracle.com/javase/8/docs/api/java/lang/String.html) or are added implicitly through scala.collection.immutable.StringOps.

A: There's the online docs and in Scala 2.11.8 the REPL can provide interactive API documentation.
scala> val s = "foo"
s: String = foo

scala> s.exists
   override def exists(p: Char => Boolean): Boolean

When I type s. and then hit tab the function definition for exists is shown. So, if we want to see if "f" exists in s we can use the definition shown for exists. i.e.
scala> s.exists(c => c == 'f')
res0: Boolean = true


text:
Q: Java Multiplayer Game Networking Concept I'm developing a multiplayer turn based strategy game in Java (both client and server). I don't have much experience in networked games but I have done small things like a multiclient chat and 2 player tic tac toe with sockets. I'm not looking for someone to code this for me but just give me some guidance.
The game goes through multiple stages: first a user connects and logins. After he is given the option to host/join a game. After he joins a game or someone joins his game, the client moves on to the game stage. The game is 1v1 and only needs to send data back and forth every 5 seconds (if that's important?). I just need some guidance on how you could design a client/server to move through these "stages".
This is how I'm currently thinking of implementing it:

*

*When a connection is made the connection will have a corresponding variable that describes state on the server. For example: 0 is before login, 1 is after login, 2 is hosting, etc...

*Whenever the client sends data to the server it checks for the state and deals with it accordingly. Like before login if data is sent, the server will assume it's login details and if they're valid it changes the variable to 1 and tells the client to advance.
Is there a better way to do this?

A: Since is Full Java + Client-Server + Game:
I recommend you to forget using straight sockets.
In my opinion Java RMI is your best bet.
Why?:

*

*Easier than sockets once you have it learned.

*You can call remote methods straight from your java client/server.

*You can use callbacks. (i.e. Server testing that the clients are still connected)
There are probably even more reasons...

A: Essentially how you described it is how it is commonly done. Simply have a server listening for client connections, and then deal with client connections in its own thread as they come up. Then send messages back and forth to confirm state (logged in vs. logged out, joining game, etc.) and messages while in game for player moves. Either a TCP or UDP socket will work in the short term, however eventually you will probably switch to a primarily UDP based system as the messages sent between server and client will be fairly small and latency could be key depending on the game type.
Consider sending/recieving messages via JSON (http://wiki.fasterxml.com/JacksonHome is a fairly popular Java parser last I checked).
Additionally, you'll need several data structures on the server side to efficiently manage clients and their states. For example, you could have an integer id for each client and a Map<Integer, Client> that you would use to store all currently connected logged in users, where Client is some object that stores the current state of that user.
Hopefully this gives you some ideas on where to start.

A: You can use Mina or Netty as Nio socket framework. Using Java both in server and client makes it easier to design message protocol. When one client moves, you send a moving message to the server, and then server pushes back a message to both clients. Both clients move together when receiving the message. Thus two clients move synchronously if avoiding network delay.
You can take a look at the open-source game framework written in java.
java game server engine


text:
Q: How to get the outer "this" reference in JavaScript So I have a class lets call it A. For this class I have written a few functions which I can call like this:
var a = new A();
a.getSomething();
a.putSomething();
a.delSomething();

And so on. Now I thought I'd organize it a bit So it wouldn't get too cluttered and would look  like a bit more like this:
a.something.get();
a.something.put();
a.something.del();

And this is how I tried to achieve this:
A.prototype.something = {
  get: function(){...},
  put: function(){...},
  del: function(){...}
};

But these functions (get, put and del) still need to access the common objects/functions found in A, so I need a reference to A, but I don't know how this can be achieved.
One option I found goes like that:
A.prototype.something = function(){
  var that = this;
  return {
    get: function(){...},
    ...
  };
};

And 'that' would be used in those (get, put and del) functions instead of 'this'. But this would mean I would have to call these functions in such way:
a.something().get();
...

Which doesn't seem very nice to me. So is there a way I could organize these things the way I originally planned?

A: You can't add this to the prototype, because the something member is not the same on all objects - internally, its methods must obtain a closure to the outer object, which is not possible to obtain at the time of execution.
You need to do it in the constructor:
function A() {
    var that = this;
    this.something = {
       get: function(){...},
       ...
    };
}

A:
So I have a class

Javascript doesn't have classes. It has prototype inheritance that can emulate classes to a limited extent, but that isn't worthwhile purely for the sake of emulating classes. Much better to make optimal use of built–in language features rather than trying to make javascript emulate some other language.
So you have a constructor...

I have written a few functions which I can call like this:
var a = new A();
a.getSomething();
a.putSomething();
a.delSomething();

Presumably those methods are all on A.prototype.

And so on. Now I thought I'd organize it a bit So it wouldn't get too cluttered and would look like a bit more like this:
a.something.get();
a.something.put();
a.something.del();

That isn't less cluttered (to me). I guess there is some common thing that is done by something, and that its get, put, etc. methods want to operate on a not on something.
The value of this is set by the call, there is no other way to set its value other than with ES5 bind. So the method being called must have access to a somehow. Other answers show how to do that with a closure, but the consequence is that each instance must have its own something object and attached methods.
The following is similar, but gets rid of the closure and puts the methods on Something.prototype for a bit of efficiency:
function A(name) {
    this.name = name;
    this.something = new Something(this);
}

function Something(that){
    this.that = that;
}

Something.prototype.get = function() {
    return this.that.name;
}
Something.prototype.put = function(prop, value) {
    this.that[prop] = value;
}

var a = new A('a');

alert(a.something.get());     // a
a.something.put('name', 'z');
alert(a.something.get());     // z

So you can have multiple somethings, each with different put, get, etc. methods. But the intervening something object is really just a device that uses more memory (probably a tiny amount) and requires an extra character. Simpler to keep the something methods on A.prototype and not have to type the extra dot (.).

A: function A() {
  this.something = this;
}
A.prototype = {
  get: function(){...},
  put: function(){...},
  del: function(){...}
};

therefore:
a.something.get();
a.something.put();
a.something.del();


text:
Q: Bug in the Late Answers, First Posts and Suggested Edits review queues allow to arbitrarily mark items as reviewed, even if they were not Both in the Late Answers and First Posts queue, clicking "edit", not editing the post and clicking "Save Edits" triggers the dimming of the "No Action Needed" button and the appearence of the "I'm Done" button:

Aside from the "per se" harmless GUI bug, the problem is that this allows to click the "I'm Done" button, which has the effect of marking the item as reviewed, even if it was not: link to the answer, link to the review.
As you can see, despite the fact that the post hasn't been touched (the edit doesn't appear in the revisions history), the item in the review has still been marked as reviewed.
A similiar thing happens also in the Suggested Edits queue, although I was able to do this only once; I don't have screenshots for this one but I have the links; clicking "Improve Edit", not editing the post and clicking "Save Edits" has the effect of marking the item as reviewed (as approved and edited), even if it was not: link to the question, link to the review.
As you can see, despite the fact that the post hasn't been touched (the edit doesn't appear in the revisions history), the item in the review has still been marked as reviewed.


text:
Q: Angular UI Grid space between capital letters in header When I use multiple capital letters in the header cells (e.g. GPRS) they automatically get separated by spaces (G P R S). This gets particularly annoying when I have two words (GPRS Signal is displayed as G P R S Signal) or two acronyms (GPRS EDGE is displayed as G P R S E D G E).
Is this meant to be like this? If so, how can i disable it?

A: I just found a way around this. In the columnDefs property of your gridOptions add a displayName for the column that contains multiple capital letters. Something like this:
$scope.gridOptions = {
  columnDefs: [
    { name: 'GPRS', displayName: 'GPRS', field: 'gprsField' }
  ]
};

A: To answer the question: how can I disable it?
I modified the source code.  My application is using a local copy of the file in lib/ui-grid.info-x.x.x/release/ui-grid.js
Search for the function called "readableColumnName" and replace or comment out the following:
      return columnName;
  //return columnName.replace(/_+/g, ' ')
    // Replace a completely all-capsed word with a first-letter-capitalized version
    //.replace(/^[A-Z]+$/, function (match) {
    //  return angular.lowercase(angular.uppercase(match.charAt(0)) + match.slice(1));
    //})
    // Capitalize the first letter of words
    //.replace(/([\w\u00C0-\u017F]+)/g, function (match) {
    //  return angular.uppercase(match.charAt(0)) + match.slice(1);
    //})
    // Put a space in between words that have partial capilizations (i.e. 'firstName' becomes 'First Name')
    // .replace(/([A-Z]|[A-Z]\w+)([A-Z])/g, "$1 $2");
    // .replace(/(\w+?|\w)([A-Z])/g, "$1 $2");
    //.replace(/(\w+?(?=[A-Z]))/g, '$1 ');

In other words, just return the columnName, don't do any replacing.
Don't forget to reload your webpage/javascript files before you test that it's working correctly.

A: You can also use display name property in UI-Grid : displayName: 'CAPITAL WORDS'

displayName : Column name that will be shown in the header. If
  displayName is not provided then one is generated using the name.

DEMO


text:
Q: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3 in IE 11 while trying to upload an excel While uploading an excel with more than some amount of records (excel with less number of records works fine) in IE 11 throws the following error in console and aborts the request.
    Network Error 0x2ef3, Could not complete the operation due to error 00002ef3
    SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3.

I'm using the following code to upload the excel,
       function uploadFile(url, file, config) {
        var fdata = new FormData();
        fdata.append('file', file);
        var promise = $http({
            url: webRoot(url),
            method: 'POST',
            data: fdata,
            withCredentials: true,
            headers: { 'Content-Type': undefined, 'X-Requested-With': 'XMLHttpRequest' },
            transformRequest: angular.identity
        });

I'm making a GET request before attempting subsequent POST request in order to avoid security certificate issue.
Any one please guide me to sort out this error..


text:
Q: i want to get subsource_type value using console.log in php using api Output code when i submit lead form, now i want to display response: sourcetype using console.log
{
 "code": 200,
  "message": "Successfully added.",
  "response": {
    "SourceType": "Digital SEM",
    "SubSourceType": "Organic",
    "VendorName": "",
    "Uid": "",
    "Phone": "919897990797",
    "LeadId": 2413493
  }
}


text:
Q: How to set up an optional host parameter in Symfony router? I would like to set up optional host parameter in Symfony router. I try it on localhost:8000 and if I call en.localhost:8000 it works but as I remove the first lang parameter it does not match the route. Route is defined in route.yaml file:
blog-index:
    path:       /blog/{page}
    host:       "{lang}.localhost"
    controller: App\Controller\BlogController::index
    defaults:
        lang: 'en'
        page: 1
    requirements:
        lang: 'en|sk'
        page: '\d+'

PHP code looks like:
public function index(Request $request, $lang = 'sk', $page = 1)
{
    return $this->render('blog/index.html.twig', [
        'route' => $request->attributes->get('_route'),
        'route_params' => $request->attributes->get('_route_params'),
        'page' => $page,
        'locale' => $lang,
    ]);
}

If I run http://localhost:8000/blog the error message says:

No route found for "GET /blog".

The example in the documentation use default so I think it should run also with optional lang param. Am I missing something?


text:
Q: Group by YYYYMM from YYYYMMDD int column - Postgresql I have date in yyyymmdd format in an int column and I would like to group by month i.e. yyyymm.I've tried the below two versions
 select to_char(to_timestamp(create_dt),'YYYYMM'),count(*)  from table_name
 group by to_char(to_timestamp(create_dt),'YYYYMM')
 order by to_char(to_timestamp(create_dt),'YYYYMM') desc

AND
 select to_char(create_dt,'YYYYMM'),count(*)  from table_name
 group by to_char(create_dt,'YYYYMM')
 order by to_char(create_dt,'YYYYMM') desc

A: select create_dt / 100, count(*)
from t
group by 1
order by 1 desc
limit 6

A: Figured it out,any alternate ways would be helpful.
 select substring(create_dt::int8,1,6),count(*)  from table
 group by substring(create_dt::int8,1,6)
 order by substring(create_dt::int8,1,6) desc
 limit 6;


text:
Q: How to change docker compose for Rails and MySql2? I have an ancient (like 2012) Ruby on Rails server that uses MySql2 database. The server, of course, is not made by me so I now have to find out how even launch it. And I want to use Docker for that.
I found this guide to setup Docker container for Rails and PostgreSQL database. So, what do I have to change here to run it with MySql2?
Here is my RoR server's database setup:
  adapter: mysql2
  encoding: utf8
  database: g_development
  pool: 5
  username: notactualusername
  password: notactualpassword

This is a line from Dockerfile in the tutorial that installs and updates all the stuff
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
I need to change postgresql to mysql2, right?
This is from tutorial docker-compose
  db:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: password

So, is MySql2 image just called mysql2? Is the password variable called MYSQL2_PASSWORD or something else?
This is also from tutorial (initialization):
docker compose run --no-deps web rails new . --force --database=postgresql
I guess changing here postgresql to mysql2? Do I actually need to run rails new .  since I already have a server built?

A: If you want to use mysql, you need change database.yml
Don't forget run xampp
I use Ubuntu Linux
default: &default
  adapter: mysql2
  encoding: utf8mb4
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: <%= ENV['USERNAME']%>
  password: <%= ENV['PAASSWORD']%>
  socket: /opt/lampp/var/mysql/mysql.sock           // run xampp
  host: <%= ENV["DB_HOST"]%>


text:
Q: How do I get Windows uptime via command prompt? How do I get Windows uptime? systeminfo | find "System Boot Time:" shows the time it has been up since, but not for how long, that would need to be calculated separately. I need something like uptime -p on Linux but for Windows. If it's a shell command, then I'll run it via Python and grab the input. If there is a way in Python, what would be even better. (Task manager shows this in the Performance CPU tab). Thanks in advance!

A: I'd leverage PowerShell, from the Command Prompt, if I wasn't already using Python!
This example outputs the number of whole minutes:
For /F %G In ('%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NoProfile "[TimeSpan]::FromMilliseconds([Math]::Abs([Environment]::TickCount)).TotalMinutes"') Do @Echo The System has been up for %~nG minutes


text:
Q: Selecting more than one non adjacent categories in komento I'm sorry if this question has been asked before, I searched through everything I could find, but did not find an answer :(
Basically what I want to do is to include komento (joomla extension) in two categories that do not lie above/below one another, here is what it looks like on the backend:
.| Category 1

.| Category 2

.| Category 3

I want to include komento in category 1 and 3, however, I somehow can´t only select category 1 and 3, I always have to select category 2 as well. How can I only select category 1 & 3?
This must be something really simple that I seem to be missing

A: It turned out to be really simple, all you need to do is hold down the ctrl key for windows or the cmd key for mac and click on the category that you would like to select.


text:
Q: how to send fcm notifications to a single device without using firebase console I am storing the registration tokens in my database. I want to send push notifications to the single device by taking registration tokens from database but without using firebase console. How to do it?

A: You need an app server or some Google Chrome extention like PostMan.
First of all, you need to understand the differences between notification message and a data message, like how the app handles the incoming message if it is in the background state or on running on the foreground.
Secondly, create a payload and send a post request to FCM endpoint. It is well documented here.
Lastly, check the FCM response. Note that getting a success response doesn't mean that the message is already delivered to the app, but rather the FCM server accepted it for delivery.
If you would like to learn more about what parameters you can use and the definition of each response codes, check out the Firebase Cloud Messaging HTTP Protocol documentation.
I hope this helps.

A: If you are using Firebase database to store your tokens and intend to send the FCM notification during an event, I suggest making use of Cloud Functions for Firebase. See my answer here for an idea on how you might use it.
If you just want to send a simple downstream message, you could use Postman (also stated by @looptheloop88 in his answer) or cURL.


text:
Q: How to configure docker to use existing local network I'm trying to make a steam cache and the headache docker wants to use it's own network. I want to force it to use the network my router made so I can connect it properly. I am using Luke's guide from LinusTechTips. In order to configure the DNS properly, docker has to use the router's network.

A: *

*You can either use host network mode

*You can create a separate network for docker and make that network interact to host network in the same way as you do for any other network.


text:
Q: jar file in Grails project lib directory not found I have a grails project and a jar file in the lib directory of the grails project. The problem is when i run the app I get class not found errors on classes within the jar file. Why can these not be seen by the grails app?

A: From your last response, I believe you're missing some more required jar files. You should probably check if there are any other jars required for Esendex. Hope it helps.

A: The lib directory is the right place for JAR files. With only the information provided above, I've no way of guessing why it's not working for you. All I can suggest is:

*

*Run "grails war" on the command line

*Unzip the created .war file and check that the JARs are in the WEB-INF\lib directory

If you're running Grails 1.2 you might want to check that the JAR isn't excluded by the new dependency resolution DSL.

A: Depends on how the classes are used. Once you've added them to your lib directory, try updating the dependencies config in BuildConfig.groovy. Here's mine:
dependencies {
        // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.
        runtime 'org.apache:commons-exec:1.1'
        runtime 'org.apache:httpcore:4.1.3'
        runtime 'org.apache:httpclient:4.1.2'
        runtime 'org.json:json:20080701'
        // runtime 'mysql:mysql-connector-java:5.1.16'
    }


text:
Q: System.Timers.Timer not working edit [in asp.net web forms] I am trying out the Timer class with this code:-
protected void Page_Load(object sender, EventArgs e)
{
    System.Timers.Timer tm = new System.Timers.Timer();
    tm.Elapsed += new System.Timers.ElapsedEventHandler(tm_Elapsed);
    tm.Interval = 1000;
    tm.Start();
}

void tm_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    int lbl = Convert.ToInt32(Label1.Text);
    Label1.Text = (lbl+1).ToString();
}

Initially, the Label1.Text is "1".
But when I run the application, the label's text shows 1 and doesn't increase.

A: As its already mentioned in the other answers the System.Timers.Timer is fired on non-GUI thread. This wont allow you access the GUI element and would raise cross thread exception. You can use MethodInvoker to access the GUI element in  tm_Elapsed event. Since you have the Timer in Forms and want to access GUI element the other Timer class suits you most i.e System.Windows.Forms.Timer.

Implements a timer that raises an event at user-defined intervals.
  This timer is optimized for use in Windows Forms applications and must
  be used in a window.

protected void Page_Load(object sender, EventArgs e)
{
     System.Windows.Forms.Timer tm = new System.Windows.Forms.Timer();
     tm.Tick += tm_Tick;
     tm.Interval = 1000;
     tm.Start();
}

void tm_Tick(object sender, EventArgs e)
{
     int lbl = Convert.ToInt32(label1.Text);
     label1.Text = (lbl + 1).ToString();
}

Edit based on comments by OP, that he is doing this in web page not win forms as the load event name suggests.
You can use javascript if you do not need anything from server. If you want update the html control and need to do it from server then you can use asp:Timer
Html (.aspx)
  <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <asp:Timer runat="server" id="UpdateTimer" interval="5000" ontick="UpdateTimer_Tick" />
        <asp:UpdatePanel runat="server" id="TimedPanel" updatemode="Conditional">
            <Triggers>
                <asp:AsyncPostBackTrigger controlid="UpdateTimer" eventname="Tick" />
            </Triggers>
            <ContentTemplate>
                 <asp:Label id="Label1" runat="server" Text="1" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>

Code behind
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
    Label1.Text = int.Parse(Label1.Text) + 1;
}

A: Try this:
    void tm_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        Label1.Invoke((Action)(() =>
        {
            int lbl = Convert.ToInt32(Label1.Text);
            Label1.Text = (lbl+1).ToString();
        }));
    }

The issue is that System.Timers.Timer fires its event in an non-UI thread and since you can't access or update controls safely from a non-UI thread it appears not to work.
Calling .Invoke(...) on a UI element allows you to push code onto the UI-thread making it safe.

A: System.Timers.Timer is intended to be used in a multithreaded environment. You are not allowed to directly access ui elements inside the Elapsed event.
If your application is Windows Forms, use System.Windows.Forms.Timer.
If your application is WPF, use System.Windows.Threading.DispatcherTimer.
If for any reason you want to use System.Timers.Timer, use Invoke method of your ui elements. For example in Windows Forms:
Label1.Invoke(new Action(() =>
{
    int lbl = Convert.ToInt32(Label1.Text);
    Label1.Text = (lbl+1).ToString();
}));

A: You can try following,
if(this.Label1.InvokeRequired)
     {
         this.Label1.BeginInVoke((MethodInvoker) delegate() { int lbl = Convert.ToInt32(Label1.Text);
Label1.Text = (lbl+1).ToString();});
     }
     else
     {
         int lbl = Convert.ToInt32(Label1.Text);
         Label1.Text = (lbl+1).ToString();
     }

The problem is, WPF/Windows Forms/Windows 8 app/WP 8(.1) apps doesn't allow UI to changed from different threads. You need UI thread to update it.

A: Try using System.Threading.Timer (Thread safe) combined with @Enigmativity solution to avoid Cross-thread exception:
    private System.Threading.Timer m_timer = null;
    private const int DUE_TIME = 1000;
    private const int INTERVAL = 1000;

    private void Page_Load(object sender, EventArgs e)
    {
        System.Threading.AutoResetEvent autoEvent = new System.Threading.AutoResetEvent(false);
        System.Threading.TimerCallback tcb = new System.Threading.TimerCallback(timer_Elapsed);
        m_timer = new System.Threading.Timer(tcb, null, DUE_TIME, INTERVAL);
    }

    void timer_Elapsed(object sender)
    {
        label1.Invoke((Action)(() =>
        {
            int lbl = Convert.ToInt32(label1.Text);
            label1.Text = (lbl + 1).ToString();
        }));
    }


text:
Q: Sum of empty area in Jxls 2 leads to error A sum formula at the bottom of a jx:each area is not transformed when the data collection (and the area in consequence as well) is empty.
As an example one can look at the docs of Jxls itself:
http://jxls.sourceforge.net/reference/formulas.html
Here, when the employees collection is empty, the Summary Payment formula SUM(C4) will remain unchanged, effectively leading to erroneous self-reference, since row 4 from template will be removed, template row 5 will become output row 4 and formula in cell C4 will try to sum itself up.
In Jxls v. 1 the result was 0 instead.
How to handle this in Jxls 2?


text:
Q: How could I manage Graylog to parse my JSON logs correctly? I have an rails app and I'm trying to configure logging to graylog. Pipeline consists of next steps:
1) Logs are written to file in JSON format by SemanticLogger gem. Log message consist of header info (first level tags) and payload with several levels of hierarchy:
{
  "tag": "mortgage",
  "app": "sneakers",
  "pid": 3448,
  "env": "production",
  "host": "thesaurus-mortgage",
  "thread": "91090300",
  "level": "info",
  "name": "Sneakers",
  "payload": {
    "class": "EgrnListenerWorker",
    "method": "work",
    "json": {
      "resource": "kontur",
      "action": "request_egrn_done",
      "system_code": "thesaurus",
      "id": 35883717,
      "project_id": "mortgage",
      "bank_id": "ab",
      "params": {
        "egrn": {
          "zip": "rosreestr/kontur/kontur_4288_2018-10-11_021848.zip",
          "pdf": "rosreestr/kontur/kontur_4288_2018-10-11_021848.pdf",
          "xml": "rosreestr/kontur/kontur_4288_2018-10-11_021848.xml"
        },
        "code": "SUCCESS"
      }
    },
    "valid_json": true
  },
  "created_at": "2018-10-11T17:44:58.262+00:00"
}

2) File is being read by Filebeat service and sent to Graylog.
And graylog could not parse correctly payload contents:

As you can see - keys are concatenated with ":" in one string in such manner: key1=value1:key2=value2. This is not what I am expected. It would be perfect if I could manage graylog to parse contents of payload into different fields with names payload.key1, payload.key2 and so on (so I could perform search on these fields)
ps: my log data is heterogeneous, i.e. payload contents depend on functionality it was produced by, so I expect that there would be a huge amount of different fields of a kind "payload.xxxxx" - is it ok?

A: This isn't exactly a filebeat question since filebeat only ships the logs in their original JSON format (zipped, if wanted).
From the Graylog Website: http://docs.graylog.org/en/2.4/pages/extractors.html
Using the JSON extractor
Since version 1.2, Graylog also supports extracting data from messages sent in JSON format.

Using the JSON extractor is easy: once a Graylog input receives
  messages in JSON format, you can create an extractor by going to
  System -> Inputs and clicking on the Manage extractors button for that
  input. Next, you need to load a message to extract data from, and
  select the field containing the JSON document. The following page let
  you add some extra information to tell Graylog how it should extract
  the information.

This should get you going.


text:
Q: Is there a way to apply Kernel density estimation on data where each 2-D data point has an associated value? I am attempting to apply a KDE to my data which is structured as follows:
|x axis values|: 1, 2, 3, ...
|y axis values|: 5, 8, 10, ...
|coord point values|: 98, 35, 15, ...
I am able to apply the KDE to the X-Y coordinate pairs and estimate the distrubution of the points but this doesn't include the Coord-point Values.
So the question:
Is there a way to estimate the KDE of the X-Y data points and also get a similar distribution on the Coordinate-point values?
Ideally, the output created would be two channel:
channel 1: The 2-D distribution of the X-Y coordinate pairs
channel 2: the 2-D estimated coord-point values on that same distribution
update:
In the code below, I attempted to solve my question, but the resulting output distribution 'gg' is too large as each point obtains some large distribution.
Currently I'm unsure the best way to condense this, prehaps simply obtaining the max value should be enough?
def kde3D(x, y, z, bandwidth, xbins=60j, ybins=60j, zbins=180j, ** kwargs):
    """Build 3D kernel density estimate (KDE)."""

    # create grid of sample locations (default: 100x100)
    xx, yy, zz = np.mgrid[0:60:xbins,
                 0:60:ybins,
                 -180:180:zbins]

    xy_sample = np.vstack([yy.ravel(), xx.ravel(),zz.ravel()]).T
    xy_train = np.vstack([y, x, z]).T

    kde_skl = KernelDensity(bandwidth=bandwidth, **kwargs)
    kde_skl.fit(xy_train)

    # score_samples() returns the log-likelihood of the samples
    gamma = np.exp(kde_skl.score_samples(xy_sample))  # Compute the log-likelihood of each sample under the model.
    gg = np.reshape(gamma, xx.shape)

    return xx, yy, zz ,gg

Update 2:
I was able to solve the problem by using the output of the 3D KDE 'gg'
By utilizing the argmax and max functions you can distil the output functions per pixel to its max value, which was good enough for the problem at hand. np.argmax for the coord-pair Value, and np.max for the probability distribution value at that point.  As a result, you no longer have an NxNxM output, but a NxN.

A: not sure if I understood your question correctly, but maybe you could try the following doing two KDEs:

*

*Channel 1: Fit only the X-Y coordinate pairs.

*Channel 2: Fit the X-Y coordinate pairs and use the z-value as sample weight.


text:
Q: "Don't ask again before sending requests to" checked or not I tried this using "Test user" and random friend , it seems "Test user"  continue to appear even previous I cheched "Don't ask again before sending requests to Test user and rand user".
Is sending apprequests only available through fb.ui and no POST method (and if post method exist - example appreciated)

A: Facebook app requests are not available via POST, only the plugin.  If the frictionless requests are not working, I would log a bug with Facebook.


text:
Q: OpenCV camera calibration of an image crop (ROI submatrix) I have a bit of a problem working with OpenCV's undistort function. I am working with a camera using a wide angle lens. Let's say my access to it is problematic as it is already installed. The problem basically boils down to this:
I have successfully measured all the lens parameters and can undistort a full frame image with no problem, the issue is I am actually working in sort of a linescan mode. We're using just a cut out in the middle of the sensor, about 100 px tall. Images for illustration:

Now, if I apply undistort to the ROI (Region of interest) of the image in question it naturally assumes it is a cutout at the top of the full frame, therefore the correction is massively different to what it should be about a halfway down the height of the full frame.
I understand how I can modify the camera matrix to compensate for image scale were I using just a lower resolution full frame, but the question is: Can I compensate for a cropped out part shift in any way to achieve correct transformation?
I figured I could use a black image with full frame resolution and just copy the relevant data to the middle of it, but that is out of the question as the processing speed would take too much of a hit that way.
Thanks for any insights!
Cheers,
Jan.

A: If you crop the image, then the principal point is going to have different coordinates. For example, if your original principal point was at (30,40), and you crop 10 pixels around the sides, then your new principal point is going to be at (20,30), because the pixel (20,30) in the cropped image is the same as pixel (30,40) in the original image.
You need to adjust the cx an cy values in your camera matrix accordingly.


text:
Q: How can I shift column values forward if the previous value is in a list of excluded values? I have some TSQL code that produces a de-normalized flat file from nicely organized relational tables. The code completes quickly, and the data isn't overwhelming, so chances are any suggestions would help. I don't have to worry much about performance because this process is only intended to be run 1 time a month. I have some wiggle room in that respect.
The source data, for example's sake, is laid out like this: One person (table 1) can have many incidents (table 2). Each incident can have many codes tied to it (table 3). Each code has an ordered sequence. So after flattening this out, one row in the extract file may look like this:
Name                IncidentId  Code1   Code2   Code3   Code4
Sue Ellen Crandell  1991        abc1    def1    xyz0    888

These de-normalized ordered code columns could potentially go out to over 50. The problem is, that there is a new requirement that if one of the ordered code columns has a value that's in the list of exclusions, then the following ordered code column values should be shifted forward one position. This means that if def1 was in the exclusion list, the row should look like this:
Name                IncidentId  Code1   Code2   Code3   Code4
Sue Ellen Crandell  1991        abc1    xyz0    888     <empty string>

Before I fetch additional relational data and export the results to the file, I use dynamic T-SQL to de-normalize these ordered code values into a temp table. Due to not wanting to mess with the dynamic T-SQL, and probable limitations with being able to use conditionals to shift the columns during that part of the process, I'm thinking that the easiest place to put the exclusion list evaluation would be after the ordered code values make it into the temp table.
If I have a temp table that looks like the first data row above, how can I

*

*Check each column value.

*Remove the value if it is included in the exclusion list

*Conditionally shift values forward when encountering a value in an exclusion list, as shown in the row examples above?

The exclusion list is just a handful of static values that I can either dump into a temp table or use with an IN operator. I'm guessing that a CTE might be needed, but the recursion logic isn't clear to me.

A: First create a CTE that unpivots the table so that each code is on a separate row:
with cte(Name, IncidentId, CodeName, Code)
as(
    select Name, IncidentId, CodeName, Code
    from Incident i
    unpivot(Code for CodeName in (Code1, Code2, Code3, Code4)) unpvt
)

Now you do an outer join on the CTE to itself, filtering out the excluded codes.  This gives you one row for each Name-Incident-Code tuple, but you have null values in the rows where the code was excluded (you need the null rows to maintain the proper count of codes).
Select *, t1.Name, t1.IncidentId, isnull(t2.Code, '') Code,
ROW_NUMBER() over(partition by t1.Name, t1.IncidentId order by isnull(t2.CodeName, 'zzz')) CodeNumber
    from cte t1
    left outer join cte t2 on t1.Name = t2.Name and
           t1.IncidentId = t2.IncidentId and
           t1.Code = t2.Code and
           not exists(select 1 from Exclude e where e.Code = t2.Code)

The ROW_NUMBER() here will create the new CodeNumber.  The order byisnull(t2.CodeNumber, 'zzz')) pushes the null rows to the end so that the rows that have valid codes get numbered first (because "zzz" is greater than "Code-whatever-").
Now you just need to pivot the previous query back so that the codes become columns again:
select Name, IncidentId, [1] Code1, [2] Code2, [3] as Code3, [4] as Code4
from
(
    Select t1.Name, t1.IncidentId, isnull(t2.Code, '') Code, ROW_NUMBER() over(partition by t1.Name, t1.IncidentId order by isnull(t2.CodeName, 'zzz')) CodeNumber
    from cte t1
    left outer join cte t2 on t1.Name = t2.Name and t1.IncidentId = t2.IncidentId and t1.Code = t2.Code and not exists(select 1 from Exclude e where e.Code = t2.Code)
) x
pivot(max(Code) for CodeNumber in ([1], [2], [3], [4])
) as pvt

SQL Fiddle
Update
There's a couple problems with the code above.  First, when I create the CodeNumber with ROW_NUMBER(), I am sorting by CodeName.  This breaks down after 9 code columns because they no longer sort correctly (they get sorted alphabetically instead of numerically).  So I need to pull the code number out in the CTE so I can use it to sort by later:
with cte(Name, IncidentId, CodeName, CodeNumber, Code)
as(
    select Name, IncidentId, CodeName, convert(int, SUBSTRING(CodeName, 5, len(CodeName))), Code
    from Incident i
    unpivot(Code for CodeName in (Code1, Code2, Code3, Code4, Code5, Code6, Code7, Code8, Code9, Code10)) unpvt
)

Now the rest of the query looks like this:
select Name, IncidentId, [1] Code1, [2] Code2, [3] as Code3, [4] as Code4, [5] as Code5, [6] as Code6, [7] as Code7, [8] as Code8, [9] as Code9, [10] as Code10
from
(
    Select t1.Name, t1.IncidentId, isnull(t2.Code, '') Code, ROW_NUMBER() over(partition by t1.Name, t1.IncidentId order by isnull(t2.CodeNumber, 999)) NewCodeNumber
    from cte t1
    left outer join cte t2 on t1.Name = t2.Name and t1.IncidentId = t2.IncidentId and t1.Code = t2.Code and not exists(select 1 from Exclude e where e.Code = t2.Code)
) x
pivot(max(Code) for NewCodeNumber in ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10])
) as pvt

Note that since I now have a column called CodeNumber in the CTE, I am calling the newly generated number "NewCodeNumber".  Also, I am ordering by t2.CodeNumber instead of t1.Code.
Updated SQL Fiddle.
Update
Regarding the question in your comment, you're essentially asking about unpivoting multiple columns, which is not as straightforward as unpivoting a single column.  One way to accomplish it is to unpivot the code and the codedate separately:
with cteCode(Name, IncidentId, CodeName, CodeNumber, Code)
as(
    select Name, IncidentId, CodeName, convert(int, SUBSTRING(CodeName, 5, len(CodeName))), Code
    from Incident i
    unpivot(Code for CodeName in (Code1, Code2, Code3, Code4, Code5, Code6, Code7, Code8, Code9, Code10)) unpvt
), cteCodeDate(Name, IncidentId, CodeName, CodeNumber, CodeDate)
as(
    select Name, IncidentId, CodeName, convert(int, SUBSTRING(CodeName, 9, len(CodeName))), CodeDate
    from Incident i
    unpivot(CodeDate for CodeName in (CodeDate1, CodeDate2, CodeDate3, CodeDate4, CodeDate5, CodeDate6, CodeDate7, CodeDate8, CodeDate9, CodeDate10)) unpvt
)

and then join them back together:
Select t1.Name, t1.IncidentId, isnull(t2.Code, '') Code, ROW_NUMBER() over(partition by t1.Name, t1.IncidentId order by isnull(t2.CodeNumber, 999)) NewCodeNumber, t3.CodeDate
    from cteCode t1
    join cteCodeDate t3 on t3.Name = t1.Name and t3.IncidentId = t1.IncidentId and t3.CodeNumber = t1.CodeNumber
    left outer join cteCode t2 on t1.Name = t2.Name and t1.IncidentId = t2.IncidentId and t1.Code = t2.Code and not exists(select 1 from Exclude e where e.Code = t2.Code)

Pivoting multiple columns isn't as easy as a single column either, so I went a different route to  get the final result:
select Name, IncidentId,
MAX(case when newCodeNumber = 1 then Code end) Code1,
MAX(case when newCodeNumber = 1 then CodeDate end) CodeDate1,
MAX(case when newCodeNumber = 2 then Code end) Code2,
MAX(case when newCodeNumber = 2 then CodeDate end) CodeDate2,
MAX(case when newCodeNumber = 3 then Code end) Code3,
MAX(case when newCodeNumber = 3 then CodeDate end) CodeDate3,
MAX(case when newCodeNumber = 4 then Code end) Code4,
MAX(case when newCodeNumber = 4 then CodeDate end) CodeDate4,
MAX(case when newCodeNumber = 5 then Code end) Code5,
MAX(case when newCodeNumber = 5 then CodeDate end) CodeDate5,
MAX(case when newCodeNumber = 6 then Code end) Code6,
MAX(case when newCodeNumber = 6 then CodeDate end) CodeDate6,
MAX(case when newCodeNumber = 7 then Code end) Code7,
MAX(case when newCodeNumber = 7 then CodeDate end) CodeDate7,
MAX(case when newCodeNumber = 8 then Code end) Code8,
MAX(case when newCodeNumber = 8 then CodeDate end) CodeDate8,
MAX(case when newCodeNumber = 9 then Code end) Code9,
MAX(case when newCodeNumber = 9 then CodeDate end) CodeDate9,
MAX(case when newCodeNumber = 10 then Code end) Code10,
MAX(case when newCodeNumber = 10 then CodeDate end) CodeDate10
from
(
    Select t1.Name, t1.IncidentId, isnull(t2.Code, '') Code, ROW_NUMBER() over(partition by t1.Name, t1.IncidentId order by isnull(t2.CodeNumber, 999)) NewCodeNumber, t3.CodeDate
    from cteCode t1
    join cteCodeDate t3 on t3.Name = t1.Name and t3.IncidentId = t1.IncidentId and t3.CodeNumber = t1.CodeNumber
    left outer join cteCode t2 on t1.Name = t2.Name and t1.IncidentId = t2.IncidentId and t1.Code = t2.Code and not exists(select 1 from Exclude e where e.Code = t2.Code)
) x
group by Name, IncidentId

SQL Fiddle

A: This is too long for a comment.
This is best handled with dynamic SQL.  Moving things over from column to column to handle exclusions is cumbersome, at best.  It would end up being some variant on:
if code1 is not excluded then code1
   else if code2 is not excluded then code2
   else if code3 is not excluded then code3
   else code4 is not excluded then code4 as code1
if code1 is not excluded
   if code2 is not excluded then code2
   else if code3 is not excluded then code3
   else if code4 is not excluded then code4
and so on, and so on and so on

Instead, you probably have a place where you can add something like this to the dynamic SQL:
where not exists (select 1 from ExcludedCodes ec where ec.code <> the.code)

And you will eliminate them before the pivot.


text:
Q: how to copy all applications from one linux machine to another I wonder how I can copy all applications from one linux machine to another? I have a "source" machine (Ubuntu 16.04) which has all the configurations, setup and many complex application installed on it. Then I have a new fresh "destination" machine (Ubuntu 17.10) which I want it to have the exact same setup, configurations and all software that are installed in the source machine. Any advice? I read some articles suggesting using Clonezilla, and others using apt-clone but I'm not sure what is the best way?

A: Clonezilla is a cloning tool. It will give you an exact duplicate. ie 16.04 on both  machines.
If you want to keep 17.10 on the second machine then apt-clone will make a list of all installed package on the sources machine. This list can then be used to install the same packages on the second machine. This will not copy configuration files.
Note: 17.10 uses wayland by default, which is radically different than Xorg (default for 16.04).


text:
Q: How to create a TTS engine for Android 2.3? In Android 4.0, I can implement the TextToSpeechService class to create a TTS engine. There is even an example TTS engine in the SDK to follow, which is really easy.
However, I can't see any information on implementing a TTS engine on Android 2.3. What I want to achieve is like SVOX TTS engine.

A: The link provided by sinisha leads to a not very detailed solution by the author of a project called eyes-free. Then in the same project I found the author gave much complete instructions on how to implement the TTS engine.
In summary, what we need to do is:

*

*Implement the TtsEngine interface and compile it as libtts[NAME_OF_TTS_ENGINE_IN_LOWWER_CASE].so.

*Create a dummy Activity class, named as [NAME_OF_TTS_ENGINE_IN_UPPER_CAMEL_CASE].

*Bind the android.intent.action.START_TTS_ENGINE action intent to the  class.

The Pico TTS Engine in the AOSP is an excellent example.


text:
Q: Magento Category Static block not displaying Hi I have a running  ecommerce sites built on  magento and in that I have created custom categories for the menu and for each categories I have created static block in the magento's admin panel and linked each one of them to their respective categories.
For ex:-
Category            Linked Static block

*

*Faq                 Faq

*History             History_New

*Press               Press_New

Now the problem is that when i refresh the cache and click on any category it shows its respective static block data but the same static block data is also displayed for all other categories.
For ex:- If I click on History it shows data from History_New static block but the same data is also displayed when I click on Faq or Press Category.
Visit the site.
http://www.jaydensjuice.com/beta
Any help is appreciated.
Thanks.

A: This sounds like the same issue as this one. It's a bug in magento 1.9.2 related to the static block cache


text:
Q: Win32 how big custom resource can be? Trying to create something similar to SFX (self extract installer), I was including the setup files in one exe using custom resource in visual c++.  When the size of the setup files reached over ~900 MB, the linker cannot generate an exe with the resources embedded.  Strange thing is that the linker does generate an exe without any warnings.  The exe generated is an statically linked MFC App (main app of the exectuable).  However, non of the resource is included.  I have watched the exe size during the linking from a console.  It was showing 900 MB for awhile befored dropped to the 2MB exe in the end.  If I removed some of the files (say total size will be 500MB), the exe is generated all OK with all the resources embedded.  Is there a pratical size limit for the custom resource?  Note that the final size of the executable is about 1GB which is way less that 2GB win32 app can address.  So I am wondering is this a vc++ 2010 bug or feature?  BTW, I also used /expectedoutputsize trick.  But it does not help except the linking is much faster with a bigger expected output size.

A: Belated answer. Might be helpful to others. May be not an answer to your question, but this may be a solution to your problem. Check for 'Bitrock installer'. This also gives Self Extract Installer. I used it successfully in many of my projects for deployment.

A: According to the PECOFF Specification, the size of the Resource Data entries is 4 bytes ( IMAGE_RESOURCE_DATA_ENTRY.Size  - see winnt.h )

The size, in bytes, of the resource data that is pointed to by the Data RVA field.

A: I've answered a similar answer here.
Basically append the binary + magic number (unique separator) to the end of the executable. At runtime open the executable for reading, find the offset via a magic number or another method and the rest of the file is your big data.


text:
Q: Text selection bug with draft.js and decorator I'm using a draft.js editor in such a way that I need to update the decorator and also the props of the component it renders on the fly inside onChange. This to mark parts of the text with a background color.
I can almost get this working, but there's a weird bug where among other things it is not possible to select the character immediately after one of the decorated components.
Here is a minimal (artificial) example to reproduce the bug:
import React from 'react';
import { CompositeDecorator, Editor, EditorState } from 'draft-js';

const Marked = ({ children, background }) => {children};

class TestEditor extends React.Component {
  constructor(props) {
    super(props);

    this.state = { editorState: EditorState.createEmpty() };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(editorState) {
    const markers = [{ from: 3, to: 7 }, { from: 12, to: 15 }];

    const strategy = (contentBlock, callback) => {
      const text = contentBlock.getText();
      markers.forEach(({ from, to }) => {
        if (text.length >= to) callback(from, to);
      });
    };

    const decorator = new CompositeDecorator([
      { strategy, component: (props) => <Marked {...props} background="#00ff2a1a" /> },
    ]);

    const newEditorState = EditorState.set(editorState, { decorator });

    this.setState({ editorState: newEditorState });
  }

  render() {
    const { editorState } = this.state;

    return <Editor editorState={editorState} onChange={this.handleChange} />;
  }
}

export default TestEditor;

This will be a text input where the text at position 3 - 7 and 12 - 15 has a green background (if it exists).
If I now for example write aaabbbbccc it is not possible to select the first c. Using the mouse it is selected until I release the mouse button; using the keyboard it doesn't appear to be selected at all (it might be momentarily).
If I use a static component with no new input in the handleChange method it works ok: const decorator = new CompositeDecorator([{ strategy, component: Marked }]);. However this doesn't fit my use case.
Any suggestions?

A: In the end it turns out I can do what I need with draft's entities, probably with much better performance


text:
Q: Is it possible in a forest plot all negative confidence intervals sum to a positive range,?
For example in that case, all confidence intervals are negative BUT the sum is in positive range (-37.62 to 0.5), which I don't understand. If there is anybody knows the explanation I would be appreciate that!

A: There are a number of issues here.
First of all it is perfectly possible in a situation where you have high heterogeneity to have a wide confidence interval for the mean of the underlying distribution of effects sizes. In this case that happens to include the null even though none of the individual studies does. In fact if you use REML to estimate $\tau^2$ instead of DerSimonian and Laird (which I assume you are using) the confidence interval just fails to include the null.
If you use a prediction interval which gives you the limits for a new study this has bounds -55.8 to 18.7 which are much wider.
You are modelling using the scale of raw means. This seems frankly quite hard to believe here. You have studies returning a mean of 13.7, 355, and 47.7 for the control group. The assumption that these are all being measured on a common scale seems difficult to explain.


text:
Q: Add scrollbar to my JQuery UI Dialog This is my dialog:

There are a lot of fields so instead of adding a scrollbar so everything can fit there the dialog simply "ends" and keeps adding them outside the dialog.
This is my html code:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" href="../css/pure/pure-min.css">
<link rel="stylesheet" type="text/css"
    href="../css/jquery/jquery-ui.theme.css">

        <form class="pure-form pure-form-stacked" id="formCadastrar">
            <fieldset>
                Órgão <input readonly="readonly" size="3" value="03">
                Unidade Orçamentaria <input name="" size="3"
                    maxlength="3"> Número do Empenho <input
                    name="" size="10" maxlength="10"> Número da
                    Liquidação <input name="" size="10" maxlength="10"> Credor
                <input name="" size="18" maxlength="18"> Serie
                    da Nota Fiscal <input name="" size="2" maxlength="2"> Número
                    da Nota Fiscal <input name="" size="10" maxlength="10"> Data
                    da Nota Fiscal <input name="" size="10" maxlength="10"> Valor
                    do Desconto <input name="NTFSC_VALORDESCONTO" size="12"
                    maxlength="12" class="double"> Codigo de
                    Verificação NFISS <input name="" size="20" maxlength="20">
                Valor da Nota <input name="NTFSC_VALORNOTA" size="12"
                    maxlength="12" class="double"> Valor Liquido
                <input name="NTFSC_VALORLIQUIDO" size="12" maxlength="12"
                    class="double"> Núm. NFE <input name=""
                    size="44" maxlength="44"> Comprovante da
                    Sefaz/MT <input name="" size="9" maxlength="9"> Modelo
                <select name="NTFSC_MODELO">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="55">55</option>
                </select> Objeto
                <textarea cols="100" rows="4" name="NTFSC_OBJETO"></textarea>
                Arquivo PDF <input type="file"
                    class="custom-file-input"> <input type="button"
                    value="Cadastrar" class="pure-button pure-button-primary"
                    id="botaoCadastrar">
            </fieldset>
        </form>

My cadastrarNotaFiscal.js file:
$(document)
        .ready(
                function() {
                    $("#divCadastrarNotaFiscal")
                            .dialog(
                                    {
                                        modal : true,
                                        buttons : [ {
                                            id : "dialogFechar",
                                            text : "Fechar",
                                            click : function() {
                                                $(this).empty();
                                                $(this).dialog("destroy");
                                            }
                                        } ],
                                        width : $(window).width() * 0.75,
                                        height : $(window).height() * 0.75,
                                        resizable : false,
                                        show : {
                                            effect : "blind",
                                            duration : 300
                                        },
                                        hide : {
                                            effect : "explode",
                                            duration : 300
                                        },
                                        close : function(event, ui) {
                                            $(this).empty();
                                            $(this).dialog("destroy");
                                        },
                                        open : function(event, ui) {
                                            document
                                                    .getElementById("divCadastrarNotaFiscal").style.color = "black";
                                            document
                                                    .getElementById("dialogFechar").style.fontSize = "10px";
                                        }
                                    });
                });

Any suggestion?
Bonus question: Why is the close button appearing there instead of it being an "X" in the upper right corner?


text:
Q: Java Code - ArrayIndexOutofBoundsException I have written the following code and keep running into this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at yournamep3.Yournamep3test.main(Yournamep3test.java:23)
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

public class Yournamep3test {

    public static void main(String[] args) {

        // Check if target file exists
        File targetFile = new File(args[0]);

        try {

            PrintWriter out = new PrintWriter(targetFile);
            out.write("\r\nStringed musical Instrument program");

            for (int arrayIndex = 0; arrayIndex < 10; arrayIndex++) {

                out.write("\r\n\r\n");
                out.write("\r\nCreating new Stringed Musical Instrument object now..............");
                Yournamep3 violinInstrument = new Yournamep3();

                violinInstrument.setNameOfInstrument("Violin # " + (arrayIndex+1));

                out.write("\r\nCreated instrument with name - "
                        + violinInstrument.getNameOfInstrument());

                int num = violinInstrument.getNumberOfStrings();
                out.write("\r\nNumber of strings in instrument is " + num);

                out.write("\r\nNames of String are ");
                String strings[] = violinInstrument.getStringNames();
                for (int counter = 0; counter < num; counter++) {
                    out.write("\r\n" + strings[counter]);
                }

                out.write("\r\nIs the Instrument playing - "
                        + violinInstrument.isPlaying());
                out.write("\r\nIs the Instrument tuned - "
                        + violinInstrument.isTuned());

                out.write("\r\nTuning now.........");

                violinInstrument.setTuned(true);
                out.write("\r\nIs the Instrument tuned - "
                        + violinInstrument.isTuned());

                out.write("\r\nCalling the Instrument play  method now..");
                violinInstrument.startPlayInstrument();
                out.write("\r\nIs the Instrument playing - "
                        + violinInstrument.isPlaying());

                out.write("\r\nStopping playing of instrument..............");
                violinInstrument.stopPlayInstrument();
                out.write("\r\nIs the Instrument playing - "
                        + violinInstrument.isPlaying());

            }
            out.close();
        } catch (IOException e) {
        }
    }
}

I think the issue is with line 23.  Any advice would be appreciated, thanks.
This is the other part of the code yournamep3
public class Yournamep3 {
//fields to determine if the instrument is isTuned,
private boolean isTuned;

//and if the instrument is currently isPlaying.
   private boolean isPlaying;
private String name;
private int numberOfStrings = 4; // number of strings
   private String nameofStringsInInstrument[] = {"E", "C", "D", "A"}; //an array of string names
//A constructor method that set the isTuned and currently isPlaying fields to false.
public Yournamep3() {
    this.isTuned = false;
    this.isPlaying = false;
}

/**
 * @return the name
 */
public String getNameOfInstrument() {
    return name;
}

/**
 * @param name the name to set
 */
public void setNameOfInstrument(String nameOfInstrument) {
    this.name = nameOfInstrument;
}

// Other methods

public boolean isPlaying() {
    return isPlaying;
}

public void setPlaying(boolean playing) {
    this.isPlaying = playing;
}

public boolean isTuned() {
    return isTuned;
}

public void setTuned(boolean isTuned) {
    this.isTuned = isTuned;
}

public void startPlayInstrument() {
    System.out.println("The Instrument is now Playing.");
    isPlaying = true;
}

public void stopPlayInstrument() {
    System.out.println("The Instrument is not Playing anymore.");
    isPlaying = false;
}

public void startTuneInstrument() {
    System.out.println("The Instrument is Tuned.");
    isTuned = true;
}

public void stopTuneInstrument() {
    System.out.println("The Instrument is not Tuned.");
    isTuned = false;
}

public int getNumberOfStrings() {
   return this.numberOfStrings ;
}

public String[] getStringNames() {
    return nameofStringsInInstrument;
}

}

A: I would look at your getStringNames() method for your violinInstrument. It seems to me that it isn't populating your String array properly, or the getNumberOfStrings() method does not give the right number of strings. If you put the code for that up, I can help a bit more.

A: Line 23 appears to be
Yournamep3 violinInstrument = new Yournamep3();

If that's the case you should check the constructor for Yournamemp3
Since Line 23 is
File targetFile = new File(args [0]);

It indicates that your args object is empty. ArrayIndexOutOfBoundException is thrown to indicate that an array has been accessed with an illegal index. 0 is an illegal index.


text:
Q: I'm not getting output for the if statement in batch script @echo off
set a=2,113 MB
for /f "tokens=2* delims=:" %%a in ('systeminfo ^| findstr /I /C:"Total Physical Memory"') do set r=%%a

echo available RAM IS %r%
pause
if "%r%" gtr "%a%"
(
echo "proceed"
)
else (
echo "no"
)
pause

A: This is just another way to check ram do the required if conditions are met.
@echo off
::set required memory size 1024=1GB | 2048=2GB | 3072=3GB | 4096=4GB ||

set reqramsize=1024

for /f "tokens=4" %%a in ('systeminfo ^| findstr Physical') do if defined totalMem (set availableMem=%%a) else (set totalMem=%%a)
set totalMem=%totalMem:,=%
set availableMem=%availableMem:,=%
set /a usedMem=totalMem-availableMem

:: Output Your Memory Variables
echo Total Memory: %totalMem%
echo Used Memory: %usedMem%

::Check Condition with Used Memory & Required Memory

if %usedMem% GTR %reqramsize% (goto available) else goto navailable

:available
echo ram available - Proceed
pause>nul
:navailable
echo ram not available - Unable to Proceed
pause>nul
exit


text:
Q: Port Forwarding on Router using same internal port number on different IP addresses
The objective that I'm trying to achieve is to be able to connect to two computers that are behind the router using RDP. My logic is that I should be able to connect to the router externally on 2 different ports. Then internally the router should be able to forward me to 2 different IP addresses using the same port. i.e. once you hit the router it can connect to each of the different IP addresses on the same port. There should be no conflict there because they are different IP addresses.
The entry that I'm trying to add in the image is getting rejected with "Port Range is overlap" (sic). I assume that the ports labeled "Internal" are the ports to connect to on the internal IP addresses.
(As an alternative I could of course configure the port for RDP on one of the internal computers to listen on 3390 instead of the default 3389. In the past I've found this to be problematic.)
Why will the router not allow me to use the same internal port on different IP addresses?

A: I just ran into this problem and emailed Netgear customer support. Their response:
"NETGEAR home routers and modem routers do not support setting up port forwarding the same port numbers for different or same IP addresses. This feature is not supported or applicable with CG3000Dv2."
Seems like a silly feature for the router to lack. If anyone comes up with a workaround, I'd really like to hear about it.

A: You will need to change the port RDP is listening on for one of the computers since the router (all routers actually) can only forward a port request to a single computer.
1.Start Registry Editor.
2.Locate and then click the following registry subkey:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp\PortNumber
3.On the Edit menu, click Modify, and then click Decimal.
4.Type the new port number, and then click OK.
5.Quit Registry Editor.
6.Restart the computer.