Q: 405: Method Not Allowed after update to Spring Boot 1.3.0 I have setup an Authorization- and Resourceserver which both running within the same application. The setup is running fine with spring boot 1.2.6.RELEASE and spring security oauth2 2.0.7.RELEASE. After an update to spring boot 1.3.0.RELEASE (no matter if spring security oauth2 2.0.7.RELEASE or 2.0.8.RELEASE) the /login endpoint for POST requests is broken. I got the response 405 "Method Not Allowed".
I spent over a day without success. I also setup an additional, straightforward authorization- and resourceserver which both are running within the same application. However this lightweight setup have the same issue. As soon as I enable the resource server, the login endpoint no longer works.
Below the config snippets form my origin server.
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    // ... some code

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .csrf()
                .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
                .disable()
                .logout()
                .logoutUrl(logoutUrl)
                .logoutSuccessHandler(logoutSuccessHandler)
                .invalidateHttpSession(true)
                .and()
                .formLogin()
                .permitAll()
                .loginProcessingUrl(loginProcessingUrl)
                .failureUrl(loginAuthenticationFailureUrl)
                .loginPage(loginPage);
    }

}

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    // ... some code

    private static final String RESOURCE_SERVER_MAPPING_REGEX = "^(?!(\\/?login|\\/?logout|\\/?oauth)).*$";

    // ...some code

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http
            // Configure the endpoints wherefore the resource server is responsible or rather should bound to.
            .requestMatchers().regexMatchers(RESOURCE_SERVER_MAPPING_REGEX)
            .and()
            .authorizeRequests().anyRequest().permitAll()
            .and()
            .headers().frameOptions().disable();
    }
}

A: Solution
It looks like that I am faced with the issue mentioned in @EnableResourceServer creates a FilterChain that matches possible unwanted endpoints with Spring Security 4.0.3 Spring Security is a dependency of spring-boot-starter-security. Due to the update of the spring-boot-starter-parent I switched from Spring Security 3.2.8 to 4.0.3. A further interesting comment regarding this issue can be found here.
I changed the ResourceServer configuration like the code snippets below which solve the problem.
It would be great to replace the RegexRequestMatcher definition by using a negation of already existing code to match the login and logout form or Matchers like the spring NotOAuthRequestMatcher which is currently a private inner class of the ResourceServerConfiguration. Please do not hesitate to post suggestion. ;-)
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    // ... some code

    private static final String RESOURCE_SERVER_MAPPING_REGEX = "^(?!(\\/?login|\\/?logout|\\/?oauth)).*$";

    // ...some code

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.requestMatcher(
                new AndRequestMatcher(
                        new RegexRequestMatcher(RESOURCE_SERVER_MAPPING_REGEX, null)
                )
        ).authorizeRequests().anyRequest().permitAll()
        // ...some code
    }

}

A: This should pretty straightforward.
POSTs and PUT requests would not be allowed if CSRF is enabled,and spring boot enables those by default.
Just add this to your ResourceServerConfig  configuration code :
.csrf().disable()

This is also covered as an example problem here


Q: Special Unicode Characters are not removed in Python 3 I have a keys list including words. When I make this command:
for key in keys:
  print(key)

I get normal output in terminal.

but when I print the entire list using print(keys), I get this output:

I have tried using key.replace("\u202c", ''), key.replace("\\u202c", ''), re.sub(u'\u202c', '', key) but none solved the problem.
I also tried the solutions here, but none of them worked either:
Replacing a unicode character in a string in Python 3
Removing unicode \u2026 like characters in a string in python2.7
Python removing extra special unicode characters
How can I remove non-ASCII characters but leave periods and spaces using Python?
I scraped this from Google Trends using Beautiful Soup and retrieved text from get_text()
Also in the page source of Google Trends Page, the words are listed as follows:
 When I pasted the text here directly from the page source, the text pasted without these unusual symbols.

A: You can just strip out the characters using strip.
>>> keys=['\u202cABCD', '\u202cXYZ\u202c']
>>> for key in keys:
...     print(key)
...
ABCD
XYZ
>>> newkeys=[key.strip('\u202c') for key in keys]
>>> print(keys)
['\u202cABCD', '\u202cXYZ\u202c']
>>> print(newkeys)
['ABCD', 'XYZ']
>>>

Tried 1 of your methods, it does work for me:
>>> keys
['\u202cABCD', '\u202cXYZ\u202c']
>>> newkeys=[]
>>> for key in keys:
...     newkeys += [key.replace('\u202c', '')]
...
>>> newkeys
['ABCD', 'XYZ']
>>>


Q: connect in qt using two different classes I want to connect a signal and a slot from two different classes in which one is using the other like this example:
form.hpp
class Form : public QDialog
{
    Q_OBJECT

public:
    explicit Form();
public slots:
     void onPushButton(void);

};

form.cpp
Form::Form() :
    QDialog(parent)
{
    ui->setupUi(this);
    connect(..., SIGNAL(clicked()),..., SLOT(onPushButton()));

}

void Form::onPushButton(void)
{
    ui->pushButton->setText(QString("clicked"));
}

mainwindow.hpp
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);

private:
    Ui::MainWindow *ui;
    Form f;
};

mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

I know it easy to solve but I don't know how to do it. What the syntax of connect in Form::Form()?
If it was the way around I would do it like that:
connect(&f, SIGNAL(clicked()),this, SLOT(onPushButton()));

A: The connection must be made in the MainWindow constructor, but you must use a lambda method since the signal does not pass the text to it.
form.h
class Form : public QDialog
{
    Q_OBJECT

public:
    explicit Form();
public slots:
     void processingFunction(const QString & text);

};

form.cpp
Form::Form() :
    QDialog(parent),
    ui(new Ui::Form)
{
    ui->setupUi(this);

}

void Form::processingFunction(const QString & text)
{
    // some processing
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->pushButton, &QPushButton::clicked, [this](){
        f.processingFunction(ui->lineEdit->text());
    });
}

A: [UPDATE]
Class Form is not emiting clicked signal. You should connect a QPushButton (or similar) instead the class Form. Otherwise you should declare signal clicked() in your class and emit it somewhere in your code:
class Form : public QDialog
{
    Q_OBJECT

public:
    explicit Form();

signals:
    void clicked();

public slots:
     void onPushButton(void);
};

void Form::someFunction(/* parameters */)
{
    emit clicked();
}

Also, if you want to make the connection you mention at the end, you should do it in the MainWindow class, because you can't access MainWindow from Form, unless you make MainWindow the parent of Form and then call parent() function to access MainWindow through a pointer. But that is an insane and discouraged programming practice because Form must not know about the existence of MainWindow.
Although Qt4-style connect() (using SIGNAL and SLOT macros) is still supported in Qt5, it's deprecated and may be removed from Qt6 in 2019, so you must switch to Qt5-style connect():
QObject::connect(lineEdit, &QLineEdit::textChanged,
                   label,  &QLabel::setText);

This has several pros:

*

*Errors can be raised at compilation-time, rather than execution time.

*C++11 Lambdas can be used.

See this:
connect(sender, &QPushButton::clicked, [=]() {
    // Code here. Do whatever you want.
});

*

*Are a lot faster to resolve.

Take a look at: Qt5 Signals and Slots


Q: Applying additional oauth scopes in an omniauth initializer I am trying to apply the coinbase wallet API with oauth to use its send functionality. I have been able to connect to the API and use its endpoints, but whenever I try to use the send functionality, I am thrown the error Invalid amount for meta[send_limit_amount]. My omniauth initializer looks like this:
provider :coinbase, , ENV['CLIENT_ID'], ENV['CLIENT_SECRET'],
scope: 'wallet:user:read wallet:user:email wallet:accounts:read wallet:transactions:send'

The reason for this error is because, in order to use the send functionality, coinbase requires additional parameter meta[send_limit_amount]. Where and how am I supposed to apply this additional scope?
UPDATE: So I've made some progress in that I am able to attach one meta scope to my initializer, which seems to be sticking (as shown when I print out the auth_info). This is the current state of my initializer:
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :coinbase, ENV['CLIENT_ID'], ENV['CLIENT_SECRET'], scope: 'wallet:user:read wallet:user:email wallet:accounts:read ', :meta => {'send_limit_currency' => 'BTC'}
end

# wallet:transactions:send
# :meta => {'send_limit_amount' => '0.0001'}

The problem now is that I cannot seem to figure the syntax necessary to add the send_limit_amount property to the oauth meta hash.

A: Managed to solve the problem with the following initializer;
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :coinbase, ENV['CLIENT_ID'], ENV['CLIENT_SECRET'],
  scope: 'wallet:user:read wallet:user:email wallet:accounts:read wallet:transactions:send',
  :meta => {'send_limit_amount' => 1}
end

Now, I need to either disable the two factor authentication or determine how to Re-play the request with CB-2FA-Token header


Q: Python assignment with AND and OR I am not much familiar with python. and I am write now looking into one code from python and it says something like this:
query = url.query and ('?' + url.query) or ''

can anyone help me understand what this means.
I found something similar here. but I couldn't interpret the above statement.
I am suppose to convert this line in Java.

A: That is very old - and quite unreliable - syntax for a ternary if. In modern Python it should be:
query = '?' + url.query if url.query else ''

and in Java:
query = url.query == '' ? '' : '?' + url.query


Q: When to use second level cache in hibernate I know how first and second level cache work in hibernate.
But I would like to know
1.when will be the first cache used and when will be the second

*how are the objects stored in the first and second. Do the second level maintains a copy same as first

A: The 1st level cache is maintained by the Session or EntityManager, and it's only used during the life of that object. That ensures that if you get/find/retrieve a specific entity more than once during the lifetime of a Session, you'll get the same instance back (or at least a proxy to the same instance).
The 2nd level cache is maintained outside the Session/EntityManager and usually there's a copy of the object, but that is not directly linked (as with objects in the Session).
A word of caution. If you use hibernate in an application that has several instances, the 2nd level cache is not shared amongst instances. For that you need to use a distributed cache (such as terracotta)... if you want consistency amongst the instances of the app. This is not a problem if you are caching static data.


Q: Google Script: Auto-trigger - if a new entry flags serious issue, spreadsheet emails admin for inspection I am pretty new to scripting. Please forgive, if I've missed an obvious step. I've searched through stack overflow, and my simple problem is not clearly mentioned.
We have a fleet of vans. The drivers enter issues through google forms, and it's added to a single google spreadsheet which has sheet/tabs for each vehicle. I want an email to be triggered once a new entry is made with the "serious issue found" and "Critical Immediate Action Requested" flag found in the drivers report.
(Spreadsheet is called "Fleet_Vehicles") (Each van is its own internal sheet: "Van_05-10" "Van_06-12" "Van_07-13") (The sheet meant for storing data (emails) for the script: Auto-Script-Logic)
This is google script I am attempting:
UPDATED: as per Coopers and Miturbe's input. Thank you gentlemen.
function CheckStatus() {
  var ss = SpreadsheetApp.openById("120u_KtdWValZXUyn8vaAlEqbNwmRROYMj-fFTx8bPOs");
  var FleetHealthRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Van_16-23");
  var row = ss.getLastRow();   var columns = ss.getLastColumn();   var range = ss.getRange(row, 1, 5, columns).getValues();
  var FleetHealth = FleetHealthRange.getValue();
  if ("How_serious?" == "Serious Symptom Discovered")
  if ("How_serious?" == "Critical Immediate Action Requested"){
      var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Auto-Script-Logic").getRange("A1");
    var emailAddress = emailRange.getValue();
    var message = '(=sum(Van_16-23!A2:E20)'
    var subject = 'This Van 16-23 has serious symptom';
    MailApp.sendEmail('#####@gmail.com', subject, message);
    }

Am I missing an embarrassing and obvious symantec?
Thank you in advance!

A: Try this:
function CheckStatus() {
  var FleetHealthRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(Van_05-11).getRange("E2");
  var FleetHealth = FleetHealthRange.getValue();
   if (How serious? == "Serious Symptom Discovered"){
      var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Auto-Script-Logic").getRange("A1");
    var emailAddress = emailRange.getValue();
    var message = 'This Van has serious symptom ' + FleetHealth; // Second column
    var subject = '(=sum(Van_05-11!D2)';
    MailApp.sendEmail(emailAddress, subject, message);
    }
}

How Serious is undefined and if it's a variable it needs to be one string without spaces.

JavaScript Variable Naming

A: Something like this should work:
function CheckStatus() {
  //var ss = SpreadsheetApp.openById("120u_KtdWValZXUyn8vaAlEqbNwmRROYMj-fFTx8bPOs");

  var FleetHealthRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Van_16-23");

  var row = FleetHealthRange.getLastRow();
  var columns = FleetHealthRange.getLastColumn();
  var range = FleetHealthRange.getRange(row, 1, 1, columns).getValues();

  // By default, range is a 2D array so range[0][0] has the first column
  var lastrow = range[0];

  Logger.log("Reading row " + row + " columns " + columns)

  //var FleetHealth = FleetHealthRange.getValue();
  var column_serious = 5 //column number you want to compare, in this case 5 is column E

  if (lastrow[column_serious] == "Serious Symptom Discovered" || lastrow[column_serious] == "Critical Immediate Action Requested")
  {
      var emailAddress = lastrow[0];
      var message = '(=sum(Van_16-23!A2:E20)'
      var subject = 'This Van 16-23 has serious symptom';
      MailApp.sendEmail('#####@gmail.com', subject, message);

  }

}

I placed the code here:
https://docs.google.com/spreadsheets/d/197oWwBDmB0iI3Ry9Km6mfO73Jjx9RWjXHI-bAM28bZs/edit?usp=sharing


Q: c++ Event queues, variadic functions, static functions and other strange stuff after yesterday's rip-roaring thread at How to implement a simple event queue? , I decided to finally make the big leap to c++11.  Just before c++14 comes out probably...
Anyway, it occured to me that variadic functions are the perfect way forward in this enjoyable endeavour.  They probably aren't really, but anyway, I managed to steal and bastardize some code I found somewhere, and ended up with this:
#include <iostream>
#include <functional>
#include <queue>

class Event
{
public:
    int timeOfCompletion;
    std::function<void()> function;
    inline bool operator<(const Event& target) const
    {
        return target.timeOfCompletion < timeOfCompletion;
    }
};

class System
{
public:

    int someValue;
    std::priority_queue<Event> funcs;

    System()
    {
        someValue = 100;
    }

    template<typename Func, typename...Args>
    void addFunctionToQueue(const int t , const Func&& myFunc, Args&&... myArgs)
    {
        Event newEvent;
        std::function<void()> func = std::bind( std::forward<Func>(myFunc), std::ref(myArgs)...);
        newEvent.function = func;
        newEvent.timeOfCompletion = t;
        funcs.push(newEvent);
    }

    void runAllFunctions()
    {
        while(!funcs.empty())
        {
            Event func = funcs.top();
            funcs.pop();
            func.function();
        }
    }

    static void doStaticFunction(int a)
    {
        std::cout <<"I would like to change someValue here, but can't :-(\n";
        //someValue -= a;//invalid
    }

    void doNonStaticFunction(int a)
    {
        someValue -= a;
        std::cout <<"Set someValue to " << someValue << "\n";
    }

};

int main()
{
    System newSystem;

    newSystem.doNonStaticFunction(5);

    newSystem.addFunctionToQueue(5, System::doStaticFunction, 1);
    newSystem.runAllFunctions();

    //newSystem.addFunctionToQueue(5, newSystem.doStaticFunction, 1);// is invalid
    //newSystem.addFunctionToQueue(5, System::doNonStaticFunction, 1);// is invalid
    //newSystem.addFunctionToQueue(5, newSystem.doNonStaticFunction, 1);// is invalid
    std::cin.ignore();
    return 0;
}

Anyhow, how can I get the "addFunctionToQueue" function to work with non-static functions?  I thought I had more questions, but I think if I can get that one answered, my other problems will hopefully be solved...

A: *

*Remove a const qualifier from the Func parameter.
template<typename Func, typename...Args>
void addFunctionToQueue(int t , Func&& myFunc, Args&&... myArgs)
//                              ~~~^ no const

Rationale: When using a forwarding reference (or an lvalue reference) type with a template argument deduction, a const qualifier is automatically deduced (depending on the argument's qualifiers). Giving it explicitly prevents the compiler from adding it to the Func type itself, which results in an error when you try to std::forward<Func>. That said,  you would need to write std::forward<const Func> instead to avoid the compiler error, but still, that would make no sense, as const T&& is not a forwarding reference.

*Non-static member functions require an object for which they will be called, just like you write a.foo(), not foo().
newSystem.addFunctionToQueue(5, &System::doNonStaticFunction, &newSystem, 1);
//                                                            ~~~~~~~~~^ context


Q: can someone confirm my isolation level understanding please There are Five Isolation levels summary is mentioned below… Please correct me if I am wrong : -

*

*Read uncommited. In this level we can read dirty pages and chages can be done(DML statements like Insert and Update) on the rows even when records are not commited.

*Read Committed. Only committed rows can be read. If transaction is open at the time records are read deadlock will happen. Modifications to the data(Inserts and Updates) can be done even if transaction is not complete or not

*Repeatable Read. Will be Read commited + any update can happen only after the END TRANSACTION but insert command(Phantom insert) will do the changes even if data is not committed.

*Serializable. Rows can not be inserted using INSERT command and niether can UPDATE command work in uncommitted transaction nor can uncommitted data be read

*Snapshot.  If there are two transactions T1 and T2. Commmitted data will be seen only after both these transactions are committed. If these two transactions are conflicting with each other then transaction will fail completely and transaction will be rollback

A: You need to first understand underline problems that isolation level resolves.

*

*Dirty read(I saw updated record however it disappeared again)

*Non repeatable read(Update - I saw an updated value but now value has
changed. Oh someone rolled back.)

*Phantom read(Insert - This appeared as a ghost and then disappeared)

Try to play around on two connections. First run connection 1 script then connection 2 script without committing anything. Once both scripts are executed then try to commit connection 1.
READ UNCOMMITTED - Connection running under this isolation level can read rows that have been modified by other transactions but not yet committed.
READ COMMITTED - Connection running under this isolation level cannot read data that has been modified but not committed by other transactions.
REPEATABLE READ -  Transaction running under this isolation level cannot read data that has been modified but not yet committed by other transactions and that no other transactions can modify data that has been read by this transaction until the this transaction completes. This is done by placing shared lock on records read by this transaction. Having a shared on lock record, no other transaction can modify this record until this transaction completes.
SERIALIZABLE - Same conditions as we have for repeatable read with an addition of one more condition i.e. Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.
Think of a record as inserting a record between date range. You are trying to insert a record between the date range read by another connection.
DIRTY READ
Connection 1
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
BEGIN TRAN

UPDATE tbl SET Col1 = 'Dummy' WHERE ID = 1

--NO COMMIT YET

Connection 2
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN TRAN

SELECT * FROM tbl WHERE ID = 1 -- will return you 'Dummy' if script
                                  on connection 1 executed first. Since transaction on
                                  connection 1 hasn't been committed yet, you did a dirty
                                  read on connection 2.

--NO COMMIT YET

Avoiding Non repeatable read
Connection 1
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
BEGIN TRAN

SELECT * FROM tbl WHERE id = 5 --Issue shared lock.  This prevents
                               other transactions from modifying any
                               rows that have been read by the current transaction.

--Not committed yet

Connection 2
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
BEGIN TRAN

SELECT * FROM tbl WHERE id = 5
UPDATE tbl set name='XYZ' WHERE ID = 5 -- this will wait until transaction
                                       at connection 1 is completed.
                                      (Shared lock has been taken)
--Not committed yet

Avoiding Phantom read
Connection 1
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRAN

SELECT * FROM tbl WHERE Age BETWEEN 5 AND 15 -- This will issue range lock

--Not committed yet

Connection 2
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
BEGIN TRAN

INSERT INTO tbl (Age) VALUES(4) -- Will insert successfully
INSERT INTO tbl (Age) VALUES(7) -- this will wait until transaction
                                       at connection 1 is completed.
                                      (Range lock has been taken)
--Not committed yet


Q: Bug in VC++ 14.0 (2015) compiler? I've been running into some issues that only occurred during Release x86 mode and not during Release x64 or any Debug mode. I managed to reproduce the bug using the following code:
#include <stdio.h>
#include <iostream>
using namespace std;

struct WMatrix {
    float _11, _12, _13, _14;
    float _21, _22, _23, _24;
    float _31, _32, _33, _34;
    float _41, _42, _43, _44;

    WMatrix(float f11, float f12, float f13, float f14,
            float f21, float f22, float f23, float f24,
            float f31, float f32, float f33, float f34,
            float f41, float f42, float f43, float f44) :
        _11(f11), _12(f12), _13(f13), _14(f14),
        _21(f21), _22(f22), _23(f23), _24(f24),
        _31(f31), _32(f32), _33(f33), _34(f34),
        _41(f41), _42(f42), _43(f43), _44(f44) {
    }
};

void printmtx(WMatrix m1) {
    char str[256];
    sprintf_s(str, 256, "%.3f, %.3f, %.3f, %.3f", m1._11, m1._12, m1._13, m1._14);
    cout << str << "\n";
    sprintf_s(str, 256, "%.3f, %.3f, %.3f, %.3f", m1._21, m1._22, m1._23, m1._24);
    cout << str << "\n";
    sprintf_s(str, 256, "%.3f, %.3f, %.3f, %.3f", m1._31, m1._32, m1._33, m1._34);
    cout << str << "\n";
    sprintf_s(str, 256, "%.3f, %.3f, %.3f, %.3f", m1._41, m1._42, m1._43, m1._44);
    cout << str << "\n";
}

WMatrix mul1(WMatrix m, float f) {
    WMatrix out = m;
    for (unsigned int i = 0; i < 4; i++) {
        for (unsigned int j = 0; j < 4; j++) {
            unsigned int idx = i * 4 + j; // critical code
            *(&out._11 + idx) *= f; // critical code
        }
    }
    return out;
}

WMatrix mul2(WMatrix m, float f) {
    WMatrix out = m;
    unsigned int idx2 = 0;
    for (unsigned int i = 0; i < 4; i++) {
        for (unsigned int j = 0; j < 4; j++) {
            unsigned int idx = i * 4 + j; // critical code
            bool b = idx == idx2; // critical code
            *(&out._11 + idx) *= f; // critical code
            idx2++;
        }
    }
    return out;
}

int main() {
    WMatrix m1(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
    WMatrix m2 = mul1(m1, 0.5f);
    WMatrix m3 = mul2(m1, 0.5f);

    printmtx(m1);
    cout << "\n";
    printmtx(m2);
    cout << "\n";
    printmtx(m3);

    int x;
    cin >> x;
}

In the above code, mul2 works, but mul1 does not. mul1 and mul2 are simply trying to iterate over the floats in the WMatrix and multiply them by f, but the way mul1 indexes (i*4+j) somehow evaluates to incorrect results. All mul2 does different is it checks the index before using it and then it works (there are many other ways of tinkering with the index to make it work). Notice if you remove the line "bool b = idx == idx2" then mul2 also breaks...
Here is the output:
1.000, 2.000, 3.000, 4.000
5.000, 6.000, 7.000, 8.000
9.000, 10.000, 11.000, 12.000
13.000, 14.000, 15.000, 16.000

0.500, 0.500, 0.375, 0.250
0.625, 1.500, 3.500, 8.000
9.000, 10.000, 11.000, 12.000
13.000, 14.000, 15.000, 16.000

0.500, 1.000, 1.500, 2.000
2.500, 3.000, 3.500, 4.000
4.500, 5.000, 5.500, 6.000
6.500, 7.000, 7.500, 8.000

Correct output should be...
1.000, 2.000, 3.000, 4.000
5.000, 6.000, 7.000, 8.000
9.000, 10.000, 11.000, 12.000
13.000, 14.000, 15.000, 16.000

0.500, 1.000, 1.500, 2.000
2.500, 3.000, 3.500, 4.000
4.500, 5.000, 5.500, 6.000
6.500, 7.000, 7.500, 8.000

0.500, 1.000, 1.500, 2.000
2.500, 3.000, 3.500, 4.000
4.500, 5.000, 5.500, 6.000
6.500, 7.000, 7.500, 8.000

Am I missing something? Or is it actually a bug in the compiler?

A: This afflicts only the 32-bit compiler; x86-64 builds are not affected, regardless of optimization settings. However, you see the problem manifest in 32-bit builds whether optimizing for speed (/O2) or size (/O1). As you mentioned, it works as expected in debugging builds with optimization disabled.
Wimmel's suggestion of changing the packing, accurate though it is, does not change the behavior. (The code below assumes the packing is correctly set to 1 for WMatrix.)
I can't reproduce it in VS 2010, but I can in VS 2013 and 2015. I don't have 2012 installed. That's good enough, though, to allow us to analyze the difference between the object code produced by the two compilers.
Here is the code for mul1 from VS 2010 (the "working" code):
(Actually, in many cases, the compiler inlined the code from this function at the call site. But the compiler will still output disassembly files containing the code it generated for the individual functions prior to inlining. That's what we're looking at here, because it is more cluttered. The behavior of the code is entirely equivalent whether it's been inlined or not.)
PUBLIC  mul1
_TEXT   SEGMENT
_m$ = 8                     ; size = 64
_f$ = 72                        ; size = 4
mul1 PROC
 ___$ReturnUdt$ = eax

    push    esi
    push    edi

    ; WMatrix out = m;

    mov ecx, 16                 ; 00000010H
    lea esi, DWORD PTR _m$[esp+4]
    mov edi, eax
    rep movsd

    ; for (unsigned int i = 0; i < 4; i++)
    ; {
    ;    for (unsigned int j = 0; j < 4; j++)
    ;    {
    ;       unsigned int idx = i * 4 + j; // critical code
    ;       *(&out._11 + idx) *= f; // critical code

    movss   xmm0, DWORD PTR [eax]
    cvtps2pd xmm1, xmm0
    movss   xmm0, DWORD PTR _f$[esp+4]
    cvtps2pd xmm2, xmm0
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    movss   DWORD PTR [eax], xmm1
    movss   xmm1, DWORD PTR [eax+4]
    cvtps2pd xmm1, xmm1
    cvtps2pd xmm2, xmm0
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    movss   DWORD PTR [eax+4], xmm1
    movss   xmm1, DWORD PTR [eax+8]
    cvtps2pd xmm1, xmm1
    cvtps2pd xmm2, xmm0
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    movss   DWORD PTR [eax+8], xmm1
    movss   xmm1, DWORD PTR [eax+12]
    cvtps2pd xmm1, xmm1
    cvtps2pd xmm2, xmm0
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    movss   DWORD PTR [eax+12], xmm1
    movss   xmm2, DWORD PTR [eax+16]
    cvtps2pd xmm2, xmm2
    cvtps2pd xmm1, xmm0
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    movss   DWORD PTR [eax+16], xmm1
    movss   xmm1, DWORD PTR [eax+20]
    cvtps2pd xmm1, xmm1
    cvtps2pd xmm2, xmm0
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    movss   DWORD PTR [eax+20], xmm1
    movss   xmm1, DWORD PTR [eax+24]
    cvtps2pd xmm1, xmm1
    cvtps2pd xmm2, xmm0
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    movss   DWORD PTR [eax+24], xmm1
    movss   xmm1, DWORD PTR [eax+28]
    cvtps2pd xmm1, xmm1
    cvtps2pd xmm2, xmm0
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    movss   DWORD PTR [eax+28], xmm1
    movss   xmm1, DWORD PTR [eax+32]
    cvtps2pd xmm1, xmm1
    cvtps2pd xmm2, xmm0
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    movss   DWORD PTR [eax+32], xmm1
    movss   xmm1, DWORD PTR [eax+36]
    cvtps2pd xmm1, xmm1
    cvtps2pd xmm2, xmm0
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    movss   DWORD PTR [eax+36], xmm1
    movss   xmm2, DWORD PTR [eax+40]
    cvtps2pd xmm2, xmm2
    cvtps2pd xmm1, xmm0
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    movss   DWORD PTR [eax+40], xmm1
    movss   xmm1, DWORD PTR [eax+44]
    cvtps2pd xmm1, xmm1
    cvtps2pd xmm2, xmm0
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    movss   DWORD PTR [eax+44], xmm1
    movss   xmm2, DWORD PTR [eax+48]
    cvtps2pd xmm1, xmm0
    cvtps2pd xmm2, xmm2
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    movss   DWORD PTR [eax+48], xmm1
    movss   xmm1, DWORD PTR [eax+52]
    cvtps2pd xmm1, xmm1
    cvtps2pd xmm2, xmm0
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    movss   DWORD PTR [eax+52], xmm1
    movss   xmm1, DWORD PTR [eax+56]
    cvtps2pd xmm1, xmm1
    cvtps2pd xmm2, xmm0
    mulsd   xmm1, xmm2
    cvtpd2ps xmm1, xmm1
    cvtps2pd xmm0, xmm0
    movss   DWORD PTR [eax+56], xmm1
    movss   xmm1, DWORD PTR [eax+60]
    cvtps2pd xmm1, xmm1
    mulsd   xmm1, xmm0
    pop edi
    cvtpd2ps xmm0, xmm1
    movss   DWORD PTR [eax+60], xmm0
    pop esi

    ; return out;
    ret 0
mul1 ENDP

Compare that to the code for mul1 generated by VS 2015:
mul1 PROC
_m$ = 8                         ; size = 64
; ___$ReturnUdt$ = ecx
; _f$ = xmm2s

    ; WMatrix out = m;

    movups  xmm0, XMMWORD PTR _m$[esp-4]

    ; for (unsigned int i = 0; i < 4; i++)

    xor eax, eax
    movaps  xmm1, xmm2
    movups  XMMWORD PTR [ecx], xmm0
    movups  xmm0, XMMWORD PTR _m$[esp+12]
    shufps  xmm1, xmm1, 0
    movups  XMMWORD PTR [ecx+16], xmm0
    movups  xmm0, XMMWORD PTR _m$[esp+28]
    movups  XMMWORD PTR [ecx+32], xmm0
    movups  xmm0, XMMWORD PTR _m$[esp+44]
    movups  XMMWORD PTR [ecx+48], xmm0
    npad    4
$LL4@mul1:

    ; for (unsigned int j = 0; j < 4; j++)
    ; {
    ;    unsigned int idx = i * 4 + j; // critical code
    ;    *(&out._11 + idx) *= f; // critical code

    movups  xmm0, XMMWORD PTR [ecx+eax*4]
    mulps   xmm0, xmm1
    movups  XMMWORD PTR [ecx+eax*4], xmm0
    inc eax
    cmp eax, 4
    jb  SHORT $LL4@mul1

    ; return out;
    mov eax, ecx
    ret 0
?mul1@@YA?AUWMatrix@@U1@M@Z ENDP            ; mul1
_TEXT   ENDS

It is immediately obvious how much shorter the code is. Apparently the optimizer got a lot smarter between VS 2010 and VS 2015. Unfortunately, sometimes the source of the optimizer's "smarts" is the exploitation of bugs in your code.
Looking at the code that matches up with the loops, you can see that VS 2010 is unrolling the loops. All of the computations are done inline so that there are no branches. This is kind of what you'd expect for loops with upper and lower bounds that are known at compile time and, as in this case, reasonably small.
What happened in VS 2015? Well, it didn't unroll anything. There are 5 lines of code, and then a conditional jump JB back to the top of the loop sequence. That alone doesn't tell you much. What does look highly suspicious is that it only loops 4 times (see the cmp  eax, 4 statement that sets flags right before doing the jb, effectively continuing the loop as long as the counter is less than 4). Well, that might be okay if it had merged the two loops into one. Let's see what it's doing inside of the loop:
$LL4@mul1:
  movups  xmm0, XMMWORD PTR [ecx+eax*4]   ; load a packed unaligned value into XMM0
  mulps   xmm0, xmm1                      ; do a packed multiplication of XMM0 by XMM1,
                                          ;  storing the result in XMM0
  movups  XMMWORD PTR [ecx+eax*4], xmm0   ; store the result of the previous multiplication
                                          ;  back into the memory location that we
                                          ;  initially loaded from

  inc      eax                            ; one iteration done, increment loop counter
  cmp      eax, 4                         ; see how many loops we've done
  jb       $LL4@mul1                      ; keep looping if < 4 iterations

The code reads a value from memory (an XMM-sized value from the location determined by ecx + eax * 4) into XMM0, multiplies it by a value in XMM1 (which was set outside the loop, based on the f parameter), and then stores the result back into the original memory location.
Compare that to the code for the corresponding loop in mul2:
$LL4@mul2:
  lea     eax, DWORD PTR [eax+16]
  movups  xmm0, XMMWORD PTR [eax-24]
  mulps   xmm0, xmm2
  movups  XMMWORD PTR [eax-24], xmm0
  sub     ecx, 1
  jne     $LL4@mul2

Aside from a different loop control sequence (this sets ECX to 4 outside of the loop, subtracts 1 each time through, and keeps looping as long as ECX != 0), the big difference here is the actual XMM values that it manipulates in memory. Instead of loading from [ecx+eax*4], it loads from [eax-24] (after having previously added 16 to EAX).
What's different about mul2? You had added code to track a separate index in idx2, incrementing it each time through the loop. Now, this alone would not be enough. If you comment out the assignment to the bool variable b, mul1 and mul2 result in identical object code. Clearly without the comparison of idx to idx2, the compiler is able to deduce that idx2 is completely unused, and therefore eliminate it, turning mul2 into mul1. But with that comparison, the compiler apparently becomes unable to eliminate idx2, and its presence ever so slightly changes what optimizations are deemed possible for the function, resulting in the output discrepancy.
Now the question turns to why is this happening. Is it an optimizer bug, as you first suspected? Well, no—and as some of the commenters have mentioned, it should never be your first instinct to blame the compiler/optimizer. Always assume that there are bugs in your code unless you can prove otherwise. That proof would always involve looking at the disassembly, and preferably referencing the relevant portions of the language standard if you really want to be taken seriously.
In this case, Mystical has already nailed the problem. Your code exhibits undefined behavior when it does *(&out._11 + idx). This makes certain assumptions about the layout of the WMatrix struct in memory, which you cannot legally make, even after explicitly setting the packing.
This is why undefined behavior is evil—it results in code that seems to work sometimes, but other times it doesn't. It is very sensitive to compiler flags, especially optimizations, but also target platforms (as we saw at the top of this answer). mul2 only works by accident. Both mul1 and mul2 are wrong. Unfortunately, the bug is in your code. Worse, the compiler didn't issue a warning that might have alerted you to your use of undefined behavior.

A: If we look at the generated code, the problem is fairly clear. Ignoring a few bits and pieces that aren't related to the problem at hand, mul1 produces code like this:
movss   xmm1, DWORD PTR _f$[esp-4] ; load xmm1 from _11 of source
; ...

shufps  xmm1, xmm1, 0               ; duplicate _11 across floats of xmm1
; ...

for ecx = 0 to 3 {
    movups  xmm0, XMMWORD PTR [dest+ecx*4] ; load 4 floats from dest
    mulps   xmm0, xmm1                     ; multiply each by _11
    movups  XMMWORD PTR [dest+ecx*4], xmm0 ; store result back to dest
}

So, instead of multiplying each element of one matrix by the corresponding element of the other matrix, it's multiplying each element of one matrix by _11 of the other matrix.
Although it's impossible to confirm exactly how it happened (without looking through the compiler's source code), this certainly fits with @Mysticial's guess about how the problem arose.


Q: Trying to flush database upon app reinstall - Titanium alloy Here is my code:
if (!Ti.App.Properties.hasProperty('installed')) {

    alert('This is my first run');

    //check first installed
    Ti.App.Properties.setBool('installed', 1);

    //store version number in Ti.App.Properties
    Ti.App.Properties.setString('currentVersion', Titanium.App.version);

    //import DB from Titanium's Resources directory or one of its descendants, if exist

    //create DB
    createDB();

}

//check app version
checkAppVersion();

function createDB() {

    //createDB
    var db = Ti.Database.open('appdb');
    alert('db created');

    db.close();

}

function checkAppVersion() {

    alert(Titanium.App.version);
    var curversion = Titanium.App.Properties.getString('currentVersion');
    var appversion = Titanium.App.version;

    if (curversion != appversion) {

        //flush database
        alert('flush database');
        flushDb();

    } else {

        //leave existing database
        alert('leave database alone!');

    }

}

function flushDb() {

    // Get database object reference to previous database, if any.
    // If it did not exist previously, this will create a new empty db.
    var dbOld = Ti.Database.open('appdb');

    // Now remove the database, whether it existed before or we just
    // created it above.  The remove() method requires a database object
    // reference, so we had to start by opening it above.
    dbOld.remove();
    dbOld.close();

    // At this point, whether or not there was a previous database it
    // is now gone.
        //store version number in Ti.App.Properties
    Ti.App.Properties.setString('currentVersion', Titanium.App.version);

    //create DB
    createDB();
}

Code works like this:
If app is freshly installed. Create a DB, set version and run app. Alloy models are then executed and everything runs fine.
The problem is when I flush the DB after a version change, I get a SQL error, complaining a table cannot be found after I have deleted it. Even though I have done a fresh reinstall of the DB.
To get it to work I have to quit app and reopen it. I have no idea why this is happening and I am pretty stuck.
UPDATE:
Coded a solution for this problem, but I am not happy with it.
When flushing the database, instead of deleting the database, I deleted all of the tables. And then in create DB, I basically called an SQL query to create the tables.
The problem here is that if I ever updated my models, I will have to update the schema in two places.
If anyone has a better solution, do let me know, cheers.


Q: Visual Studio: DLL locations for release I have a project that I am working on that references a "Common Library (DLL)". In the DevEnv it works fine, however if I build and try to organize my files it doesn't work. Basically if I have things setup like so:

*

*C:\Program Files\MyApp\MyApp.exe

*C:\Program Files\MyApp\Common\WPF Commons.dll

*C:\Program Files\MyApp\Modules\SomeModule.dll

*etc

MyApp.exe doesn't work. It tries to look only in the current directory for the DLL files. So how do I set it up in Visual Studio so that when I build the application knows to look for the DLLs in those other folders?
Oh, and I realize that it does work in Dev because all the DLLs are put in the same folder. I don't want to do that for release though :-/

A: What you need to do is add a private probing path into the application configuration file. This tells the CLR which directories to look in for extra assemblies.

*

*http://msdn.microsoft.com/en-us/library/823z9h8w.aspx
Sample app.config
<configuration>
   <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
         <probing privatePath="Common;Modules"/>
      </assemblyBinding>
   </runtime>
</configuration>


Q: I'm a prolog newbie and I'm stuck in a program Goal:
Apply a loop in the above given code so that it will ask, “Do you want to continue? (Y/ N)”        and then act accordingly. (Hint: make a predicate ‘again/0’ for doing above task).
go:-
    write('What is the name of Patient?'),
    read(Patient),nl,
    hypo(Patient, Disease),
    write(Patient),
    write(' probably has '),
    write(Disease),nl.

go:-
    write('Sorry I am unable to diagnose the Disease.'),nl.

hypo(Patient,flu):-
    sym(Patient,fever),
    sym(Patient,cough).
hypo(Patient,headche):-
    sym(Patient,bodypain).
sym(Patient,fever):-
    write(' Does '),
    write(Patient),
    write(' has fever (y/n)?'),
    res(R),  R='y'.
sym(Patient,cough):-
    write('Does '),
    write(Patient),
    write(' has cough (y/n)?'),
    res(R),  R='y'.
sym(Patient,bodypain):-
    write('Does '),
    write(Patient),
    write(' has bodypain (y/n)?'),
    res(R),  R='y'.
res(R):-
    read(R),nl.

A: You've given a model with a go predicate. The trick is that you get a loop by calling a predicate again recursively if R='y' doesn't fail.
again :-
   write('Do you want to continue? (Y/ N)'),
   res(R),  R='y',
   go,
   again.
again :-
   write('OK, bye'),nl.


Q: Can't get this query to work. Mysql update select another query then update UPDATE `tombaldi_2bj3de9ad`.`catalog_product_option_type_value`
SET `catalog_product_option_type_value`.`option_id` = '72'
WHERE `catalog_product_option_type_value`.`option_id` IN
(SELECT  `catalog_product_option_type_value`.`option_id`
FROM `tombaldi_2bj3de9ad`.`catalog_product_option_type_title`
INNER JOIN `tombaldi_2bj3de9ad`.`catalog_product_option_type_value` ON catalog_product_option_type_title.option_type_id = catalog_product_option_type_value.option_type_id
 WHERE (
    CONVERT( `title` USING utf8 ) LIKE '%initials%'
 ))

I get the error

#1093 - You can't specify target table 'catalog_product_option_type_value' for update in FROM clause

Trying to solve this one. Have researched and tried and tried again.

A: In mysql you can't use same table in query during update,this can be done by giving the new alias to your subquery
UPDATE tombaldi_2bj3de9ad.catalog_product_option_type_value
SET catalog_product_option_type_value.option_id = '72'
WHERE catalog_product_option_type_value.option_id
IN (SELECT t.option_id
FROM (
SELECT catalog_product_option_type_value.option_id
FROM tombaldi_2bj3de9ad.catalog_product_option_type_title
INNER JOIN tombaldi_2bj3de9ad.catalog_product_option_type_value
 ON catalog_product_option_type_title.option_type_id = catalog_product_option_type_value.option_type_id
WHERE ( CONVERT( title USING utf8 ) LIKE '%initials%' )
)  t
)

Or even better to use join in your update query
UPDATE
  tombaldi_2bj3de9ad.catalog_product_option_type_value cv
  JOIN tombaldi_2bj3de9ad.catalog_product_option_type_title  ct
  ON(ct.option_type_id = cv.option_type_id )
SET
  cv.option_id = '72'
WHERE CONVERT(ct.title USING utf8) LIKE '%initials%'


Q: Run Ajax from java script function in tpl file PRESTASHOP Im working on a PrestaShop payment method and I have a tpl page with a button and a div which is hidden. On the button click, I want to execute an ajax function and show the div on success, but its not doing anything.
HTML Elements:
<input id="showVerifCode" type="button" value="Get Verification Code" style="background: #3e64ff; border-color: #3e64ff; color: #fff; padding: 11px 16px; cursor: pointer; border-width: 1px; border-radius: 2px; font-size: 14px; font-weight: 400; margin-top: 16px; margin-bottom: 0px;">

Please check your mail for the verification code!

Verification Code:

    <input placeholder="E.g 1234567890" width="50px" name="verifCode" required type="text" style="margin-top: 1px; width: 100%; padding: 12px 20px; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box;"/>

JavaScript Function:
{literal}

  {/literal}

PHP Ajax page (located in /modules/my_module/AjaxSendMail.php
<?php
return;

I only have this return there because I want to test out the ajax part first.
Sorry if this a very noob question but this is the first time I am using ajax, and I am no PHP or JavaScript master either.
Thank you in advance.
EDIT: I have tried using JQuery but the result is the same. I made sure the code runs when the button is pressed by only making it show the hidden div and it works, but not when I put the ajax code.

EDIT 2: The link was why this was giving problems. I have change to url to url: '{/literal}{$link}{literal}', but the request on my browser tools still gives a 404 not found despite the path looking alright to me.
Image of Request
EDIT 3: I fixed it. The issue was still with the url. The final method is as follows:
$link = $this->context->link->getModuleLink($this->name, 'ajax', array('ajax'=>true), true);


Q: Extremely simple Swift signal SIGABRT
I fail to understand why my app is giving me a Thread 1: signal SIGABRT error.
I basically have a text field that I only want to be numbers, do a calculation when the button is pressed an put it in the other label.
I had more code around it with more boxes and buttons and simplified it to this and it still doesn't work!
Thank you!

A: I suggest you to check the following thread: Thread 1: signal SIGABRT in Xcode 9
Quoting from my answer:

SIGABRT happens when you call an outlet that is not there.

*

*No view is connected

*Duplicate might be there

  Outlets are references to storyboard/xib-based UI elements inside
  your view controller. Make sure whatever you are trying to call is
  there.


Q: How to implement input JSON validation in Grails? What is the correct way of implementing request body (JSON, XML) sent with POST or PUT method in Grails framework?
In Spring there is a @Valid annotation used to annotate method's argument and a bunch of field annotations (@NotNull e.g.) and exception mapper used to send validation response automatically. I can't find anything similar in Grails.

A: Grails performs validation via a Domain's constraints block.  For example:
class User {
  String username
  String password

  static constraints = {
    username nullable: false, maxSize: 50, email: true
    password nullable: false, maxSize: 64
  }
}

See documentation.
Validation is performed during a couple of different actions on the domain:
user.save() // validates and only persists if no errors
user.validate() // validates only

Again, see the documentation.  This is similar to what Spring's @Valid does.  Looking at its documentation, it states:

Spring MVC will validate a @Valid object after binding so-long as an
  appropriate Validator has been configured.

What makes this basically the same as what Grails is doing is that it occurs after binding.  For JSON/XML to Domain object conversion, it is really as simple as this:
def jsonObject = request.JSON
def instance = new YourDomainClass(jsonObject)

See this answer here.


Q: Vista services: Can show form on invisible desktop? I am attempting to show a form from a service on Vista (using .NET winforms)
Obviously the form would not show to the console user, as services are isolated in session 0.
However the experiment is to see if it is possible to "show" an invisible form and obtain a window handle & message loop
I have tried but when I issue form.Show(), only the form.Load event fires not .Shown or .FormClosing
Is there any way to capture windows messages in this way as a user application would?
I have not attempted to make the service 'interactive' as I do not wish to interact with the logged-on user.

A: Yes you can show a form on a service's desktop. It will not be shown to any logged in user, in fact in Vista and later OSes you cannot show it to a user even if you set the service to 'interactive'. Since the desktop is not interactive the windows messages the form receives will be slightly different but the vast majority of the events should be triggered the same in a service as they would be on an interactive desktop (I just did a quick test and got the form load, shown, activated and closing events).
One thing to remember is that in order to show a form your thread must be an STA thread and a message loop must be created, either by calling ShowDialog or Applicaton.Run. Also, remember all external interaction with the form will need to be marshaled to the correct thread using Invoke or BeginInvoke on the form instance.
This is certainly very doable but is really not recommended at all. You must be absolutely sure that the form and any components it contains will not show any unexpected UI, such as a message box, under any circumstances. The only time this method can really be justified is when you are working with a dubious quality legacy or 3rd party tool that requires handle creation in order to function properly.


Q: In PowerShell, how to map a list to a search string PowerShell noob question here. I have groups of servers that are listed in separate lists. Each server has an error log that I scan for certain errors. However, each group of servers has its own unique set of errors that I scan using a specific search string for that server group. What I'm basically doing is creating a condition based on the server list name and mapping the appropriate search string for that server group.
Something like this:
$SERVER_LST_1 = "$pwd\servers\servers_1.lst"
$SERVER_LST_2 = "$pwd\servers\servers_2.lst"
$SERVER_LST_3 = "$pwd\servers\servers_3.lst"

$SEARCH_STR_1 = "Error text for server group 1"
$SEARCH_STR_2 = "Error text for server group 2"
$SEARCH_STR_3 = "Error text for server group 3"

$Servers1 = Get-Content $SERVER_LST_1
ForEach ($Server1 in $Servers1)
{
  $StartupErrorLog1 = Get-ChildItem -Path \\$Server1\$LOG_PATH -Include StartupError.log -Recurse | Select-String -notmatch $SEARCH_STR_1
}
$Servers2 = Get-Content $SERVER_LST_2
ForEach ($Server2 in $Servers2)
{
  $StartupErrorLog2 = Get-ChildItem -Path \\$Server2\$LOG_PATH -Include StartupError.log -Recurse | Select-String -notmatch $SEARCH_STR_2
}
$Servers3 = Get-Content $SERVER_LST_3
ForEach ($Server3 in $Servers3)
{
  $StartupErrorLog3 = Get-ChildItem -Path \\$Server3\$LOG_PATH -Include StartupError.log -Recurse | Select-String -notmatch $SEARCH_STR_3
}

I would like to make the code more efficient by not using so many conditions. Is there a cleaner approach to map the search strings to their appropriate server group by using less code? Hope that makes sense.

A: You can refactor it into something like below:
$groups = @{
"$pwd\servers\servers_1.lst"="Error text for server group 1";
"$pwd\servers\servers_2.lst"="Error text for server group 2";
"$pwd\servers\servers_3.lst"="Error text for server group 3";
}
$startupErrors = @{}
$groups.keys | %{
    $key = $_
    gc $key | %{
        $startupErrors[$_] = Get-ChildItem -Path \\$_\$LOG_PATH -Include StartupError.log -Recurse | Select-String -notmatch $groups["$key"]
    }
}

Basically, using an HashTable to associate the search text and the server group. Also, I have given only the refactoring solution, but the Get-ChildItem and Select-String may not be doing what you want to.


Q: getParent returns wrong ViewGroup When execute code below I can verify in my LogCat that getParent returns an other ViewGroup then FrameLayout (It returns LinearLayout). Normally I would expect that getParent would return the framelayout...
Does anyone know why this is occuring?
java:
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button button = (Button) findViewById(R.id.actionbar_btn);
        if (button.getParent() instanceof FrameLayout) {
            Log.v("TAG", "parent was framelayout");
        } else {
            Log.v("TAG", "parent was no framelayout");
        }

    }

xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#00FF00"
        android:orientation="horizontal" >

        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <Button
                android:id="@+id/actionbar_home"
                android:layout_width="33dp"
                android:layout_height="32dp"
                android:background="@drawable/ic_launcher"
                />

        </FrameLayout>

        .....

    </LinearLayout>

</RelativeLayout>

A: Shouldn't you change your R.id.actionbar_btn to R.id.actionbar_home?

A: I think you are getting wrong id for Button:
 <Button
                    android:id="@+id/actionbar_home"
                    android:layout_width="33dp"
                    android:layout_height="32dp"
                    android:background="@drawable/ic_launcher"
                    />

final Button button = (Button) findViewById(R.id.actionbar_btn);

"R.id.actionbar_btn"  and  android:id="@+id/actionbar_home" should be same


Q: Can only scrape the base price with requests html In the product price listed below, I fail to scrape the prices of the more expensive options.
Strangely, I can save a direct URL link and see the correct price when the page loads. However, when I scrape the same link with requests-html, I only get the base price of the base product.
from requests_html import HTMLSession
url = 'https://www.staegerag.ch/shop/index.php?id_product=321&controller=product&search_query=level&results=2#/273-farbe-gold_tone_light_oak/233-sprachsteuerung-nein'
session = HTMLSession()
r = session.get(url)
print(r.html.find('span[id="our_price_display"]', first=True).text)

Results in 1'399.00 CHF instead of 1'699.00 CHF

A: After various google searches, i came across a simple solution. since i'm still a relatively new kid on the programming block, i didn't notice that my code didn't call chromium at all. my price to be scrapped is in java. I just had to render the page via: r.html.render() in chromium.
solution:
from requests_html import HTMLSession
url = 'https://www.staegerag.ch/shop/index.php?
id_product=321&controller=product&search_query=level&results=2#/273-farbe-
gold_tone_light_oak/233-sprachsteuerung-nein'
session = HTMLSession()
r = session.get(url)
r.html.render()
print(r.html.find('span[id="our_price_display"]', first=True).text)


Q: How can I unit test whether the ChangeNotifier's notifyListeners was called in Flutter/Dart? I'm using the provider package in our app and I want to test my ChangeNotifier class individually to have simple unit tests checking the business logic.
Apart from the values of ChangeNotifier properties, I also want to ensure that in certain cases (where necessary), the notifyListeners has been called, as otherwise, the widgets that rely on up-to-date information from this class would not be updated.
Currently, I'm indirectly testing whether the notifyListeners have been called: I'm using the fact that the ChangeNotifier lets me add a callback using its addListener method. In the callback that I add in our testing suite, I simply increment an integer counter variable and make assertions on that.
Is this the right way to test whether my ChangeNotifier calls its listeners? Is there a more descriptive way of testing this?
Here is the class I'm testing:
import 'package:flutter/foundation.dart';

class ExampleModel extends ChangeNotifier {
  int _value = 0;

  int get value => _value;

  void increment() {
    _value++;
    notifyListeners();
  }
}

and this is how I test it:
import 'package:mobile_app/example_model.dart';
import 'package:test/test.dart';

void main() {
  group('$ExampleModel', () {
    ExampleModel exampleModel;
    int listenerCallCount;

    setUp(() {
      listenerCallCount = 0;
      exampleModel = ExampleModel()
        ..addListener(() {
          listenerCallCount += 1;
        });
    });

    test('increments value and calls listeners', () {
      exampleModel.increment();
      expect(exampleModel.value, 1);
      exampleModel.increment();
      expect(listenerCallCount, 2);
    });

    test('unit tests are independent from each other', () {
      exampleModel.increment();
      expect(exampleModel.value, 1);
      exampleModel.increment();
      expect(listenerCallCount, 2);
    });
  });
}

A: I've ran into the same Issue. It's difficult to test wether notifyListeners was called or not especially for async functions. So I took your Idea with the listenerCallCount and put it to one function you can use.
At first you need a ChangeNotifier:
class Foo extends ChangeNotifier{
  int _i = 0;
  int get i => _i;
  Future<bool> increment2() async{
    _i++;
    notifyListeners();
    _i++;
    notifyListeners();
    return true;
  }
}

Then the function:
Future<R> expectNotifyListenerCalls<T extends ChangeNotifier, R>(
    T notifier,
    Future<R> Function() testFunction,
    Function(T) testValue,
    List<dynamic> matcherList) async {
  int i = 0;
  notifier.addListener(() {
    expect(testValue(notifier), matcherList[i]);
    i++;
  });
  final R result = await testFunction();
  expect(i, matcherList.length);
  return result;
}

Arguments:

*

*The ChangeNotifier you want to test.

*The function which should fire notifyListeners (just the reference to the function).

*A function to the state you want to test after each notifyListeners.

*A List of the expected values of the state you want to test after each notifyListeners (the order is important and the length has to equal the notifyListeners calls).
And this is how to test the ChangeNotifier:
test('should call notifyListeners', () async {
  Foo foo = Foo();

  expect(foo.i, 0);

  bool result = await expectNotifyListenerCalls(
      foo,
      foo.increment2,
      (Foo foo) => foo.i,
      <dynamic>[isA<int>(), 2]);

  expect(result, true);
});

A: Your approach seems fine to me but if you want to have a more descriptive way you could also use Mockito to register a mock callback function and test whether and how often the notifier is firing and thus notifying your registered mock instead of incrementing a counter:
import 'package:mobile_app/example_model.dart';
import 'package:test/test.dart';

/// Mocks a callback function on which you can use verify
class MockCallbackFunction extends Mock {
  call();
}
void main() {
  group('$ExampleModel', () {
    late ExampleModel exampleModel;
    final notifyListenerCallback = MockCallbackFunction(); // Your callback function mock

    setUp(() {
      exampleModel = ExampleModel()
        ..addListener(notifyListenerCallback);
      reset(notifyListenerCallback); // resets your mock before each test
    });

    test('increments value and calls listeners', () {
      exampleModel.increment();
      expect(exampleModel.value, 1);
      exampleModel.increment();
      verify(notifyListenerCallback()).called(2); // verify listener were notified twice
    });

    test('unit tests are independent from each other', () {
      exampleModel.increment();
      expect(exampleModel.value, 1);
      exampleModel.increment();
      expect(notifyListenerCallback()).called(2); // verify listener were notified twice. This only works, if you have reset your mocks
    });
  });
}

Just keep in mind that if you trigger the same mock callback function in multiple tests you have to reset your mock callback function in the setup to reset its counter.

A: I have wrap it to the function
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';

dynamic checkNotifierCalled(
  ChangeNotifier notifier,
  Function() action, [
  Matcher? matcher,
]) {
  var isFired = false;
  void setter() {
    isFired = true;
    notifier.removeListener(setter);
  }

  notifier.addListener(setter);

  final result = action();
  // if asynchronous
  if (result is Future) {
    return result.then((value) {
      if (matcher != null) {
        expect(value, matcher);
      }
      return isFired;
    });
  } else {
    if (matcher != null) {
      expect(result, matcher);
    }
    return isFired;
  }
}

and call it by:
final isCalled = checkNotifierCalled(counter, () => counter.increment(), equals(2));
expect(isCalled, isTrue);


Q: error while passing the date value in the URL I want to pass the value which is of date format through the URL to the java controller, but it's throwing javascript errors near the date.
My URL is as below:
var dataUrl = myAppURL+'/detailData/'+adviceNum+'/'+dateCreated +'/myDetailData.form';

Below code is how i'm getting the date value.
                    dateCreated = new Date(value.dateCreated);
                    var dd = dateString.getDate();
                    var mm = dateString.getMonth()+1;
                    var yyyy = dateString.getFullYear();
                    if(dd<10) {
                        dd='0'+dd
                    }
                    if(mm<10) {
                        mm='0'+mm
                    }
                    dateCreated = yyyy + '-' + mm+'-'+dd;

dateCreated has the value 2015-01-20.
Error :
Failed to load the resource: the server : 8080/detailData/23/detailData/myDetailData.form responded with status of 404.
Please advice how can i pass the dateCreated value to java controller.

A: Is "dateString" supposed to be "dateCreated"?
This code works:
var dateCreated = new Date('2015-01-20');
var dd = dateCreated.getDate();
var mm = dateCreated.getMonth()+1;
var yyyy = dateCreated.getFullYear();
if(dd<10) {
    dd='0'+dd
}
if(mm<10) {
    mm='0'+mm
}
dateCreated = yyyy + '-' + mm+'-'+dd;
;
console.log(dateCreated, typeof(dateCreated));

2015-01-20 string


Q: Add element to own c++ template class with overloading operator+= I have to write a header file to an existing cpp with making an own template class. There is a simple add method but I have to overload the operator+= function.
If I try to add the elements separately, like this:
ls += lmb;
ls += lmc;

than it works well, but if I try to do it like in the cpp file:
(ls += lmb) += lmc;

than it doesn't work, it only add one element.
It's important: I can't change the cpp file!
The cpp look like this:
#include <iostream>
#include "mapalign.h"
#include <string>
#include <algorithm>
#include <map>
#include "mapalign.h"

struct string_size_less
{

  bool operator()( const std::string& a,
                   const std::string& b ) const
  {
    return a.size() < b.size();
  }

};

const int max = 1000;

bool check()
{

  std::map<std::string, int> sma;
  std::map<std::string, int> smb;
  std::map<std::string, int> smc;

  map_aligner<std::string, int> sa;
  sa.add( sma );
  sa.add( smb );
  sa.add( smc );

  sma[ "C++" ] = 1;
  smb[ "Ada" ] = 2;
  smc[ "C" ] = 3;
  smc[ "Python" ] = 4;
  smc[ "Ada"] = 5;

  sa.align();

  std::map<int, double> ima;
  std::map<int, double> imb;
  for( int i = 0; i < max; ++i )
  {
    if ( 0 == i % 2 )
    {
      ima[ i ] = max - i;
    }
    else
    {
      imb[ i ] = max;
    }
  }

  map_aligner<int, double> ia;
  ia.add( ima );
  ia.add( imb );

  ia.align();

  if ( ( 4 != sma.size() && 1 != imb.count( 0 )) || max * 1U != ima.size() ||
       1 != smc.count( "C++" ) || "Ada" != sma.begin()->first ||
       0 != sma.begin()->second ||  4 != smc.size() ||
       1 != smb.count( "Python" ) || 0 != imb.begin()->first ||
       0.8 <= imb.begin()->second || 1 != imb.count( max / 2 ) )
  {
    return false;
  }

  sma[ "Pascal" ] = 5;
  sa.set_filler( max );
  sa.align();

  std::map<std::string, std::string> langsa;
  langsa[ "C++" ] = "<3";
  langsa[ "Python" ] = ":|";
  std::map<std::string, std::string> langsb;
  langsb[ "Brainfuck" ] = ":S";
  langsb[ "Python" ] = ":/";
  langsb[ "C" ] = ":)";

  map_aligner<std::string, std::string> lsa;
  lsa.add( langsa );
  lsa.add( langsb );

  lsa.align();
  lsa.erase( "Python" );

  if ( 0 != langsa.count( "Python" ) || max != smc[ "Pascal" ] ||
       !langsa.begin()->second.empty() || max != smb[ "Pascal" ] ||
       2 * 1U != langsb.begin()->second.size() ||
       0 != langsb.count( "Python" ) || 1 != langsb.count( "C++" ) )
  {
    return false;
  }

  std::map<std::string, std::string, string_size_less> lma;
  std::map<std::string, std::string, string_size_less> lmb;
  std::map<std::string, std::string, string_size_less> lmc;

  lma[ "C++" ] = ":D";
  lmb[ "Eiffel" ] = ":P";
  lmc[ "C" ] = "8-)";
  lmc[ "Ada" ] = "!";

  map_aligner<std::string, std::string, string_size_less> ls;
  ls.add( lma );
  (ls += lmb) += lmc;

  ls.align();

  std::cout << ls.count() << "\n";
  std::cout << lmb.size() << "\n";

  std::cout << (3 == ls.count()) << (1 == lmc.count( "Ada" )) <<
       (3 * 1U == lmb.size()) << (1 == lma.count( "Python" )) <<
       (2 == lsa.count()) << (2 == ia.count()) << "\n" ;

  return ( 3 == ls.count() && 1 == lmc.count( "Ada" ) &&
       3 * 1U == lmb.size() && 1 == lma.count( "Python" ) &&
       2 == lsa.count() && 2 == ia.count() );
}

int main()
{
  std::cout
    << "Your solution is "
    << (check() ? "" : "not ")
    << "ready for submission."
    << std::endl;
}

This is my operator+= function now:
            map_aligner operator+=(std::map<KEY, VALUE, COMPARE>& m){
                maps_.push_back(&m);
                map_aligner ma = *this;
                return ma;
            }

The whole header look like this:
#ifndef MAPALIGN_H
#define MAPALIGN_H

#include <vector>
#include <map>
#include <typeinfo>

template<typename KEY, typename VALUE, typename COMPARE = std::less<KEY>>
class map_aligner{

    public:
            typedef typename std::map<KEY, VALUE, COMPARE>::size_type size_type;

            map_aligner() {}

            void add(std::map<KEY, VALUE, COMPARE>& m) {
                maps_.push_back(&m);
            }

            map_aligner operator+=(std::map<KEY, VALUE, COMPARE>& m){
                maps_.push_back(&m);
                map_aligner ma = *this;
                return ma;
            }

            size_type count() const {
                return maps_.size();
            }

            void align(){
                for(int i = 0; i != (int)maps_.size(); i++ ){
                    std::map<KEY, VALUE, COMPARE>* first_map = maps_.at(i);
                    for(typename std::map<KEY, VALUE, COMPARE>::iterator j = first_map->begin(); j !=first_map->end(); j++ ){
                        for(int h = 0; h != (int)maps_.size(); h++ ){
                            std::map<KEY, VALUE, COMPARE>* second_map = maps_.at(h);
                            if(first_map != second_map && notContainsPair(second_map, j)){
                                second_map->insert(std::make_pair(j->first, filler_));
                            }
                        }
                    }
                }
            }

            bool notContainsPair(std::map<KEY, VALUE, COMPARE>* map,typename std::map<KEY, VALUE, COMPARE>::iterator it){
                for(typename std::map<KEY, VALUE, COMPARE>::iterator g = map->begin(); g != map->end(); g++ ){
                    if(it->first != g->first){
                        return true;
                    }
                }
                return false;
            }

            void set_filler(VALUE filler){
                filler_ = filler;
            }

            void erase(KEY key){
                for(int h = 0; h != (int)maps_.size(); h++ ){
                    std::map<KEY, VALUE>* map = maps_.at(h);
                    typename std::map<KEY, VALUE, COMPARE>::iterator it;
                    map->erase(key);
                    if(typeid(it->first) == typeid(it->second)){
                        for(it = map->begin(); it != map->end(); it++){
                            if(key == it->second){
                                map->erase(it->first);
                            }
                        }
                    }
                }
            }

    private:
        std::vector<std::map<KEY, VALUE, COMPARE>*> maps_;
        VALUE filler_ = VALUE();
};

#endif


Q: ngFor with ngIf

             {{ shop.name }}

It's created empty a tags but I need

             {{ shop.name }}

This code throws an error.

core.es5.js:1084 ERROR Error: Uncaught (in promise): Error: Template
  parse errors: Can't have multiple template bindings on one element.
  Use only one attribute named 'template' or prefixed with *
  ("lledby="selectShop">

]*ngIf="shop._id == s">{{ shop.name }}

"):

How can I fix this problem?


Q: Search node/text() from (Result Tree Fragment) my templates (XSLT 1.0)

<xsl:template name="doo">

    <xsl:variable name="nodelist">
        <root>

                <sex>male</sex>
                Hulk

                <sex>male</sex>
                Steven XXXXXXXXXXX

        </root>
    </variable>

    <xsl:call-template name="findString">
       <xsl:with-param name="content1" select="$nodelist"></xsl:with-param>
    </xsl:call-template>

</xsl:template>

<xsl:template name="findString">
    <xsl:param name="content1" select="."></xsl:param>

</xsl:template>

is this possible like
for each node in Tree Fragment from myvariable
if node/text()='xxxxxxxx'
  do something

A: With xslt version=1.0 you can use a extension "not-set".
<xsl:call-template name="findString">
   <xsl:with-param name="content1" select="exsl:node-set($nodelist)"></xsl:with-param>
</xsl:call-template>

To make it  woke you have to add following lines.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:exsl="http://exslt.org/common"
    extension-element-prefixes="exsl"
    version="1.0">

Update:
Based on solution from Mads Hansen
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0"
    xmlns:exsl="http://exslt.org/common"
    extension-element-prefixes="exsl">
    <xsl:template name="doo">
        <xsl:variable name="nodelist">
            <root>

                    <sex>male</sex>
                    Hulk

                    <sex>male</sex>
                    Steven XXXXXXXXXXX

            </root>
        </xsl:variable>
        aaa
        <xsl:call-template name="findString">
            <xsl:with-param name="content1" select="exsl:node-set($nodelist)"></xsl:with-param>
        </xsl:call-template>
    </xsl:template>
    <xsl:template match="/">
        <xsl:call-template name="doo" />
    </xsl:template>

    <xsl:template name="findString">
        <xsl:param name="content1" select="."></xsl:param>

        <xsl:apply-templates mode="mytext" select="$content1"/>

    </xsl:template>

    <xsl:template match="@*|node()" mode="mytext">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" mode="mytext"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="text()[contains(.,'XXXXXXXXXXX')]"  mode="mytext">
        <xsl:variable name="findString" select="'XXXXXXXXXXX'"/>
        <xsl:variable name="replaceString" select="'YYYYYYYYYYYY'"/>
        <xsl:value-of select="concat(substring-before(., $findString),
                                    $replaceString,
                                    substring-after(., $findString))"/>
    </xsl:template>

</xsl:stylesheet>


Q: cUrl alternatives to get POST answer on a webpage I would like to get the resulting web page of a specific form submit. This form is using POST so my current goal is to be able to send POST data to an url, and to get the HTML content of the result in a variable.
My problem is that i cannot use cUrl (not enabled), that's why i ask for your knowledge to know if an other solution is possible.
Thanks in advance

A: See this, using fsockopen:
http://www.jonasjohn.de/snippets/php/post-request.htm
Fsockopen is in php standard library, so all php fron version 4 has it :)

A: try file_get_contents() and stream
$opts = array(  'http'=>array('method'=>"POST", 'content' => http_build_query(array('status' => $message)),));

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);


Q: Perf profiling shows wrong call-graph I am trying to profile my code.
After running perf, the resulting flame graph looks like that:

The 30% left follows my program calling graph. The 70% on the right are various samples, which are incorrectly detached from the left 30%, as they are always called from these 30%.
So, the 30% left should in fact stretched to 100%, and the right 70% should be on top.
Why is perf loosing track of callers in stack at some point?


Q: Android: Having trouble getting html from webpage I'm writing an android application that is supposed to get the html from a php page and use the parsed data from thepage.  I've searched for this issue on here, and ended up using some code from an example another poster put up.  Here is my code so far:
HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    try {
        Log.d("first","first");
        HttpResponse response = client.execute(request);
        String html = "";
        Log.d("second","second");
        InputStream in = response.getEntity().getContent();
        Log.d("third","third");
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        Log.d("fourth","fourth");
        StringBuilder str = new StringBuilder();
        String line = null;
        Log.d("fifth","fifth");
        while((line = reader.readLine()) != null) {
            Log.d("request line",line);
        }
        in.close();
    } catch (ClientProtocolException e) {

    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.d("error", "error");
    }
    Log.d("end","end");
}

Like I said before, the url is a php page.  Whenever I run this code, it prints out the first first message, but then prints out the error error message and then finally the end end message.  I've tried modifying the headers, but I've had no luck with it.  Any help would be greatly appreciated as I don't know what I'm doing wrong.
Thanks!
When I do e.getMessage() and print that out, in the logger all it says is stanford.edu.  Hope that helps.  Here is the stack trace:
01-17 16:58:27.687: WARN/System.err(452): java.net.UnknownHostException: stanford.edu
01-17 16:58:27.947: WARN/System.err(452):     at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
01-17 16:58:27.947: WARN/System.err(452):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
01-17 16:58:27.977: WARN/System.err(452):     at java.net.InetAddress.getAllByName(InetAddress.java:256)
01-17 16:58:27.977: WARN/System.err(452):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
01-17 16:58:28.027: WARN/System.err(452):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-17 16:58:28.027: WARN/System.err(452):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-17 16:58:28.047: WARN/System.err(452):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)
01-17 16:58:28.057: WARN/System.err(452):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-17 16:58:28.057: WARN/System.err(452):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-17 16:58:28.117: WARN/System.err(452):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-17 16:58:28.117: WARN/System.err(452):     at edu.stanford.cs247.util.ColorHandler.getInfo(ColorHandler.java:44)
01-17 16:58:28.217: WARN/System.err(452):     at edu.stanford.cs247.util.ColorHandler.handleMessage(ColorHandler.java:70)
01-17 16:58:28.217: WARN/System.err(452):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-17 16:58:28.247: WARN/System.err(452):     at android.os.Looper.loop(Looper.java:123)
01-17 16:58:28.257: WARN/System.err(452):     at android.app.ActivityThread.main(ActivityThread.java:3647)
01-17 16:58:28.257: WARN/System.err(452):     at java.lang.reflect.Method.invokeNative(Native Method)
01-17 16:58:28.297: WARN/System.err(452):     at java.lang.reflect.Method.invoke(Method.java:507)
01-17 16:58:28.297: WARN/System.err(452):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-17 16:58:28.327: WARN/System.err(452):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-17 16:58:28.337: WARN/System.err(452):     at dalvik.system.NativeStart.main(Native Method)

A: First of all, the Log.d() method calls may be something like Log.d("MyAppName", "Message") not Log.d("Message", "Message") In this way you can create a filter in LogCat for your app and see only your messages. (Check this on Eclipse)
For your problem, try putting some useful message in the catch block, something like:
try{
...
} catch (IOException e){
Log.d("MyAppName", e.getMessage());
}

This will show you the problem that throw the exception.
Consider take a look to this sample code, the getUrlContent() do exactly what you wont.
Good luck

A: The first line of your stacktrace says:

java.net.UnknownHostException:
  stanford.edu

You should learn to read stacktraces.  A quick search for "UnknownHostException" tells you it is:

Thrown to indicate that the IP address
  of a host could not be determined.

This means that it can't turn stanford.edu into an IP.  You probably need www.stanford.edu or something like that.  Try pinging the address on the command line ping www.stanford.edu , and make sure it resolves to an ip address.

A: I forgot to add the internet permission in my manifest file.

A: add to Manifest
<uses-permission android:name="android.permission.INTERNET" />


Q: Regarding fltk installation I am new to c++ and overall programming. I tried reading one book by Bjarne Stroustrup he mentioned in the very first chapter to first install fltk and write the code. Should I install fltk or use online compiler. If I should install fltk then please tell how as I am unable to do so. Thank you.
I tried downloading and unzipping the fltk file two times. It got unzipped but the fltk.snl file is getting opened by visual studios but othing is happening since I am unable to run c++ code in VS.


Q: How to update the single property from array of object using setState (with a class component)? I have an array of objects in this.state, and I am trying to update the single property from the array of objects.
This is my object
 this.state = {
  persons: [
    { name: "name1", age: 1 },
    { name: "name2", age: 2 },
    { name: "name3", age: 3 }
  ],
  status: "Online"
};

and i tried to update the persons[0].name
import React, { Component } from "react";
class App extends Component {
      constructor() {
        super();
        this.state = {
          persons: [
            { name: "John", age: 24 },
            { name: "Ram", age: 44 },
            { name: "Keerthi", age: 23 }
          ],
          status: "Online"
        };
      }
      changeName() {
        console.log(this);
        this.setState({
         persons[0].name: "sdfsd"
        });
      }

      render() {
        return (
        <button onClick={this.changeName.bind(this)}>change name</button>
        );
      }
    }

am getting an error.

A: You should code:
let persons = [...this.state.persons]
persons[0].name= "updated name"
this.setState({ persons })

A: using dot operator we can achieve this.
    let persons = [...this.state.persons]
persons[0].name= "updated name"
this.setState({ persons })

A: Proble with that you mutate component state, below it's example of immutable changing, I recommend you to read articles about how to change react state. Or you can try to use Mobx because it supports mutability
changePerson(index, field, value) {
  const { persons } = this.state;

  this.setState({
    persons: persons.map((person, i) => index === i ? person[field] = value : person)
  })
}

// and you can use this method
this.changePerson(0, 'name', 'newName')

A: this.setState(state => (state.persons[0].name = "updated name", state))

A: Assuming some conditional check to find the required person.
const newPersonsData = this.state.persons.map((person)=>{
    return person.name=="name1" ? person.name="new_name" : person);
                      //^^^^^^^ can be some condition
});

this.setState({...this.state,{person:[...newPersonsData ]}});

A: I think the best way is to copy the state first in temporary variable then after update that variable you can go for setState
let personsCopy = this.state.persons
personsCopy [0].name= "new name"
this.setState({ persons: personsCopy  })

A: Here's how I would do it.
See if that works for you.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      persons: [
        { name: "John", age: 24 },
        { name: "Ram", age: 44 },
        { name: "Keerthi", age: 23 }
      ],
      status: "Online"
    };
    this.changeName = this.changeName.bind(this);
    this.changeAge = this.changeAge.bind(this);
  }

  changeName(value,index) {
    this.setState((prevState)=>{
      const aux = prevState.persons;
      aux[index].name = value;
      return aux;
    });
  }

  changeAge(value,index) {
    this.setState((prevState)=>{
      const aux = prevState.persons;
      aux[index].age = value;
      return aux;
    });
  }

    render() {
      const personItems = this.state.persons.map((item,index)=>
        <React.Fragment>
          <input value={item.name} onChange={(e)=>this.changeName(e.target.value,index)}/>
          <input value={item.age} onChange={(e)=>this.changeAge(e.target.value,index)}/>

        </React.Fragment>
      );

      return(
        <React.Fragment>
          {personItems}

{JSON.stringify(this.state.persons)}

        </React.Fragment>
      );

    }
}

ReactDOM.render(<App/>, document.getElementById('root'));


Q: How do I replace only PART of an image source on hover using jquery?
Personal
 Information

This is what i trying
$(".navbar-nav li a").hover(function(){
        $(this).children("img").attr('src').replace('hover','static');
});

A: Firstly your arguments to replace() are the wrong way around. Secondly, you need to actually set the value after making the replacement. Lastly you'll also need to provide another function argument to hover() that sets the original image back on mouseout. Try this:

$(".navbar-nav li a").hover(function() {
  $(this).children("img").prop('src', function(i, src) {
    return src.replace('static', 'hover');
  })
}, function() {
  $(this).children("img").prop('src', function(i, src) {
    return src.replace('hover', 'static');
  })
});

      Personal
 Information

A: You are replacing src code, but not assigning it back.
$(".navbar-nav li a").hover(function(){
    var newSrc = $(this).children("img").attr('src').replace('hover','static');
     $(this).children('img').attr('src', newSrc)
});

A: Why are you targeting , then select its child ? Why not apply that to the image directly?
$(".navbar-nav li a img").hover(function(){
    $(this).attr('src') = $(this).attr('src').replace('hover','static');
});


Q: How can I let a set retain all strings that contain my specified substring in java? I use a hashset for a dictionary. Now I would like to filter out words that do not start with my substring. So it should be something like this:
String word = 'ab';
List<String> list = Arrays.asList(word);
boolean result = lexiconSet.retainAll(list);

And instead of this resulting in the lexicon only containing the word 'ab', I would like to keep all words beginning with 'ab'. How can I do this?
I know I can convert the set to a string arraylist, and loop over all elements to see if the strings starts with 'ab', but since I think this can be time consuming and not efficient, I would like to hear better solutions. Thank you in advance!

A: With Java 8, life is easy:
list.removeIf(s -> !s.startsWith("ab"));

This will remove all elements that don't begin with "ab".
Note that you can use values() to retrieve the map's values and work directly on them, without the need to convert to ArrayList.


Q: Put File Mask on tFileList Component dynamically I was wondering if you let me know how I can set file mask for tFilelist component in Talend that it recognize date automatically and it will download only data for desired date?
I have tried some approach and I faced with some errors like "the method add (string) in the type list <String> is not applicable for the arguments (Date)"

A: There are two ways of doing it.

*

*Create context variable and use this variable in file mask.

*Directly use TalendDate.getDate() or any other date function in file mask.

See both of them in component
1st approach,

*

*Create context variable named with dateFilter as string type.

*Assign value to context.dateFilter=TalendDate.getDate("yyyy-MM-dd");

*Suppose you have file name as "ABC_2015-06-19.txt" then

*In tFileList file mask use this variable as follows.
"ABC_"+context.dateFilter+".*"
2nd approach

*

*In tFileList file mask use date function as follows.
"ABC_"+TalendDate.getDate("yyyy-MM-dd")+".*"
these are the two best way, you can make changes in file mask per your file names.


Q: Material Design Lite responsive CSS not working on a Mobile/Tablets or in the Chrome DevTools emulator When experimenting with the responsive features of Google's Material Design Lite, this code hides messages as expected when resizing the browser window, but when I look at my page in Chrome DevTools device emulator or on an actual device, it only shows the "Desktop" version. How do I fix my HTML?

     <link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.1/material.indigo-pink.min.css">

          You are on a desktop

          You are on a phone

          You are on a tablet

A: To fix MDL not scaling for different devices, add this line inside your HTML's  :
<meta name="viewport" content="width=device-width, initial-scale=1.0">


Q: Flutter Gridview button functionality to new screen with Firebase I've made a Gridview using Firebase and Streambuilder and Gridview.builder. This grid displays album titles, the album cover art for each album, and the artists that make each album. I'd like for each grid tile to be able to be pressed and navigate to a separate page with its specific album details. The plan was on press, the app would be able to identify the entire document the grid tile was referring to, move to a new page, and display the document in full to unveil the album details. The thing is, I don't know how to do that. Since snapshot.data.documents[index]['Title'] worked when iterating though all the documents to create the gridview, I thought that typing snapshot.data.documents[index] would work, but it just displays Instance of 'DocumentSnapshot' in the debug console. I'm out of ideas on how to tackle this, so any suggestions are welcome
My code is shown below
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final Services services = Services();
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: bgcolour,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: Icon(Icons.menu),
        title: Text("Home"),
        actions: <Widget>[
          Padding(padding: EdgeInsets.all(10), child: Icon(Icons.more_vert))
        ],
      ),
      body: StreamBuilder(
          stream: Firestore.instance.collection('music').snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) return const Text("Loading...");
            return GridView.builder(
              itemCount: snapshot.data.documents.length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2, childAspectRatio: 0.655172413),
              //cacheExtent: 1000.0,
              itemBuilder: (BuildContext context, int index) {
                var url = snapshot.data.documents[index]['Cover Art'];

                return GestureDetector(
                  child: Container(
                    width: 190.0,
                    child: Card(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(32)),
                      color: hexToColor(
                          snapshot.data.documents[index]['Palette'][0]),
                      elevation: 1,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          SizedBox(height: 12),
                          ClipRRect(
                              borderRadius: BorderRadius.circular(21.0),
                              child: Image.network(url,
                                  height: 180.0, width: 180)),
                          SizedBox(height: 10),
                          Text(
                              snapshot.data.documents[index]['Artist']
                                  .join(', '),
                              textAlign: TextAlign.center,
                              style: GoogleFonts.montserrat(
                                  textStyle: TextStyle(color: Colors.white),
                                  fontSize: 14,
                                  fontWeight: FontWeight.w300)),
                          SizedBox(height: 10),
                          Text(snapshot.data.documents[index]['Title'],
                              style: GoogleFonts.montserrat(
                                  textStyle: TextStyle(color: Colors.white),
                                  fontSize: 16,
                                  fontWeight: FontWeight.w600),
                              textAlign: TextAlign.center),
                        ],
                      ),
                    ),
                  ),
                  onTap: () {
                    print("Tapped ${snapshot.data.documents[index]}");
                  },
                );
              },
            );
          }
          ),
    );
  }
}

A: Is there an ID for your snapshot.data.documents[index]? If yes, add it to the end.
onTap: () {
     print("Tapped ${snapshot.data.documents[index]['the property you want']}");
},


Q: Unable to get text values present within strong tag using Selenium Java While trying to print values present with in strong tag using xpath I'm getting following exception:
org.openqa.selenium.NoSuchElementException: Unable to locate element: strong

This is my code :
WebElement eleText = driver.findElement(By.xpath("//strong"));
String testerName = eleText.getText();
System.out.println(testerName);

This is my webpage which I'm trying to get values within strong tag :

    heizil :
      " First Device Test"

    riya:
     " Second Device Test"

Expected output: heizil,riya
If this is not the proper way can any one suggest any other way of getting the values present in  tag

A: As per the given HTML text heizil is within  tag which is the immediate descendant of the  tag.

    heizil
    :

        ...
        ...

Solution
To print the text heizil you can use either of the following locator strategies:

*

*Using cssSelector and getAttribute("innerHTML"):
System.out.println(driver.findElement(By.cssSelector("a.activity > strong")).getAttribute("innerHTML"));

*Using xpath and getText():
System.out.println(driver.findElement(By.xpath("//a[@class='activity']/strong")).getText());

Ideally, to extract the text value, you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following locator strategies:

*

*Using cssSelector and getText():
System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a.activity > strong"))).getText());

*Using xpath and getAttribute("innerHTML"):
System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='a-link-normal' and @id='vvp-product-details-modal--product-title']"))).getAttribute("innerHTML"));


Q: File Level Tracking In Git (Files from multiple branches in same directory) Is there any script that lets one remember branch/commit seperatly for files in some directory so that one can simultaneously work on file1 on branch1 and file2 on branch2 in the same directory and have them commit appropriately.  If not I'll implement it myself.
My plan is to have hidden checkout directories for various branches/repos and populating the apparent checkout with links to these files so that commits simply committed their respective hidden branches but advice would be appreciated.  Thus one could do something like
mgit checkout branch1 filename/filegroup
mgit add filename   (automatically to it's correct branch/repo)
mgit commit  (automatically to it's correct branch/repo)

Before anyone tells me this is a bad idea or incorrect use of version control consider the application:
So often when writing academic documents in TeX you end up with loosely related files that you wish to keep in version control. The problem is that these files are related and can benefit from the history/merging info git provides but often different versions of the files need to be selected independently.  Most commonly you simply want to work on variant1 of some paper while also working of variant2 of another but you also have situations where TeX combines several files so it's important to be able to put your choice of variants in the same folder.
In short you have a bunch of distinct files with distinct names which often derive from each other (thesis becomes paper), benefit from being in a single repo but it is unwieldy to have a dozen different checkouts to work on whatever versions of each file currently need attention.

A: No, I don't think this is natively supported by git.
May be a local hook like a pre-commit one hook might try to check and checkout the right branch before allowing the commit to proceed.


Q: Are atomic operations on non-atomic types in C atomic? The C17 standard specifies a list of atomic operations. For example, an atomic read-write-modify operation on an atomic object of type A is defined in the standard as:
C atomic_fetch_add(volatile A *object, M operand);

But we can call atomic_fetch_add on non-atomic types:
static int x;
static int foo(void *arg) {
  atomic_fetch_add(&x, 3);
}

My question: is the above atomic_fetch_add operation on the non-atomic object x guaranteed to be atomic?

A:
on an atomic object of type A is defined in the standard
But we can call

GCC will accept it. But on clang you'll get an error.

is the above atomic_fetch_add operation on the non-atomic object x guaranteed to be atomic?

No. In the standard the behavior of the code you presented is not defined, there is no guarantee of any kind. From https://port70.net/~nsz/c/c11/n1570.html#7.17 :

5 In the following synopses:

*

*An A refers to one of the atomic types. [...]

And then all the functions are defined in terms of A, like in https://port70.net/~nsz/c/c11/n1570.html#7.17.7.5p2 :
C atomic_fetch_key(volatile A *object, M operand);
Atomic type is a type with _Atomic.


Q: convert ElasticSearch SearchResponse object to JsonObject I want to convert the elasticsearch search result to Json Object. I havent found any proper way to convert directly.
SearchResponse response = client.prepareSearch(index).setExplain(true).execute().actionGet();

response->JSON Object.

Is there any way to convert an ElasticSearch response to a Json Object?

A: In Java, you can directly convert the SearchResponse to JSONObject.
Below is the handy code.
SearchResponse SR = builder.setQuery(QB).addAggregation(AB).get();

JSONObject SRJSON = new JSONObject(SR.toString());

A: You need to use the SearchResponse.toXContent() method like this:
SearchResponse response = client.prepareSearch(index).setExplain(true).execute().actionGet();

XContentBuilder builder = XContentFactory.jsonBuilder();
response.toXContent(builder, ToXContent.EMPTY_PARAMS);
JSONObject json = new JSONObject(builder.string());