text:
Q: Catching different syntax with Regular Expression I'll have code embedded in HTML, it will look something like this:
<div id="someDiv">
{:
    HTMLObject
    id: form
    background: blue
    font: large
    fields [
        username: usr
        password: pwd
    ]

    foo: bar
:}
</div>

I am trying to write a regular expression that will take these HTMLObjects and break them into manageable arrays. I already have the regexp that will do the lines such as
id: form

However, I'm having trouble with making the regexp also match ones like
fields [
    username: usr
    password: pwd
]

Here is the function I have that performs these tasks:
function parseHTMLObjects($html) {
    $details = preg_replace('/[{:]([^}]+):}/i', '$1', $html);
    $details = trim(str_replace('HTMLObject', '', $details));

    $dynamPattern = '/([^\[]+)\[([^\]]+)]/';
    $dynamMatch = preg_match_all($dynamPattern, $details, $dynamMatches);

    print_r($dynamMatches); // nothing is shown here

    $findMatch = preg_match_all('/([^:]+):([^\n]+)/', $details, $matches);

    $obs = array();
    foreach($matches[0] as $o) {
        $tmp = trim($o);
        echo $tmp . "\n";
    }
}

When I pass an HTML string like I demonstrated at the beginning of the page, the $findMatch regexp works fine, but nothing gets stored in the dynams one. Am I going about this in the wrong way?
Basically all I need is each object stored in an array, so from the sample HTML string above, this would be an ideal array:
Array() {
    [0] => id: form
    [1] => background: blue
    [2] => font: large
    [3] => fields [
               username: usr
               password: pwd
           ]
    [4] => foo: bar
}

I have all the sorting and manipulation handled beyond that point, but like I said, I'm having trouble getting the same regexp that handles the colon style objects to also handle the bracket style objects.
If I need to use a different regexp and store the results in a different array that is fine too.

A: It would be easly made with some black sorcery called YAML or JSON with these syntaxes:
YAML
{:
    HTMLObject:
      id: form
      background: blue
      font: large
      fields: [
        username: usr,
        password: pwd
      ]
      foo: bar
:}

JSON
{:
    {
      "HTMLObject":{
        "id": "form",
        "background": "blue",
        "font": "large",
        "fields": [
          {"usernamd": "usr"},
          {"password": "pwd"}
        ],
        "foo": "bar"
      }
    }
:}

Bu-bu-but why? 'Cuz it's natively parsed. No dirty RegExps.

A: I can't comment on posts yet, but definitely looking for conversion functions from one notation to php arrays is the way forward, json_decode is one, though your data is starting life as something else.
regex can be very tricky with complicated data that is often complex because it has some other structure to it that is better interpreted with other tools
PS if you do use json_decode in php at any point, don't get caught out by the second parameter - it needs to be set to 'true' to get an array !


text:
Q: Procedure to wholly migrate SQL Server 2005 to a new server I'm tasked with 'rebuilding' a database server, because the old one is dying. To reduce potential for the new server f**king up, we had decided to rebuild the server as similar as possible to the old one, hence, SQL Server 2005 Enterprise on top of Windows Server 2003.
Now, the original dev/maintainer of the old server has gone the way of the dodo (as in, he's left the company quite some time ago, and nowhere to be found now). So, we had to do the migration in-whole.
To make matters worse, the old server is a hodge-podge of: Databases, a mix of user credentials (SQL Server authentication and Windows authentication), a crowd of Linked Servers, and a gaggle of SQL Server Agent Jobs.
So, how do I approach this monumental task? In my mind, I had the following half-baked plan:

*

*Copy the databases using the Copy Database Wizard

*Copy the users using Script > CREATE To

*Re-create all Linked Servers

*Copy the Jobs using Script > CREATE To

For every step above, I might have to do it one-by-fricking-one :(
Is there an easier (as in, less tedious) way to do the migration?

A: Do not use copy database wizard. Instead use backup/restore. Also, if you want to minimize the downtime then below steps would be sufficient :
Prepwork on the New server :

*

*Create blank databases with the same name as the old server. This is because if any logins or jobs has that database as default, there would be errors.

*Script out all the logins using the sp_help_revlogin from the old server to the new server and create them on the new server.

*Script out all the jobs. You dont have to Script > CREATE To for each jobs. Instead right click in Object Explorer and script all the jobs in one shot :-) Remember to disable the jobs until you failover to the new server.

*Scrip out all Linked servers and recreate them on the destination server. Remember that passwords will not be scripted out.

*Once 1-4 is set up then set up either Logshipping or database mirroring (Async mode) from source server to destination server.

*On the day of failover

*

*if using logshipping then manually failover to new server.

*if using Mirroring then change the mode to synchronous and then initiate a failover to new server.
This way you will do all the prep work before hand and then during the day of failover, the downtime will be minimal.
You can refer to my answer HERE for more steps (they are for migration from old version to higher version, but still will help you).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Power query: Passing a table within a cell to a custom function I'm pretty new to custom functions in Power Query.
I've created this one. Its purpose is to add a custom column whose content AND name are based on the parameters it gets. I've saved it as fnCompactedExamples:
let

    CompactedExamples = (BaseTable as table, ExamplesTable as table, ExampleNumber as text) =>

        let
            Source = BaseTable,
            #"Add example column" = Table.AddColumn( Source, "sb" & ExampleNumber, each Table.Column( ExamplesTable, Campaign & "_b" & ExampleNumber & "_example")),
            #"Extracted values" = Table.TransformColumns(#"Add example column", { "sb" & ExampleNumber, each Text.Combine(List.Distinct(List.Transform(_, Text.From)), "#(lf)"), type text} )
        in
            #"Extracted values"

in
     CompactedExamples

This function gets called in the following query:
let
    Source = #"raw entities table",
    #"Group by cny ID and Cny" = Table.Group(Source, {"Company ID", "Company"}, {{"Data", each _, type table}}),
    #"create sb1 column" = fnCompactedExamples(#"Group by cny ID and Cny", [Data], "1")
in
    #"create sb1 column"

Here is what the table looks like on the "Group by cny ID and Cny" stage

But on the "create sb1 column" stage, I get an error: "Expression.Error: There is an unknown identifier. Did you use the [field] shorthand for a _[field] outside of an 'each' expression?"
I feel close to the end, and that my error is some tiny detail. I scoured the web for hints on my case, but couldn't find any. Can anybody tell me what it that detail?
Edit, per @Olly's request:
The second argument ExamplesTable , is indeed a table that bears columns I want to kinda concatenate without any duplicate:

My purpose is to build a table like this, but right now I use a very repetitive series of instructions :

A: Here's a slightly simpler solution, which unpivots your 'example' columns, renames them appropriately, then pivots again, combining distinct values in the output:
let
    Source = Table1,
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"Company ID", "Company"}, "Attribute", "Value"),
    #"Renamed Attributes" = Table.TransformColumns(#"Unpivoted Other Columns", {{"Attribute", each "s" & Text.BetweenDelimiters(_, "_", "_"), type text}}),
    #"Pivoted Column" = Table.Pivot(#"Renamed Attributes", List.Distinct(#"Renamed Attributes"[Attribute]), "Attribute", "Value", each Text.Combine(List.Distinct(_),", "))
in
    #"Pivoted Column"

You can then tweak this to suit - for example, this removes blank values, sorts each list, and separates values with a linefeed:
let
    Source = Table1,
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"Company ID", "Company"}, "Attribute", "Value"),
    #"Removed Empty Values" = Table.SelectRows(#"Unpivoted Other Columns", each [Value] <> null and [Value] <> ""),
    #"Renamed Attributes" = Table.TransformColumns(#"Removed Empty Values", {{"Attribute", each "s" & Text.BetweenDelimiters(_, "_", "_"), type text}}),
    #"Sorted Attributes" = Table.Sort(#"Renamed Attributes",{{"Attribute", Order.Ascending}}),
    #"Pivoted Column" = Table.Pivot(#"Sorted Attributes", List.Distinct(#"Sorted Attributes"[Attribute]), "Attribute", "Value", each Text.Combine(List.Sort(List.Distinct(_)),"#(lf)"))
in
    #"Pivoted Column"


text:
Q: Lost months with core data I am storing dates in a core data data file whenever the user uses my app and then displaying them back to the user. For some reason, just every now and again, i get an entry with the the right day and year but the month has dropped back to the fires. Has anyone heard of this happening in the past and know how to fix it?
Everything seems unaffected (ie time, days and years) except month. It only ever changes to january (IE it either works right eg 23/5/2011 or it defaults to january eg 23/1/2011)
Thanks to anyone who can shed some light on this or can even point me in the right direction as to finding the problem as so far it looks random
thanks

A: Found my issue. It wasn't random, it only happens when I quit the app then go back in. I wasn't handling the date correctly when I feed it back into the app.


text: Q: Storing MySQL Username/Password In Config File I have a web app that will connect to a MySQL database and I want to store the connection credentials encrypted in a config file in the web root. I have seen a number of articles and posts on what to do, but can't find any instruction on HOW to do it. The app is run on a WAMP Server on Azure.


text:
Q: MDIsubwindow inside mdi subwindow Qt I only wants to know if it is possible to do in QT what I'm imaging:
I want to open several different Windows (lets say widgets) inside several MIDsubwindows. So the MDIsubwindows functionality permits to open different files at the same time inside the MDIarea. Now, I want to put inside each MDIsubwindow diferentes Qwidgets (or another layer or MDIsubwindow) and have the possibility of changing separetely the size these Qwindows (and tile them) inside each MIDsubwindows. That is, A separately behaviour of each MDIsubwindow.
If this is posible, may you give some guides, links or documentations.
Thanks a lot

A: Sure that's possible, QMDIsubwindow it's nothing more then just specialised QWidget, so you are free to put any content inside.. let's say QScrollArea and then you can put any of you 'sub-sub' windows.


text:
Q: Constructing a Binary Tree with node sharing same information I wanted to build a binary tree in java where some nodes must be the same as in another part.
For example, i have my tree in one side and a node in another side (Set class). The node at the other side is a node which will be also at the tree. And that node in the tree may be multiple or single.
So, basically, we have a node sharing informations with the tree.
When i will change the content of that node, it must also change the content in the tree !
So i decided to write something as a proof of concept, and couldn't make it ...
This is my code:
Main Class
public class Main {

    public static void main(String [] args) {
        Set s = new Set();
        System.out.println(s.toString());

        Node n1 = new Node(new String("2"),null,null);
        Node n2 = new Node(new String("3"),null,null);
        Node n3 = new Node(new String("+"),n1,n2);

        s.setIdentifier(n3);
        System.out.println(s.toString());
    }
}

Set Class
public class Set {
    private Node identifier; // This is the node where is apart of the tree
    private Node head; // This is the head of the tree

    // Pre-Condição : Cria o conjunto de universo
    public Set() {
        Node id = new Node(new String("x"), null, null);
        this.identifier = id;
        Node left = new Node(new String("<"), this.identifier, new Node(new String("0"), null, null));
        Node right = new Node(new String(">="), this.identifier, new Node(new String("0"), null, null));
        this.head = new Node(new String("&&"), left, right);
    }

    // Pre-Condicao : Cria o conjunto vazio
    public Set(String identifier) {
        Node id = new Node(identifier);
        this.identifier = id;
        this.head = null;
    }

    // Pre-Condicao: Cria o conjunto dado
    public Set(String identifier, Node h) {
        Node id = new Node(identifier);
        this.identifier = id;
        this.head = h;
    }

    public Node getHead() {
        return head;
    }

    public void setHead(Node head) {
        this.head = head;
    }

    public void setIdentifier(Node identifier) {
        if (this.identifier != null) {
            this.identifier = identifier;
        }
    }

    public Node getIdentifier() {
        return this.identifier;
    }

    public void isntASet() {
        this.identifier = null;
    }

    public String toStringSort(String type) {
        StringBuilder s = new StringBuilder();
        if (this.identifier != null && this.head != null) {
            s.append(this.identifier.toStringSort(type));
            s.append(" | ");
            s.append(this.head.toStringSort(type));
        }
        return s.toString();
    }

    public String toString() {
        StringBuilder s = new StringBuilder();
        if (this.identifier != null && this.head != null) {
            s.append(this.toStringSort("infix"));
        } else if (this.identifier != null && this.head == null) {
            s.append("{");
            s.append(this.identifier.toStringSort("infix"));
            s.append(" | ");
            s.append(" }");
        } else {
            s.append("Problem detected with the expression of the Set (not a boolean Expression).");
        }
        return s.toString();
    }
}

Node Class
public class Node {
    private String data;
    private Node left;
    private Node right;

    public Node(String data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }

    public Node(String data, Node left, Node right) {
        this.data = data;
        this.left = left;
        this.right = right;
    }

    public Node(Node n) {
        this.data = n.getData();
        this.left = n.getLeft();
        this.right = n.getRight();
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public Node getLeft() {
        return left;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public Node getRight() {
        return right;
    }

    public boolean doesLeft() {
        return (this.left != null) ? true : false;
    }

    public boolean doesRight() {
        return (this.right != null) ? true : false;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    public Node clone() {
        return new Node(this);
    }

    public String toStringSort(String type) {
        StringBuilder s = new StringBuilder();

        if (type.equals("prefix")) {
            s.append(this.data.toString());
            if (this.left != null) {
                s.append(this.left.toStringSort("prefix"));
            }
            if (this.right != null) {
                s.append(this.right.toStringSort("prefix"));
            }
        } else if (type.equals("infix")) {
            if (this.left != null) {
                s.append("(" + this.left.toStringSort("infix"));
            }
            s.append(this.data.toString() + " ");
            if (this.right != null) {
                s.append(this.right.toStringSort("infix") + ")");
            }
        } else if (type.equals("postfix")) {
            if (this.left != null) {
                s.append(this.left.toStringSort("postfix"));
            }
            if (this.right != null) {
                s.append(this.right.toStringSort("postfix"));
            }
            s.append(this.data.toString());
        }
        return s.toString();
    }

    public String toString() {
        StringBuilder s = new StringBuilder();

        s.append(this.data.toString());

        return s.toString();
    }
}

And the result of my output from my main class is that one :
x  | ((x < 0 )&& (x >= 0 ))
(2 + 3 ) | ((x < 0 )&& (x >= 0 ))

Normally, every 'x' where appears in my function should be replaced by the '2+3'. Which is not being replaced as shown in the figure...
What's wrong whit my code ? Should i use another architecture ?
Thanks.

A: When you set the identifier, you forgot to set the head too. The identifier is printed out correctly, and so is the head in the toStringSort funtion:
public String toStringSort(String type){
StringBuilder s = new StringBuilder();
    if(this.identifier != null && this.head != null) {
        s.append(this.identifier.toStringSort(type));
        s.append(" | ");
        s.append(this.head.toStringSort(type));
   }
   return s.toString();
}

The head is initialized with the left and right being a reference to the nodes:
    Node left = new Node(new String("<"),this.identifier, new Node(new String("0"),null,null));
    Node right = new Node(new String(">="),this.identifier, new Node(new String("0"),null,null));
    this.head = new Node(new String("&&"), left,right);

This is what is printed out in the toStringSort, as these references are never touched.
One more thing about your implementation. I think you're making this too complicated. Why don't you build the tree just out of nodes? You could build a tree easily in the way that every node contains references to it's father and it's children.
Now when you change a node, every occurence of this node is changed, and as it's only a refence, the node is changed in every of it's occurencs.


text:
Q: How to make JOINS faster? I had this query to start out with:
SELECT DISTINCT spentits.*
FROM `spentits`
WHERE (spentits.user_id IN
         (SELECT following_id
          FROM `follows`
          WHERE `follows`.`follower_id` = '44'
            AND `follows`.`accepted` = 1)
       OR spentits.user_id = '44')
ORDER BY id DESC
LIMIT 15 OFFSET 0

This query takes 10ms to execute.
But once I add a simple join in:
SELECT DISTINCT spentits.*
FROM `spentits`
LEFT JOIN wishlist_items ON wishlist_items.user_id = 44 AND wishlist_items.spentit_id = spentits.id
WHERE (spentits.user_id IN
         (SELECT following_id
          FROM `follows`
          WHERE `follows`.`follower_id` = '44'
            AND `follows`.`accepted` = 1)
       OR spentits.user_id = '44')
ORDER BY id DESC
LIMIT 15 OFFSET 0

This execute time increased by 11x. Now it takes around 120ms to execute. What's interesting is that if I remove either the LEFT JOIN clause or the ORDER BY id DESC , the time goes back to 10ms.
I am new to databases so I don't understand this. Why is it that removing either one of these clauses speeds it up 11x ? And how can I keep it as is but make it faster?
I have indexes on spentits.user_id, follows.follower_id, follows.accepted, and on primary ids of each table.
EXPLAIN:
1   PRIMARY spentits    index   index_spentits_on_user_id   PRIMARY 4   NULL    15 Using where; Using temporary
1   PRIMARY wishlist_items  ref index_wishlist_items_on_user_id,index_wishlist_items_on_spentit_id  index_wishlist_items_on_spentit_id  5   spentit.spentits.id 1   Using where; Distinct
2   SUBQUERY    follows index_merge index_follows_on_follower_id,index_follows_on_following_id,index_follows_on_accepted

index_follows_on_follower_id,index_follows_on_accepted  5,2 NULL    566 Using intersect(index_follows_on_follower_id,index_follows_on_accepted); Using where

A: You should have index also on:

wishlist_items.spentit_id

Because you are joining over that column

A: The LEFT JOIN is easy to explain: A cross product of all entries against all other entries is made. The conditions of the join (in your case: Take all entries on the left and find fitting ones on the right) are applied afterwards. So if your spentits table is large it will take the server some time. Would suggest you get rid of your subquery and make three joins. Start with the smallest table to avoid big amounts of data.

A: In the 2nd example the subselect runs for every spentits.user_id.
If you write is like this it will be faster because the subselect runs once:
SELECT DISTINCT spentits.*
FROM `spentits`, (SELECT following_id
          FROM `follows`
          WHERE `follows`.`follower_id` = '44'
            AND `follows`.`accepted` = 1)
       OR spentits.user_id = '44') as `follow`
LEFT JOIN wishlist_items ON wishlist_items.user_id = 44 AND wishlist_items.spentit_id = spentits.id
WHERE (spentits.user_id IN
         (follow)
ORDER BY id DESC
LIMIT 15 OFFSET 0

As you can see the subselect moved to the FROM-part of the query and creates a imaginary tabel (or view).
This imaginary tabel is a inline-view.
JOINs and inline-views are faster every time than a subselect in the WHERE-part.


text:
Q: The only non-trivial Homomorphic images of a field $F$ is $F$-------Is the statement true? The only non-trivial Homomorphic images of a field $F$ is $F$-------Is the statement true?
How we can prove or disprove it. I know that a field does not contain any non trivial proper ideal.  and Unity will be mapped to unity itself. But with these two statements I can not progress.
Can anyone please help me?

A: Hint: Given a field $F$ and a homomorphism $F\to R$, the homomorphism is either injective (in which case the image is isomorphic to $F$), or it isn't. Show that if it isn't injective, then it's trivial.


text:
Q: core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading 'name') In the console.log, I have an error message but I cannot solve this problem...
Here is the error message
core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading 'name')

How should I declare name below?
 ...
    <ng-container *ngIf="dta && dta.PP">
 ...

HTML
<ng-container *ngIf="dta && dta.PP  ">

                Year
                {{ fiscalYear }}

                Country
                {{ selectedCountry.name }}

                Register
                {{ registreNational }}

</ng-container>

TS
selectedCountry: Country;

ngOnInit(): void {
    ...

    this.service.getPaysDta().pipe(
        takeUntil(this.unsubscribe$)
    ).subscribe((countries) => {
        this.countries = countries;

        let selectedCountry = this.countries.find(c => c.id == this.country);
        if (selectedCountry) {
            this.selectedCountry = selectedCountry;
        }
    });

}

Country.ts
export class Country {
    id : string;
    name: string;

}

I don't know how to correctly declare the variable name... :S
Thank you for your help.

A: The selectedCountry is undefined by default, it only gets assigned a value in the asynchronous getPaysDta() subscribe callback.
In the HTML you string interpolate {{ selectedCountry.name }}. Initially it will try to access the name property of undefined, hence the error message.
You can fix this very easily, by wrapping the string interpolation with an *ngIf.
Example:

{{ selectedCountry.name }}


text:
Q: Using multiple parameters in conditional statements In the following code I have been trying to get it to check for multiple parameters (when checking if the username AND password are correct).
 string username;
    string password;
    cout << "Hello there. To access this program, please put in your user name and password." << endl;
    cout << "Username: ";
    cin >> username;
    cout << "Password: ";
    cin >> password;
    if(username != "admin", password != "therealpassword"){
        do{
            cout << "Username or password is incorrect." << endl;
            cout << "Username: ";
            cin >> username;
            cout << "Password: ";
            cin >> password;
        }while(username != "admin", password != "therealpassword");
    }

For whatever reason, when running the program and I put in the incorrect username, but the correct password, it allows me to login. At the (do...while) section, if I put in the wrong username, but the right password again, I am able to login correctly still, even though the username is incorrect. How can I get this to check for both the username and password? Any and all help is appreciated.

A: The comma does not do what you think it does.  You want the logical AND operator && or the logical OR ||.  In your case you want the if to be false if both conditions are true.  So
Change your if statement to if( !( (username == "admin" ) && (password == "therealpassword" )) )
I would say better is to use string.compare
if( !( (username.compare("admin") == 0) && (password.compare("therealpassword") == 0) ) )

The while statement you want to be true if either are false so it would need to be the logical OR ||.
while( (username.compare("admin") != 0) || (password.compare("therealpassword") != 0) )

A simpler approach would be just use the do while loop and forget the if statement altogether.

A: The comma operator should be replaced with "||" or "or". There are two basic ways the arguments can be related, one is the logical "and" ("&&") and one is the logical "or" ("||"). You use the first one when both conditions have to be true, and the second one if one of the conditions has to be true (and it doesn't matter if both of them are). If you put a comma operator,  only the second argument is being taken into account, and that's not what you want.

A: If you objective is to check if both password and username are correct, the if statement should look like this:
If( ( username.compare("admin") == 0) || ( password.compare("therealpassword") ==0) )

And to keep getting the user and password until the right ones comes. You could rewrite your code to this:
string username;
string password;

cout << "Hello there. To access this program, please put in your user name and password." << endl;
do{
    cout << "Username: ";
    cin >> username;
    cout << "Password: ";
    cin >> password;
    if( username.compare("admin") || password.compare("therealpassword") ){
        cout << "Username or password is incorrect." << endl;
    }
}while( username.compare("admin") || password.compare("therealpassword") );


text:
Q: How to restart Apache on Linux In order for my php.ini changes to take effect I need to restart Apache.
I have never done this before and so wary of getting it wrong. After researching several sites it seems to me thre are a few ways to do this. Which is the simplest way for me to understand? I do not require a server restart..
It is Linux server and I am accessing with ssh (Terminal on Mac)
Many Thanks

A: Lots of ways, depending on what Linux distro (and version), whether systemd is installed, etc.
But the one that ALWAYS works is to use apache2ctl -
First, check to make sure your new config is good
apache2ctl configtest

And if it reports that your syntax is OK, etc. then restart
apache2ctl restart

Prefix with sudo as needed... again, depends on your distribution, etc.


text:
Q: My linter does not detect none reference error One of my junior colleague wrote the following code
File: a.py
s = None
for i in range(10):
    s.startswith('hello')
    s = ""

Line 3 for sure throws none reference error but he didn't notice.
I'm shocked that PyCharm does not warn this, and flake8 and pylint on our continuous integration do not report this error either.
$ flake8 a.py
a.py:3:1: W191 indentation contains tabs
a.py:4:1: W191 indentation contains tabs

$ pylint a.py
************* Module a
a.py:3:0: W0311: Bad indentation. Found 1 spaces, expected 4 (bad-indentation)
a.py:4:0: W0311: Bad indentation. Found 1 spaces, expected 4 (bad-indentation)
a.py:1:0: C0114: Missing module docstring (missing-module-docstring)
a.py:1:0: C0103: Constant name "s" doesn't conform to UPPER_CASE naming style (invalid-name)
a.py:4:1: C0103: Constant name "s" doesn't conform to UPPER_CASE naming style (invalid-name)

--------------------------------------------------------------------
Your code has been rated at -2.50/10 (previous run: -2.50/10, +0.00)

Besides educating the junior to test code more carefully, is there any linter or static analysis tool that is able to report this none reference error in a loop?


text:
Q: .Net Core different cultures per view I have a scenario where I want to support multi-language only for few views and not for the others.
Meaning, that if a user navigates to:
/en/home or /fr/home user should get a translated view. However, if a user navigates to /en/locations or /fr/locations user should get 404 and locations view should only be available on /locations.
What I tried is:
app.UseWhen(x => !x.Request.Path.Value.Contains("locations", StringComparison.OrdinalIgnoreCase),
        appBuilder =>
        {
            app.UseRequestLocalization(GetMultiLangOptions());
        });
app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{culture=tr}/{controller=Home}/{action=Index}/{id?}");

            endpoints.MapControllerRoute(
                name: "type2",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            endpoints.MapRazorPages();
        });

But that didn't achieve what I need. Any way I can define a route template per controller?


text:
Q: Tapestry t:palette NPE when options selected I have a palette who's model is populated by a user search of customers. This works perfectly when searching initially, however once a customer is selected and the user continues to search for more customers to select a NPE is thrown.
Code from .tml
    <t:palette t:id="custSelect" model="customerModel" t:encoder="stringValueEncoder"
                         availableLabel="Search Results"  t:selected="custSelected" value="custSelected">
                         ${custSelected}

                 </t:palette>

Coresponding .java
Object listResults(List<TbgWebIntCustomer> customers) {
    log.debug("LISTRESULTS");
    customerList = new ArrayList<String>();

    if (customerList != null) {
        customerList.clear();
        if (request.isXHR()) {
            ajaxResponseRenderer.addRender(resultZone);
        }
    }
    String result;
    log.debug("LISTRESULTS2 " + customers.size());

    for (int i = 0; i <= customers.size() - 1; i++) {
        log.debug("counter: " + i);

        TbgWebIntCustomer currentCustomer = customers.get(i);

        String customerNumber = currentCustomer.getCustomerId();
        // Remove leading zeros

        String customerName = currentCustomer.getLocationName();

        result = customerNumber + " - " + customerName + " - "
                + currentCustomer.getCity();
        log.debug(result);
        customerList.add(result);

    }

    log.debug("LISTRESULTS3");
    log.debug("customer list size: " + customerList.size());
    getCustomerModel();
    log.debug("customermodel after customerlist: "
            + getCustomerModel().size());

    if (customerList.size() == 100) {
        resultsMessage = "Search returned over 100 results. Showing top 100.";
        log.debug(resultsMessage);
    } else {
        String numResults = Integer.toString(customerList.size());
        resultsMessage = "Search returned " + numResults + " customers";
        log.debug(resultsMessage);
    }
    log.debug("LISTRESULTS4");
    log.debug("customerModel returns at i 0: " + getCustomerModel().get(0));

    return request.isXHR() ? resultZone.getBody() : null;
}

Note: getCustomerModel() returns getCustomerList().
I understand that NPEs in Palette happen when one of the selected options is not present in the model you passed to it however I can't identify where it is I'm doing this. I can post setupRender() code if necessary, just trying to keep OP compact.


text:
Q: does retrieve data from cache will be count as Read Operation in Firestore? I want my app to fetch data from my server only once in every one hour. so if the timestamp is over one hour, then I use Source.SERVER to retrieve data from firestore server, otherwise, if it is below range of one hour, then just get previous data from cache using Source.CACHE
so my question is, if I get the data from Source.CACHE, will it be counted as Read operation in Firestore ?
currently I am investigating the number of read operation in firestore, because in my project, the number of reads is way above the expected number. so I suspect this cache is the problem, because I now assume the data from cache will also be counted as read operation. am I right ?
I have no other idea why the number of read is so high in my project.

A: Documents read from cache are not billed as reads.


text:
Q: Microsoft-graph API email messages detecting deleted email I'm using the delta query api as specified in the docs

https://graph.microsoft.com/v1.0/me/mailFolders/{id}/messages/delta?%24deltaToken={token}

I'm trying to detect deleted messages in the outlook folder.
I managed to detect if  they are in the 'Trash Folder'. The problem is, this isn't able to detect if the user has message in a folder, delete from the 'trash', then delete permanently.
E.g. of flow

*

*Message in inbox

*Delete message from inbox

*Delete message from 'Trash' folder

I have a delta query token monitoring for the 'Trash' Folder but whenever the sync runs, it doesn't detect any activity in the Trash folder.
However,  if the user stopped at step 2 and my sync runs, then step 3 then my sync runs. I am able to detect that the message is permanently deleted.
How do I detect if the message was deleted when the user does step 2 and step 3 consecutively then my sync runs?


text:
Q: "Processes" or "Threads" strategy to fill independant blocks into global array? In python2, I would like to fill a global array by filling with parallel processes (or threads) different sub-arrays (there is a total 16 blocks). I must precise that each block doesn't depend of the others, I mean when I perfom the assignement of each cells of the current block.
1) From what I have found, I would have a great benefit from a CPU multi-cores by using different "processes" but it seems a little bit complicated to share the global array by all others processes.
2) From another point of view, I can use "threads" instead of "processes" since the implementation is less hard. I have found out the libray "ThreadPool" from "multiprocessing.dummy" allows to share this global array by all others concurrent threads.
For example, with python2.7, the following code works :
from multiprocessing.dummy import Pool as ThreadPool

## discretization along x-axis and y-axis for each block
arrayCross_k = np.linspace(kMIN, kMAX, dimPoints)
arrayCross_mu = np.linspace(-1, 1, dimPoints)
# Build all big matrix with N total blocks = dimBlock*dimBlock = 16 here
arrayFullCross = np.zeros((dimBlocks, dimBlocks, arrayCross_k.size, arrayCross_mu.size))
dimBlocks = 4
# Size of dimension along k and mu axis
dimPoints = 100
# dimension along one dimension of global arrayFullCross
dimMatCovCross = dimBlocks*dimPoints

# Build cross-correlation matrix
def buildCrossMatrix_loop(params_array):
  # rows indices
  xb = params_array[0]
  # columns indices
  yb = params_array[1]
  # Current redshift
  z = zrange[params_array[2]]
  # Loop inside block
  for ub in range(dimPoints):
    for vb in range(dimPoints):
      # Diagonal blocs
      if (xb == yb):
      # Fill the (xb,yb) su-block of global array by
        arrayFullCross[xb][xb][ub][vb] = 2*P_obs_cross(arrayCross_k[ub], arrayCross_mu[vb] , z, 10**P_m(np.log10(arrayCross_k[ub])),

        ...
        ...

# End of function buildCrossMatrix_loop

# Main loop
while i < len(zrange):

  def generatorCrossMatrix(index):
    for igen in range(dimBlocks):
      for lgen in range(dimBlocks):
        yield igen, lgen, index

if __name__ == '__main__':

  # Use 20 threads
  pool = ThreadPool(20)
  pool.map(buildCrossMatrix_loop, generatorCrossMatrix(i))

  # Increment index "i"
  i = i+1

But unfortunately, even by using 20 threads, I realize that the cores of my CPU are not fully running (actually, with 'top' or 'htop' command, I only see a single process at 100%).
3) What is the strategy that I have to chose if I want to full exploit the 16 cores of my CPU (like this is the case with pool.map(function, generator)) but with also the sharing of global array ?
4) some people told me to do I/O for each sub-array (basically, write each block in a file and gather all sub-arrays by reading them and get the full array filled). This solution is handy but I would like to avoid I/O (unless there is really not other solutions).
5) I have practised MPI library with C language and the operation of filling sub-array and finally gather them to build a big array, is not very complicated. However, I wouldn't like to use MPI with Python language (I don't know even if it exists).
6) I tried also to use Process with target equal to my filling function (buildCrossMatrix_loop) like this into while Main loop above :
from multiprocessing import Process

# Main loop on z range
while i < len(zrange):

  params_p = []
  for ip in range(4):
    for jp in range(4):
      params_p.append(ip)
      params_p.append(jp)
      params_p.append(i)
      p = Process(target=buildCrossMatrix_loop, args=(params_p,))
      params_p = []
      p.start()

  # Finished : wait everybody
  p.join()

  ...
  ...

  i = i+1
  # End of main while loop

But the final 2D global array is filled only of zeros. So I must deduce that Process function doesn't share the array to fill ?
7) So which strategy I have to look for ? :
1. The using of "pool processes" and find a way to share the global array knowing all my 16-cores will be running
2. The using of "Threads" and share the global array but performances, at first sight, seems to be less good than with "pool processes". Maybe there is a way to increase the power of each "Threads", I mean like with "pool processes" ?
I tried to follow the different examples on https://docs.python.org/2/library/multiprocessing.html but without success, this is to say, without relevant performances from a speed-up point of view.
I think that in my case, the major issue is the gathering of all sub-arrays OR the fact that the global array arrayFullCross is not shared by other processes or threads.
If someone had a simple example of the sharing of global variable in a multi-threading context (here an array), this would nice to put it here.
UPDATE 1: I made test with the Threading (and not multiprocessing) but performances remain rather bad. GIL is not apparently unlocked, i.e only one process appears in htop command (maybe the version of Threading library is not the right one).
So I am going to try to handle my issue with using the "return" method.
Naively, I tried to return the whole array at the end of the function on which I apply the map function, like this :
# Build cross-correlation matrix
def buildCrossMatrix_loop(params_array):

  # rows indices
  xb = params_array[0]
  # columns indices
  yb = params_array[1]
  # Current redshift
  z = zrange[params_array[2]]
  # Loop inside block
  for ub in range(dimPoints):
    for vb in range(dimPoints):
      # Diagonal blocs
      if (xb == yb):
        arrayFullCross[xb][xb][ub][vb] = 2*P_obs_cross(arrayCross_k[ub], arrayCross_mu[vb])

      ...
      ... #others assignments on arrayFullCross elements

  # Return global array to main process
  return arrayFullCross

Then, I tried to receive this global array from map like this :
if __name__ == '__main__':

  pool = Pool(16)
  outputArray = pool.map(buildCrossMatrix_loop, generatorCrossMatrix(i))
  pool.terminate()
  ## Print outputArray
  print 'outputArray = ', outputArray

  ## Reshape 4D outputArray to 2D array
  arrayFullCross2D_swap = np.array(outputArray).swapaxes(1,2).reshape(dimMatCovCross,dimMatCovCross)

Unfortunately, when I print the outputArray, I get :
outputArray =  [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]

This is not the 4D outputArray expected, just a list of 16 None (I think that number of 16 correspond to the number of processes provided by generatorCrossMatrix(i)).
How could I get back the whole 4D array once map is launched and when it has finished ?

A: First of all I believe multiprocessing.ThreadPool is a private API so you should avoid it. Now multiprocessing.dummy is a useless module. It does not do any multithreading/processing that's why you don't see any benefit. You should use the "plain" multiprocessing module.
The second code does not work because it is using multiple processes. Processes do not share memory, so the changes you do in a subprocess are not reflected in the other subprocesses or the main process. You either want to:

*

*Return the value and combine them together in the main process, for example using multiprocessing.Pool.map

*Use threading instead of multiprocessing: just replaceimport multiprocessingwithimport threadingandmultiprocessing.Processwiththreading.Thread` and the code should work.

Note that the threading version will work only because numpy releases the GIL during computations, otherwise it would be stuck at 1 CPU.
You may want to look at this similar question which I answered a couple of minutes ago.


text:
Q: How to create a listener for Git events through the EGit/JGit plug-in? I have been using the Subclipse API to create a plug-in for Eclipse that listens for Subversion events that happen through the Subclipse plug-in. I am basically implementing a listener interface that then gets notified during run-time about the events going on.
I would like to do something similar, but for Git. It seems that EGit (which is built on JGit) will be the best option when it comes to utilizing another plug-in. I don't have much experience with their API though. I am wondering if anyone knows if EGit, or the underlying JGit, has a similar API interface for listening for Git events (such as commit, push, pull, etc.)?
Thanks!

A: You can register listeners through JGit for all repositories or individual repositories through the following methods:
Global listeners notified for all repositories:
org.eclipse.jgit.lib.Repository.getGlobalListenerList().addIndexChangedListener
org.eclipse.jgit.lib.Repository.getGlobalListenerList().addConfigChangedListener
org.eclipse.jgit.lib.Repository.getGlobalListenerList().addRefsChangedListener

Listeners on an invidiual repository:
org.eclipse.jgit.lib.Repository.getListenerList().addIndexChangedListener
org.eclipse.jgit.lib.Repository.getListenerList().addConfigChangedListener
org.eclipse.jgit.lib.Repository.getListenerList().addRefsChangedListener

These listeners support events for changes to the index, changes to the repository configuration, and changes to the repository's references (branches, tags, etc.).
You can find all the repositories registered in EGit through the following:
Get the absolute paths to all the repositories present in EGit by calling:
org.eclipse.egit.core.Activator.getDefault().getRepositoryUtil().getConfiguredRepositories()

You can get a handle to a specific Repository object by creating a File for a path returned from the previous method and then call the following with that File:
org.eclipse.egit.core.Activator.getDefault().getRepositoryCache().lookupRepository

A: So far there are no public listeners or extension points available. There are some extension points in the Commit dialog and also maybe other dialogs, but these are all non-public, and may be changed in the future. However, to track your interests, you should file an enhancement request at the Eclipse Bugzilla in the EGit project (i think, there are already some requests for similar features, so you can search them and vote for them).


text:
Q: remove/replace/gsub all words matching list in df (size 6001) from df (size 29175) in r, different size dataframes i have been trying to remove any words in dfmedia (size 29175) matching any contained in dfvocab (size 6001).
dfmedia: each row is a sentence of words in chinese.
我喜歡吃蘋果; 我愛吃饅頭; 我不喜歡菠菜; 我最討厭蘋果!;我很愛菠菜啊;哪個中國人敢不喜歡饅頭?;哎呀饅頭蘋果菠菜都是食物管人家喜歡否?

dfvocab: 蘋果,饅頭,菠菜

desired result: 我喜歡吃; 我愛吃; 我不喜歡; 我最討厭!;我很愛啊;哪個中國人敢不喜歡?;哎呀都是食物管人家喜歡否?

i don't think the results will be any different in chinese or english since it is a simple match and remove/replace, but i'm including the chinese here just in case since my og data is chinese.
I have tried gsub(), mapply(), and using stringr to bind dfmedia and dfvocab together into one dataframe/removing. however since dfvocab and dfmedia are different sized, I am unsure how to approach this with the suggested methods online.
any help would be really appreciated!!

A: It's pretty straightforward with gsub. Just paste0 all the vocab together with the regex OR operator and replace with ""
> gsub(paste0(dfvocab, collapse="|"), "",  dfmedia)
[1] "我喜歡吃"                 " 我愛吃"                  " 我不喜歡"                " 我最討厭!"              "我很愛啊"                 "哪個中國人敢不喜歡?"
[7] "哎呀都是食物管人家喜歡否"

(I do not speak or read Chinese.) I imagine with such a large vocab set to be deleted you might need to break the 6000 vocab words in chunks and I suspect it will be slow. You might want to look at the tm package since text mining might a task that would require such operations to be optimized.
Here's a way to build a reproducible example:
> dfmedia <- scan(text="我喜歡吃蘋果; 我愛吃饅頭; 我不喜歡菠菜; 我最討厭蘋果!;我很愛菠菜啊;哪個中國人敢不喜歡饅頭?;哎呀饅頭蘋果菠菜都是食物管人家喜歡否", what="", sep=";")
Read 7 items
>
> dfvocab <- scan(text="蘋果,饅頭,菠菜", what="", sep=",")
Read 3 items


text:
Q: opamp instead LDO I have very tough requirements on noise (sub mV, no 50Hz allowed) and LDO seem to fail in that. The required current is like 20-40mA, so i am thinking about using opamp with reference voltage.
Is there any showstopper for that? Maybe, somebody did it before?

A: The main gotcha is that op-amp stability with capacitive load is often dubious at best- if you do this you can add extra compensation or use a special op-amp that is guaranteed stable with nF of capacitive load. Connecting an ordinary op-amp voltage follower to a reference will typically result in oscillation when the bypass capacitors are added to the output, and op-amps have pretty high output resistance at high frequencies (tens of ohms) so you usually need bypass capacitors.
We never have a problem with 50Hz noise here, but 60Hz (or 120Hz) can be a possibility.
Personally, I don't think you should do that, there are LDOs available with a few uV of noise (eg. LP5907). If you don't like the 90dB PSRR at 100Hz, add another regulator in front of it (doesn't have to be a great one) and it should be undetectable, if your layout is good. If uV of noise is too much, then add some passive filtering afterwards or, as GH says, a capacitive multiplier.


text:
Q: Error running emrfs delete - Metadata 'EmrFSMetadata' does not exist As title.
We have stage/prod emr clusters and we may need to run emrfs delete s3_path command on both clusters via the jenkins jobs.
However, I can run the emrfs delete successfully on stage emr one, but failed on prod. Below are the log:
22:54:51 Clear meta-store before loading into DW table.
22:54:51 ----------------------------------------------------------
22:54:51

22:54:51 Pseudo-terminal will not be allocated because stdin is not a terminal.
22:54:52 19/03/23 02:54:52 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
22:54:53 EmrFsApplication.scala(91): dynamoDB endPoint = dynamodb.us-east-1.amazonaws.com
22:54:53 EmrFsApplication.scala(99): s3 endPoint = s3.amazonaws.com
22:54:53 EmrFsApplication.scala(107): sqs endPoint = sqs.us-east-1.amazonaws.com
22:54:54 Metadata 'EmrFSMetadata' does not exist

I don't know why EmrFSMetadata not exist in my prod emr? or is it something special settings need to apply to the prod one?
Thanks.

A: Ah.. I think I got the answer. Our prod emr doesnt enable EMRFS consistent view.
That's why...
Question can be closed.


text:
Q: Angular 2 : Type ChildComponent is a part of the declarations of 2 modules : parent1Module and Parent2Module I have 2 parent component and 1 child component. And my project structure is below:
app
   -> app.module.ts
   -> app.component.ts
   -> app.routing.module.ts
parentComponent1
   -> parent1.module.ts
   -> parent1.component.ts
parentComponent2
   -> parent2.module.ts
   -> parent2.component.ts
childComponent
   -> child.module.ts
   -> child.component.ts

Now my problem is when i am using child componet's selector in parentComponent1 and parentComponent2 as :
<child-component [name]="parent1"></child-component>

And importing child module in both parent component as :
parent1.module.ts--
 @NgModule({
          imports:[ChildModule],
           declarations:[ChildComponent]
})
----
----
and so on....

And same in parentComponent2's Moudle as :
parent2.module.ts--
 @NgModule({
              imports:[ChildModule],
               declarations:[ChildComponent]
    })
    ----
    ----
    and so on....

Now when i starts my project, my default routes go to parentComponent1 and there is no error in console and it works fine, but when i go to parentComponent2, then the error comes in console as :

Unhandled Promise rejection: Type ChildComponent part of the
  declarations of 2 modules: Parent1Module and Parent2Module! Please
  consider moving ChildComponent to a higher module that imports
  Parent1Module and Parent2Module . You can also create a new NgModule
  that exports and includes ChildComponent then import that NgModule in
  Parent1Module and Parent2Module

.
Please help me out what wrong i am doing here.

A: Use this solution
You should not declarations a component in more than one NgModule, you could export in one NgModule, then import this NgModule in other NgModule.
child.module.ts
@NgModule({
  imports:[...],
  declarations:[ChildComponent],
  exports:[ChildComponent]
})

parent1.module.ts
@NgModule({
  imports:[ChildModule],
  declarations:[...]
})

parent2.module.ts
@NgModule({
  imports:[ChildModule],
  declarations:[...]
})


text:
Q: Importing jqueryui with Typescript and RequireJS I've been having trouble getting jQueryUI work properly. Before I tried to add jQueryUI, having jQuery alone worked just fine.
With the code below, I currently get "TypeError: jQuery is not a function(...)" in chrome, which is strange, considering that jquery is marked as a dependency in the require.config file.
The compiling from .ts to .js happens with no errors.
initApp.ts:
/// <reference path="../../../typings/jqueryui/jqueryui.d.ts"/>
import * as jQuery from "jquery"; //Works completely fine
import * as jQueryUI from "jquery-ui"; //Can't even find the module unless
                                       //d.ts file is modified

Compiled to js:
define(["require", "exports", "jquery-ui"], function (require, exports, jQuery) {...}

jqueryui.d.ts:
/// <reference path="../jquery/jquery.d.ts"/>
declare module JQueryUI { <unmodified code>}

//Added this declare

declare module "jquery-ui" {
  export = jQuery;
}

Require.config.js:
require.config({
    baseUrl: "./components/",
    paths: {
        "jquery": "./javascripts/lib/jquery-2.1.4",
        "jquery-ui": "./javascripts/lib/jquery-ui",
        "go": "./javascripts/lib/go-debug"
    },
    shim: {
        "jquery": {
          exports: "jQuery",
        },
        "jquery-ui": {
            //exports: "jQuery", //Adding this line doesn't fix the problem
            deps: ["jquery"],
        }
    },
});
require(["./javascripts/initApp"]);

Directory Tree:
typings/
    jquery/
        jquery.d.ts
    jqueryui/
        jqueryui.d.ts
web/
    components/
        javascripts/
            lib/
                jquery-2.1.4.js
                jquery-ui.js
                require.js
            initApp.js
            initApp.ts
            require.config.js

Links to full d.ts files:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/jquery/index.d.ts (jquery V3.3)
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/jqueryui/index.d.ts (QueryUI V1.12)
Any help would be greatly appreciated

A: So what happens is that you have jQuery which has an export, and jQueryUi which imports jQuery, augments it, and then exports $.widget not $.
This is why, as I think you already pointed out,
import * as jQuery from 'jquery-ui';

is problematic.
As you go on to note,
import jQueryUi from 'jquery-ui';

Does not work because jQueryUi is never used in a value position and so it gets elided by the compiler, which is actually really useful, if tricky, behavior that can make a number of asynchronous loading scenarios easier.
What you need is a way to tell TypeScript to perform an import of the library regardless of whether or not it is actually used, that is to say, we are importing it for its side effects.
Fortunately, ECMAScript has an import form which is provided specifically for this scenario. By writing
import 'jquery-ui';

you indicate that you depend on 'jquery-ui' for its side effects.
Furthermore, you do not need the shims for jQuery these days (don't quote me on this, my AMD is rusty).
So you should only need the following.
import $ from 'jquery';
// typescript will not remove this as the point of this syntax is: import for side-effects!
import 'jquery-ui';

You should not need to modify your require.config(....), but I could be misreading it.
Also, note the jquery-ui declarations, which you should probably update (your link was dead due to package restructuring) does not declare an exports and references jQuery as a global which sucks and messes up multi-version .d.ts scenarios, but should not make a practical runtime difference in your case.

A: I also ran into this problem. After reading several of these questions where the answers were fairly muddled, I came up with the following:
including reference paths at the top of each file will solve this problem. No other changes needed. TS just needs to know where to find the definition files that describes all the functions that are available. Including a direct ref in each file solves that problem:
/// <reference path="/typings/jquery.d.ts"/>
/// <reference path="/typings/someotherlibrary.d.ts"/>

I could not get other methods mentioned to properly resolve. (I presume I am just stupid, but there could be bugs in the code or changing syntax in the APIs) If you have large numbers of files to resolve, this approach might not be the best solution.

A: My initial workaround used to be embedded in the body of my question. I'm reposting it as an answer to meet StackOverflow's editorial guidelines.
Aluan's answer directly answers some of the questions I posed in this block.

I can manually fix the error by editing the compiled javascript to include both "jquery" and "jquery-ui" modules, and assigning them to variables:

define(["require", "exports", "jquery", "jquery-ui"], function (require, exports, jQuery, jQueryUI) {...}

However, I wanted the typescript compiler to automatically do this, or something similar to set both jquery-ui and jquery as dependencies of my file.
TypeScript takes the declared module name and compiles that string into the dependency parameters of the AMD define() function. Therefore, the TypeScript definition d.ts file must declare the module by the same string that represents my library in require.config.js
Simply having an import statement doesn't trigger any action from the TypeScript compiler. Whichever variable (foo, in this case) the properties from the module/library is imported into needs to be called at least once, and cannot conflict with any existing variables in that scope.
Earlier, I used this line:

import * as jQuery from "jquery-ui"

This occupied the 'jQuery' variable name, and thus, the jQuery function was no longer able to be assigned to that variable name, resulging in the error: "jQuery is not a function(...)"
As jquery-ui simply extends jQuery library, I never need call it. But the compiler got too smart on me and decided to not actually compile jquery-ui to be a dependency in my define(...). This was an easy fix once I realized the problem.
Final code

initApp.ts
/// <reference path="../../../typings/jqueryui/jqueryui.d.ts"/>
import * as jQueryUI from "jquery-ui";
import uiVar from "./uiVariables";
jQueryUI

Compiled to js:

define(["require", "exports", "jquery-ui"], function (require, exports, jQueryUI) {...}

require.config.js
require.config({
    baseUrl: "./components/",
    paths: {
        "jquery": "./javascripts/lib/jquery-2.1.4",
        "jquery-ui": "./javascripts/lib/jquery-ui",
        "go": "./javascripts/lib/go-debug"
    }
});
require(["./javascripts/app"]);

A: I produced a little example on GitHub for using TypeScript 2 with ES 6 modules and JQuery / JQuery UI with custom plugins, I hope this will help:
https://github.com/lgrignon/typescript-es6-jquery


text:
Q: What is the command to check the version of the postgresql jdbc driver on Linux command line? I am working on Linux server with PostgreSQL that is installed through the command line.
How could I check the version of the PostgreSQL JDBC Driver using Linux command line?
I use this command  psql -V and it shows the PostgreSQL version psql (PostgreSQL) 9.5.24, but I need the PostgreSQL JDBC Driver version. What is the command the should I use?

A: When you run:
java -jar /path/to/driver.jar

it will report its version.
Obviously you need to replace /path/to/driver.jar with the correct location where you stored the driver when you downloaded it.
By default the file name itself contains the version. So if you downloaded postgresql-42.2.19.jar then it's highly likely its version is 42.2.19

As a side note: psql -V prints the version of the command line tool. That's not necessarily the same version as the server.

A: From Java, you can use code like this:
java.sql.Driver d = new org.postgresql.Driver();
System.out.println(d.getMajorVersion() + "." + d.getMinorVersion());

See the documentation for details.


text:
Q: Scrolling body after dismissing bootstrap 3 modal I am launching a bootstrap 3 modal on document ready of index.html. I also have a link on about.html like index.html#people which is accessing a section on index.html with id 'people' but when I click index.html#people on about.html the window navigates to index.html but not to the section #people because the modal opens on its document.ready. What should I do to navigate to the people section after dismissal of the modal.
Thanks in advance

A: On your document ready function, check if there is a hash present in the URL, and if there is, scroll to that element:
$( document ).ready(function() {
    /*
      Your actual code here
    */
    if(window.location.hash) {
          $('html, body').animate({
            scrollTop: $("#"+window.location.hash).offset().top
          }, 2000);
    }
});


text:
Q: Use Device Camera instead of Webcam on Play I've downloaded and used Vuforia with success and when I play the project, It uses my webcam on my laptop. But how can I use my connected iPhone's camera instead when I play the project in Unity?

A: Simple answer: You can't.
Vuforia accesses the camera hardware directly with C++ and not with Unity's  WebCamTexture API. This would have worked with the new Unity Remote 5 if they used WebCamTexture in their API to get camera frames, but they didn't because WebCamTexture is extremely slow for image processing.


text:
Q: How to get node path from id on multi lingual website? I have a node, with nid. i.e. 78 and it's on French language (main language is English) so local name to it is:
fr/node/78

or just
node/78

?
Also that page has some alias, i.e. "hello" so it's relative path would be:
/fr/hello

How can I get that relative path?
Yes, I know that:
$alias = drupal_get_path_alias('node/78');

should give me my page alias, but it's not working, probably because of different language?!? Or that should be:
$alias = drupal_get_path_alias('fr/node/78');

I  tried both, but none of them is working?!? I can't believe that there is no simple function available, which would take node id as parameter and return SEO (with alias) page path?!?
Please help. What is the easiest way to get node seo path on multi lingual website if I have nid?

A: Finally I got it. In case somebody else strugles with this:
// Returns root relative path
function get_node_url_ml ($nid, $language){
    $defaultLanguage = language_default();
    $local_path = 'node/' . $nid;
    $url = drupal_lookup_path('alias', $local_path, $language);
    if (!$url)  $url = 'node/' . $nid;
    if ($language != $defaultLanguage->language) $url = $language.'/'.$url;
    return '/'.$url;
}


text:
Q: Does Sublime Text have a feature such as the Shift+Tab in Jupyter Notebook? I could not find a similar question. I have started using Sublime Text but it is frustrating after switching from Jupyter Notebook because when I hit shift+tab, it would show me all the parameters and the documentation of the method. But in sublime text I am not sure if I would be able to do that?
Thanks

A: If I understand what you're looking for you could try installing:
codeintel


text:
Q: How to go initial state after onClick function fired in reactJS? I have made copy to clipboard component. It's working fine. But i want to make it  goes to initial state after copied the text. That's mean before onClick event it will show on hover "Copy to Clipboard" and when it clicked, it will show "Copied to clipboard" and goes to initial state (Copy to Clipboard) and if i click again then onClick event will be fire again.
Here is my working code
  copyToClipboard = async e => {
    window.getSelection().removeAllRanges();
    var range = document.createRange();
    range.selectNode(this.textContent);
    window.getSelection().addRange(range);
    document.execCommand("copy");
    window.getSelection().removeAllRanges();
    this.setState({ copied: true });
  };

  initRef = c => (this.textContent = c);

  render() {
    const { copied } = this.state;
    return (

          chonchol@gmail.com

        {copied === false ? (

Copy to Clipboard

        ) : (

Copied to Clipboard

        )}

    );
  }

Thanks in advance.

A: Try this simple thing.
When you leave mouse from email, it makes you always back to copy to clipboard

 this.setState({ copied: false })}
   onClick={this.copyToClipboard}
   ref={this.initRef}

> chonchol@gmail.com

A: well i added a function to fire on mouse enter ! so if u state is true it will set to false!

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class CopyClipboard extends React.Component {
  constructor(props) {
    super(props);
    this.textContent = null;
    this.state = {
      copied: false
    };
  }

  copyToClipboard = async e => {
    window.getSelection().removeAllRanges();
    var range = document.createRange();
    range.selectNode(this.textContent);
    window.getSelection().addRange(range);
    document.execCommand("copy");
    window.getSelection().removeAllRanges();
    this.setState({ copied: true });
  };
  copy = () => {
    if (this.state.copied) {
      this.setState({ copied: false });
    }
  };
  initRef = c => (this.textContent = c);

  render() {
    const { copied } = this.state;
    return (

          chonchol@gmail.com

        {copied === false ? (

Copy to Clipboard

        ) : (

Copied to Clipboard

        )}

    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<CopyClipboard />, rootElement);

A: Something like this
Just set state.copied to 'false' after a desired timeout.
copyToClipboard = async e => {
    window.getSelection().removeAllRanges();
    var range = document.createRange();
    range.selectNode(this.textContent);
    window.getSelection().addRange(range);
    document.execCommand("copy");
    window.getSelection().removeAllRanges();
    this.setState({ copied: true });
  };

  clickHandler = e => {
    setTimeout(() => {
      this.setState({ copied: false });
    }, 2000);
    this.copyToClipboard(e);
  };

  initRef = c => (this.textContent = c);

  render() {
    const { copied } = this.state;
    return (

          chonchol@gmail.com

        {copied === false ? (

Copy to Clipboard

        ) : (

Copied to Clipboard

        )}

    );
  }
}

A: You just need to set the state after a delay.
this.setState({ copied: true });

setTimeout(() => {
  this.setState({ copied: false });
}, 1000);


text:
Q: Store the login details in session in laravel I have a function in controller checklogin() which checks the user details. I want to store into session. So I can get the name of the user and display in blade view
Controller
public function checklogin(Request $request)
    {

        $req=$request->validate([
                    'name'=>'required',
                    'email'=>'required|email',
                    'password'=>'required|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[@_!]){8,}/'

                    ]);
        $userdata = array(
          'name' => $request->input('name') ,
          'email'=>$request->input('email'),
          'password' => $request->input('password')
        );
        if (Auth::attempt($userdata))
        {

            $data = $request->session()->put('user',$userdata['name']);
             dd($data) ; //returning null

             return redirect('/home');
        }
        else
        {

            return back()->with('error', 'Wrong Login Details');
        }

    }

A: No need to store logged in user detail in session.You can call auth helper function which will return auth instance.
{{auth()->user()->name}}

if you have both logged in or guest page same then you can do null check
 {{ auth()->user()!=null?auth()->user()->name:null }}


text:
Q: Python replace string pattern with output of function I have a string in Python, say The quick @red fox jumps over the @lame brown dog.
I'm trying to replace each of the words that begin with @ with the output of a function that takes the word as an argument.
def my_replace(match):
    return match + str(match.index('e'))

#Psuedo-code

string = "The quick @red fox jumps over the @lame brown dog."
string.replace('@%match', my_replace(match))

# Result
"The quick @red2 fox jumps over the @lame4 brown dog."

Is there a clever way to do this?

A: Try:
import re

match = re.compile(r"@\w+")
items = re.findall(match, string)
for item in items:
    string = string.replace(item, my_replace(item)

This will allow you to replace anything that starts with @ with whatever the output of your function is.
I wasn't very clear if you need help with the function as well. Let me know if that's the case

A: A short one with regex and reduce:
>>> import re
>>> pat = r'@\w+'
>>> reduce(lambda s, m: s.replace(m, m + str(m.index('e'))), re.findall(pat, string), string)
'The quick @red2 fox jumps over the @lame4 brown dog.'

A: You can pass a function to re.sub. The function will receive a match object as the argument, use .group() to extract the match as a string.
>>> def my_replace(match):
...     match = match.group()
...     return match + str(match.index('e'))
...
>>> string = "The quick @red fox jumps over the @lame brown dog."
>>> re.sub(r'@\w+', my_replace, string)
'The quick @red2 fox jumps over the @lame4 brown dog.'

A: I wasn't aware you could pass a function to a re.sub() either. Riffing on @Janne Karila's answer to solve a problem I had, the approach works for multiple capture groups, too.
import re

def my_replace(match):
    match1 = match.group(1)
    match2 = match.group(2)
    match2 = match2.replace('@', '')
    return u"{0:0.{1}f}".format(float(match1), int(match2))

string = 'The first number is 14.2@1, and the second number is 50.6@4.'
result = re.sub(r'([0-9]+.[0-9]+)(@[0-9]+)', my_replace, string)

print(result)

Output:
The first number is 14.2, and the second number is 50.6000.
This simple example requires all capture groups be present (no optional groups).


text:
Q: html and css background url image compacted I created a web page image fills the screen 100%.
but, Problems occurred.
I want to fill up the picture on a Web page, as shown below:

<!DOCTYPE html>

The results came out, there are some problems.
Without being tightly filled, the image is repeated.
I want a solution.
I want delete "This part":

A:
You can add this style

#top-slogan{
background-repeat: no-repeat;
background-size : cover;
background position : center center;
}

A: You can add no-repeat. Then it won't repeat.
" background-repeat: no-repeat;"
<!DOCTYPE html>

A: You can scale this image by setting it's width and height .
#top-slogan

 {
    width:100%;
    height:953px;
    background: url('backgroung.png') center;
background-size: 100% 100%;
repeat:no-repeat;
 }

A:
Try this One

#top-slogan
{
width:100%;
height:953px;
background: url('background.png') no-repeat  center;
background-size :cover;
}


text:
Q: My Python program doesn't have file, edit, shell, debug options I've installed and re-installed Python 3.6.1. I am not given the options at the top like "file, edit, shell, debug, etc" at the top. I have no idea what to do at this point as I've searched around for a while and haven't come up with a solution. Does anyone have any idea of what I should do about this?

A: In Windows, at least, the console does not have a menu at the top.  When you run interactive python, there is no menu.  When you run a program that does not create a menu, there is no menu.  When you run an IDE such as IDLE, the IDE puts its menu at the top.  The particular menu entries you refer to occur on the IDLE menu.  So start IDLE from an icon or from a console.  For the latter, <python> -m idlelib should work, where ` refers to a python binary.  Some details depend on the OS.


text:
Q: REST API what is the proper way of URI naming using nouns and not verbs? I have a login and I need to do something like this:
1. POST .../authentication/login

2. POST .../authentication/verifyToken

3. POST .../authentication/forgotPassword

*

*Will ask for a phone and a password.

*Will ask for an auth token.

*Will ask for a phone and a password.

But as I read, this structure is not good since it contains verbs rather than nouns.
I have tried to make something like this:
1. POST .../sessions/new
2. GET .../sessions/:token
3. GET .../sessions/forgot

1. Will create a new token, based on phone and password correct credentials.
2. Will verify the token validation or expiration.
3. Will send a SMS within a new password or a new temporary password reset code.

This first method is not REST. But its totally clear.
You can read the URL and understand exactly what it gonna to do. You do not need any kind of explanation.
However, more and more articles say that verbs in REST is not RESTFUL and thus, not a good practice to achieve.
What is the proper way of handle this?

A: REST doesn't care what spelling you use for your resource identifiers.

But as I read, this structure is not good since it contains verbs rather than nouns.

The structure is fine.

You can read the URL and understand exactly what it gonna to do.

Right -- REST does not care if you can read the URL and understand what it is going to do.
URL/URI are identifiers, in the same way that variable names in your program are identifiers.  Your compiler doesn't particularly care whether your variable is named accountBalance, purpleMonkeyDishwasher, or x.  The spellings described in our coding standards are for human readers, and the same is true for hackable urls.

However, more and more articles say that verbs in REST is not RESTFUL and thus, not a good practice to achieve.

REST is an architectural style

As an architectural style for network-based applications, its definition is presented in the dissertation incrementally, as an accumulation of design constraints that derive from nine pre-existing architectural styles and five additional constraints unique to the Web

Fielding describes the constraints in his thesis; any who claim that verbs in identifiers "are not RESTful" should be able to point to a specific constraint that they violate.
I have yet to see a compelling argument that any of the REST constraints are violated by identifier spellings.

A: First I would not use the term session. This implies a server side state, what is problematic in stateless communication as REST requires.
So your problem could be solved by modeling resources, probably like:
GET ./authentication/token

to get a token if valid credentials provided in the request headers.
GET ./authentication/password

to get a new temporary password if E-mail address provided in the request headers.
You also can use POST in order to transport values in the request body.
Be aware of that the service should answer with an HTTP 204 in case of the result is being sent by SMS.


text:
Q: In socket programming in c,why to specify the socket address in server program? In socket programming in c,why to specify the socket address in server program?
Im unable to understand why to specify socket address in server program because socket address we anyways specify in client program,what is the need to specify in server program.
Here is the code:
bzero((char *)&serv_addr,sizeof(serv_addr));

serv_addr.sin_family=AF_INET;

serv_addr.sin_addr.s_addr=inet_addr(argv[1]);

serv_addr.sin_port=htons(atoi(argv[2]));

A: Most servers don't specify the socket address explicitly, they use INADDR_ANY (as @ybo addresses).
The reason a server might specify the address, however, is to control which interface clients arrive on. For example, you might bind to the address 127.0.0.1 (localhost) to ensure that clients are running on the local machine only, reducing a security risk associated with remote connections. You also might bind explicitly to an external port in order to better sandbox remote clients.

A: You don't have to, you can use INADDR_ANY instead of the real address, but it can be useful when you have multiple network interfaces on your machine.

A: Actually same answer as the rest, but in other words:
A server usually just uses 1 public IP address. And also has 1 or more internal IP addresses (like localhost 127.0.0.1 and maybe for lan 192.168.0.1).
But a server can easily also have multiple public IP addresses. Your hosting provider will give these to you (and may be charge you for them.)
A server even NEEDS multiple public IP addresses if it will host multiple HTTPS certificates on port 443, as each one is bound to a specific IP address.
When listening , you can listen on 1 specific IP address, and thus ingore traffic from the other IP addresses. You can even have other applications use the same port number on the other IP adresses.
If for security reasons you only want applications to connect from localhost (eg client and server are on the same machine), you are better off listening only on 127.0.0.1 rather than ALL ip's.

A: Your computer may have many IP addresses. (Even 127.0.0.1 can be thought of as a separate IP from your "real" one.) On the server socket you can choose which of these addresses you're "listening" to. Following the above example, I believe that binding a server socket to 127.0.0.1 means you'll only be able to connect to that server program locally.


text:
Q: Use sqlcmd and setvar dynamically show hide columns I toggle the display of PHI when generating data extracts from a vendor's EHR system.
To date, I've been manually enabling and disabling these fields in my script files:
-- PHI enabled
SELECT  MRN
        --,HASHBYTES('SHA2_256',MRN) MRN_HASH
...
GO

-- PHI disabled
SELECT  -- MRN
        ,HASHBYTES('SHA2_256',MRN) MRN_HASH
...
GO

Is there a way to do this dynamically?
 --
 -- disable this variable when running `SQLCMD` from command line
 -- PS> sqlcmd -E -S server -d database -i .\script.sql -v hide_phi=1
 --
:setvar hide_phi 0

:out c:\users\x\desktop\patients.csv
SELECT
       <if $(hide_phi)=0 then hide MRN>
       <if $(hide_phi)=1 then hide MRN_HASH>
...
GO

A: SQLCMD accepts variables.  You can simply pass in the variable to your .SQL file, and inside your file, do a conditional check on the variable value.  You could use a CASE statement to check value of the variable, and return the appropriate value.
Pseudo sample query:
select "MRN" = case
   when '$(hide_phi)' = '1' then HASHBYTES('SHA2_256', MRN)
   else MRN
END
...
GO

or possibly this:
select "MRN" = case '$(hide_phi)'
   when '1' then HASHBYTES('SHA2_256', MRN)
   else MRN
END

More info: https://msdn.microsoft.com/en-us/library/ms188714.aspx


text:
Q: ReadTimeout error when starting server sidekiq on ubuntu 14.10 I installed redis server by default it's running 6379 port but when i am running sidekiq its not starting, I added in Gemfile gem 'sidekiq', '3.3.0'
please help me out with this problem
thanks in ADVANCE
this is the error
santosh@santosh-Vostro-3560:~/Roorah$ bundle exec sidekiq
Starting up a new ElasticSearch client with
Net::ReadTimeout
/usr/lib/ruby/2.1.0/net/protocol.rb:158:in `rescue in rbuf_fill'
/usr/lib/ruby/2.1.0/net/protocol.rb:152:in `rbuf_fill'
/usr/lib/ruby/2.1.0/net/protocol.rb:134:in `readuntil'
/usr/lib/ruby/2.1.0/net/protocol.rb:144:in `readline'
/usr/lib/ruby/2.1.0/net/http/response.rb:39:in `read_status_line'
/usr/lib/ruby/2.1.0/net/http/response.rb:28:in `read_new'
/usr/lib/ruby/2.1.0/net/http.rb:1408:in `block in transport_request'
/usr/lib/ruby/2.1.0/net/http.rb:1405:in `catch'
/usr/lib/ruby/2.1.0/net/http.rb:1405:in `transport_request'
/usr/lib/ruby/2.1.0/net/http.rb:1378:in `request'
/var/lib/gems/2.1.0/gems/newrelic_rpm-3.9.5.251/lib/new_relic/agent/instrumentation/net.rb:27:in `block (2 levels) in   request_with_newrelic_trace'
/var/lib/gems/2.1.0/gems/newrelic_rpm-3.9.5.251/lib/new_relic/agent.rb:454:in `disable_all_tracing'
/var/lib/gems/2.1.0/gems/newrelic_rpm-3.9.5.251/lib/new_relic/agent/instrumentation/net.rb:26:in `block in request_with_newrelic_trace'
/var/lib/gems/2.1.0/gems/newrelic_rpm-3.9.5.251/lib/new_relic/agent/cross_app_tracing.rb:38:in `tl_trace_http_request'
/var/lib/gems/2.1.0/gems/newrelic_rpm-3.9.5.251/lib/new_relic/agent/instrumentation/net.rb:23:in `request_with_newrelic_trace'
/usr/lib/ruby/2.1.0/net/http.rb:1371:in `block in request'
/usr/lib/ruby/2.1.0/net/http.rb:853:in `start'
/usr/lib/ruby/2.1.0/net/http.rb:1369:in `request'
/var/lib/gems/2.1.0/gems/newrelic_rpm-3.9.5.251/lib/new_relic/agent/instrumentation/net.rb:27:in `block (2 levels) in request_with_newrelic_trace'
/var/lib/gems/2.1.0/gems/newrelic_rpm-3.9.5.251/lib/new_relic/agent.rb:454:in `disable_all_tracing'
/var/lib/gems/2.1.0/gems/newrelic_rpm-3.9.5.251/lib/new_relic/agent/instrumentation/net.rb:26:in `block in request_with_newrelic_trace'
/var/lib/gems/2.1.0/gems/newrelic_rpm-3.9.5.251/lib/new_relic/agent/cross_app_tracing.rb:43:in `tl_trace_http_request'
/var/lib/gems/2.1.0/gems/newrelic_rpm-3.9.5.251/lib/new_relic/agent/instrumentation/net.rb:23:in `request_with_newrelic_trace'
/var/lib/gems/2.1.0/gems/faraday-0.9.0/lib/faraday/adapter/net_http.rb:80:in `perform_request'
/var/lib/gems/2.1.0/gems/faraday-0.9.0/lib/faraday/adapter/net_http.rb:39:in `call'
/var/lib/gems/2.1.0/gems/faraday-0.9.0/lib/faraday/rack_builder.rb:139:in `build_response'
/var/lib/gems/2.1.0/gems/faraday-0.9.0/lib/faraday/connection.rb:377:in `run_request'
/var/lib/gems/2.1.0/gems/elasticsearch-transport-1.0.5/lib/elasticsearch/transport/transport/http/faraday.rb:21:in `block in perform_request'
/var/lib/gems/2.1.0/gems/elasticsearch-transport-1.0.5/lib/elasticsearch/transport/transport/base.rb:187:in `call'
/var/lib/gems/2.1.0/gems/elasticsearch-transport-1.0.5/lib/elasticsearch/transport/transport/base.rb:187:in `perform_request'
/var/lib/gems/2.1.0/gems/elasticsearch-transport-1.0.5/lib/elasticsearch/transport/transport/http/faraday.rb:20:in `perform_request'
 /var/lib/gems/2.1.0/gems/elasticsearch-transport-1.0.5/lib/elasticsearch/transport/client.rb:104:in `perform_request'
 /var/lib/gems/2.1.0/gems/elasticsearch-api-1.0.5/lib/elasticsearch/api/actions/bulk.rb:81:in `bulk'
 /var/lib/gems/2.1.0/gems/elasticsearch-model-0.1.6/lib/elasticsearch/model/importing.rb:120:in `block in import'
 /var/lib/gems/2.1.0/gems/elasticsearch-model-0.1.6/lib/elasticsearch/model/adapters/active_record.rb:96:in `block in __find_in_batches'
 /var/lib/gems/2.1.0/gems/activerecord-4.1.4/lib/active_record/relation/batches.rb:125:in `find_in_batches'
 /var/lib/gems/2.1.0/gems/activerecord-4.1.4/lib/active_record/querying.rb:9:in `find_in_batches'
 /var/lib/gems/2.1.0/gems/elasticsearch-model-0.1.6/lib/elasticsearch/model/proxy.rb:80:in `method_missing'
  /var/lib/gems/2.1.0/gems/elasticsearch-model-0.1.6/lib/elasticsearch/model/adapters/active_record.rb:95:in `__find_in_batches'
  /var/lib/gems/2.1.0/gems/elasticsearch-model-0.1.6/lib/elasticsearch/model/importing.rb:119:in `import'
  /var/lib/gems/2.1.0/gems/elasticsearch-model-0.1.6/lib/elasticsearch/model.rb:112:in `import'
 /home/santosh/Roorah/app/models/city_coordinate.rb:8:in `<top (required)>'
   /var/lib/gems/2.1.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:443:in `load'
  /var/lib/gems/2.1.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:443:in `block in load_file'
  /var/lib/gems/2.1.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:633:in `new_constants_in'
 /var/lib/gems/2.1.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:442:in `load_file'
    /var/lib/gems/2.1.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:342:in `require_or_load'
    /var/lib/gems/2.1.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:307:in `depend_on'
  /var/lib/gems/2.1.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:225:in `require_dependency'
  /var/lib/gems/2.1.0/gems/railties-4.1.4/lib/rails/engine.rb:468:in `block (2 levels) in eager_load!'
   /var/lib/gems/2.1.0/gems/railties-4.1.4/lib/rails/engine.rb:467:in `each'
   /var/lib/gems/2.1.0/gems/railties-4.1.4/lib/rails/engine.rb:467:in `block in eager_load!'
   /var/lib/gems/2.1.0/gems/railties-4.1.4/lib/rails/engine.rb:465:in `each'
    /var/lib/gems/2.1.0/gems/railties-4.1.4/lib/rails/engine.rb:465:in `eager_load!'
    /var/lib/gems/2.1.0/gems/railties-4.1.4/lib/rails/engine.rb:346:in `eager_load!'
    /var/lib/gems/2.1.0/gems/railties-4.1.4/lib/rails/application/finisher.rb:58:in `each'
    /var/lib/gems/2.1.0/gems/railties-4.1.4/lib/rails/application/finisher.rb:58:in `block in <module:Finisher>'
     /var/lib/gems/2.1.0/gems/railties-4.1.4/lib/rails/initializable.rb:30:in `instance_exec'
    /var/lib/gems/2.1.0/gems/railties-4.1.4/lib/rails/initializable.rb:30:in `run'
    /var/lib/gems/2.1.0/gems/railties-4.1.4/lib/rails/initializable.rb:55:in `block in run_initializers'
    /usr/lib/ruby/2.1.0/tsort.rb:226:in `block in tsort_each'
    /usr/lib/ruby/2.1.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'
     /usr/lib/ruby/2.1.0/tsort.rb:427:in `each_strongly_connected_component_from'
    /usr/lib/ruby/2.1.0/tsort.rb:347:in `block in each_strongly_connected_component'
  /usr/lib/ruby/2.1.0/tsort.rb:345:in `each'
 /usr/lib/ruby/2.1.0/tsort.rb:345:in `call'
   /usr/lib/ruby/2.1.0/tsort.rb:345:in `each_strongly_connected_component'
  /usr/lib/ruby/2.1.0/tsort.rb:224:in `tsort_each'
  /usr/lib/ruby/2.1.0/tsort.rb:205:in `tsort_each'
  /var/lib/gems/2.1.0/gems/railties-4.1.4/lib/rails/initializable.rb:54:in `run_initializers'
    /var/lib/gems/2.1.0/gems/railties-4.1.4/lib/rails/application.rb:300:in `initialize!'
      /home/santosh/Roorah/config/environment.rb:5:in `<top (required)>'
    /var/lib/gems/2.1.0/gems/activesupport-4.1.4/lib/active_support      /dependencies.rb:247:in `require'
    /var/lib/gems/2.1.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:247:in `block in require'
    /var/lib/gems/2.1.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:232:in `load_dependency'
       /var/lib/gems/2.1.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:247:in `require'
         /var/lib/gems/2.1.0/gems/sidekiq-3.3.0/lib/sidekiq/cli.rb:236:in `boot_system'
        /var/lib/gems/2.1.0/gems/sidekiq-3.3.0/lib/sidekiq/cli.rb:50:in `run'
        /var/lib/ gems/2.1.0/gems/sidekiq-3.3.0/bin/sidekiq:8:in `<top (required)>'
     /usr/local/bin/sidekiq:23:in `load'

Here is the city_coordinate model
class CityCoordinate < ActiveRecord::Base
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks
  # Elasticsearch::Model.client = Elasticsearch::Client.new url: ENV['BONSAI_URL'], log: true

end

CityCoordinate.import


text:
Q: How to dump html string into a python twisted template I'm making a website using twisted.web.template, where multiple pages have sub-windows with identical html code. So I want to use templates, and just dump a complete html string into place holders, wherever there is identical code. But it the twisted templating system quotes these strings (partly for security reasons it seems), so the browser can't interpret it as html. Is there any way of getting around this? It seems like a pretty normal use scenario, and is one of the basic uses of php with apache in my experience...
Some sample code. My template looks like this

and my rendering class in python
class ExampleElement(Element):
    loader = XMLFile(FilePath('template.xml'))

    @renderer
    def content(self, request, tag):
        return tag('This content should be in bold, but is quoted')

I know for the last line I could write (with appropriate import)
return tag(tags.b('Bold content'))

but the html strings I actually want to put in are a lot bigger, and it's inconvenient having to write it like this, rather than just a single raw html string

A: Use a loader:
class ExampleElement(Element):
    loader = XMLFile(FilePath('template.xml'))

    extraContent = XMLFile(FilePath('extra-content.xml'))

    @renderer
    def content(self, request, tag):
        return self.extraContent.load()

Or if you really need the extra stuff to be in a string in your source file instead of in a template file:
class ExampleElement(Element):
    loader = XMLFile(FilePath('template.xml'))

    extraContent = XMLString("This content will be in bold")

    @renderer
    def content(self, request, tag):
        return self.extraContent.load()


text:
Q: How Should I do to limit the value calculated by AVG or SUM I would like to make the result value of AMY within 300 .
example
270 -> 270
300 -> 300
350 -> 300

How should I modify it ?
Is it possible to use case when in Case when?
select
no, sum(case when type = 'A' then cost else -cost end) * 0.08 as AMY
from MIKE
where
MIKE.type in ('A', 'B')
and exists (select 1 from users u where u.no = c.otaku_no)
group by no

A: You can use least():
   least(sum(case when type = 'A' then cost else -cost end) * 0.08, 300) as AMY

If the sum() exceeds 300, then the return value is 300.  You can use greatest() if you want to impose a minimum.  So, this would ensure that the value is between -300 and 300:
   greatest(least(sum(case when type = 'A' then cost else -cost end) * 0.08, 300), -300) as AMY


text:
Q: Symfony2 : Form Validation with Collection I use assert to check values of my form. I am not able to work with assert on a collection. The main goal it to check if each values are not empty and is a number.
I tried to use this link to solve my issue without success.
Here is part of my entity :
namespace MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

class Myclass
{

    private $id;
    /**
     * @Assert\NotBlank()
     * @Assert\Regex(pattern="/^0[1-9]([-. ]?[0-9]{2}){4}$/",message="Invalid")
     */
    private $numbers;

    ...

    public function __construct()
    {
        $this->numbers= new ArrayCollection();
    }

    ...

    public function addNumber($number)
    {
        $this->numbers[] = $number;
        return $this;
    }

    public function removeNumber($number)
    {
        $this->numbers->removeElement($number);
    }

    public function getNumbers()
    {
        return $this->numbers;
    }
}

And here is a part of my form :
namespace MyBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class MyclassType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
        ->add('numbers',"Symfony\Component\Form\Extension\Core\Type\CollectionType",array(
            'required'=>true,
            'prototype' => true,
            'allow_add' => true,
            'allow_delete' => true,
            'entry_type'=>"Symfony\Component\Form\Extension\Core\Type\TextType",
            'entry_options'   => array(
                'required'  => true,
                'attr'      => array('class' => 'form-control'),
                )
            )
        );
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
          'data_class' => 'MyBundle\Entity\Myclass'
        ));
    }

    public function getBlockPrefix()
    {
        return 'mybundle_myclass';
    }
}

A: "All" assert seems to be the job All (The Symfony Reference)
Here is the solution :
/**
 * @Assert\All({
 *     @Assert\NotBlank(),
 *     @Assert\Regex(pattern="/^0[1-9]([-. ]?[0-9]{2}){4}$/",message="Invalid")
 * })
 */
private $numbers;

A: You'll need to make a Custom
http://symfony.com/doc/current/cookbook/validation/custom_constraint.html
This has a good example that I use to find a unique entities: How to validate unique entities in an entity collection in symfony2 You can change the logic to check values.


text:
Q: Pronoun first, then name? When you use propositional phrases or conjunctive phrases, do you use a pronoun that matches your subject prior to mentioning the actual subject?

I don't think you'll need her number, but Jennifer's number is x.

I don't think you'll need Jennifer's number, but her number is x.

Although she is late, I think Jennifer will be here any minute now.

Although Jennifer is late, I think she will be here any minute now.

A: In your first two examples, the repetition of the word number makes me think you are talking about two different people.

As for Susan, I don't think you'll need her number. But Jennifer's number is 555-5555.

I think the meaning you want would be conveyed better without mentioning the subject twice:

I don't think you'll need her number, but it's 555-5555.

or

I don't think you'll need Jennifer's number, but it's 555-5555.

Your second two examples are both standard, and have identical meanings.

A: Yes, you can use a pronoun prior to mentioning its subject (and you should always use a pronoun matching the subject).
Some other examples:

If you need it, Jennifer's number is 555-1212.
If you need to call her, Jennifer is available after 9 am.
An hour after I started looking for him, I found John in the mall cafe.


text:
Q: how to make use of STL's for better result and performance in this issue I have some set of strings in format : country/currency/minimum_amount
For example:
US/USD/18
US/EUR/20
DE/USD/22
GB/EUR/19

Let's say i have drop downs each for country, currency and minimum amount.
Once i select the country, i should get the possible combination of currency and min amount from the above set of strings.
ex. Once i select country as US in dropdown_1, then currency(dropdown) should display - USD and EUR and min_amt - 18 and 20.\
ex. 2:
Once i select Currency as USD in dropdown_2, then country(dropdown) should display - US and DE and min_amt - 18 and 22.. similarly for the third drop down as well.
My solution,
Lets assume i have these specific strings in a vector(name - myvector),
then I'm retrieving the strings using:
std::string str2("US"); // i need the strings that has country as US
string credt_fin_str;

for (unsigned j=0; j<myvector.size(); j++)
{
    credt_fin_str = myvector.at(j);
    std::size_t found = credt_fin_str.find(str2);

    if(found != string::npos)
    {
        std::cout<<"creditfin found:"<<credt_fin_str<<std::endl;
    }

}

Output:
US/USD/18
US/EUR/20
DE/USD/22

Since i using string::find, it displays even "USD" as it contains "US" but it shouldn't be for my use case.
can anyone suggest a better solution to this use case so that i can improve the result and performance.

A: I'd use std::map.
Map each country name to vector of possible combinations. Typical workflow for this goes as follow:

*

*Parse input string

*Store parsing results

*Query storage container

So, start with structure for results:
struct CurrencyVal
{
    string currency;
    int minimum_ammount;
};

It will be stored in the vector for each country. This represents single entry like USD/18 and is not related to any country.
Now, lets make some space for storing it:
std::map<string,vector<CurrencyVal>> dropdowns;

It will map any country to list of possible CurrencyVal values. Lets now parse the input vector. Lets say the input vector is vector<string> input.
//Helper function, note the pos is passed by reference to modify it
string parseToToken(string& str, int& pos, char delim)
{
    string result="";
    for (; pos<str.length(); pos++)
    {
        if (str[pos] == delim)
            break;
        result+=str[pos];
    }
    pos++; //Skip the token
    return result;
}

for (unsigned i=0; i<input.size(); i++)
{
    int pos = 0;
    string country;
    CurrencyVal value;

    country = parseToToken(input[i],pos,'/');
    value.currency = parseToToken(input[i],pos,'/');

    //stoi from <string> in C++11, if you are not using c++11, try with atoi(input[i].substr(pos).c_str())
    value.minimum_ammount = stoi(input[i].substr(pos));

    //Store the results
    dropdowns[country].push_back(value);
}

That's all. Now we can query this struct like this:
vector<CurrencyVal> allForUs = dropdowns["US"];
for (unsigned i = 0; i < allForUs.size(); i++)
    cout << allForUs[i].country << " - " << allForUs[i].minimum_ammound << endl;

If you have any questions post a comment so I can improve this answer.


text:
Q: JQuery to disable button not working I have the following button:
Download

I want to disable it using the .prop property of JQuery. Like this:
$('.disabledButton').prop('disabled', true);

However, it is not working as nothing changed. Any ideas?

A: Has to be a button not an anchor
<button class="btn btn-primary disabledButton">Download</button>

Now this should work
$('.disabledButton').prop('disabled', true);

UPDATED as OP mentioned he has to use an anchor
Workaround one:
$('.disabledButton').css('pointer-events', 'none');

Workaround two: (Prevent default)
 $('.disabledButton').click(function (e) {
    e.preventDefault();
});

A: The reason it is not working is because it's a hyper link and it does not have the disabled property. Only thing you can do is preventDefault
https://dev.w3.org/html5/html-author/#the-a-element
Download

$('a.disabledButton').on('click', function(e) {
    e.preventDefault();
});


text:
Q: Unificar 2 registros en 1 - SQL SERVER 2014 Buenos días,
Tengo 2 registros que son casi idénticos, donde solo difieren en 1 columna.
Lo que necesitaría hacer es tener un solo registro con los campos que difieren.
En la imagen lo que tengo (Los dos registros de arriba) y lo que necesito (Un solo registro con toda la info de ambos registros sin repetir).

Agradeceria toda idea que aporte a una solucion.
Muchas Gracias.

A: Bueno, si siempre son sólo 2 filas de datos, y el dato diferente siempre es en la última columna, entonces puedes usar el siguiente código:
SELECT  col1,
        col2,
        col3,
        col4,
        MIN(col5) col5,
        MAX(col5) col6
FROM dbo.TuTabla
GROUP BY col1,
         col2,
         col3,
         col4
;

Ahora, de esta forma no vas a saber de antemano en cuál columna está el email y en cuál el nombre. Para esto, podrías usar el siguiente código:
SELECT  col1,
        col2,
        col3,
        col4,
        MIN(CASE WHEN col5 LIKE '%@%' THEN col5 END) col5,
        MAX(CASE WHEN col5 NOT LIKE '%@%' THEN col5 END) col6
FROM dbo.TuTabla
GROUP BY col1,
         col2,
         col3,
         col4
;


text:
Q: How do I solve issues with adding Tabbed Control with Expression Blend 3 for Silverlight App? I am using Microsoft Expression Blend 3 + SketchFlow Version 3.0.1927.0 for a Visual Studio 2008 Windows Embedded CE program.
I am trying to add a tabbed control and Expression Blend does not seem to be cooperating.  I have tried googling for a solution.  I found this link:
https://msdn.microsoft.com/en-us/library/cc295163.aspx
This talks about SimpleTabControl and SimpleTabItem.  I did not find these controls in my list of available controls I can add.  This page says it is specific to WPF projects.  Could this be the problem and this particular page from MSDN.Microsoft.com is not applicable to my Silverlight project?
This web page says "The tab control is an items control that displays content in tabs".  I have the ability to add an items control:
http://i67.photobucket.com/albums/h292/Athono/Embedded/itemscontrolpng_zpsq6zokxvq.png
The page also says "Typically, the child elements of a tab control are tab items, which are headered content controls, each of which can have a header element and a content element".  I did not find the ability to add a headered content control from the graphic list of available controls.
A google search also found this web page:
http://www.dotnetperls.com/tabcontrol-wpf
Trying this example producted this error:
http://i67.photobucket.com/albums/h292/Athono/Embedded/tabcontroldoesnotexist_zpstq4euslm.png
It says "The name 'TabControl' does not exist in the namespace 'http://schemas.microsoft.com/client/2007' "
Trying an exact copy of the example code produces an error that says that "Window" does not exist in the namespace "http://schemas.microsoft.com/client/2007"
http://i67.photobucket.com/albums/h292/Athono/Embedded/windowdoesnotexist_zpsy4dn8rkm.png
I need to find an example or plan or solution for using a tab control for the namespace "http://schemas.microsoft.com/client/2007"