text:
Q: Inconsistent KeyEvent Consumption by TextField I have a TextField and a TableView in a BorderPane.
I wanted to assign program-wide hotkey to the program for the key s, so I put a EventListener <KeyEvent> on the BorderPane.
This seemed to work perfectly -- events pressed on the table were passed through to the BorderPane but events in the TextField that created text were consumed before getting to my listener.
I then wanted to add a similar hotkey for Shift + s. In this case, the TextField does not consume the KeyEvent, so it types the letter S (capital) into the TextField but also passes the key event to my BorderPane rather than consuming the event.
Here is a runnable example:
import java.util.Locale;
import javafx.application.Application;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class KeyEventIssue extends Application {

    @Override
    public void start ( Stage stage ) throws Exception {

        TextField textInput = new TextField();
        TableView <Locale> table = getFilledTable();

        BorderPane primaryContainer = new BorderPane();

        primaryContainer.setTop( textInput );
        primaryContainer.setCenter( table );

        primaryContainer.setOnKeyPressed( ( KeyEvent e ) -> {
            if ( e.getCode() == KeyCode.S
            && !e.isControlDown() && !e.isAltDown() && !e.isShiftDown() && !e.isMetaDown() ) {
                System.out.println ( "Heard s" );
                e.consume();
            } else if ( e.getCode() == KeyCode.S && e.isShiftDown()
            && !e.isControlDown() && !e.isAltDown() && !e.isMetaDown() ) {
                System.out.println ( "Heard Shift + s" );
                e.consume();
            }
        });

        Scene scene = new Scene( primaryContainer );
        stage.setScene( scene );
        stage.setWidth( 700 );
        stage.show();
    }

    private TableView <Locale> getFilledTable () {
        TableView <Locale> table = new TableView <>( FXCollections.observableArrayList( Locale.getAvailableLocales() ) );
        TableColumn <Locale, String> countryCode = new TableColumn <>( "CountryCode" );
        countryCode.setCellValueFactory( new PropertyValueFactory <>( "country" ) );
        TableColumn <Locale, String> language = new TableColumn <>( "Language" );
        language.setCellValueFactory( new PropertyValueFactory <>( "language" ) );

        TableColumn <Locale, Locale> local = new TableColumn <>( "Locale" );
        local.setCellValueFactory( c -> new SimpleObjectProperty <>( c.getValue() ) );

        language.setCellValueFactory( new PropertyValueFactory <>( "language" ) );

        table.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY );

        table.getColumns().addAll( countryCode, language, local );

        return table;
    }

    public static void main ( String[] args ) {
        Application.launch ( args );
    }
}

Actions for you to take to reproduce the issue:

*

*Compile and run this program

*Press s while Tableview has focus -- "Heard s" is printed -- good

*Press s while TextField has focus -- nothing is printed and the s is put in the text box -- good

*Press shift + s while Tableview has focus -- "Heard Shift + s" is printed -- good

*Press shift + s while TextField has focus -- "Heard Shift + s" is printed and S is put in the text box -- BAD -- nothing should print.

This appears to me to be inconsistent behavior. Am I doing something wrong, or is this a bug in javafx?
I can do a workaround by checking whether the text box has focus, and I'll probably do that for my project, but it has a handful of textboxes, and more may be added in the future. I am hoping to avoid having to do that because it will lead to harder-to-maintain code.

A: I posted a bug report. This is a known issue in Java 8, fixed in Java 9 according to the Java developers: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8194280


text:
Q: ios Facebook Login not working; Sandbox Mode=on
Bundle ID =same FBid=Ok ..Anything else does not matter

-(void) askForPublishPermission
{ BOOL isSessionActive = [self isFacebookSessionActive];
//BOOL useUI = !isSessionActive;
//useUI = YES;
BOOL publishPermissionAvailable = NO;

if (isSessionActive)
{
    NSArray* validPermission = [[FBSession activeSession] permissions];

    for (int i=0; i<[validPermission count]; i++)
    {
        NSObject* permission = [validPermission objectAtIndex:i];

        if ([permission isKindOfClass:[NSString class]])
        {
            NSString* validPermission = (NSString*)permission;
            //NSLog(@"Valid Permissions = %@", validPermission);
            if ([validPermission isEqualToString:@"publish_actions"])
            {
                publishPermissionAvailable = YES;
                break;
            }
        }
    }
}

if (publishPermissionAvailable == YES)
{
    //NSLog(@"------------------ CALL AT TWO --------------");
    //NSLog(@"Login Success");
}
else // Request for publish permission.
{
    NSArray* permissionArray = [NSArray arrayWithObjects:
                                @"publish_actions",nil];
    [FBSession openActiveSessionWithPublishPermissions:permissionArray
                                       defaultAudience:FBSessionDefaultAudienceEveryone
                                          allowLoginUI:YES
                                     completionHandler:^(FBSession *session,
                                                         FBSessionState state,
                                                         NSError *error) {
                                         [self sessionStateChanged:session
                                                             state:state
                                                             error:error];
                                     }];

  }
}

and
-(void) askForPublishPermission
{
BOOL isSessionActive = [self isFacebookSessionActive];
//BOOL useUI = !isSessionActive;

//useUI = YES;
BOOL publishPermissionAvailable = NO;

if (isSessionActive)
{
    NSArray* validPermission = [[FBSession activeSession] permissions];

    for (int i=0; i<[validPermission count]; i++)
    {
        NSObject* permission = [validPermission objectAtIndex:i];

        if ([permission isKindOfClass:[NSString class]])
        {
            NSString* validPermission = (NSString*)permission;
            //NSLog(@"Valid Permissions = %@", validPermission);
            if ([validPermission isEqualToString:@"publish_actions"])
            {
                publishPermissionAvailable = YES;
                break;
            }
        }
    }
}

if (publishPermissionAvailable == YES)
{
    //NSLog(@"------------------ CALL AT TWO --------------");
    //NSLog(@"Login Success");
}
else // Request for publish permission.
{
    NSArray* permissionArray = [NSArray arrayWithObjects:
                                @"publish_actions",nil];
    [FBSession openActiveSessionWithPublishPermissions:permissionArray
                                       defaultAudience:FBSessionDefaultAudienceEveryone
                                          allowLoginUI:YES
                                     completionHandler:^(FBSession *session,
                                                         FBSessionState state,
                                                         NSError *error) {
                                         [self sessionStateChanged:session
                                                             state:state
                                                             error:error];
                                     }];

  }
}

But ..Not login..
error code see below:
Error = Error Domain=com.facebook.sdk Code=2 "The operation couldn't be completed. (com.facebook.sdk error 2.){com.facebook.sdk:ErrorLoginFailedReason=com.facebook.sdk:SystemLoginCancelled, com.facebook.sdk:ErrorInnerErrorKey=Error Domain=com.apple.accounts Code=7 "The Facebook server could not fulfill this access request: The app must ask for a basic read permission  like email at install time."

I'd spent a few months this issue..Please Help me

A: Your error message says:

The app must ask for a basic read permission  like email at install time.

From the docs:

When someone connects with an app using Facebook login, the app can access their public profile and friend list, the pieces of information that are visible to everyone. To create this basic connection, apps must always request access to a person's basic profile information by asking for the basic_info permission.

Try adding basic_info to permissionArray array. If that doesn't work, try adding email as well.

A: I replaced :
[FBSession openActiveSessionWithPublishPermissions:@[@"publish_actions"] defaultAudience:FBSessionDefaultAudienceFriends allowLoginUI:YES completionHandler:stateHandler];

with
[FBSession openActiveSessionWithPublishPermissions:@[@"basic_info", @"publish_actions", @"email"] defaultAudience:FBSessionDefaultAudienceFriends allowLoginUI:YES completionHandler:stateHandler];

And now it's working
(permissions orders matter, basic_info have to be in first position)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sum of ideals in a ring I have the following question:
If $I,J$ are ideals in $R$, then denote $I+J = \{ r \in R | r = x+y, x \in I, y \in J  \}$
It is not hard to show that $I+J$ is again an ideal in $R$
If we then assume that $I+J = R$ we have the identity $R/(I \cap J) \simeq R/I \times R/J$
I managed to show this by constructing a function $f: R \to R/I \times R/J$ and then using the first isomorphism theorem. The proof then basically follows how one would derive the second isomorphism theorem from the first, which leads me the question: is it possible to approach this problem using the 2nd/3rd isomorphism theories directly?

A: In general, you always have that $R/(I\cap J)$ embeds into $R/I \times R/J$. This simply follows because if $f$ and $g$ are any two ring homomorphism $f\colon R\to S$ and $g\colon R\to T$, then letting $f\times g\colon R\to S\times T$ by the map $(f\times g)(r) = (f(r),g(r))$, you always have $\mathrm{ker}(f\times g) = \mathrm{ker}(f)\cap\mathrm{ker}(g)$. Thus, $R/(I\cap J)$ is isomorphic to its image in $R/I\times R/J$ by the First Isomorphism Theorem. This always holds, without any conditions on $I$ or on $J$.
The only issue here is showing that this map is onto, and for this you use the fact that $I+J=R$: given $x,y\in R$ and $(x+I,y+J)\in R/I\times R/J$, there exists $a_1,a_2\in I$, $b_1,b_2\in J$ such that $x=a_1+b_1$, $y=a_2+b_2$. Then $(b_1+a_2)+I = b_1+I = x+I$ and $(b_1+a_2)+J = a_2+J = y+J$, so $b_1+a_2$ maps to $(x+I,y+J)$.
As far as I can tell, this only uses the first isomorphism theorem, and
I don't see any use or reconstruction of the second isomorphism theorem (usually, that there is an inclusion preserving bijection between the subrings of $R/I$ and the subrings of $R$ that contains $I$, and the bijection maps ideals to ideals) nor the third (usually, that for a subring $R'$ and an ideal $I$, $(R'+I)/I \cong R'/(R'\cap I)$). Perhaps you have a different numbering, but I still don't see the application of anything other than the first isomorphism theorem and some basic properties about products in the proof above.

A: It is possible to prove this with the help of the "third isomorphism theorem". However you need to prove the following fact (which of course can be obtained from your result but can also be proved directly).
Step 1: If $I$ is an ideal of $R$ with complement $J$ (i.e. $I+J=R$ and $I\cap J=0$), then $R \cong I\times J$
Step 2: Let use the above to prove your result. Writing $q:R\to R/(I\cap J)$ for the canonical ring homorphism and taking images we obtain $q(I)=I/(I\cap J) \cong (I+J)/J = R/J$ and $q(J)=J/(I\cap J)\cong (I+J)/J = R/J$ (using the third isomorphism theorem twice). Applying the result from Step 1 (since $q(I) + q(J)=R/(I\cap J)$, and $q(I)\cap q(J) = 0$ we obtain that $R/(I\cap J) \cong q(I) \times q(J) \cong R/J \times R/I$ as desired.
Proof of statement in Step 1: By the "third isomorphism theorem" $R/I =(I+J)/I \cong J/(I\cap J)= J$ and similarly $R/J \cong I$ we obtain a
homorphism $R \to I\times J$ (from the two quotient homorphisms). A straight forward calculation shows that this homorphism is an isomorphism.
As a final remark this result is true in any semi-abelian category. This means that it is true for groups, Lie algebras over a commutative ring, Heyting semi-lattices and many other related structures (and that one can give a single proof to cover all of these cases). As another example in the language of groups it would be: If $I$ and $J$ are normal subgroups of a group $G$ and $IJ=G$, then $G/(I\cap J) \cong G/I \times G/J$.


text:
Q: Javascript- Getting an uncaught type error Creating a tic tac toe game, but for some reason, I'm getting an uncaught type error when doing observer.observe.
Here is the line where the error is occurring:
board.positions.forEach((el) => observer.observe(el,config));

Here is the function it is occurring in:
function TicTacToeGame() {
    const board = new Board();
    const humanPlayer = new HumanPlayer(board);
    const computerPlayer = new ComputerPlayer(board);
    let turn = 0;

    this.start = function () {
    const config = {childlist: true};
    const observer = new MutationObserver(()=> takeTurn());
    board.positions.forEach((el) => observer.observe(el,config));
   takeTurn();
    }

What is this error trying to say and what is the best way to resolve it.
Edit:
Here is the error I am getting:
Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': The options object must set at least one of 'attributes', 'characterData', or 'childList' to true.


text:
Q: Is there a way to find the nᵗʰ entry in itertools.combinations() without converting the entire thing to a list? I am using the itertools library module in python.
I am interested the different ways to choose 15 of the first 26000 positive integers. The function itertools.combinations(range(1,26000), 15) enumerates all of these possible subsets, in a lexicographical ordering.
The binomial coefficient 26000 choose 15 is a very large number, on the order of 10^54. However, python has no problem running the code y = itertools.combinations(range(1,26000), 15) as shown in the sixth line below.

If I try to do y[3] to find just the 3rd entry, I get a TypeError. This means I need to convert it into a list first.  The problem is that trying to convert it into a list gives a MemoryError. All of this is shown in the screenshot above.

Converting it into a list does work for smaller combinations, like 6 choose 3, shown below.

My question is:
Is there a way to access specific elements in itertools.combinations() without converting it into a list?
I want to be able to access, say, the first 10000 of these ~10^54 enumerated 15-element subsets.
Any help is appreciated. Thank you!

A: You can use a generator expression:
comb = itertools.combinations(range(1,26000), 15)
comb1000 = (next(comb) for i in range(1000))

To jump directly to the nth combination, here is an itertools recipe:
def nth_combination(iterable, r, index):
    """Equivalent to list(combinations(iterable, r))[index]"""
    pool = tuple(iterable)
    n = len(pool)
    if r < 0 or r > n:
        raise ValueError
    c = 1
    k = min(r, n-r)
    for i in range(1, k+1):
        c = c * (n - k + i) // i
    if index < 0:
        index += c
    if index < 0 or index >= c:
        raise IndexError
    result = []
    while r:
        c, n, r = c*r//n, n-1, r-1
        while index >= c:
            index -= c
            c, n = c*(n-r)//n, n-1
        result.append(pool[-1-n])
    return tuple(result)

It's also available in more_itertools.nth_combination
>>> import more_itertools  # pip install more-itertools
>>> more_itertools.nth_combination(range(1,26000), 15, 123456)
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 18, 19541)

To instantly "fast-forward" a combinations instance to this position and continue iterating, you can set the state to the previously yielded state (note: 0-based state vector) and continue from there:
>>> comb = itertools.combinations(range(1,26000), 15)
>>> comb.__setstate__((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 17, 19540))
>>> next(comb)
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 18, 19542)

A: If you want to access the first few elements, it's pretty straightforward with islice:
import itertools

print(list(itertools.islice(itertools.combinations(range(1,26000), 15), 1000)))

Note that islice internally iterates the combinations up to the specified point, so it can't magically give you the middle elements without iterating all the way there. You'd have to go down the route of computing the elements you want combinatorially in that case.


text:
Q: problem with sql syntax The sql syntax is following:
SELECT y.NAME, y.EMAIL, k.DATE, k.WORK_NR, k.SCORE, k.FILENAME
FROM bas1.students y, bas1.assignments k, bas1.topics a
WHERE y.ID = k.student_id AND k.topic_id = a.id
WHERE a.NAME = 'History';

But I get some errors, any Ideas?

A: You're  using WHERE twice
SELECT y.NAME, y.EMAIL, k.DATE, k.WORK_NR, k.SCORE, k.FILENAME
FROM bas1.students y, bas1.assignments k, bas1.topics a
WHERE y.ID = k.student_id AND k.topic_id = a.id
AND a.NAME = 'History';

change to this

A: Don't you need join statements?  E.g.,
SELECT y.NAME, y.EMAIL, k.DATE, k.WORK_NR, k.SCORE, k.FILENAME
FROM bas1.students y JOIN bas1.assignments k ON y.ID = k.student_id
JOIN bas1.topics a ON k.topic_id = a.id
WHERE a.NAME = 'History';


text:
Q: SELECT query not retrieving up to date data Currently I have a dropdown menu and a text area. By selecting a number from the dropdown you get the corresponding data loaded into the text area from my sql database. There is also a button to save/edit the text, this works and updates the database successfully. However what does not work is when new text is entered into the text area, its saved, selecting another number from drop down and then going back to the previous one the new text does not appear, the old text does, even though the database has been updated.
Previously when I submitted the form the page reloaded which meant everything worked fine, however since then I needed to stop this reloading which I did, now the dropdown isn't retrieving the up to date data from the database?
dropdown onchange function (course.php)
function selectedItem(selection){

  if(selection=="page1"){

   document.getElementById("commentid").value = "<?php query2('page1',$_SESSION['courseID'], $_SESSION['userID']) ?>";

  }

  if(selection=="page2"){

    document.getElementById("commentid").value = "<?php query2('page2',$_SESSION['courseID'], $_SESSION['userID']) ?>";
  }

  if(selection=="page3"){

    document.getElementById("commentid").value = "<?php query2('page3',$_SESSION['courseID'], $_SESSION['userID']) ?>";
  }

  if(selection=="page4"){

    document.getElementById("commentid").value = "<?php query2('page4',$_SESSION['courseID'], $_SESSION['userID']) ?>";
  }

  if(selection=="page5"){

    document.getElementById("commentid").value = "<?php query2('page5',$_SESSION['courseID'], $_SESSION['userID']) ?>";
  }

}

'commentid' being the id of the text area
query2 code (func.inc.php)
function query2($page,$courseID,$userID){//POPULATE COMMENT BOX FROM THE CORRECT PAGE, COURSE ID AND USER ID
        $myData = mysql_query("SELECT {$page} FROM comments WHERE user_id='{$userID}' AND course_id='{$courseID}'");
        while($record = mysql_fetch_array($myData)){
            echo $record[$page] ;
        }

    }

When reloading the page the latest comment will now be visible for each dropdown option. It would seem the SELECT query is not retrieving the latest data from the database?

A: The new text isn't displayed because it isn't in the browser.
What you're doing is this:
1) Load course.php from the server. It creates the function selectedItem(selection) and outputs it to the browser. Inside the browser, the function now looks like this:
if(selection=="page1"){
   document.getElementById("commentid").value = "Text A";
  }

if(selection=="page2"){
   document.getElementById("commentid").value = "Text B";
  }

etc....
2) You post 'Text CCCC' for page1. This post is picked up by the server and put into the database. The browser however still has the old javascript and has no way of knowing there is a new text. Only if you somehow change the  javascript, you get to see the new text.
There are a few options to do this:
Refresh the page, like you did before. The function selectedItem will be created again an now contains the new Text CCCC from the database. This is the simplest solution.
If you don't want to refresh the page, you can replace the content of the javascript in the browser. To do so, you could do this:
In course.php
var text=new Array(
   'page1'=>"<?php query2('page1',$_SESSION['courseID'], $_SESSION['userID']) ?>",
   'page2'=>"<?php query2('page2',$_SESSION['courseID'], $_SESSION['userID']) ?>",
   'page3'=>"<?php query2('page3',$_SESSION['courseID'], $_SESSION['userID']) ?>"
      );
var selected_page='page1';

function selectedItem(selection){
   selected_page=selection;
   document.getElementById("commentid").value = text[selection];
}

Now the browser has an javascript array called 'text', containing the text of the different pages:
Text=['page1'=>'Text A','page2'=>'Text B','page3'=>'Text C']

Everytime you run your function selectedItem it puts the value of the selected text variable inside commentid. It also updates the variable selected_page, so you can keep track on what variable is displayed.
When you post your form, you only have to change the content of the corresponding variable. This could be done like:
In your form add this:
<form onsubmit="change_text()">

And add a little javascript function
function change_text(){
   //replace the corresponding variable with the new text
   text[selected_page]=document.getElementById('mytextarea').value;

   return true; // (to submit the form)
}

This will overwrite the value of text[selected_page] with the text in the textarea. Now javascript 'knows' that there is new text an can display it. So if you changed page1 to 'Text DDDDD', the array now contains
Text=['page1'=>'Text DDDDD','page2'=>'Text B','page3'=>'Text C']

Note This is a (very) simplified example. It is for one not checking if the post is correctly handled by the server. So you could still end up with different texts in the browser and the database. I suggest you look into ajax (possibly jquery ajax) to do it properly.


text:
Q: Does Firefox PCKS#11 modules support headless mode? Is it possible to use the PCKS#11 module of Firefox in headless mode?
I.e., for this scenario:
- use system console
- start Firefox in headless mode
- point it to a secured url
- PCKS#11 issues a console prompt for token instead of UI


text:
Q: Making a trainable initial state for an LSTM in TensorFlow I have a sequence which is too long to fit in memory, but the initial state is quite critical so I would like to train that as a variable too. How can I train the initial state variable to pass in at the start of the sequence, but keep using the output state for the rest of the sequence?
This is what I've got so far:
    cell = tf.contrib.rnn.BasicLSTMCell(num_lstm_cells, state_is_tuple=True)

    init_vars = cell.zero_state(batch_size, tf.float32)
    init_c = tf.Variable(init_vars.c, trainable=True)
    init_h = tf.Variable(init_vars.h, trainable=True)
    init_state = tf.contrib.rnn.LSTMStateTuple(init_c, init_h)

    state_vars = cell.zero_state(batch_size, tf.float32)
    state_c = tf.Variable(state_vars.c, trainable=False)
    state_h = tf.Variable(state_vars.h, trainable=False)
    state = tf.contrib.rnn.LSTMStateTuple(state_c, state_h)

    layer = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=0.7)
    val, new_state = tf.nn.dynamic_rnn(layer, lstm_input, initial_state=state, dtype=tf.float32)

    with tf.control_dependencies([state[0].assign(new_state[0]), state[1].assign(new_state[1])]):
        output = tf.identity(val)

    inititalise_c = tf.assign(state[0], init_state[0])
    inititalise_h = tf.assign(state[1], init_state[1])
    initialise_state = tf.group([inititalise_c, inititalise_h])

The idea is that I have a trainable initial state variable (init_vars), and a non-trainable state (state_vars) which I assign the initial state to at the start of each sequence by calling the initialise_state op.
I don't think this will work though because the init_state isn't actually part of the training, it is just getting used for copying. How can I do this?
edit: I've confirmed in testing that the initial state is not being trained and remaining all 0's

A: I ended up solving this by creating an initial state variable inside a separate variable scope. Then using the var_list optional parameter in Optimizer.Minimize(), I could specify to train the initial state at the start of each sequence. After the training the initial state, I would copy it to this separate variable scope, and train the graph for the the rest of the sequence.
    with tf.variable_scope("state"):
        state_c = tf.Variable(tf.random_uniform([batch_size, num_lstm_cells], 0, 1), trainable=True)
        state_h = tf.Variable(tf.random_uniform([batch_size, num_lstm_cells], 0, 1), trainable=True)
        state = tf.contrib.rnn.LSTMStateTuple(state_c, state_h)

    with tf.variable_scope("nn"):
        layer = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=0.7)
        val, new_state = tf.nn.dynamic_rnn(layer, lstm_input, initial_state=state, dtype=tf.float32)

        logits = tf.layers.dense(val, units=5, activation=tf.nn.relu)
        losses = tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=targets)

    init_c = tf.Variable(tf.zeros([batch_size, num_lstm_cells]), trainable=False)
    init_h = tf.Variable(tf.zeros([batch_size, num_lstm_cells]), trainable=False)
    init_state = tf.contrib.rnn.LSTMStateTuple(init_c, init_h)

    restore_c = tf.assign(state[0], init_state[0])
    restore_h = tf.assign(state[1], init_state[1])
    restore_state = tf.group([restore_c, restore_h])

    save_c = tf.assign(init_state[0], state[0])
    save_h = tf.assign(init_state[1], state[1])
    save_state = tf.group([save_c, save_h])

    propagate_c = tf.assign(state[0], new_state[0])
    propagate_h = tf.assign(state[1], new_state[1])
    propagate_state = tf.group([propagate_c, propagate_h])

    nn_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "nn")
    state_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "state")

    total_loss = tf.reduce_mean(losses)

    train_nn_step = tf.train.AdamOptimizer().minimize(total_loss, var_list=nn_vars)
    train_nn_state_step = tf.train.AdamOptimizer().minimize(total_loss, var_list=[nn_vars, state_vars])

So you start a sequence by calling:

*

*sess.run(restore_state) to copy the initial state back to the graph

*_, er = sess.run([train_nn_state_step, error]) to train the initial state and nn

*sess.run(save_state) to save the initial state

*sess.run(propagate_state) to propagate the state to the next train step

And you train the rest of the sequence by calling:

*

*_, er = sess.run([train_nn_step, error]) to just train the neural network

*sess.run(propagate_state) to keep passing the state through

A: How about switching between training the network and initial state? Freeze the model, make initial state trainable, train for some time. Then switch the freezing.

A: I am not sure what you want to do but, why don't you assign new_state to another state variable like below,
batch_size = 10
num_lstm_cells = 20
num_times = 5
input_dims = 6

lstm_input = tf.random_normal([batch_size, num_times, input_dims],0.,1.0)

cell = tf.contrib.rnn.BasicLSTMCell(num_lstm_cells, state_is_tuple=True)

init_vars = cell.zero_state(batch_size, tf.float32)
init_c = tf.Variable(init_vars.c, trainable=True)
init_h = tf.Variable(init_vars.h, trainable=True)
init_state = tf.contrib.rnn.LSTMStateTuple(init_c, init_h)

state_vars = cell.zero_state(batch_size, tf.float32)
state_c = tf.Variable(state_vars.c, trainable=False)
state_h = tf.Variable(state_vars.h, trainable=False)
state = tf.contrib.rnn.LSTMStateTuple(state_c, state_h)

layer = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=0.7)
val, new_state = tf.nn.dynamic_rnn(layer, lstm_input, initial_state=state, dtype=tf.float32)

trained_state_c = tf.assign(state[0], new_state[0])
trained_state_h = tf.assign(state[1], new_state[1])
trained_state = tf.contrib.rnn.LSTMStateTuple(trained_state_c, trained_state_h)


text:
Q: HTTP request libraries for Python 3.x Consensus seems to be that requests is by far the best option for making HTTP requests in Python 2.x. However, in Python 3.x urllib2 has been "split into parts and renamed to urllib.request, urllib.parse, and urllib.error." Has it just been renamed, or has it had parts rewritten making it a decent alternative to requests?

A: The urllib and urllib2 libraries have been cleaned up for Python 3, moving various disparate parts into a clear package hierarchy. The APIs themselves haven't changed all that much. It's mostly a tightening of the naming conventions.
You only need to compare the Python 2 urllib2 documentation with the urllib.request page for Python 3 (with only exceptions moved to request.error) to see that the basic functionality has not been updated.
requests itself remains the better choice for handling your HTTP client needs in Python 3.


text:
Q: How can I solve $x$ from $\int_0^x e^{t^3}dt=4$? I'm interested in numerical analysis but I don't have experience on it. I was wondering how one can solve integral equations numerically like
$\int_0^x e^{t^3}dt=4$? I was thinking whether there is some numerical differential equation solution method faster that finding some range $a\leq x\leq b$ and then splitting that range half and repeating.

A: I will map out the approach and see if you can fill in the details.
We are asked to find the value of $x$ where:
$$\int_0^x e^{t^3}~dt = 4$$
We need two numerical approaches here. One to find the zeros of the function $f(x)$, Newton's Method, and one to estimate the integral, Composite Simpson or whichever integration rule you prefer, like Composite Trapezoidal or many others, above where:
$$f(x) = \displaystyle \int_0^{x}~ e^{t^3}~dt - 4 = 0$$
The derivative wrt $x$ of this function is:
$$f'(x) = e^{x^3}$$
The Newton-Raphson method is given by:
$$\displaystyle x_{n+1} = x_n - \dfrac{f(x_n)}{f'(x_n)} = x_n - \dfrac{\displaystyle \int_0^{x_n} e^{t^3}~dt - 4}{e^{x_n^3}}$$
At each iteration, we have to use the Composite Simpson's Rule to find the value of that integral for the next $x_n$.
$$s = \int_a^b f(x) \approx \dfrac{h}{3} \left( f(a) + f(b) + 4 \sum_{i=1}^{n/2}~f(a + (2i - 1)h)+2 \sum_{i=1}^{(n-2)/2} f(a+2 ih) \right)$$
Choose the initial starting point is $x_0$ with a desired accuracy of $\epsilon$.
The iterations will proceed as follows:

*

*$x_0 = x_0$

*Using Composite Simpson, with needed $n$: $s$ evaluated between $(0, x_0)$ gives $s = s_0$

*Using Newton's iteration: $x_1 = x_0 - \dfrac{f(x_0)}{f'(x_0)} = x_1$

*$s$ evaluated between $(0, x_1)$ gives $s = s_1$

*Continue this until the number of iterations converges to the desired accuracy.

The numerical approach should yield an $x \approx 1.39821$. Next, you can compare this to the exact result and validate we found the correct value of $x$.
Curious question, is it possible to calculate the value of $n$ for the desired accuracy apriori to doing the iterative steps when using these two numerical approaches? Probably (actually the answer is yes), but I will leave that for you to ponder.
Aside: We can also just use a numerical integrator and randomly try points and more easily bound the problem and then use a the procedure above to fine tune to the desired accuracy. It all comes down to computational complexity.


text:
Q: Why does MSVS 2010 MFC project depend on vcredist_x86.exe for MSVS 2008? I have an MFC project in MSVS 2010. When I compile it, MSVS generates manifest file that contains the following lines:
<assemblyIdentity publicKeyToken="1fc8b3b9a1e18e3b"
    processorArchitecture="x86" version="9.0.21022.8"
    name="Microsoft.VC90.CRT" type="win32"/>

As a result, I get a binary that depends on both vcredist_x86.exe for MSVS 2008 and vcredist_x86.exe for MSVS 2010, though it actually uses only vcredist_x86.exe for MSVS 2010!
I tried to switch off manifest generation in project properties. After it my app started to work with only vcredist_x86.exe for MSVS 2010 installed. But some controls (especially comboboxes) broke and began to be displayed incorrectly. I guess this happens because windows doesn't have the following information from manifest any more:
<assemblyIdentity language="*" publicKeyToken="6595b64144ccf1df"
    processorArchitecture="x86" version="6.0.0.0"
    name="Microsoft.Windows.Common-Controls" type="win32"/>

*

*Why does MSVS write a wrong version of CRT in the manifest file?

*How to fix the problem/make MSVS write the correct version of CRT in the manifest file?

I figured it out. I had a reference to libcurl.lib which had a reference to openssl libs compiled in MSVS 2008... After rebuilding libcurl with the proper versions of openssl the reference to crt 9.0 disappeared from the manifest file.

A: Probably this happens because of the platform toolset in project properties.
Change it to v100 (I suppose now it is set to v90), re-activate manifest generation and embedding (Manifest Tool\Input and Output) and rebuild your project.


text:
Q: Android/HTML5/CSS3 Fade In issues I'm having an issue regarding the Android browser. Not an Android app but a regular HTML5/CSS3 webpage involved webkit based CSS3 animation. Simple enough, I just want a div/section to fade in on the screen. Method I'm showing below works in iOS browser's but not Android browsers. What happens here is the fade in does occur and then the object disappears instead of sticking on the screen:
section {
width: 480px;
height: 100px;
overflow: hidden;
position: absolute;
left: 0px;
top: 0px;
background-image: url(images/home/bkg.jpg);
background-repeat: no-repeat;
background-position: 0px 0px;
z-index: 1;
-o-animation-name: fadeIn;
-o-animation-duration: 1s;
-o-animation-delay: 0s;
    -o-animation-fill-mode: both;
-moz-animation-name: fadeIn;
-moz-animation-duration: 1s;
-moz-animation-delay: 0s;
    -moz-animation-fill-mode: both;
-webkit-animation-name: fadeIn;
-webkit-animation-duration: 1s;
-webkit-animation-delay: 0s;
    -webkit-animation-fill-mode: both;

}

A: Apparently webkit-animation-fill-mode doesn't work on Android.
You may have to make a work around in javascript by getting the last style of your animation and apply it on animation end.


text:
Q: Highcharts - Axis minPadding and maxPadding not working I was adding some padding to my chart because I want to control the space between the actual chart and the container, and I encountered a problem.
Look at mi first fiddle, all seems legal but the padding isn't being applied:
https://jsfiddle.net/9r2Lqmpj/
Highcharts.chart('container', {
    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        minPadding: 0.4,
        maxPadding: 0.4
    },
    yAxis: {
        startOnTick: false,
        minPadding: 0.2
    },
    series: [{
        data: [129.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    }]
});

But if I duplicate the "xAxis" key, this time without the categories array, which seems highly wrong, for no reason it works:
https://jsfiddle.net/v0rj1xkg/
Highcharts.chart('container', {
    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        minPadding: 0.4,
        maxPadding: 0.4
    },
    xAxis: {
        minPadding: 0.4,
        maxPadding: 0.4
    },
    yAxis: {
        startOnTick: false,
        minPadding: 0.2
    },

    series: [{
        data: [129.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    }]
});

I wasn't expecting at all that this worked, in fact, I discovered it by mistake. Why is it working only when I repeat the xAxis key definition?

A: Well Agustin, not much of a discovery rather than a common logic there in your second scenario. I am not really sure what you're trying to achieve, but having xAxis defined twice is not necessary. Just remove the first one to get the same result, so it looks like your second one is overwriting the first one. Have a look at your fiddle here https://jsfiddle.net/xcmq869s/ which looks the same to me. Also it might be the case that the padding doesn't work with categorical data, so it works fine when no categories are specified. U can certainly alter the padding with removed categories.
On the other note, if you want to keep your x-axis labels and add only outer spacing, try using the chart.spacing config option as in the fiddle here https://jsfiddle.net/xcmq869s/1/.

A: Properties minPadding and maxPadding don't work with category axis type. Use min and max options instead.
Highcharts.chart('container', {
    xAxis: {...},
    ...
}, function() {
    var xAxis = this.xAxis[0];
    this.update({
        xAxis: [{
            min: xAxis.min + 0.2,
            max: xAxis.max - 0.2
        }]
    }, true, true, false);
});

Live demo: https://jsfiddle.net/BlackLabel/96s30khd/


text:
Q: workflow to send single mail for bulk approval I have situation where clicking on Bulk-Approve button, a mail has to be triggered. When I click on approve button, it approves many items at a time.
Now I want to send a mail when this button is clicked. If I do it by workflow, it sends multiple mails to same person as multiple items has been modified.
What should be done so that it sends only one mail?

A: I had similar situation, to send reminder to the assigned users. In button click you can use below code, which will send single mail to single user who are assigned to more than one task.
What happening here actually i am saving the user information who is already informed, so that it should not receive more than one mail on single button click.
  StringBuilder nusers = new StringBuilder();

  nusers.Append(" ");
  SPFieldUserValueCollection userVals = (SPFieldUserValueCollection)ListItem[SPBuiltInFieldId.AssignedTo];
   foreach (SPFieldUserValue userVal in userVals)
     {
    SPUser user = userVal.User;

    string nAssignedTo = user.Name.ToString();

       if (!nusers.ToString().Contains(nAssignedTo))
         {
         //do your stuff...
         }
    }

Try out the code and let me know if you have any doubt.
It's Done!!


text:
Q: iCal4J is throwing Exception on TimeZone I'm trying to create a ics file with iCal4J.
I follow the examples given by the developer in this page: Example iCal4J
Then I did this code:
The timezone is taken from http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
//Create a TimeZone...
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
TimeZone timezone = registry.getTimeZone("Europe/Madrid");
VTimeZone tz = timezone.getVTimeZone();

Calendar startDate = new GregorianCalendar();
startDate.setTimeZone(timezone);

//Start Date...
if(log)
    Log.d("CALENDAR iCAL", "Start Date");
startDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date_begin[0]));
startDate.set(Calendar.MONTH, Integer.parseInt(date_begin[1]));
startDate.set(Calendar.YEAR, Integer.parseInt(date_begin[2]));

startDate.set(Calendar.HOUR_OF_DAY,Integer.parseInt(hour_begin[0]));
startDate.set(Calendar.MINUTE, Integer.parseInt(hour_begin[1]));
startDate.set(Calendar.SECOND, 0);

//End Date...
if(log)
    Log.d("CALENDAR iCAL", "End date");
Calendar endDate = new GregorianCalendar();
endDate.setTimeZone(timezone);

endDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date_end[0]));
endDate.set(Calendar.MONTH, Integer.parseInt(date_end[1]));
endDate.set(Calendar.YEAR, Integer.parseInt(date_end[2]));

endDate.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour_begin[0]));
endDate.set(Calendar.MINUTE, Integer.parseInt(hour_begin[1]));
endDate.set(Calendar.SECOND, 0);

//Create the event...
if(log)
    Log.d("CALENDAR iCAL", "creando evento");
String eventName = subject.toString();
DateTime start = new DateTime(startDate.getTime());
DateTime end = new DateTime(endDate.getTime());
VEvent meeting = new VEvent(start, end, eventName);
Location locat = new Location();
locat.setValue(location.toString());
meeting.getProperties().add(locat);

//add timezone info...
if(log)
    Log.d("CALENDAR iCAL", "añadiendo timezone");
meeting.getProperties().add(tz.getTimeZoneId());

//generate unique identifier...
UidGenerator ug;
try {
    if(log)
        Log.d("CALENDAR iCAL", "generando uid");
    ug = new UidGenerator("uidGen");
    Uid uid = ug.generateUid();
    meeting.getProperties().add(uid);
} catch (SocketException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

//Add attendees...

//TODO: en un bucle para añadir todos
if(log)
    Log.d("CALENDAR iCAL", "añadiendo un participante");
Attendee dev1 = new Attendee(URI.create("mailto:user@mail.es"));
dev1.getParameters().add(Role.REQ_PARTICIPANT);
//                  dev1.getParameters().add(new Cn("Developer 1"));
meeting.getProperties().add(dev1);

//Create a calendar...
if(log)
    Log.d("CALENDAR iCAL", "creando el icsCalendar");
net.fortuna.ical4j.model.Calendar icsCalendar = new net.fortuna.ical4j.model.Calendar();
icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
icsCalendar.getProperties().add(CalScale.GREGORIAN);

//Add the event and show in log
icsCalendar.getComponents().add(meeting);
if(log)
    Log.d("CALENDAR iCAL","calendario:"+icsCalendar.toString());

//TODO: cambiar por la variable correspondiente
FileOutputStream fout;
try {
    if(log)
        Log.d("CALENDAR iCAL", "creando el archivo");
    fout = new FileOutputStream("NombreReunion"+".ics");
    CalendarOutputter outputter = new CalendarOutputter();
    outputter.output(icsCalendar, fout);
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (ValidationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

//END CALENDAR ICS
startActivityForResult(intent, REQUEST_CALENDAR);

But when I launch it, the app crashes, in the line:
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();

Given this error:
05-18 11:27:07.129: E/AndroidRuntime(23245): FATAL EXCEPTION: main
05-18 11:27:07.129: E/AndroidRuntime(23245): Process: info.guardianproject.otr.app.im, PID: 23245
05-18 11:27:07.129: E/AndroidRuntime(23245): java.lang.NoClassDefFoundError: edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap
05-18 11:27:07.129: E/AndroidRuntime(23245):    at net.fortuna.ical4j.model.TimeZoneRegistryImpl.<clinit>(TimeZoneRegistryImpl.java:71)
05-18 11:27:07.129: E/AndroidRuntime(23245):    at net.fortuna.ical4j.model.DefaultTimeZoneRegistryFactory.createRegistry(DefaultTimeZoneRegistryFactory.java:48)
05-18 11:27:07.129: E/AndroidRuntime(23245):    at info.guardianproject.otr.app.im.app.Meeting$6.onClick(Meeting.java:219)
05-18 11:27:07.129: E/AndroidRuntime(23245):    at android.view.View.performClick(View.java:4445)
05-18 11:27:07.129: E/AndroidRuntime(23245):    at android.view.View$PerformClick.run(View.java:18446)
05-18 11:27:07.129: E/AndroidRuntime(23245):    at android.os.Handler.handleCallback(Handler.java:733)
05-18 11:27:07.129: E/AndroidRuntime(23245):    at android.os.Handler.dispatchMessage(Handler.java:95)
05-18 11:27:07.129: E/AndroidRuntime(23245):    at android.os.Looper.loop(Looper.java:136)
05-18 11:27:07.129: E/AndroidRuntime(23245):    at android.app.ActivityThread.main(ActivityThread.java:5139)
05-18 11:27:07.129: E/AndroidRuntime(23245):    at java.lang.reflect.Method.invokeNative(Native Method)
05-18 11:27:07.129: E/AndroidRuntime(23245):    at java.lang.reflect.Method.invoke(Method.java:515)
05-18 11:27:07.129: E/AndroidRuntime(23245):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
05-18 11:27:07.129: E/AndroidRuntime(23245):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
05-18 11:27:07.129: E/AndroidRuntime(23245):    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
05-18 11:27:07.129: E/AndroidRuntime(23245):    at dalvik.system.NativeStart.main(Native Method)

At first time I thought about the build path...etc
But I think is everything ok.

Is any way to fix it?

A: You're missing at least one dependency (backport-util-concurrent)
I recommend using gradle or maven to fix your dependency tree and save you the time to search for such errors in the future. A proper dependency management software can save you hours if you are willing to use it and makes your project smaller and easier to manage on multiple stations, besides its easier to use with a VCS. And of course gradle is default in Android Studio.


text:
Q: Apache Camel http routing with no connection caching I need Apache Camel to stop caching information on HTTP connections because it prevents my F5 load balancer from working properly.
This is the route definition:
from("direct:source").to("http://www.destination.com?bridgeEndpoint=true&throwExceptionOnFailure=false");

The situation is that I have 2 processes running Camel routes and consuming traffic. Then these 2 processes forward all the traffic to load balancer address, which should then balance the traffic uniformly between 4 servers. Currently, Camel overcomes load balancer and directs all the traffic directly to 2 out of 4 servers. The other 2 servers remain idle. I'm sure that this is not a load balancer issue.

A: Have you tried setting a the http header
Connection: Close

To tell the http client to close the connection.
You can set it from Camel also
from aaa
   .setHeader("Connection", constant("Close"))
   .to bbb

A: I've been trying various configurations. What I found which solves the issue is the following:
<bean id="http" class="org.apache.camel.component.http.HttpComponent">
    <property name="camelContext" ref="camel"/>
    <property name="httpConnectionManager" ref="httpConnectionManager"/>
</bean>

<bean id="httpConnectionManager" class="org.apache.commons.httpclient.SimpleHttpConnectionManager">
    <constructor-arg index="0" value="true"/>
</bean>

SimpleHttpConnectionManager has a constructor with a boolean "alwasyClose", which does the job.


text:
Q: Change textsize in afterTextChanged There is a EditText whose width is fixed and maxLines = 1. I want to change the text size when length of text is increasing.
override fun afterTextChanged(s: Editable?) {
    val paint = edit_text.paint
    var textSize = edit_text.textSize
    var newWidth = paint.measureText(s.toString())
    while (newWidth >= edit_text.width) {
        textSize -= 1
        paint.textSize = textSize
        newWidth = paint.measureText(s.toString())
    }
    edit_text.setTextSize(COMPLEX_UNIT_PX, textSize)
}

As you see, when the newWidth is larger than width, I will search a new textSize (in the while loop).
However when I input word one by one, there is a strange bug.
As you see, now the text has become upper limit.

Now I input another char
K.

I can nor figure out why the new char appears singly.

A: android:inputType="text" works for me. But I do not know why.


text:
Q: What could be bad about using symbolic links with local.xml Synopsis
First and foremost nobody likes to work on production applications.  Therefore it is advised and good practice for someone to set-up separate stores, my structure is as follows:

*

*dev.magento.local -> Development store;

*stage.magento.local -> UAT/QA store;

*magento.local -> Production store;

Meanwhile the store is tracked in source control, including the app/etc/local.xml, which is the first conflict of this structure. Nevertheless once the Magento installation process has complete and we have the local.xml, the idea was to:
1) Export the recently installed however fresh Magento store.
icanhas$ mysqldump --single-transaction magestore_dev > magestore_dev.dmp.sql

2) Then import the structure for the remaining environments.
icanhas$ mysql -u'magestage_user' -p'magestage_pwd' < magestore_dev.dmp.sql
icanhas$ mysql -u'mageprod_user' -p'mageprod_pwd' < magestore_dev.dmp.sql

3) The new environments need their urls corrected, although that's beyond this question let's assume they've been done.
4) As previously mentioned, we need to solve the conflict with app/etc/local.xml so I created the following directories:

*

*/app/etc/development/local.xml -> Moved local.xml here;

*/app/etc/staging/local.xml -> Copied development/local.xml here;

*/app/etc/production/local.xml -> Copied development/local.xml here;

5) I corrected the database credentials for each environment, this was committed to the repository.
6) Finally I had so create the following symbolic links:

*

*On dev.magento.local; app/etc/local.xml -> app/etc/development/local.xml;

*On stage.magento.local; app/etc/local.xml -> app/etc/staging/local.xml;

*On magento.local; app/etc/local.xml -> app/etc/production/local.xml;

Questions

*

*Could there be anything bad about using this method?

*After installation does Magento write to this file at any point?

Any advice would be greatly appreciated.

A: In my opinion, local.xml is not an issue you need to be tackling in version control. It's also questionable from a security perspective.
I recommend you just place /app/etc/local.xml in .gitignore and set it up once on your individual environments.

A: Magento shouldn't write to local.xml after installation (I've never seen that behavior). The Bad(TM) thing about your approach is that's it's typically advised to avoid storing configuration files in your project's repository.
One reason is related to security. Anyone with access to the repository now has some sensitive information about your infrastructure. It's could be unlikely that you'd be targeted or it would happen but people tend to follow the convention because it's not that difficult to do so.
If you're team/organization is expected to grow then it's a good Idea to separate application code and configuration. Which can then be managed with the appropriate technologies.

A: I can't imagine anything bad about that so long as the additional files aren't world accessible (which they wouldn't be in a default install). I can't think of any instances where the core writes to local.xml (willing to be corrected on that), some extensions might though, but this should be a non-issue with your set-up anyway, as it should write to the relevant file via the symlink anyway.
Personally we tend to keep local.xml out of source control, for development I just copy the local.xml from the last project I worked on and modify the database name, as this is all that tends to change. And production / staging we just create it on the server.


text:
Q: Sql How to increment a field in a Select I'm trying to create a view from a simple SELECT.
SELECT NULL AS productcode
       , name
  FROM item;

productcode    name
NULL           Toto
NULL           Titi
NULL           Tata

Instead of the null i'd like to get my product code (9000) from another table and increment it to get :
 productcode    name
 90001           Toto
 90002           Titi
 90003           Tata

Thank You

A: If I understood your question, you can try to work on a query like this one:
CREATE TABLE P (product_code VARCHAR(10), NAME VARCHAR(10));
CREATE TABLE U (product_code VARCHAR(10));

INSERT INTO P VALUES (NULL,'Toto');
INSERT INTO P VALUES (NULL,'Titi');
INSERT INTO P VALUES (NULL,'Tata');
INSERT INTO P VALUES (1,'Prod1');

INSERT INTO U VALUES ('90000');  #THIS MUST HAVE ONLY ONE RECORD!

SELECT NEW_CODE, NAME
FROM (
    SELECT P.NAME
    , @r:= @r+1 R
    , CONCAT(U.product_code,@r) NEW_CODE
    FROM P
    CROSS JOIN (SELECT @r:=0) C
    CROSS JOIN U
    WHERE P.product_code IS NULL
    ) Y;

Output:
    NEW_CODE    NAME
1   900001  Toto
2   900002  Titi
3   900003  Tata


text:
Q: Match the last 3 letters of words in a string using regex I have a string "cough\tbough" or "quod erat demonstrandum\
tand that, ladies and gentlemen, is the end of my memorandum". And i need to check if last 3 letters of last words of this sentences are equal. But backslash is confusing me.
pairOfLines="cough\tbough"
pattern = ?????
match = re.match(pattern, pairOfLines)
return match.group(1) == match.group(2)

A: You can just split:
pairOfLines="cough\tbough"
val1, val2 = pairOfLines.split("\t")
if val1[-3:] == val2[-3:]:
   #do something

However, if you want to implement regex, you can use re.split():
import re

val1, val2 = re.split("\t", pairOfLines)
if val1[-3:] == val2[-3:]:
   #do something

A: import re

pairOfLines="cough\tbough"

m = re.match(r'.*?(\w{3})\b.*?(\w{3})\b', pairOfLines)
print(m.groups())
('ugh', 'ugh')

*

*.*? - match anything before the first group

*(\w{3})\b - 1st capture group, of which

*

*\w{3} - 3 letters

*\b - word boundary - indicating that the letters must lie at the end

*.*? - match anything before the second group

*(\w{3})\b - 2nd capture group, similar to the first

You could also use re.findall to the same effect:
pairOfLines="cough\tbough"

l = re.findall(r'(?:.*?(\w{3})\b)', pairOfLines)
print(l)
['ugh', 'ugh']

*

*(?:...) - non-capturing outer-group

*(\w{3})\b - solitary capture group, of which

*

*\w{3}  - 3 letters

*\b - word boundary

A: you could use regex backreference to match the capturing text twice
pairOfLines="cough\tbough"
pattern = r'(\w{3})\b.*?\1\b'
match = re.search(pattern, pairOfLines)
# match.group(1) = 'ugh'

match will return the match object if it fullfill the regex which match the last 3 char twice, else it will return None
for example, if pairOfLines = "cough\toughs", match will return None

*

*(\w{3})  - 1st capturing group of last 3 char

*\b       - end of
word boundary

*.*?(\1)  - non greedy match of any char follow by
matching of 1st capturing group again

*\b       - end of word
boundary


text:
Q: Inline validation scrolling to left I am using jquery inline validation plugin:
http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
here:
http://bybyweb.com/mealbook/user/add
If you test this page (by clicking upload at the bottom), on lower screen resolutions (less than 1680x1050), you will notice strange scrolling to the left hand side (scroll top is default, normal behavior)... i have used this plugin before, and i've never had similar problems...
something is probably wrong in my html/css structure. If you have idea what could it be - please help. Thanks!

A: If you take away body{overflow-x: hidden;} you can see at the smaller window sizes the page has extra space to the right. This extra space is caused by having set widths that are larger than their containers in the #header.

*

*In your #header you set the width of #logo_main_menu to 940px. This means that all the child elements need to add up to 940px.

*Inside that div you set a width of 272px on #logo and 705px on #search. They add up to a total of 977px not 940px!

*To make things worse inside #search you set the width of the #menu to 940px, which means actually you now are trying to fit 940 + 272 = 1212px into a space that you have set as 940px.

*I am sure there are other elements within #search that have fixed widths too.

To sum it up, you need to make sure that if you use fixed pixel widths they all add up to the width of the parent container, in this case 940px
p.s. I tested removing those widths and the scroll seemed to work well. No sideways motion. At even smaller widths it starts to look a bit odd again. To fully test you need to make sure body{overflow-x: hidden;} is turned off and that all of your widths add up to their container.


text:
Q: Double and Float RuntimeError while training fasterrcnn_mobilenet For the last couple of weeks, I have been really struggling to debug this new problem when training my detection model. Couple of weeks before the training worked great, but now all of a sudden I get this new unheard error.
I make my model and train overall like this but still get an error.
#Model
torch.set_default_dtype(torch.float)
backbone = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_320_fpn(pretrained=True)
backbone.roi_heads.box_predictor.cls_score.out_features = len(classes)
backbone.roi_heads.box_predictor.bbox_pred.out_features = 4 * (len(classes))

#Training
for epoch in range(epochs):
      train_one_epoch(net, optimizer, train_loader, device, epoch, print_freq=10)
      evaluate(net, test_loader, device=device)

    print("Time for Total Training {:0.2f}".format(time.time() - start_time))

    return net

My weird error was:
—> 27 train_one_epoch(net, optimizer, train_loader, device, epoch, print_freq=10)
28 evaluate(net, test_loader, device=device)
29

/content/engine.py in train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq)
44 if not math.isfinite(loss_value):
45 print("Loss is {}, stopping training".format(loss_value))
—> 46 print(loss_dict_reduced)
47 sys.exit(1)
48

/usr/local/lib/python3.7/dist-packages/torch/_tensor.py in backward(self, gradient, retain_graph, create_graph, inputs)
253 create_graph=create_graph,
254 inputs=inputs)
→ 255 torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs)
256
257 def register_hook(self, hook):

/usr/local/lib/python3.7/dist-packages/torch/autograd/init.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables, inputs)
147 Variable.execution_engine.run_backward(
148 tensors, grad_tensors, retain_graph, create_graph, inputs,
→ 149 allow_unreachable=True, accumulate_grad=True) # allow_unreachable flag
150
151

RuntimeError: Found dtype Double but expected Float.

I also have boxes and labels encoded like this boxes = torch.as_tensor(boxes, dtype = torch.float32) labels = torch.as_tensor(labels, dtype = torch.int64) and my images are float tensors.
How do I get rid of this runtime error?
For all of my code with my data class, imported libs, and train check over here and you can also see how train_one_epochs looks like over here
Thanks for the help,
Sarthak

A: I found the answer to my question.
I had duplicated engine.py files. The idea is if you are importing a package then don't make another file with the exact same name and import that too.
Additionally, I learned that in google collab if you make changes to a .py file and reimport it, collab does not seem to register the changes. I found a factory restart works well.
Sarthak Jain


text:
Q: Showing a module is not flat Let us consider the finitely generated $k$-algebra $M=k[x,y,z]/(xy,yz,zx)$. Its Noether normalisation is $R=k[w]$, where $w=x+y+z$. Now I need to show that $M$ is not a flat $R$-module. For this it is enough to show that $M$ is torsion as $R$ is PID.
M is generated by $(1,x,y,z)$ as an $R$-module. So I need to find a torsion element in $M$. How do I find a torsion element in $M$? Is there a procedure?
Thank you.

A: In the comments, I showed that $M$ is actually generated by $1,x,y$.
Note that this a linear independent set of generators, i.e. a basis:
Take a linear combination, which is zero:
$$0=f(w) \cdot 1 + g(w) \cdot x + h(w) \cdot y = f(x+y+z) + xg(x)+yh(y).$$
Assume $f \neq 0$. Note that $f$ cannot be constant, because the other summands do not admit constant terms to cancel the constant. Let $d > 0$ be the degree of $f$, then $f(x+y+z)$ admits the term $z^d$, which cannot be canceled by the other terms. Hence $f=0$ and from there it is trivial to see that $g=h=0$.
Summarizing, $M$ is a free $k[w]$-module of rank $3$.


text:
Q: Python - equivalent of Ruby new method I'm trying the implement the following into Python:
NAMES = {"fn" => ["James", "John", "John"], "ln" => ["Smith", "Johnson", "Brown"]}

class RandomNameGenerator
  def self.generate
    new.to_s
  end

  def initialize
    @fn = NAMES['fn'].sample
    @ls = NAMES['ln'].sample
  end

  def to_s
    @fn + " " + @ls
  end
end

Which returns:
>> RandomNameGenerator.generate
=> "James Smith"
>> RandomNameGenerator.generate
=> "John Johnson"

My code thus far looks like:
import random

NAMES = {"fn": ["James", "John", "John"], "ln": ["Smith", "Johnson", "Brown"]}

class RandomNameGenerator(object):
    @classmethod
    def generate(cls):
        RandomNameGenerator().__str__

    def __init__(self):
        self.fn = random.choice(NAMES["fn"])
        self.ln = random.choice(NAMES["ln"])

    def __str__(self):
       return self.fn + " " + self.ln

>>> RandomNameGenerator.generate()
>>> print(RandomNameGenerator.generate())
None

I feel like Ruby's new.to_s isn't the same as Python'sRandomNameGenerator().__str__. What am I not understanding?

A: You don't return anything in the generate method. Also the __init__ code is called when you initialiaze the class, in you case you are not doing it. You are just calling the class static method. In order to make your code work you have to create a new instance of the RandomNameGenerator in the generate method.
class RandomNameGenerator(object):
    @classmethod
    def generate(cls):
        return cls()

    def __init__(self):
        self.fn = random.choice(NAMES["fn"])
        self.ln = random.choice(NAMES["ln"])

    def __str__(self):
       return self.fn + " " + self.ln

A: You are not returning from the method generate():
import random

NAMES = {"fn": ["James", "John", "John"], "ln": ["Smith", "Johnson", "Brown"]}

class RandomNameGenerator(object):
    @classmethod
    def generate(cls):
        return str(cls())

    def __init__(self):
        self.fn = random.choice(NAMES["fn"])
        self.ln = random.choice(NAMES["ln"])

    def __str__(self):
       return self.fn + " " + self.ln

for i in range(5):
    print(RandomNameGenerator.generate())

OUTPUT:
John Johnson
John Brown
James Johnson
James Brown
James Johnson


text:
Q: How can I avoid infinite loop in Java How can i re write this so I'm not using a while(true) loop?
I need the method to break upon the conditions of the while loop and I can't seem to work it out.
ArrayList<Account> accounts = new ArrayList<Account>();

public void enterCustomers()
{
   System.out.println("Enter customer names or q to quit entering names");

   while(true)
    {
        Scanner scan = new Scanner(System.in);                          //find alternative to while true

        System.out.print("Enter a customer name: ");
        String name = scan.nextLine();

        if(name.equalsIgnoreCase("q"))
        {
            break;
        }

        System.out.print("Enter openning balance: ");
        Double balance = scan.nextDouble();

        Account a = new Account(name, balance);
        accounts.add(a);}
}

A: So if you want to remove the while(true) loop, you could use the following:
String name = scan.nextLine();
while(!name.equalsIgnoreCase("q")){
  //do stuff here
  name = scan.nextLine();
}

Or an even better way would be, (avoiding the duplicate name assignments,) using the do while loop, because do while would check the condition after we enter the loop:
String name;
do{
  name = scan.nextLine();
  //do stuff here
}while(!name.equalsIgnoreCase("q"));

A: I think the easiest way to approach this is to set the condition of a while loop to the opposite of the if condition like so:
ArrayList<Account> accounts = new ArrayList<Account>();

public void enterCustomers()
{
   Scanner scan = new Scanner(System.in);
   System.out.println("Enter customer names or q to quit entering names");
   System.out.println("Enter a customer name:");
   Stirng name = scan.nextLine();

   while(!name.equalsIgnoreCase("q"))
    {
        System.out.print("Enter openning balance: ");
        Double balance = scan.nextDouble();

        Account a = new Account(name, balance);
        accounts.add(a);

        System.out.print("Enter a customer name: ");
        name = scan.nextLine();
    }
}

A: first of all be aware of scan.nextDouble() as it is reading the number but not the breakline, you will have to add a dummy scan.nextLine() or sth similar to read the break line after the number.
I always prefer to have methods doing one thing for example askForData(Scanner scan), so It would look like that:
import java.util.Scanner;

public class SomeTest {

public static void main(String[] args) {
    System.out.println("Enter customer names or q to quit entering names");
    Scanner scan = new Scanner(System.in);
    String name="notExit"; //some name that is not exiting
    while(!name.equalsIgnoreCase("q")){
        name = askForData(scan);
    }
}

private static String askForData(Scanner scan) {
    System.out.print("Enter a customer name: ");
    String name = scan.nextLine();
    if (!name.equalsIgnoreCase("q")) {
        System.out.print("Enter openning balance: ");
        Double balance = scan.nextDouble();
        scan.nextLine(); //to read the break line
    }
    return name;
}
}


text:
Q: 70s Book about an intergalactic cruise When I was a kid I had this large (coffee table-ish) hard cover illustrated book, which was basically a travel-companion guide for people going on this intergalactic cruise.  The whole thing was spun (basically) as a brochure for all these different exotic destinations that the cruise would visit.  It was (as I recall) incredibly well crafted, with a lot of very clever detail and gorgeous art.

A: "Tour of the Universe"...? You can buy second-hand copies on Amazon.

A: It isn't Sci-Fi, but your description makes me think of the book "Galaxies."  It's non-fiction with lots of information on stars, galaxies, etc., but I'm pretty sure there's an overall narrative that runs through the book presenting the information as if to passengers on an intergalactic cruise.  It certainly has beautiful pictures.


text:
Q: In relativity, why does spacetime diagram have position on $x$-axis and time on $y$-axis? In regular Newtonian physics, we use $ x(t) - t$ graph to under position of a particle but why is it that in special relativity that we switch up the axis notation? I was seeing the lecture by Leonard Susskind and, after one hour, I came under the impression that it is just a relabelling of an the axes because, I think it'd be possible to write every derivation said in the $t-x$ in the $x-t$ plane. Or is there something more deep about it which I am missing?

A: It is merely a convention. It has no particular importance or significance.

A: I believe the reason for this is because in the first spacetime diagrams Minkowski was using a pseudo-euclidean metric with a complex time
$$
ds^2 = (icdt)^2 + dx^2
$$
But the convention is that complex quantities are plotted on the y-axis. And so Minkowski chose to also draw the the (complex) time on the y-axis and the (real) position on the x-axis.
Later the pseudo-euclidean metric fell out of fashion, but the habit of drawing the time on the y-axis in spacetime diagrams stayed.
I believe that from a pedagogical point of view this is a bad convention and the physics community should stop using it. It simply does not make a lot of sense to plot $t(x)$ instead of $x(t)$. For example, the slope of a $x(t)$ curve is the velocity. But the slope of a $t(x)$ curve is the inverse of velocity, a quantity which just helps to confuse students.

A: It makes past and future clearer, with past being down and future up, rather than having to remember which is right and left.

A: It doesn't matter. You can switch things: put position in the vertical axis and time in the horizontal axis. This time around though, the worldline for clocks at fixed position will be horizontal lines instead of vertical


text:
Q: Deep linking not working in facebook and twitter I am using deep linking feature in my app for facebook and twitter. Earlier the below lines in the manifest file used to give me option to open a link in the app, but presently it is redirecting to the browser. Below is my manifest
 <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />

            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="example.com"
                android:pathPrefix="/prefis"
                android:scheme="https" />

        </intent-filter>

A: Check the url in browser and add deeplink in accordance with tutorial in your app
https://developer.android.com/training/app-links/deep-linking#adding-filters


text:
Q: Amcharts - how to format valueField inside custom tooltip? I've got a basic AmGraph:
    graph = new AmCharts.AmGraph();

    graph.lineThickness = 4;
    graph.valueAxis = valueAxis;
    graph.fillAlphas = 0;
    graph.valueAxis = valueAxis;
    graph.valueAxis.minimum = 0;

    graph.title = "likes";
    graph.labelText = " ";
    graph.valueField = "likes_1";

The problem is that the numberFormatter doesn't format values if I'm using a custom balloonText function:
    graph.numberFormatter = {precision: -1, decimalSeparator:",", thousandsSeparator:","};

So if I use this:
    graph.balloonText = "<b>got: [[likes_1]] </b>";

The tooltip looks like this:
   "got: 1000"

How can I format the value? if I try to use javascript for formatting it (Numeral.js):
    graph.balloonText = "<script>numeral( [[likes_1]] ).format("0,0") </script>";

The wildcard isn't replaced with the actual value when building the page (but rather when hovering the chart?), so I just get:
    Uncaught ReferenceError: likes_32 is not defined

What should I do?

A:
(First I highly recommend to use the newer way of chart
  initialization! Look
  here
  for that.)

Instead of balloonText you can use balloonFunction, which allows you to change the text with JavaScript. Inside there you can format the number according to your wishes.
I prepared a demo using the AmCharts.formatNumber formatter.
return AmCharts.formatNumber(graphDataItem.values.value, {
        precision: -1,
        decimalSeparator: '.',
        thousandsSeparator: ','
    }, -1);

You can still use Numeral.js in there though (it's syntax seems a little more straight forward to me).
return numeral(graphDataItem.values.value).format("0,0");


text:
Q: Match/sort 2 columns in openoffice How do i match/sort my columns A and B to be like the example in the right, in the image below? It is a big list so i cant do it manualy.
What are the steps and formulas? I prefer in openoffice.
example image:

A: INDEX / MATCH is commonly used as a better alternative to VLOOKUP.  Enter the following formula in E1 and fill down to E3.
=INDEX(B$1:B$6;MATCH("*"&A1&"*";B$1:B$6;0))

For this to work, wildcards must be enabled in Tools -> Options -> LibreOffice Calc -> Calculate.


text:
Q: Get Elastic IP from running instance From a java application running on an EC2 instance, I'd like to know what my own elastic IP address that was manually assigned from the management console.  Is there a way to query EC2 API for this?

A: If you using a linux ec2 instance this should work:
Command:
curl http://169.254.169.254/latest/meta-data/public-ipv4

Java Code:
public static String getIP() throws IOException, InterruptedException {
    Process p = Runtime.getRuntime().exec("curl http://169.254.169.254/latest/meta-data/public-ipv4");
    int returnCode = p.waitFor();
    if ( returnCode == 0 ) {
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String ip = r.readLine();
        r.close();
        return ip;
    }
    else {
        //handle error
        return null;
    }
}

A: Alternative (not clearest solution), might be request an external service like this to know your public IP.
http://whatismyip.org/
EDIT: I found a nice service that returns json or text format. https://www.ipify.org/

A: You can call DescribeInstances - it returns a bunch of information including Public IP Address (ip-address filter).
...
DescribeInstancesRequest dis = new DescribeInstancesRequest();
DescribeInstancesResult disresult = ec2.describeInstances(dis);
...


text:
Q: ArcGIS Visual Studio IDE Integration Framework? i need to integrate arcgis 9.3 with visual studio c# 2008 express edition.
i found the integration framework for 9.1 but no chance for 9.3 and i've seen a lot of questions on web about it.
What should i do to integrate?
the version of .net is 3.5

A: Here is a similar question about getting the integration to work with VS 2010:
ArcGIS Server Object Extensions - Visual Studio Templates
Which version of the .Net framework are you using?  In this case it was working for 3.5, but not for 4.


text:
Q: How do I manage the technical debate over WCF vs. Web API? I'm managing a team of like 15 developers now, and we are stuck at a point on choosing the technology, where the team is broken into two completely opposite teams, debating over usage of WCF vs. Web API.
Team A which supports usage of Web API, brings forward these reasons:

*

*Web API is just the modern way of writing services (Wikipedia)

*WCF is an overhead for HTTP. It's a solution for TCP, and Net Pipes, and other protocols

*WCF models are not POCO, because of [DataContract] & [DataMember] and those attributes

*SOAP is not as readable and handy as JSON

*SOAP is an overhead for network compared to JSON (transport over HTTP)

*No method overloading

Team B which supports the usage of WCF, says:

*

*WCF supports multiple protocols (via configuration)

*WCF supports distributed transactions

*Many good examples and success stories exist for WCF (while Web API is still young)

*Duplex is excellent for two-way communication

This debate is continuing, and I don't know what to do now. Personally, I think that we should use a tool only for its right place of usage. In other words, we'd better use Web API, if we want to expose a service over HTTP, but use WCF when it comes to TCP and Duplex.
By searching the Internet, we can't get to a solid result. Many posts exist for supporting WCF, but on the contrary we also find people complaint about it. I know that the nature of this question might sound arguable, but we need some good hints to decide. We're stuck at a point where choosing a technology by chance might make us regret it later. We want to choose with open eyes.
Our usage would be mostly for web, and we would expose our services over HTTP. In some cases (say 5 to 10 percent) we might need distributed transactions though.
What should I do now? How do I manage this debate in a constructive way?

A:
What should I do now? How do I manage this debate in a constructive way?

First, keep subjectivity away. In your WebAPI team's arguments, I find "Web API is just the modern way"*, "WCF models are not POCO, because of those attributes" and "SOAP is not as readable and handy as JSON" pretty opinionated, if not plain wrong, and will not help make a decision.
So, what to do: decide what you want to do with your service(s), then choose a technique that accommodates that goal and its maintainability and extensibility with the least amount of pain. You can do this by simply researching whether any given aspect is supported by the framework to use.
Interesting reading material:

*

*Mvc 4 vs. Wcf Web Api

*WCF or ASP.NET Web APIs? My two cents on the subject

*WebAPI or WCF?
*: note you refer to Wikipedia for this, where the citation is: "Web 2.0 web applications have moved away from a service-oriented architecture (SOA) with SOAP-based web services towards more cohesive collections of RESTful web resources". That's an example of use for when your service is to be consumed from a webpage. This can also easily be done with WCF, using the WebHttpBinding. It does not say "Use WebAPI for this".
If this question stretches beyond the "how to manage the discussion": I would use WCF if the services are to be consumed by non-web-clients, because its metadata allows for astonishingly easy strongly-typed client generation.

A: Team management aside, you do not choose one over the other. You need to look at the purpose of each web service and use the appropriate technology for the specific part of the application. It's like banning store procedures when the team is using entity framework.

Our usage would be mostly for web, and we would expose our services
  over HTTP. In some cases (say 5 to 10 percent) we might need
  distributed transactions though.

Then you write those 5~10% web services in WCF. If the service is to be referenced internally in other projects, there's no debate. The advantage of the ability to import WCF contract to create the client proxy is NOT open for discussion. It takes the whole integration, efficiency, and type safety to a whole new level.
You write what's to be used for public api(maybe) / Ajax requests in Asp.net web api.
If it's just page specific ajax call, you can just use Asp.Net MVC.
Don't choose, embrace them all. WCF and Asp.net web api serve different purposes. No one says you can't have apple and orange both in your fruit salad. Trying to pick one over the other and shoving it down every single scenario is just sheer laziness.

A: Our team had a similar discussion a couple of months ago. The deciding factor for us came down to how we would create and implement each technology. Since we were already building an MVC application and were using Knockout.js for data binding, we were effectively using MVVM with the controllers just being an API for data.
This allowed us to categorize our use of the technologies with this project as follows:

*

*Web API would be used as our API for knockout and Ajax calls, making them our commands for the MVVM pattern. Our business logic for the web application is wrapped up behind this layer through a number of classes and repositories and factories.

*WCF is then used for our data store, exposing data from our database for not only this website, bit also for any other site or service that consumed the exposed data.

While this might not be a popular or hyper technical response, determining what you need first and how or if the technology will help is what helped my team decide which technology to use where.

A: When both sides have good arguments and the opinions on the issue are too strong to come to a consensus, you as a manager need to make a decision and end the debate. Otherwise it will just turn in circles and fortify the positions of all participants even more. The longer you wait, the harder will it be for the "losing" side to admit defeat and work productively with the outcome.
Write down all the arguments, value their importance for the project, and then make your decision. When you can't, flip a coin. Your project can likely be completed succesfully with either technology, and wasting valuable time with unnecessary debates will just cost unnecessary money.

A:
In other words, we'd better use Web API, if we want to expose a service over HTTP, but use WCF when it comes to TCP and Duplex.

That would be the most reasonable approach. It's quite common to have both WCF and WebApi services in the same web application where both serve different purposes.
Just to correct few arguments:

WCF models are not POCO, because of [DataContract] & [DataMember] and those attributes

In many cases WCF models work without datacontract/datamember attributes.

SOAP is not as readable and handy as JSON

It is not, true, but WCF web services usually carry plain XML rather than bloated SOAP. This definitely is readable.
One argument for WCF: if there is a WSDL available, there are tons of tools in almost all technologies that can create proxies out of the metadata. On the other hand, the JSON Schema is not yet all widely supported.

A: Why not walk the line with WCF Data Services? nice OData/webapi style queries and usability with the powers of WCF, and the ability to return JSON just fine. Also Wcf isn't that bad if you have a nice automatic wcf hosting code like the following:
https://github.com/ImaginaryDevelopment/MvcOdata
I'd say they aren't far separated at all, except that when we went to use WebApi on the front end and WCF data services on the middle tier, the WebApi threw up on simple things like string contains or string matching odata operators.

A: Assuming both sides are 100% correct in all of their arguments, which ones matter?

WCF models are not POCO, because of [DataContract] & [DataMember] and those attributes

Do you care?  Are you planing on doing something that requires POCO?

WCF supports distributed transactions

Again is this something you are going to use and need to build if you don't have it because you took the other path?
Basically get to the heart of which one:

*

*Offers everything you need (If neither offer everything you need which makes you have to do the least amount of work).

*Offers the least amount of junk you aren't going to use but have to put up with anyway.

Any argument put forth that isn't in the path of what you need to accomplish is irrelevant and should not factor in to your decision, with some wiggle room for considering future expansion.

A: Put my two cents in.
As a manager, you should ask your teammates to keep in mind the Yagni principle. This will help to reduce the list of reasons brought forward by both Teams.

Our usage would be mostly for web, and we would expose our services
  over HTTP. In some cases (say 5 to 10 percent) we might need
  distributed transactions though.

Rather than diving into distributed transaction, you should consider working with compensation instead.
Last thing to take into account is the learning curve. Depending on the deadline of your project, as a manager, you should be able to decide whether it's ok to start learning a new technology or not.
If you have plenty of time to waste, then go for some kind of Innovation Day where Team A and B would have a day to produce proof of concepts based on the same requirements.
By the way, to the guy that says "WCF models are not POCO, because of [DataContract] & [DataMember] and those attributes", tell him that POCOs are generaly meant to be domain entities and that it's not a best practice to expose your domain object to any kind of clients, this is what DTO's are for.

A: A good architect delays technology decisions until they're absolutely necessary to make.
In other words, don't make the decision until a client needs to actually connect. You can build a fully tested service layer without actually putting a transport/commnication mechanism over it. 95%+ of the work can be done "beneath" the adapter, outside the framework.
Come time to expose those services to remote clients, you can pick the trendiest framework off the shelf and write thin wrappers over a versatile service layer.
Hell, if your "real" service layer is done well, you can even try several wrappers at a minimal expense.
That's the dogmatic answer, anyway. In practice, you may want to pick the simplest tool off the shelf to facilitate early and frequent integration tests -- but, still limit your dependence on it and treat it strictly as a simply thin communication layer over the real services.

If you take this approach, you'll probably find that you pick the simplest tool to use initially and no one will fuss, because the team knows they can implement a more sophisticated or trendy tool or framework later, if necessary, with minimal effort.

A: Hence I'm facing the same choice now, I asked myself what is the subset of features from WCF our team is using at the moment.
Do we use different protocols? No. Do we use transaction support? No (although we use custom eventual consistency mechanisms). Do we use duplex? No.
Why we would like to use Web API? Easier frontend integration (removes additional service layer existing now), SignalR for pushing reply to clients, caching for GETs.
May be, one could find other reasons :) As well, reasons to stay with WCF.

A: If I were in your position I would start by examining your teams abilities.  If everyone on your team already knows WCF and only a small percentage know Web API then your decision is already made for you.
By all means if you have the time then invest it in learning and improving your knowledge base, but not at the expense of the business need and company productivity.

A: I would ask what model of interaction do you need to support?  Does your desired external interface more resemble RPC or REST?  In my experience it's usually somewhere between but mostly one or the other.
Are you consuming your own services for other projects in .Net?  This is probably the single most revealing question you can ask.   WCF does have the advantage of being able to abstract your interfaces into a separate class library and be able to build and inject your client.  As an extension to this, you can mount your WCF based project with both JSON and SOAP/WSDL endpoints, I've done it.  WCF also offers better assurances against your defined interfaces.
That said, if you expect to have clients from other platforms XML in general, let alone SOAP has a measurable overhead beyond what simple JSON endpoints have.  If you go the JSON/Web API route, then you will need to become much better at documenting how to interact with your endpoints and API.
In general, I would suggest writing a simple API document that states how you will submit data, and how you want a response for a single request object structure.  Write your test case in the most universal way, and document it as such.  I'd recommend a simple curl statement.  Then have several of your members implement this using WCF and with Web API.  Then see which wins.
Personally, despite having done some relatively large projects and implementations with WCF, I actually lean towards the simplest implementation which in my mind is actually straight WCF with using JSON results and some override behavior in the Global.asax.cs for dealing with error conditions.  If an API's documentation includes curl statements, and you can exercise all of the functionality of your API with curl examples it becomes much easier for clients to be implemented in any language that supports web interfaces.  This is really where WCF starts to fall down.  Having a well defined API with agnostic documentation is better than having structures with automated tooling when dealing with foreign systems.  Speaking as a consumer of those systems from other platforms.
One thing beyond that, is implement your client in two disparate languages.  Do a client in C#, but also do one in Node.js or Python and see how well they actually fit.  That exercise alone will help you shake out the loose ends in your API.


text:
Q: Using :: (scope resolution operator) in C++ I am learning C++ and I can never tell when I need to use :: . I do know that I need to use std:: in front of cout and cin. Does this mean that inside of the iostream file the developers that created it  made a namespace called std and put the functions cin and cout into the namespace called std? When I created a new class that isn't in the same file as main() for some reason I must add :: .
For example, if I create a class called A , why do I need to put A:: in front of a function that I make, even though I didn't put it into a namespace? For example void A::printStuff(){} . If I create a function in main, why don't I have to put main::printStuff{} ?
I know that my question is probably confusing, but could someone help me?

A: The :: are used to dereference scopes.
const int x = 5;

namespace foo {
  const int x = 0;
}

int bar() {
  int x = 1;
  return x;
}

struct Meh {
  static const int x = 2;
}

int main() {
  std::cout << x; // => 5
  {
    int x = 4;
    std::cout << x; // => 4
    std::cout << ::x; // => 5, this one looks for x outside the current scope
  }
  std::cout << Meh::x; // => 2, use the definition of x inside the scope of Meh
  std::cout << foo::x; // => 0, use the definition of x inside foo
  std::cout << bar(); // => 1, use the definition of x inside bar (returned by bar)
}

unrelated:
cout and cin are not functions, but instances of stream objects.

A: The :: is called scope resolution operator.
Can be used like this:
:: identifier
class-name :: identifier
namespace :: identifier
You can read about it here
https://learn.microsoft.com/en-us/cpp/cpp/scope-resolution-operator?view=vs-2017

A: You're pretty much right about cout and cin. They are objects (not functions) defined inside the std namespace. Here are their declarations as defined by the C++ standard:

Header <iostream> synopsis
#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>

namespace std {
  extern istream cin;
  extern ostream cout;
  extern ostream cerr;
  extern ostream clog;

  extern wistream wcin;
  extern wostream wcout;
  extern wostream wcerr;
  extern wostream wclog;
}

:: is known as the scope resolution operator. The names cout and cin are defined within std, so we have to qualify their names with std::.
Classes behave a little like namespaces in that the names declared inside the class belong to the class. For example:
class foo
{
  public:
    foo();
    void bar();
};

The constructor named foo is a member of the class named foo. They have the same name because its the constructor. The function bar is also a member of foo.
Because they are members of foo, when referring to them from outside the class, we have to qualify their names. After all, they belong to that class. So if you're going to define the constructor and bar outside the class, you need to do it like so:
foo::foo()
{
  // Implement the constructor
}

void foo::bar()
{
  // Implement bar
}

This is because they are being defined outside the class. If you had not put the foo:: qualification on the names, you would be defining some new functions in the global scope, rather than as members of foo. For example, this is entirely different bar:
void bar()
{
  // Implement different bar
}

It's allowed to have the same name as the function in the foo class because it's in a different scope. This bar is in the global scope, whereas the other bar belonged to the foo class.

A: One use for the 'Unary Scope Resolution Operator' or 'Colon Colon Operator' is for local and global variable selection of identical names:
    #include <iostream>
    using namespace std;

    int variable = 20;

    int main()
    {
    float variable = 30;

    cout << "This is local to the main function: " << variable << endl;
    cout << "This is global to the main function: " << ::variable << endl;

    return 0;
    }

The resulting output would be:

This is local to the main function: 30
This is global to the main function: 20

Other uses could be: Defining a function from outside of a class, to access a static variable within a class or to use multiple inheritance.

A: look at it is informative [Qualified identifiers
A qualified id-expression is an unqualified id-expression prepended by a scope resolution operator ::, and optionally, a sequence of enumeration, (since C++11)class or namespace names or decltype expressions (since C++11) separated by scope resolution operators. For example, the expression std::string::npos is an expression that names the static member npos in the class string in namespace std. The expression ::tolower names the function tolower in the global namespace. The expression ::std::cout names the global variable cout in namespace std, which is a top-level namespace. The expression boost::signals2::connection names the type connection declared in namespace signals2, which is declared in namespace boost.
The keyword template may appear in qualified identifiers as necessary to disambiguate dependent template names]1


text:
Q: OSX Directory not empty cant mv Im looking for item that  starts with WaveShell-VST* and want to move t to the mac trash
can (.trash).
So im using that:
find  /Library/Audio/Plug-Ins/VST3/ -maxdepth 1 -name 'aVST*' -exec mv {} ~/.Trash/ \;

when run that command again i get "Directory not empty" message in terminal , how can i force it to move the file to trash either renaming it or deleting what in the trash can?
( I added -f and didn't help).
The 'aVST*' is a directory.


text:
Q: LibGDX - Independent intersector for detecting collisions Does LibGDX have independent from snapshots collision detector? For instance, I don't want to use Box2D and want to detect collision of very fast objects. I know that it has Intersector class which is designed for this purpose, but I can't use it for very fast objects, because it doesn't work for them. So, does LibGDX have this kind of class or I should implement them by myself?

A: LibGDX does not have anything built-in to do swept collision detection/response (aside from what Box2D provides).
Here's an article on gamedev.net that covers it if you implement your own:
http://www.gamedev.net/page/resources/_/technical/game-programming/swept-aabb-collision-detection-and-response-r3084

A: There's nothing sort of that in libgdx. It canbe achieved through box2d but you didnt want that... So you have to write something on your own.
I think your problem is if the object is too fast that it passes other object completely without giving any collison callback.
Basically what you want is predictive collision. It means you find that collision is going to occur one step before. and then act accordingly..
try this
http://seb.ly/2010/01/predictive-collision-detection-techniques/

A: I have found implementation of different collision detection such as circle and line or circle and circle. But it is in russian language and for Macromedia Flash MX: swept collision detection
If someone has wish to convert those functions to Java, you are welcome! :)

A: If u are using Rectangle or Circle for bounds
U can use
Rectangle bound1=new Rectangle(0,0,10,10);
Circle c=new Circle(0,0,10);

if(c.contains(vector.x,vector.y))
{
//do something
}

if(bound1.contains(vector.x,vector.y))
{
//do something
}

This should help u out


text:
Q: Why is the formal parameter of C + + overloaded extraction operator in the form of reference? for example,
istream &operator(istream &input,PhoneNumber &number)

(the PhoneNumber is a class made by me)
I'm very thankful if you can reply to me


text:
Q: Manipulate Observable Let's take for example the following hero code to get heroes:
/** GET heroes from the server */
  getHeroes (): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl)
      .pipe(
        tap(heroes => this.log(`fetched heroes`)),
        catchError(this.handleError('getHeroes', []))
      );
  }

I want to manipulate each element of hero[]. I tried .map function:
  getHeroes (): Observable<Hero[]> {
            return this.http.get<Hero[]>(this.heroesUrl)
              .pipe(
                tap(heroes => this.log(`fetched heroes`)),
                catchError(this.handleError('getHeroes', []))
              ).map((result) => {
                 console.log(result); // I am getting all the array and not iteration.
                 return  Object.assign(new Hero(), result);
             );
          }

but I am getting all the array or Hero[] and its not iterate the heroes one by one.

A: Map manipulates the Observable data which you get at the moment, not each data inside it. And because you get your heroes in the array, not one by one, you get the whole array inside map as a single data.
You need to use Array.map on the result, create your mapped array and pass it to the next.
RxJS 5 now uses do instead of the tap.


text:
Q: How to solve $x^2 \equiv 12 \pmod {13}$?
Solve $x^2 \equiv 12 \pmod {13}$

By guessing I can say that the solutions are $5$ and $8$, but is there another way to find the solution besides guessing?

A: Hint :
As $x^2 \equiv a^2 \pmod {n}$ is easiest to handle, and $12\equiv25 \pmod {13}$, we have
$$ x^2 \equiv (\pm 5)^2 \pmod {13}$$

A: As cosmo5 mentioned in his comment. You can do the following which is a little bit better than guessing since you probably can instantly recognise square numbers.
For every natural number $n$ we have
$$
x^2 \equiv 12 \mod 13
\quad\Leftrightarrow\quad
x^2 \equiv 12+13n \mod 13.
$$
Hence, you can start
$$
\begin{array}{c|c}
n & 12+13n \\
\hline
1 & 25 \\
2 & 38 \\
3 & 51 \\
4 & 64
\end{array}
$$
Then you will see that for $n=1$ you have $5^2$ and for $n=4$ you have $8^2$, which gives you the solutions $x_1=5$ and $x_2=8$.
Alternative you can make a polynomial division after you found one solution, because
$$
x^2-12 \equiv (x-x_1)(x-x_2) \mod 13.
$$
However, this might take longer than guessing for small numbers.

A: In the special case of trying to find a square root of $-1$ modulo a prime $p \equiv 1 \pmod{4}$, we can use the following algorithm: first, select some random integer $a$ with $1 < a < p - 1$.  Now, if $p-1 = 2^k \cdot q$ with $q$ odd, then form $a^q \operatorname{mod} p$.  If you get something other than $1$ or $-1$ at this point, then repeatedly square until you get $-1$.  Then, the number just before $-1$ will be a square root of $-1$.  (The reason this works: by Fermat's little theorem, $a^{p-1} \equiv 1 \pmod{p}$, so after taking the square $k$ times, you get to $1$.  Since $p$ is prime, the number just before you reach $1$ for the first time is forced to be $-1$.)
On the other hand, if $a^q \equiv \pm 1 \pmod{p}$ already, then go back and choose another random value of $a$ to try.  Since $q < \frac{p - 1}{2}$, it is impossible for every value of $a$ to satisfy $a^q \equiv \pm 1 \pmod{p} \Leftrightarrow a^{2q} \equiv 1 \pmod{p}$.
So, in the case of $p = 13$, where $p - 1 = 2^2 \cdot 3$ and so $q = 3$, let us first start with a trial of $a = 2$.  Then, $a^q = 2^3 = 8$ and $8 \not\equiv \pm 1 \pmod{13}$, so we're good to go.  From here, $8^2 = 64 \equiv -1 \pmod{13}$, and so we find 8 as a square root of $-1 \pmod{13}$.

A: In the field ${\displaystyle \mathbb {Z} /13\mathbb {Z}}$, $\,[1] + [1] \ne [0]$, and therefore there are either zero or two distinct $\text{modulo-}13$ solutions for,
$\tag 1 x^2 \equiv 12 \pmod{13}$
When one solution $[u]$ has been found the other solution is $-[u]$.
We have
$\; \large x^2 \equiv 12 \pmod{13} \; \text{ iff }$
$\; \large x^2 \equiv 2^{-2} \cdot (2^2 \cdot 12) \pmod{13} \; \text{ iff }$
$\; \large x^2 \equiv 2^{-2} \cdot (3^2) \pmod{13} \; \text{ iff }$
$\; \large x^2 \equiv \bigr(2^{-1} \cdot 3^1\bigr)^2 \pmod{13}$
Now the inverse of $[2]$ is easily calculated,
$\quad [2]^{-1} = [\frac{13 + 1}{2}] = [7]$
and so one solution to $\text{(1)}$ is given by
$\quad x \equiv 7 \cdot 3 \equiv 8 \pmod{13}$
The other solution is given by
$\quad x \equiv -8 \equiv 5 \pmod{13}$

Note: Examining this question resulted in a conjecture,
$\quad$ A new method for finding a solution (when they exist) to $x^2 = a \pmod p$?