text:
Q: What is the vba regular expression for tab key? My string is "  1.1" which has one tab key at the front and I use the regular expression pattern ^\t to find it.
But I failed. So what is the VBA regular expression for the tab key?

A: The regex for this would be (specifically for 1.1) :
^[\t]1\.1

That said, it would be nice to see how you're implementing it in your VBA because, as GSerg says, VBA does not have native regex.

A: If you want to put a tab character before the "1.1" in your string you use Char(9) & "1.1"
If you want to find it, it may work. You would also like to try with vbTab


text:
Q: Не работает проверка If  private boolean checkPhoneNumber()
{
    EditText checkingPhoneNumber = (EditText)findViewById(R.id.Number);
    String phoneNumber = checkingPhoneNumber.getText().toString();
    if (phoneNumber.length()<8 || phoneNumber.length()>20)
    {
        return false;
    }
    else
    {
        return true;
    }
}
private boolean checkEmail()
{
    EditText checkingEmail = (EditText)findViewById(R.id.Email);
    String email = checkingEmail.getText().toString();
    if (email.matches("@") & email.matches("."))
    {
        Email = true;
        return true;
    }
    else
    {
        Email = false;
        return false;
    }
}
private boolean checkName()
{
    EditText checkingName = (EditText)findViewById(R.id.Name);
    String Name = checkingName.getText().toString();
    if (Name.length()<3)
    {

        name = false;
        return false;
    }
    else
    {
        name = true;
        return true;
    }
}

    public void onClick(View v){
    TextView Hint = (TextView)findViewById(R.id.Hint);
    if (checkPhoneNumber() == true || checkName() == true || checkEmail() == true)
    {
        Intent giftActivity = new Intent(RegistrationActivity.this, GiftHomeActivity.class);
        startActivity(giftActivity);
    ....

Не работает проверка. При вводе любых значений все равно начинается следующая активность.

A: Ваша валидация email совершенно неправильная. Она намного сложнее, чем проверить, содержит ли имейл коммерческое эт, и точку. Кроме того, matches не проверяет, содержится ли подстрока в строке. Вы наверно имели в виду contains?
А вот как нужно валидировать email правильно, в Android SDK есть специальный паттерн для этого:
public final static boolean isValidEmail(CharSequence target) {
  if (TextUtils.isEmpty(target)) {
    return false;
  } else {
    return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
  }
}

A: Скорее всего ошибка тут:

if (email.matches("@") & email.matches("."))

Вы, наверное, имели в виду вот этот оператор: &&

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unit test storage on Android apps I've been experimenting recently with Android applications.
I've developed the convention (which I've seen used elsewhere) of placing my unit tests in a parallel source folder within an Eclipse project. This works well because the Eclipse JUnit runner can find the tests easily and the project with it's tests are nicely contained in the project.
However, Android applications have a very specific structure, and I don't think that my normal unit tree design will work. Also, I don't really want my test code in the published app; it could effectively double the size on disk. How are Android unit tests usually organized?

A: You typically set up a separate project for Android unit tests.  There's an article on the Android Developer's site called Testing Fundamentals that takes you through the steps of setting up a test project in Eclipse. Also, see the Activity Testing Tutorial for a somewhat more advanced (and detailed) guide to testing Android apps.


text:
Q: how can Python see changes made to MariaDB by another client? On my Windows machine, I have a very simple database on MariaDB (10.3.7) to which I connect with the mysql-connector-python-rf (2.2.2).
I also connect to the database with 2 instances of HeidiSQL workbench.
When I add or delete a line in a data table using one of the work benches, I can immediately access the changed data with a SELECT statement in the other work bench. My conclusion: the first work bench has already committed the change to the data base.
However, seeing the change in Python seems more complicated. I have to add a commit() before the query to see the changes:
config = {'user'    : 'some_user',
          'password': 'some_password',
          'host'    : '127.0.0.1',
          'database': 'some_database',
          'raise_on_warnings': True,
         }
db = mysql.connector.connect(**config)

# wait some to make changes to the database using the HeidiSQL workbenches

db.commit() # even though Python has not changed anything which needs to be
            # committed, this seems necessary to re-read the db to catch
            # the changes that were committed by the other clients
cursor = db.cursor()
cursor.execute('some_SQL_query')
for result in cursor:
    do_something_with(result)
cursor.close()

So far I thought commit() is used to commit changes that Python wants to make to the database.
Is it correct to say that commit() also reads changes into Python that were done by other clients since the last connect()? Is this a bug/inconvenience or a feature?
Or is something else going on here that I am missing?

A: The thread writing issues COMMIT after writing.  Doing the COMMIT in the reading thread has no effect.
I would not change the "isolation level" unless you need for the reader to see unfinished changes while they are happening.  This is not normally required.
So, the writer should issue COMMIT as soon as it has finished some unit of work.  That might be a single INSERT; it might be a long, complicated, combination of operations.  A simple example is the classic 'transfer of funds:
BEGIN;
UPDATE accounts SET balance = balance + 100 WHERE id = 123; -- my account
UPDATE accounts SET balance = balance - 100 WHERE id = 432; -- your account
COMMIT;

For the integrity of accounts you want both UPDATEs to either happen nor not, even if the system crashes in the middle.  And you don't want any other thread to see an inconsistency in balance if it reads the data in the middle.
Another way to phrase it:  The writer is responsible for saying "I'm done" (by calling commit).

A: As @brunodesthuilliers has pointed out, the answer seems to be in the isolation levels. The default for Python seems to be REPEATABLE READ. To always read the latest commits it is necessary to change the transactions' isolation level, e.g. to READ COMMITTED.
config = {'user'    : 'some_user',
          'password': 'some_password',
          'host'    : '127.0.0.1',
          'database': 'some_database',
          'raise_on_warnings': True,
         }
db = mysql.connector.connect(**config)
cursor = db.cursor()
cursor.execute('SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;')
cursor.close()

# wait some to make changes to the database using the HeidiSQL workbenches

cursor = db.cursor()
cursor.execute('some_SQL_query') # will now read the last committed data
for result in cursor:
    do_something_with(result)
cursor.close()


text:
Q: I can't get the Sqlite database to communicate properly with my JavaFX application IDE - Eclipse packaging with Maven I have been having the most difficult time trying to package my application. The code is complete, I ended up using a JavaFX archetype with the Eclipse Maven plug-in. I continue to get errors when using the database, it seems like it is not a complete version of the database. I can go to the sqlite database manager from firefox and see the 6 users from the users table but I can only log in with 3 of them and then it gives me errors that the other tables do not exist. I am currently getting other errors right now, but I believe they are stemming from the database issue. My code for the login model is:
public class LoginModel {

String username, userLevel;

Connection connection;

public LoginModel () {

    connection = SqliteConnection.Connector();

    if (connection == null) {

        System.exit(1);
    }
}

public boolean isDbConnected () {

    try {

        return !connection.isClosed();

    } catch (SQLException e) {

        e.printStackTrace();
        return false;

    }
}

public boolean isLogin (String user, String pass) throws SQLException {
    //setUsername(user);
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    String query = "select * from users where username = ? and password = ?";

    try {
        // This is where the error is occuring
        preparedStatement = connection.prepareStatement(query);

        preparedStatement.setString(1, user);
        preparedStatement.setString(2, pass);
        resultSet = preparedStatement.executeQuery();

        if (resultSet.next()) {
            System.out.println(resultSet);
            userLevel = resultSet.getString(7);
            return true;

        } else {

            return false;

        }
    } catch (SQLException e) {

        System.out.println("Error is an SQLException");
        return false;

    } finally {

        preparedStatement.close();
        resultSet.close();

    }
}

}
I have commented where the error is occurring, I have done a system out println before and after, the before shows up and the after does not. It also prints out the SQLException as well, "Error is an SQLException". I have been reading posts on what people have done for the past 5 hours and am getting to my wits end. It appears that this needs a static connection while none of the other parts of the program uses a static connection (I have 2 database connection classes). Is it possible to keep the DB with the program location, or will it need to be placed somewhere on the users hard drive? Packaging a program seems to be insanely difficult, I had a much easier time learning how to code. Please help, thanks!
PrintStackTrace:
Error is an SQLException
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException:     java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)

I tried to print the whole stackTrace but it says my code isn't properly formatted...
EDIT: Complete stacktrace.
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException:       java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at             javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at     com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventH    andler.java:86)
    at     com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManag    er.java:238)
    at     com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManag    er.java:191)
    at     com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEve    ntDispatcher.java:59)
    at     com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.jav    a:58)
    at     com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl    .java:114)
    at     com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.jav    a:56)
    at     com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl    .java:114)
    at     com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.jav    a:56)
    at     com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl    .java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8411)
    at javafx.scene.control.Button.fire(Button.java:185)
    at     com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavio    r.java:182)
    at     com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.jav    a:96)
    at     com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.jav    a:89)
    at     com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubbli    ngEvent(CompositeEventHandler.java:218)
    at     com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventH    andler.java:80)
    at     com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManag    er.java:238)
    at     com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManag    er.java:191)
    at     com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEve    ntDispatcher.java:59)
    at     com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.jav    a:58)
    at     com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl    .java:114)
    at     com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.jav    a:56)
    at     com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl    .java:114)
    at     com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.jav    a:56)
    at     com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl    .java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at     com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Glass    ViewEventHandler.java:352)
    at     com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Glass    ViewEventHandler.java:275)
    at java.security.AccessController.doPrivileged(Native Method)
    at     com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$355(Glas    sViewEventHandler.java:388)
    at     com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.jav    a:389)
    at     com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventH    andler.java:387)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at     com.sun.glass.ui.win.WinApplication.lambda$null$149(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)
    Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at     sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at     sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.jav    a:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at     sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.jav    a:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
    ... 48 more
    Caused by: java.lang.NullPointerException
    at     tolmar.inventory.app.tolmarinventoryapplication.LoginModel.isLogin(LoginModel.ja    va:68)
    at      tolmar.inventory.app.tolmarinventoryapplication.LoginController.Login(LoginContr    oller.java:70)
... 58 more


text:
Q: How to match and parse specific info in tags with varying form I need to parse and process input data pushed into our webservice as (UTF-8) text files from a 3rd party. The input files contain tags in the general form
<{ _N ('some_domain_id','this can be an arbitary string',{'a':'b','c':'d'}) }>
-- --   --------------   ------------------------------  -----------------  --
        ^                 ^                              ^
        i need to         |                              this part is
        extract this      and this (payload)             optional

these tags can appear anyway in the textfile, no assumptions can be made about their distribution and whats between the tags. Also <{,_N and }>are present for any given valid tag, but there might be spaces in between without disrupting the values (e.g. between <{ and _N)
With that info, my initial test set was limited and my current implementation is a regex along with a split of the result at the ,

*

*Regex /<{\s*_N\s*\(([^\)]*)\)\s*}>?/g (Example: https://regex101.com/r/NuJD2V/1)

*Then split resulting match 'some_domain_id' , 'this can be an arbitary string',{'a':'b','c':'d'}with str_getcsv($match,',','\'','\\')

*use first two segments of str_getcsv result, dicard other results as they are optional

*After that, some_domain_id and this can be an arbitary string can be trimmed and processed as needed

The service is up for a while now and i had to realize that although the vast majority of tags is correctly catched, there is a small number of tags that contain anomalies and are not recognized by this implementation.
Caveats (things that can happen in the payload part):

*

*brackets in payload

*escaped quotes in payload \'

*optional modifiers after the outermost brackets of the _N call (see below)

Here are some sample tags i identified that can not be parsed or produce wrong results (even worse than not recognizing).
<{_N( 'some_domain_id' , 'this can ( be an arbitary ) string',{'a':'b','c':'d'})}>

- Not recognized, note the brackets, they can occur anywhere in the data string, they don't even need to be balanced (Example: https://regex101.com/r/BCiaaj/1)
<{_N( 'some_domain_id' , 'this can  be an arbitary  string' {'a':'b','c':'d'})|e('modifier')}>
<{_N( 'some_domain_id' , 'this can  be an arbitary string')|e('modifier')}>

*

*Not recognized, note the extra (optional) modifier after the outermost brackets of the _N element. the modifier can consist of different letters (e,r,w) and an arbitary string argument, also there might be spaces around the chain operator | (Example: https://regex101.com/r/XmR2uO/1)

Experimentally, i tried a few other regexes already, but they always fail on one or more of the tags in my extended testset, e.g.

*

*/_N\s*(\(\s*(?:\(??[^(]*?\s*\)))+/ - catches the modifier case, but fails on brackets in the relevant string

So my questions as i am not a real regex expert

*

*is this solvable with a regex and if so, can anyone hint me in the right direction?

*is there a better solution viable in vanilla php 7+ without installing/using some external library

Any help is highly appreciated!

A: You may use
<{\s*_N\s*\(\s*'([^\\']*(?:\\.[^\\']*)*)'\s*,\s*'([^\\']*(?:\\.[^\\']*)*)'\s*(.*?)}>

See the regex demo
Details:

*

*<{\s* - a <{ plus 0+ whitespaces

*_N - tag start

*\s*\(\s* - a ( enclosed with 0+ whitespaces

*'([^\\']*(?:\\.[^\\']*)*)' - a single quoted string literal that may contain escaped single quotes and other chars (the inside contents are captured into a capturing group #1)

*\s*,\s* -  a , enclosed with 0+ whitespaces

*'([^\\']*(?:\\.[^\\']*)*)' - a single quoted string literal that may contain escaped single quotes and other chars (the inside contents are captured into a capturing group #2)

*\s* - 0+ whitespaces

*(.*?) - any 0+ chars as few as possible up to the first

*}> - literal char sequence }>.

A: Why could you not just retrieve the parts you need (that being in the single quotes);
//example 1
$str = '<{_N( \'some_domain_id\' , \'this can ( be an arbitary ) string\',{\'a\':\'b\',\'c\':\'d\'})}>';
test_pregex($str);

//example 2
$str = '<{_N(\'some_domain_id\'      , \'this can ( be an arbitary ) string\'  ,{\'a\':\'b\',\'c\':\'d\'})}  >';
test_pregex($str);

//example 3
$str = '<{_N( \'some_domain_id\' , \'this can ( be an arbitary ) string\')|e(\'modifier\')}>';
test_pregex($str, '\'modifier\'');

function test_pregex($str, $optional = "{'a':'b','c':'d'}") {
    $re = '/\'([^\']*?)\'|(\{\'[^\']*?\'.+?})/m';
    preg_match_all($re, $str, $matches);
    $matches = $matches[0];
    var_export($matches);
    assert($matches[0] == "'some_domain_id'");
    assert($matches[1] == "'this can ( be an arbitary ) string'");
    assert($matches[2] == $optional);
}

Output will be all three cases with no assertion warnings. You can then process what you require further.


text:
Q: Stripe - STPPaymentCardTextField - How to remove or hide CVC code field? Stripe's iOS SDK's "STPPaymentCardTextField" has 4 fields for generating a token for a card : 1. credit card number 2. expiration month 3. expiration year 4. CVC field
We are saving only credit card number and expiration month/year. We don't need to get CVC number from user. So how to hide or remove CVC field from STPPaymentCardTextField.
Please give me some idea to handle this process.

A: it is possbile but we need to do this carefully , ok open STPPaymentCardTextField.m file and you get the property of CVC field name as STPFormTextField
@property(nonatomic, readwrite, weak)STPFormTextField *cvcField;

finally hide related to cvcField where ever it comes on that page around it occupy the 21 Places in that page , for e.g
STPFormTextField *cvcField = [self buildTextField];
cvcField.tag = STPCardFieldTypeCVC;
cvcField.alpha = 0;
self.cvcField = cvcField;
self.cvcPlaceholder = @"CVC";
[self.fieldsView addSubview:cvcField];

- (void)setCvcPlaceholder:(NSString * __nullable)cvcPlaceholder {
_cvcPlaceholder = [cvcPlaceholder copy];
self.cvcField.placeholder = _cvcPlaceholder;
}

else make a trick hide
[self.fieldsView addSubview:cvcField];

A: First way: Modifying the framework source
If you are fine with modifying the framework source, you can do this actually way easier:
In STPPaymentCardTextField.m change
self.allFields = @[numberField,
                   expirationField,
                   cvcField,
                   postalCodeField];

into
self.allFields = @[numberField,
                   expirationField,
                   postalCodeField];

and in STPPaymentCardTextFieldViewModel.m change
- (BOOL)isValid {
    return ([self validationStateForField:STPCardFieldTypeNumber] == STPCardValidationStateValid
            && [self validationStateForField:STPCardFieldTypeExpiration] == STPCardValidationStateValid
            && [self validationStateForField:STPCardFieldTypeCVC] == STPCardValidationStateValid
            && (!self.postalCodeRequired
                || [self validationStateForField:STPCardFieldTypePostalCode] == STPCardValidationStateValid));
}

into
- (BOOL)isValid {
    return ([self validationStateForField:STPCardFieldTypeNumber] == STPCardValidationStateValid
            && [self validationStateForField:STPCardFieldTypeExpiration] == STPCardValidationStateValid
            && (!self.postalCodeRequired
                || [self validationStateForField:STPCardFieldTypePostalCode] == STPCardValidationStateValid));
}

Second way: Subclassing STPPaymentCardTextField
I don't like editing a framework since I like to update, so I did it this by subclassing STPPaymentCardTextField (example in Swift):
class STPPaymentCardTextFieldNoCVC: STPPaymentCardTextField {

  func removeCVC() {
    if let fieldsView = subviews.first {
      for view in fieldsView.subviews where view.tag == 2 {
        // set a default cvc for the validator and remove the field
        (view as? UITextField)?.text = "123"
        view.removeFromSuperview()
      }
    }
  }

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    removeCVC()
  }

  override init(frame: CGRect) {
    super.init(frame: frame)
    removeCVC()
  }
}


text:
Q: RCP - How to add Menu Item DropDown on CoolBar I want to create something like this:

I have found a tutorial here http://www.vogella.com/tutorials/EclipseCommands/article.html. It is implemented using a config.xml file and I want to know how to implement that by code.


text:
Q: Migrating ctypes function from Python 2 to Python 3 In case this is a XY problem, here is what i want to do:
I have a wxPython app, that has to communicate with another process using the WM_COPYDATA windows message. While sending the message with the ctypes module was surprisingly easy, receiving the answer requires me to overwrite the wx loop, since wx does not provide a specific event for this case.
On python2, I used the ctypes.windll.user32.SetWindowLongPtrW and the ctypes.windll.user32.CallWindowProcW Functions to get the desired behaviour. However, in python3, the same code leads to OSError: exception: access violation writing.
As far as I found out, the only difference between the python2 ctypes module and the python3 ctypes module is how they handle strings.
I also read, that there is a difference in how the two version layout the memory, but since I'm no C Expert, I can't find the problem in my code.
I have tested the code with python3.7 (64Bit) and python2.7(64Bit) and wx 4.0.7 (though it also works with wx2.8 and python2)
Here is minimal reproducible example:
import ctypes, ctypes.wintypes, win32con, wx, sys

_LPARAM = ctypes.wintypes.LPARAM
_WPARAM = ctypes.wintypes.WPARAM
_HWND = ctypes.wintypes.HWND
_UINT = ctypes.wintypes.UINT
_LPCWSTR = ctypes.wintypes.LPCWSTR
_LONG_PTR = ctypes.c_long
_LRESULT = _LONG_PTR
_LPCWSTR = ctypes.wintypes.LPCWSTR

_WNDPROC = ctypes.WINFUNCTYPE(_LPARAM,   # return Value
                              _HWND,     # First Param, the handle
                              _UINT,     # second Param, message id
                              _WPARAM,   # third param, additional message info (depends on message id)
                              _LPARAM,   # fourth param, additional message info (depends on message id)
)

_SetWindowLongPtrW = ctypes.windll.user32.SetWindowLongPtrW
_SetWindowLongPtrW.argtypes = (_HWND, ctypes.c_int, _WNDPROC)
_SetWindowLongPtrW.restypes = _WNDPROC

_CallWindowProc = ctypes.windll.user32.CallWindowProcW
_CallWindowProc.argtypes = (_WNDPROC, _HWND, _UINT, _WPARAM, _LPARAM)
_CallWindowProc.restypes = _LRESULT

def _WndCallback(hwnd, msg, wparam, lparam):
    print(hwnd, msg, wparam, lparam)
    return _CallWindowProc(_old_wndproc, hwnd, msg, _WPARAM(wparam), _LPARAM(lparam))
_mywndproc = _WNDPROC(_WndCallback)

app = wx.App(redirect=False)
frame = wx.Frame(None, title='Simple application')
frame.Show()

_old_wndproc = _WNDPROC( _SetWindowLongPtrW(frame.GetHandle(), win32con.GWL_WNDPROC, _mywndproc ) )
if _old_wndproc == 0:
    print( "Error" )
    sys.exit(1)

app.MainLoop()

Edit: I know that there is a pywin32 module, that could potentially help me. However, since the code works on python2 I'm rather curious what is going on here.

A: One problem is here:
_LONG_PTR = ctypes.c_long
_LRESULT = _LONG_PTR

The type LONG_PTR is "an integer the size of a pointer", which varies between 32-bit and 64-bit processes.  Since you are using 64-bit Python, pointers are 64-bit and LONG_PTR should be:
_LONG_PTR = ctypes.c_longlong

If you want more portable code for 32- and 64-bit, LPARAM is also defined as LONG_PTR in the Windows headers so the below definition would define LONG_PTR correctly for 32-bit and 64-bit Python since ctypes already defines it correctly based on Python's build:
_LONG_PTR = ctypes.wintypes.LPARAM  # or _LPARAM in your case

After that change I tested your script with wxPython and still had an issue.  I suspect wxPython is compiled without the UNICODE/_UNICODE definitions so the SetWindowLongPtr and CallWindowProc APIs must use the A version to retrieve and call the old window procedure.  I made that change and the following code works.
Full code tested with 64-bit Python 3.8.8:
```py
import ctypes, ctypes.wintypes, win32con, wx, sys

_LPARAM = ctypes.wintypes.LPARAM
_WPARAM = ctypes.wintypes.WPARAM
_HWND = ctypes.wintypes.HWND
_UINT = ctypes.wintypes.UINT
_LPCWSTR = ctypes.wintypes.LPCWSTR
_LONG_PTR = _LPARAM
_LRESULT = _LONG_PTR
_LPCWSTR = ctypes.wintypes.LPCWSTR

_WNDPROC = ctypes.WINFUNCTYPE(_LRESULT,  # return Value
                              _HWND,     # First Param, the handle
                              _UINT,     # second Param, message id
                              _WPARAM,   # third param, additional message info (depends on message id)
                              _LPARAM,   # fourth param, additional message info (depends on message id)
)

_SetWindowLongPtr = ctypes.windll.user32.SetWindowLongPtrA
_SetWindowLongPtr.argtypes = (_HWND, ctypes.c_int, _WNDPROC)
_SetWindowLongPtr.restypes = _WNDPROC

_CallWindowProc = ctypes.windll.user32.CallWindowProcA
_CallWindowProc.argtypes = (_WNDPROC, _HWND, _UINT, _WPARAM, _LPARAM)
_CallWindowProc.restypes = _LRESULT

@_WNDPROC
def _WndCallback(hwnd, msg, wparam, lparam):
    print(hwnd, msg, wparam, lparam)
    return _CallWindowProc(_old_wndproc, hwnd, msg, wparam, lparam)

app = wx.App(redirect=False)
frame = wx.Frame(None, title='Simple application')
frame.Show()

_old_wndproc = _WNDPROC(_SetWindowLongPtr(frame.GetHandle(), win32con.GWL_WNDPROC, _WndCallback))
if _old_wndproc == 0:
    print( "Error" )
    sys.exit(1)

app.MainLoop()

As an aside, there is a note about SetWindowLongPtr (and similar for CallWindowProc) in the MSDN documentation that hinted at this solution:

The winuser.h header defines SetWindowLongPtr as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.


text:
Q: To bifurcate integer value into HH:MM format I have a column with integer datatype and it contains time duration in the below format. I want to bifurcate these values in HH and MM format as per the values in the below table:
Time      HH     MM
---------------------
3         00     03
17        00     17
207       02     07
786       07     86
1234      12     34

A: You can do this with string concatenation:
select time / 100 as hh, mod(time, 100) as mm

If you want them as zero-padded strings:
select right('00' + cast(time / 100), 2) as hh,
       right('00' + mod(time, 100), 2) as mm

A: CREATE TABLE #tt
  (
     tim INT
  )

INSERT INTO #tt
VALUES     (3 ),
            (17 ),
            (207),
            (786),
            (1234 )

SELECT tim,
           left(right('0000'+cast(tim AS varchar(4)),4),2),
           right(right('0000'+cast(tim AS varchar(4)),4),2)
    FROM   #tt


text:
Q: Object to ImageIcon I have this piece of code:
public ImageIcon getNextImage() {
    if (PhotoWalker.hasNext()) {
        return (ImageIcon) PhotoWalker.next();
    } else {
        return null;
    }
}

And PhotoWalker is an iterator for an ArrayList. And when I run this I get a java.util.ConcurrentModificationException .
Does anyone know how to solve this?


text:
Q: Is there a Qt Dialog or Widget to interactively sort a string list? I need to provide a reordering Dialog to let a user interactively order a list of strings. Does Qt already provide something fitting for this purpose?
I have searched the usual forums and examples but found nothing appropriate.
To clarify what I need:
Raw List:

*

*FileBaz

*FileFoo

*FileBar

User sorted list

*

*FileBar

*FileFoo

*FileBaz

So an arbitrary order as for example needed for merging formerly selected pdf files

A: Not that I know of. Something simple with a Move up button and a Move down button in coordination with a QListWidget may be useful, however. Up and Down would move around the list items in the respective direction, naturally.
Even easier, in my opinion, would be to use a QTreeWidget, as, if I recall correctly, there are some easy functions for swapping items around. A combination of something like
void insertTopLevelItem ( int index, QTreeWidgetItem * item )
QTreeWidgetItem *itemAbove ( const QTreeWidgetItem * item )
QTreeWidgetItem *itemBelow ( const QTreeWidgetItem * item )
QTreeWidgetItem *currentItem ()
int indexOfTopLevelItem ( QTreeWidgetItem * item )

may be useful. (Excerpts from http://qt-project.org/doc/qt-4.8/QTreeWidget.html)
Edit: I haven't used QListWidget much, but seems fairly similar to the QTreeWidget in terms of ease of swapping items around. Either one works.

A: Qt already supports it, there's nothing for you to do: The standard views automatically support internal drag and drop, where items are moved around to change the order in which they are displayed.
Further quoting the documentation:

*

*To enable item dragging, set the view's dragEnabled property to true.

*To allow the user to drop both internal or external items within the view, set the view's viewport()'s acceptDrops property to true.

*To show the user where the item currently being dragged will be placed if dropped, set the view's showDropIndicator property. This provides the user with continuously updating information about item placement within the view.

*To enable the user to move the items around within the view, we must set the list widget's dragDropMode to QAbstractItemView::InternalMove.

Below is a sscce that you can run to see it in action.
#include <QApplication>
#include <QListWidget>
#include <QListWidgetItem>

int main(int argc, char ** argv)
{
    QApplication a(argc, argv);
    QListWidget w;
    w.addItem("Rosalind");
    w.addItem("Celia");
    w.addItem("Adam");
    w.addItem("Jaques");
    w.setDragEnabled(true);
    w.setDropIndicatorShown(true);
    w.setDragDropMode(QAbstractItemView::InternalMove);
    w.show();
    return a.exec();
}

A: Just for completeness sake:
Here is the solution I'm using in the end:
#include <QtGui>

class SortDialog:public QDialog{
    Q_OBJECT
  public:
    SortDialog(QStringList* pList, QString const& title,  QString const& middleButton);
    int getSelectedItem() const;

  private slots:
    void slotAccept();
    void slotItemUp();
    void slotItemDown();
    void slotSelectItem();

  private:
    QStringList* mpList;
    QListWidget* mpListWidget;
    int mSelectedItem;

};

SortDialog::SortDialog(QStringList* pList, QString const& title,  QString const& middleButton):
  QDialog(),
  mpList(pList),
  mpListWidget(new QListWidget()),
  mSelectedItem(-1){
  this->setWindowTitle(title);

  QHBoxLayout* pMainLayout = new QHBoxLayout();
  this->setLayout(pMainLayout);

  QVBoxLayout* pListLayout = new QVBoxLayout();
  pMainLayout->addLayout(pListLayout);

  pListLayout->addWidget(mpListWidget);
  mpListWidget->setDragEnabled(true);
  mpListWidget->setDropIndicatorShown(true);
  mpListWidget->setDragDropMode(QAbstractItemView::InternalMove);

  boostForeach(QString const& string, *mpList) {
    mpListWidget->addItem(string);
  }
  mpListWidget->setMinimumWidth(mpListWidget->sizeHintForColumn(0)+10);
  mpListWidget->adjustSize();

  mpList->clear();

  QPushButton* confirm = new QPushButton(tr("Confirm"));
  connect(confirm, SIGNAL(clicked()), this, SLOT(slotAccept()));
  pListLayout->addWidget(confirm);
  confirm->setDefault(true);

  QVBoxLayout* pUpDownLayout = new QVBoxLayout();
  pMainLayout->addLayout(pUpDownLayout);

  QPushButton* up = new QPushButton(tr("Up"));
  connect(up, SIGNAL(clicked()), this, SLOT(slotItemUp()));
  pUpDownLayout->addWidget(up);

  QPushButton* down = new QPushButton(tr("Down"));
  connect(down, SIGNAL(clicked()), this, SLOT(slotItemDown()));
  pUpDownLayout->addWidget(down);

  QPushButton* ground = new QPushButton(middleButton);
  connect(ground, SIGNAL(clicked()), this, SLOT(slotSelectItem()));
  pUpDownLayout->addWidget(ground);

  this->adjustSize();
}

int SortDialog::getSelectedItem() const{
  return mSelectedItem;
}

void SortDialog::slotAccept(){
  int count = mpListWidget->count();
  for(int index = 0; index < count; index++){
    QListWidgetItem * item = mpListWidget->item(index);
    mpList->push_back(item->text());
  }

  this->close();
}

void SortDialog::slotItemUp(){
  int row = mpListWidget->currentRow();
  if(row>0){
    QListWidgetItem* pTemp = mpListWidget->takeItem(row);
    mpListWidget->insertItem(row-1,pTemp);
    mpListWidget->setCurrentRow(row-1);
  }
}

void SortDialog::slotItemDown(){
  int row = mpListWidget->currentRow();
  if(row<mpListWidget->count()-1){
    QListWidgetItem* pTemp = mpListWidget->takeItem(row);
    mpListWidget->insertItem(row+1,pTemp);
    mpListWidget->setCurrentRow(row+1);
  }
}

void SortDialog::slotSelectItem(){
  int count = mpListWidget->count();
  for(int index = 0; index < count; index++){
    QListWidgetItem * item = mpListWidget->item(index);
    QFont font = item->font();
    font.setBold(false);
    item->setFont(font);
  }

  mSelectedItem =mpListWidget->currentRow();
  qDebug() << mSelectedItem;
  QListWidgetItem* pTemp = mpListWidget->currentItem();
  QFont font = pTemp->font();
  font.setBold(true);
  pTemp->setFont(font);
}


text:
Q: MPI: Sending an array of a structure containing a pointer I have got the following C structure:
typedef struct chromosome{
int *genes;
float cout;
}chromosome;

I would like to send an array of chromosomes using MPI_Send. I've defined an MPI_CHROMOSOME data type like this:
MPI_Datatype MPI_CHROMOSOME;
MPI_Datatype TYPES_ELEMENTAIRES[2] = {MPI_INT, MPI_FLOAT};
int blocklengths[2] = {NB_SOMMETS,1}; //NB_SOMMET is a known integer value at this point (number of elements of the "genes" array)
MPI_Aint offsets[2];

offsets[0] = offsetof(chromosome, genes);
offsets[1] = offsetof(chromosome, cout);

MPI_Type_create_struct(2, blocklengths, offsets, TYPES_ELEMENTAIRES, &MPI_CHROMOSOME);
MPI_Type_commit(&MPI_CHROMOSOME);

Then I tried to send an array of chromosomes:
chromosome *sub_pop = malloc(taille_sub_pop*sizeof(chromosome));//taille_sub_pop is a known integer value
/* ... Fills sub_pop with chromosomes ...*/
MPI_Send(sub_pop,taille_sub_pop,MPI_CHROMOSOME, 1, 3, MPI_COMM_WORLD);

... But I got an error (BAD TERMINATION OF ONE OF YOUR APPLICATION PROCESSES... Exit Code 139... YOUR APPLICATION TERMINATED WITH THE EXIT STRING: Segmentation fault (signal 11)).
How can I send this array properly ? I would appreciate your help. Thanks a lot.

A: You can't send pointers to other processes with MPI. Well, technically you can, but because each process has its own memory space and addressing, a pointer that was valid on one process will most likely point to invalid memory on another. Anyway, you want to send the data that the pointer is pointing to, not the pointer itself.
See this question:
Creating an MPI_Datatype for a structure containing pointers


text:
Q: Angular material tooltip does not display as expected I've been rummaging around various tutorial sites trying to get material tool tips to work. Super frustrating because it looks really easy. The console displays no errors or warnings. I'm using Angular 11. It is my understanding that once I've imported the MatTooltipModule into my app.module.ts then this functionality will be available for all components in the same module.
npm list @angular/core
finfo@0.0.0 C:\source\finfo
+-- @angular/core@11.2.9
`-- codelyzer@6.0.1
  `-- @angular/core@9.0.0
npm list @angular/material
C:\source\finfo
`-- @angular/material@11.2.8

....app.module.ts....
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatTooltipModule } from '@angular/material/tooltip';
....app.module.ts....
imports: [
    HttpClientModule,
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    MatButtonModule,
    MatCardModule,
    MatTooltipModule,
    ReactiveFormsModule,
    RouterModule.forRoot(appRoutes),

....store.html....
<div>
  <button matTooltip="Info about the action"
      matTooltipPosition="above"
      class="example-button">
      Action
  </button>
</div>

*

*Tooltip | Angular Material

*Simple YouTube Video showing how easy it is
Update: The answer provided by Zunayed Shahriar is correct. One small addendum, for what ever reason, my project started working with the tooltip after I moved the @import statement up to the top of the .css file.

A: Working fine for me.
Make sure that you import material CSS (depending on your theme) at your styles.css file.
@import "~@angular/material/prebuilt-themes/indigo-pink.css";

Demo at StackBlitz.
Result:


text:
Q: Can't display data from Mongo database I'm following this tutorial: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/
When I do db.usercollection.find().pretty() in my mongo terminal, my records print - so I know I have records to display.
When I do http://localhost:3000/userlist in my browser, I get the words "User List" at the top - but I don't get any of the user data.
It should look like this.
Question: Is my link in my userlist.jade file not pointing to the database data??
userlist.jade
extends layout

block content
    h1.
        User List
    ul
        each user, i in userlist
            li
                a(href="mailto:#{user.email}")= user.username

index.js
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

/* GET Userlist page. */
router.get('/userlist', function(req, res) {
    var db = req.db;
    var collection = db.get('usercollection');
    collection.find({},{},function(e,docs){
        res.render('userlist', {
            "userlist" : docs
        });
    });
});

module.exports = router;

app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// new code
// we want to talk to mongodb, use monk to do it, databasebase is lcoated at localhost:27017/nodetest1
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Make our db accessible to our router - new code
app.use(function(req,res,next){
    req.db = db;
    next();
});

// telling Express what route files to use
app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

// our master app exporting its app object. All modules export an object whch can easily be called elsewhere in code.
module.exports = app;

A: i was getting the same error and then i fixed the problem:

app.js

var db = monk('localhost:27017/nodetest1');

change the localhost to 127.0.0.1

and make sure the collection name is nodetest1


text:
Q: get div current (rendered) width with javascript Hey, Ive got an php script dragging some images from a database and displaying them using float:left; so they go left to right.
However unless in the css i define i width for the container they jump down onto a 2nd line.
So the question IS!
How for the life of me could I get it to figure out the width of the content and then set the width attribute via javascript all on the one load.
I did have a slight worry that this wouldnt be easily possible as it wud have had to render the images/layout first to get a width before then adjusting it.
Ideas please people!! x

A: Your question has to do with how the flows of floats work...
If two images are floated and the sum of their widths is wider than the containing element, they will wrap (similar to the way words in a paragraph wrap).
Visual references describing the flow of "float"ed elements (way too difficult to describe in a few words):

*

*http://css.maxdesign.com.au/floatutorial/introduction.htm


text:
Q: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server PYTHON I'm trying to insert some variables into my database, but I'm getting this error, I don't know what I'm doing wrong, could you help me? Thanks in advance
import mysql.connector as co
import time as tm
dbConnect = {
    'host':'mx102.hostgator.mx',
    'port':'3306',
    'user':'meandmic_root',
    'password':'abcde',
    'database':'meandmic_analizador'
}

felicidad = 0
enojo = 0
sorpresa = 0
tristeza = 0
neutral = 0
dt = tm.strftime("%d/%m/%y")
conexion = co.connect(**dbConnect)
cursor = conexion.cursor()
sqlInsertar = "insert into registros(CFELICIDAD,CENOJO,CSORPRESA,CTRISTEZA,CNEUTRAL,FECHA)values(%s,%s,%s,%s,%s,%s)"
cursor.execute(sqlInsertar,[felicidad,enojo,sorpresa,tristeza,neutral,dt])
conexion.commit()

A: Try changing your list to tuple:
cursor.execute(sqlInsertar,(felicidad,enojo,sorpresa,tristeza,neutral,dt))

A: As Mikhail Ilin mentioned, the cursor.execute method expects a tuple as the second parameter.
The official documentation 6.9.5.4 MySQLCursor.execute() Method has an example query that is very similar to yours.
insert_stmt = (
   "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
   "VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)

In this example, data is a tuple, not a list.


text:
Q: Unifying Receiver Unite Old Keyboard With Mouse Here's my situation. I had a wireless mouse and a wireless keyboard. Owing to enthusiastic cleaning of my wife, I no longer have the mouse and I no longer have the receiver for the keyboard. So I am left with the Keyboard and the receiver for the mouse.
The receiver for the mouse is NOT a unifying receiver. But I note that on the underside of the keyboard, the logo for the unifying stuff is present.
So, to my question. If I buy a wireless mouse with a unifying receiver, and download the unifying software, will I be able to get my old keyboard and the new wireless mouse both running off the same unifying receiver (the one which will come with the new wireless mouse)?

A: Just a quick note to confirm that the following course of action worked:
I purchased a new mouse with a unifying receiver.
I downloaded the Logitech unifying software and was able to use the simple instructions to set things up so that the unifying receiver is able to drive both the new mouse and old keyboard.
So, keyboard not wasted! Result!!!


text:
Q: How can I solve the Tikz Quotes Library comma problem? The Tikz Quotes Library provides a convenient means of drawing labeled edges between nodes. However, I have encountered a problem when the edge label has a comma in it. Given below is a MWE of the problem. The comma between x and y in the edge drawing statement causes the code not to compile. The code compiles when the comma is removed.
I would appreciate any help with the resolution of the comma issue.
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning,quotes}
\begin{document}
\begin{tikzpicture}
    \node (A) at (0,0) {$x$};
    \node (B) [right = 2cm of A] {$y$};
    \draw[-latex] (A) edge ["$\left(x,y\right)$"] (B);
\end{tikzpicture}
\end{document}

A: Try curly brackets around the statement which causes the problem: \draw[-latex] (A) edge ["{$\left(x,y\right)$}"] (B); works fine for me.


text:
Q: Is B-Method an alternative to traditional programming languages? I heard about B-Method which is invented in France. Is it an alternative to traditional programming languages like c++ and java or is it a completely different thing with different purposes?

A: Quote the B-website:

B is a formal specification method
  which, thanks to an adequate language,
  allows for highly accurate expressions
  of the properties required by
  specifications. One can then prove in
  a fully automated fashion that these
  properties are unambiguous, coherent
  and are not contradictory. This then
  allows us to mathematically prove that
  these properties are taken into
  account as the design stages progress.
Therefore, this method and its
  associated proof allow for:
  (1) Clear technical specifications and
  system specifications to be reached
  that are structured, coherent and
  unambiguous, and (2) The development of
  software that is contractually
  guaranteed to be fault-free.

To answer your question: No, B-Method is not an alternative to programming languages. It's a way of creating blueprints for programs and for verifying that the thing you created really works as described by the blueprints. If you don't understand this you can safely forget about it.

A: No, as the Wikipedia article says, B-Method is a Formal Method not a programming language. You can read up on Formal Methods on Wikipedia too. Basically, they can be used during development to describe and verify algorithms.


text:
Q: What ways there are to stop and restart JSCover Server and apply configuration changes? At the moment to stop JSCover server I go to http://localhost:8080/stop.
What are other ways (commandline or not) to stop/restart JSCover server, in case one needs to apply some configuration changes and wants to do it in automated manner?

A: None really, except if you run JSCover as a thread in a Java application (such as shown here).
You could put in a feature request at https://github.com/tntim96/JSCover/issues if you can describe exactly what you need and think it would be useful to others.


text:
Q: Meteor data won't update Tracker Autorun? I use Meteor and React Native to display what deputy the user has selected. If the user changes his deputy, field {number} refreshes, but {depute.nom} and {depute.groupe_sigle} does not. Should I use Tracker Autorun ? Any idea ?
class Info extends Component {

  render() {
    const {nom, groupe_sigle, nom_circo, picture, num_circo, id} = this.props.navigation.state.params;
//This updates into the component
const number= Meteor.user().profile.selectedDeputy;
//This does not update into the component
const depute= this.props.selectedDeputy && this.props.selectedDeputy.depute;

  return (
    <View>
      <Text>Your deputy is : {depute.nom}</Text>
      <Text>Your deputy group is : {depute.groupe_sigle} </Text>
      <Text>The deputy Id gets updated : {number} </Text>
    </View>
    )
}
}

export default createContainer(params=>{
  Meteor.subscribe('selectedDeputy');
  return{
    selectedDeputy: Meteor.collection('deputies').findOne(Meteor.user().profile.selectedDeputy),
};
},info);

A: First check the inserted data are there inside the database.If the data is not added to the database, there is an issue with your insert function.If the values are there in the database your subscribe should be inside autorun otherwise your data will not reactive.If you got conflicts please feel free to share you code with us


text:
Q: node http get function works only a few times I am new to node, so please bear with me. I'm trying to write a function that tests to make sure there is a live connection to the web server before redirecting the page.
This works for the first 6 - 7 clicks, then the page will not redirect anymore - it just sits there. Then a few minutes later, an alert will show.
What is going on?!
var http = require("http");
var url = 'http://example.com/';

mainMenu.click(function () {
  var menulink = $(this).attr('rel');
  var menuvar = http.get(url, function () {
    window.location = menulink;
  }).on('error', function () {
    alert('Cannot Connect to Server');
  });
});

A: I suspect you have a problem with non-flowing streams.
Since you never consume the data of your responses, the connection never closes. The HTTP Agent limits the number of concurrent connections and refuses to open any new connection after a while.
You should try to manually switch the response to flowing mode:
mainMenu.click(function () {
  var menulink = $(this).attr('rel');
  var menuvar = http.get(url, function (res) {
    // FORCE FLOWING MODE
    res.resume();
    window.location = menulink;
  }).on('error', function () {
    alert('Cannot Connect to Server');
  });
});


text:
Q: Using for_each to iterate over form inputs I have two forms, one with uk_inputs and one with international_inputs. When one or more of the uk_inputs are filled out I want it so the international inputs in the other form are disabled.
This currently works when the first uk_input is filled out, but I can't manage to make it work but iterating over all of them with for_each.
The first code snippet is where it works with the first uk_input and the second code snippet is my attempt to iterate over all of them.
apologies if this isn't clear. thanks

$(document).ready(function() {
    var uk_input = document.querySelector(".uk_input");
    uk_input.onchange = function () {
        international_input =  document.querySelectorAll(".international_input")
        international_input.forEach(function(international) {
            international.disabled = uk_input.value
        });
    }
});

$(document).ready(function() {
    var uk_input = document.querySelectorAll(".uk_input");
    uk_input.for_each.onchange = function (uk) {
        international_input =  document.querySelectorAll(".international_input")
        uk.international_input.forEach(function(international) {
            international.disabled = uk_input.value
        });
    }
});

<%= fields.input :line_1, input_html: {class: "uk_input"} %>
<%= fields.input :line_2, input_html: {class: "uk_input"}  %>
<%= fields.input :line_3, input_html: {class: "uk_input"}  %>
<%= fields.input :town, input_html: {class: "uk_input"}  %>
<%= fields.input :county, input_html: {class: "uk_input"}  %>
<%= fields.input :postcode, input_html: {class: "uk_input"}  %>

<%= fields.input :line_1, input_html: {class: "international_input"} %>
<%= fields.input :line_2, input_html: {class: "international_input"} %>
<%= fields.input :line_3, input_html: {class: "international_input"} %>
<%= fields.input :town, label: "City / Region", input_html: {class: "international_input"} %>
<%= fields.input :postcode, label: "Postcode / ZIP Code", input_html: {class: "international_input"} %>

A: Syntax of a for each function:
The correct syntax of the for each function in JavaScript is:
let uk_inputs = document.querySelectorAll(".uk_inputs");
uk_inputs.forEach(input=>{
    input.addEventListener("click",event=>{
      //Code you want to run for every uk_inputs class input
  })
})

Also, as you can see detailed in the code above, to assign an event listener you must reference the DOM element you want to assign that event. This is a vanilla JavaScript solution. It's exactly the same result as it would be with jQuery.
Here is a functional fiddle. In case you want to check it out.
Adjustments to fit your question:
$(document).ready(function() {
    let uk_inputs = document.querySelectorAll(".uk_inputs"),
        international = document.querySelectorAll(".international");

    const enabledInternational = (enabled) => {
        international.forEach(input => {
            if (enabled) {
                input.removeAttribute("disabled");
            } else {
                input.setAttribute("disabled", `${enabled}`);
            }
        })
    }

    uk_inputs.forEach(input => {
        input.addEventListener("change", event => {
            enabledInternational(event.target.value === "");
        })
    })
});


text:
Q: iOS Swift - AVCaptureSession - Capture frames respecting frame rate I'm trying to build an app which will capture frames from the camera and process them with OpenCV before saving those files to the device, but at a specific frame rate.
What I'm stuck on at the moment is the fact that AVCaptureVideoDataOutputSampleBufferDelegate doesn't appear to respect the AVCaptureDevice.activeVideoMinFrameDuration, or AVCaptureDevice.activeVideoMaxFrameDuration settings.
captureOutput runs far quicker than 2 frames per second as the above settings would indicate.
Do you happen to know how one could achieve this, with or without the delegate?
ViewController:
override func viewDidLoad() {
    super.viewDidLoad()

}

override func viewDidAppear(animated: Bool) {
    setupCaptureSession()
}

func setupCaptureSession() {

    let session : AVCaptureSession = AVCaptureSession()
    session.sessionPreset = AVCaptureSessionPreset1280x720

    let videoDevices : [AVCaptureDevice] = AVCaptureDevice.devices() as! [AVCaptureDevice]

    for device in videoDevices {
        if device.position == AVCaptureDevicePosition.Back {
            let captureDevice : AVCaptureDevice = device

            do {
                try captureDevice.lockForConfiguration()
                captureDevice.activeVideoMinFrameDuration = CMTimeMake(1, 2)
                captureDevice.activeVideoMaxFrameDuration = CMTimeMake(1, 2)
                captureDevice.unlockForConfiguration()

                let input : AVCaptureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)

                if session.canAddInput(input) {
                    try session.addInput(input)
                }

                let output : AVCaptureVideoDataOutput = AVCaptureVideoDataOutput()

                let dispatch_queue : dispatch_queue_t = dispatch_queue_create("streamoutput", nil)
                output.setSampleBufferDelegate(self, queue: dispatch_queue)

                session.addOutput(output)

                session.startRunning()

                let previewLayer = AVCaptureVideoPreviewLayer(session: session)
                previewLayer.connection.videoOrientation = .LandscapeRight

                let previewBounds : CGRect = CGRectMake(0,0,self.view.frame.width/2,self.view.frame.height+20)
                previewLayer.backgroundColor = UIColor.blackColor().CGColor
                previewLayer.frame = previewBounds
                previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
                self.imageView.layer.addSublayer(previewLayer)

                self.previewMat.frame = CGRectMake(previewBounds.width, 0, previewBounds.width, previewBounds.height)

            } catch _ {

            }
            break
        }
    }

}

func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
    self.wrapper.processBuffer(self.getUiImageFromBuffer(sampleBuffer), self.previewMat)
}

A: So I've figured out the problem.
In the comments section for AVCaptureDevice.h above the activeVideoMinFrameDuration property it states:

On iOS, the receiver's activeVideoMinFrameDuration resets to its
  default value under the following conditions:

*

*The receiver's activeFormat changes

*The receiver's AVCaptureDeviceInput's session's sessionPreset changes

*The receiver's AVCaptureDeviceInput is added to a session

The last bullet point was causing my problem, so doing the following solved the problem for me:
        do {

            let input : AVCaptureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)

            if session.canAddInput(input) {
                try session.addInput(input)
            }

            try captureDevice.lockForConfiguration()
            captureDevice.activeVideoMinFrameDuration = CMTimeMake(value: 1, timescale: 2)
            captureDevice.activeVideoMaxFrameDuration = CMTimeMake(value: 1, timescale: 2)
            captureDevice.unlockForConfiguration()

            let output : AVCaptureVideoDataOutput = AVCaptureVideoDataOutput()

            let dispatch_queue : dispatch_queue_t = dispatch_queue_create("streamoutput", nil)
            output.setSampleBufferDelegate(self, queue: dispatch_queue)

            session.addOutput(output)


text:
Q: H2 failing to insert data I am testing this DB and I am trying to insert data on a table with attributes: ID, password and username. I get this error:
bad SQL grammar
...
Syntax error in SQL statement "insert into users(id,username,password) values(2,'TEST[*]','TEST');
...expected "[, ::, *, /, %, +, -, ||, ~, !~, NOT, LIKE, ILIKE, REGEXP, IS, IN, BETWEEN, AND, OR, ,, )"; ... [42001-199]

It is marking the string as a problem.
I have also try insert into users values(2,'test','test') and insert into users values('test','test') unsuccessfully.
What is wrong with my query?


text:
Q: How can i partition market basket items into clusters? I have a data set as follows:  (i took a simple example but the real data set is much bigger)
     V1 V2 V3 V4
1    1  0  0  1
2    0  1  1  0
3    0  0  1  0
4    1  1  1  1
5    0  1  1  0
6    1  0  0  1
7    0  0  0  1
8    0  1  1  1
9    1  0  1  0
10   0  1  1  0
...

where V1, V2,V3...Vn are items and 1,2,3,4...1000 are transactions. I want to partition these items into k clusters such that in each cluster i have the items that appear the most frequently together in the same transactions.
To determine the number times each couple of items appear together i tried crosstable, i got the following results:
   V1 V2 V3 V4
V1  4  1  2  3
V2  1  5  5  2
V3  2  5  7  2
V4  3  2  2  5

For this small example if i want to create 2 clusters (k=2) such that a cluster must contain 2 items (to maintain the balance between clusters), i will get:
Cluster1={V1,V4}
Cluster2={V2,V3}
because:
1) V1 appears more frequently with V4 (V1,V4)=3 > (V1,V3) > (V1,V2) and same for V4.
2) V2 appears more frequently with V2 (V2,V3)=5 > (V2,V4) > (V2, V1) and same for V3.
How can i do this partition with R and for a bigger set of data ?

A: I think you are asking about clustering.  It is not quite the same as what you are doing above, but you could use hclust to look for similarity between variables with a suitable distance measure.
For example
plot(hclust(dist(t(df),method="binary")))

produces the following...

You should look at ?dist to see if this distance measure is meaningful in your context, and ?hclust for other things you can do once you have your dendrogram (such as identifying clusters).
Or you could use your crosstab as a distance matrix (perhaps take the reciprocal of the values, and then as.dist).

A: library(data.table)

data:
df<-
fread("
    V1 V2 V3
1    1  0  0
2    0  0  1
3    0  0  1
4    1  1  1
5    0  0  1
6    1  0  0
7    0  0  0
8    0  1  1
9    1  0  1
10   0  1  1
")[,-1]

code:
setDT(df)
sapply(names(df),function(x){
    df[get(x)==1,lapply(.SD,sum,na.rm=T),.SDcols=names(df)]
    })

result:
   V2 V3 V4
V2 4  1  2
V3 1  3  3
V4 2  3  7

A: df <- read.table(text="
ID V1 V2 V3
1    1  0  0
2    0  0  1
3    0  0  1
4    1  1  1
5    0  0  1
6    1  0  0
7    0  0  0
8    0  1  1
9    1  0  1
10   0  1  1
", header = TRUE)

k = 3 # number of clusters

library(dplyr)
df %>%
  # group and count on all except the first id column
  group_by_at(2:ncol(df)) %>%
  # get the counts, and collect all the transaction ids
  summarize(n = n(), tran_ids = paste(ID, collapse = ',')) %>%
  ungroup() %>%
  # grab the top k summarizations
  top_n(k, n)

# V1    V2    V3     n tran_ids
# <int> <int> <int> <int> <chr>
# 1     0     0     1     3 2,3,5
# 2     0     1     1     2 8,10
# 3     1     0     0     2 1,6

A: You can transpose your table and use standard methods of clustering. Thus, you will cluster the items. The features are the transactions.
Geometrical approaches can be used like kmeans. Alternatively, you can use mixture models which provide information criteria (like BIC) for selecting the number of clusters. Here is an R script
require(VarSelLCM)

my.data <- as.data.frame(t(df))
# To consider Gaussian mixture
# Alternatively Poisson mixture can be considered by converting each column into integer.
for (j in 1:ncol(my.data)) my.data[,j] <- as.numeric(my.data[,j])

## Clustering by considering all the variables as discriminative
# Number of clusters is between 1 and 6
res.all <- VarSelCluster(my.data, 1:6, vbleSelec = FALSE)

# partition
res.all@partitions@zMAP

# shiny application
VarSelShiny(res.all)

## Clustering with variable selection
# Number of clusters is between 1 and 6
res.selec <- VarSelCluster(my.data, 1:6, vbleSelec = TRUE)

# partition
res.selec@partitions@zMAP

# shiny application
VarSelShiny(res.selec)


text:
Q: How to resolve "The expression of type Class needs unchecked conversion to conform to Class" I have the ff. test method:
@Mock
private DBAccessor accessor;

/**
 * Successful find().
 */
@Test
public void testFind() {
    // Prepare
    MockDto mockDto = mock(MockDto.class);
    try {
        when(accessor.executeQuery(any(Class.class), anyString(), any(ConcurrentHashMap.class))).thenReturn(
                mockDto);
    } catch (Exception e) {
        fail("Unexpected exception.");
    }
}

However, the ff. warning occcurs:
Multiple markers at this line
    - Type safety: Unchecked invocation executeQuery(Class, String, ConcurrentHashMap) of the generic method executeQuery(Class<T>, String, Object) of type DBAccessor
    - Type safety: The expression of type Class needs unchecked conversion to conform to Class<Object>

How do I resolve the above warnings?
I'm using Mockit and Powermock as mocking frameworks and JUnit.

A: As indicated in the ff. post, it can be removed by @SuppressWarnings("unchecked").


text:
Q: How to pass Formcollection and Model value at the same time from view to controller? I have cshtml page having code like this
model Kouponer.Models.person_T
@using (Html.BeginForm("BuynowForm", "Home"))
{
    @Model.name
    address
    @Html.TextBox("address")

    <input type="submit" value="Submit" class="btn btn-primary" />
}

And my current actionresult method is
[HttpPost]
public ActionResult BuynowForm(FormCollection col)
{  string address = col["address"];
        return View();
}

Here I will get only the formcollection values. How to pass the model along with
the formcollection?

A: In the Controller class of System.Web.Mvc namespace there is an HttpRequestBase property called Request with all the data of the current http request. Among its properties, there is the NameValueCollection property called Form you are looking for.
The usage would be something like this:
[HttpPost]
public ActionResult BuynowForm(person_T model)
{
    string addressFromModel = model.Address;
    string addressFromRequest = Request.Form["address"];
    return View();
}

A: Unless I'm completely missing something, you should simply be able to add the model type on the controller's sig.
[HttpPost]
public ActionResult BuynowForm(Models.person_T model, FormCollection col)
{  string address = col["address"];
   string addressFromModel = model.Address;
   return View();
}

However, it seems redundant to need the FormCollection object if you are going to be using model binding. I would read the link given in the comments and just go with model binding.


text:
Q: Why can I boot Windows only with grub2 chainloader? When I updated my dual boot (Windows and Linux) PC my grub menu.lst file was deleted and I could no longer boot into Windows or Linux.
Finally I have succeeded in installing grub2 and I can boot both OSs but I cannot repair my Windows OS with the recovery console.
I've still some problems with grub2 and Windows 7 but I expected to repair it from the recovery console.
I assume the mbr of my Windows disk is ok because it works with the chainloader from grub2.
The problem is I cannot boot Windows without the chainloader or grub. It even failed to write a new boot sector because Windows cannot detect the filesystem. This happens to me with the bootrec.exe /FixBoot command. I also cannot command bootrec.exe /RepairBCD it gives the same error.


text:
Q: grep match with following lines that start with whitespace The Problem
Let's say I have a file with the following content:
lmtp_bind_address (default: empty)
       The LMTP-specific version of the smtp_bind_address configuration parameter.  See there for details.

       This feature is available in Postfix 2.3 and later.

lmtp_bind_address6 (default: empty)
       The LMTP-specific version of the smtp_bind_address6 configuration parameter.  See there for details.

       This feature is available in Postfix 2.3 and later.

lmtp_body_checks (default: empty)
       The LMTP-specific version of the smtp_body_checks configuration parameter. See there for details.

       This feature is available in Postfix 2.5 and later.

I want to get the line starting with "lmtp_bind_address6" and all following lines that start with a whitespace:
lmtp_bind_address6 (default: empty)
       The LMTP-specific version of the smtp_bind_address6 configuration parameter.  See there for details.

       This feature is available in Postfix 2.3 and later.

How can I do this in bash?
Background Info
I am moving away from Centos 7 and am setting up Postfix on Debian 8. Therefore, I intend to read the "man 5 postconf" which is 7255 lines long as of Postfix version 2.11.3. In order to speed thing up I want to group Postfix options in the manpage that cover the same thing but for different protocols such as:
smtpd_tls_mandatory_ciphers
lmtp_tls_mandatory_ciphers
smtp_tls_mandatory_ciphers
tlsproxy_tls_mandatory_ciphers

As you can see up above, each of these four options makes it possible to select the TLS ciphers, but for different protocols (SMTPD, LMTP etc.).
First, I grouped the Postfix options the following way:
postconf | awk -F"=" '{print $1}' | sed 's/ //g' | rev | sort | \
rev > postconf_options.txt

Then, I dumped the manpage to a file:
man 5 postconf > postconf_manpage.txt

Now, I want to go through the grouped list and dump every match with the following lines, that start with a whitespace, to a third file:
cat postconf_options.txt | while read I; do
  grep -w "^$I" postconf_manpage.txt
done > postconf_manpage_grouped.txt

The above grep command just gives out the line with the match, but not the following lines starting with a whitespace.
Solution
I used double quotes with sed in order to be able to use variables. Here is the complete procedure with the solution from hek2mgl:
postconf | awk -F"=" '{print $1}' | sed 's/ //g' | rev | sort | rev > postconf_options.txt
man 5 postconf > postconf_manpage.txt
cat postconf_options.txt | while read I; do sed -n "/^$I/{p;:a;n;/^[[:space:]]\|^$/{p;ba}}" postconf_manpage.txt; done > postconf_manpage_grouped.txt

A: I would use sed:
sed -n '/^lmtp_bind_address6/{p;:a;n;/^[[:space:]]\|^$/{p;ba}}' file

*

*/^lmtp_bind_address6/ matches the search pattern

*{p;:a;n;/^[[:space:]]\|^$/{p;ba}} does print the line using p, defines a label :a which acts as a jump-mark to be able to iterate over lines starting with a space. n will read another line into the pattern buffer. /^[[:space:]]\|^$/ matches a line that starts with a space or an empty line. If that's the case the line will get printed using p and we'll jump back to a using ba.

A:
I want to get the line starting with "lmtp_bind_address6" and all following lines that start with a whitespace

You can use this awk:
awk 'p && /^[^[:blank:]]/{p=0} /^lmtp_bind_address6/{p=1} p' file

lmtp_bind_address6 (default: empty)
       The LMTP-specific version of the smtp_bind_address6 configuration parameter.  See there for details.

       This feature is available in Postfix 2.3 and later.

*

*/^lmtp_bind_address6/{p=1} sets p=1 when desired pattern is found at line start

*p && /^[^[:blank:]]/{p=0} resets p=0 when p is set and when a non-blank character is found at line start.


text:
Q: gvfsd-trash's way of clearing the trash One of the way that make the laptop reach for its limits is when its clearing up the trash in a gnome based DE with nautilus based FM. With the trash has about a plethora of files (for example, a copy of the whole android open source project) clearing it up makes it very hot and stop before it can delete them.
Based on top, the process gvfsd-trash uses about 50% plus it will take a long time to do it.
Clearing the directory ~/.local/share/Trashor any directory where the "trash files" go for a hope of a salvation from deletion with a rm -rf command do the task a whole lot faster than gvfsd-trash. What does gvfsd-trash do to do that compared to a simple rm -rf command?

A: I have a hate-hate relationship with gvfsd-trash.  I think can work well on a single PC but with a small office network it can become a bit of a nightmare.  I suspect that when it empties the trash, it does the "tidying up" as it goes along.  That can get complicated when mount points are moved or permissions & ownerships are changed.  It also seems to tie up the CPU for long periods trying to work things out each time the machine starts.
My technique when gvfsd-trash starts slowing down the machines is to use:
$ sudo rm -rf ~/.local/share/Trash

This gets rid of the Trash on my own machine.  The daemon also creates directories called ".Trash-1000" in the roots of the network mounts.  Deleting them using
$ sudo rm -rf [..path to file..]/.Trash-1000

from the server where each network share resides cures a lot of performance problems.  Here "1000" is my UID, yours may be different.   "gvfsd-trash" seems to be quite good at getting rid of it's baggage once the Trash directories are gone.
NOTE:   "This works on a Ubuntu / Mint system where "sudo" provides root privileges.  With other distros use the appropriate technique.  If the "rm" command works without root privileges all the better but the problem is usually at its worst when it can't.

A: I'm not very familiar with gvfsd-trash, but I think there are a couple of things that contribute to this.  The GNOME Trash folder applies to files and folders across the entire system and even on the network.  So, I believe it keeps a database of where those files were originally stored so that if you go right-click on a file in the Trash folder and restore it, it knows where to restore it to.  It also likely keeps some other metadata about those files - like the timestamp of deletion, perhaps original ownership, access time, and modification time information - data that would normally be "lost" when the file is moved from some location on the system to a user's trash folder.  In the case of something like an Android source directory, that is a lot of files to keep that kind of metadata about, and my guess is that delete those from the Trash folder takes a while to clean up all that information.


text:
Q: Proving a matrix identity: if $Z = VT^{-1}V^T$, then $ (I - Z + Z(I + Z)^{-1}Z)^{-1} = I + Z $ I'm walking through a least squares derivation for the Kalman Filter, and after several hours I'm still unable to derive the statement made on page 15. In particular, that for a  matrix $Z = VT^{-1}V^T$,
$$
(I - Z + Z(I + Z)^{-1}Z)^{-1} = I + Z
$$
I've been attempting to use the Woodbury Matrix Identity to no avail. Is this obvious to you?

A: Just verify
$$(I+Z)(I-Z + Z(I+Z)^{-1} Z) = I - Z^2 + Z^2 = I$$

A: To flesh out Robert's answer,
$$
\begin{align*}
 & (I+Z)(I-Z+Z(I+Z)^{-1}Z) \\
=& (I - Z + Z(I+Z)^{-1}Z) + (Z - Z^2 + Z^2(I+Z)^{-1}Z) \\
=& \, I - Z^2 + Z(I+Z)(I+Z)^{-1}Z \\
=& \, I
\end{align*}
$$
I failed to notice that $Z(I+Z)^{-1}Z + Z^2 (I+Z)^{-1}Z = Z (I+Z)(I+Z)^{-1} Z = Z^2$ when originally attempting to derive this identity.


text:
Q: How to do spatial autocorrelation for 2 raster data of different spatial resolution How to create spatial autocorrelation map showing the relation between 2 raster data with different spatial resolution?
I am encountering neighborhood list error after resampling and giving moran test command.
As I am new to R language and spatial analysis, i am unable to understand and correct the error. Can anyone please help me with this?
The code which I tried:
# Load required packages

library(spdep)
library(raster)

# Load example satellite data

data("elev")
data("prec")

# Create a stack of the two variables
sat_stack <- stack(elev, prec)

# Convert the stack to a SpatialPixelsDataFrame
sat_sp <- as(sat_stack, "SpatialPixelsDataFrame")

# Check spatial autocorrelation of the satellite data
sat_moran <- moran(sat_sp, listw = nb2listw(knearneigh(coordinates(sat_sp), k = 10)))

#raster1 is not a listw object
#raster2_resampled is not a listw object\`


text:
Q: Identifying the number sequence Once I needed to calculate a certain quadratic form on random vectors:
$$
I = \sum_{i,j=1}^N x_i x_j  \;,
$$
where $x_i = \pm 1$ are random variables, the probabilities of their values are $P[x_i=-1] = P[x_i=+1] = 1/2$. All $x_i$ are statistically independent. Hence $I$ is the integer-valued random variable.
I needed to know a probability of event $I = N$. So for the start I just sampled the vectors $(x_1, \dots x_N)$ and found that the values of the $I$ give a sequence
0, 4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900, 1024, 1156, 1296, 1600, ...

(the higher $N$ the longer the sequence, of course). As seen, the condition $I = N$ may or may not be satisfied.
Does anyone have an idea about this sequence?
Here, the Python code:
import numpy as np
S = 10000
N = 10
xx = 2 * np.random.randint(2, size=(S, N)) - 1
I = np.array([ np.einsum('ij,i,j', np.ones((N, N)), xx[s], xx[s])
               for s in range(S) ])
print(np.unique(I))

A: Looks like
$(2n)^2$.
(additional characters)


text:
Q: Is it possible to get parameters of an unpublished plugin without querying the database directly? Is there a Joomla 2.5.x API that would allow for retrieval of a plugin information(i.e. parameters) if the desired plugin is unpublished?
Why: We have a few plugins that are only enabled in production and I'm looking for a way to get at some of the parameters programmatically and without querying the database directly.

A: Try something like
$userPlugin = JPluginHelper::getPlugin('user', 'joomla'); // group, specific - optional
  $userPluginParams = new JRegistry();
  $userPluginParams->loadString($userPlugin->params); //get the string as a jregistry
  $useStrongEncryption = $userPluginParams->get('strong_passwords', 0); // get the one you want.

Here's a workaround to make it not run but still able to get:
Okay how about this for a trick/workaround. Did you realize plugins have access levels? Why don't you create an access level with no one in it and assign to the plugin as the only level it runs for. Then you can publish it but it won't run.


text:
Q: Props are undefind when using StackNavigator I am new to React native and I have an issue with undefined props while using the StackNavigator component in React-Native.
I've spent some days looking an answer for my question, but didn't find a propper way to resolve an issue.
The issue is in passing props to child component, they are undefined, but, the tutorial i followed is not doing anything else except of these steps.
Here screens and code of my app

When hitting green button in my LoginScreen the expected result is navigation to my MainScreen, but the result is "props are undefined"

I would be very gratful if someone can help me to solve this problem and help me to figure out, where the problem is!
My code :
App.js file
 import React from 'react';
 import { StyleSheet, Text, View, StatusBar} from 'react-native';
 import Login from './src/components/login/Login';
 import {StackNavigator} from 'react-navigation';
 import MainScreen from './src/components/main/MainScreen';

 export default class App extends React.Component {
   static navigationOptions = { title: 'Welcome', header: null };
   render() {
     return (
     <AppNavigation />
     );
    }
 }
  const AppNavigation = StackNavigator({
    LoginScreen : {screen : Login},
    MainScreen : {screen : MainScreen},
  })
  const styles = StyleSheet.create({
    container: {
      backgroundColor: '#3498db',
      alignItems: 'center',
      justifyContent: 'center',
    },
  });

Login.js , this component describes my Login page. It also renders component LoginForm, where i'm describing InputText and TouchableOpacity where i have onPress method, which must navigate me to MainScreen
import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Image
} from 'react-native';
import LoginForm from './LoginForm'

export default class Login extends React.Component {
  static navigationOptions = { title: 'Welcome', header: null };

  render() {
    return (
      <View style={styles.container}>
          <View style={styles.logoContainer}>
            <Image
              source = {require('../../../images/logo.png')}
              style = {styles.logo}>
            </Image>
            <Text style = {styles.title}>Добро пожаловать!</Text>
            <Text style = {styles.titleLower}>Введите код для         авторизации</Text>
      </View>

      <View style = {styles.formContainer}>
        <LoginForm/>
      </View>
  </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex : 1,
    backgroundColor : '#3493db'
  },
  logoContainer : {
    flexGrow : 1,
    alignItems : 'center',
    justifyContent : 'center'
  },
  logo : {
    width : 120,
    height : 120
  },
  title : {
    color : '#fff',
    marginBottom : 10,
    fontSize : 22
  },
  titleLower : {
    color : '#fff',
    marginTop : 5,
    fontSize : 12
  }
});

LoginForm.js
import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  KeyboardAvoidingView,
  StatusBar
} from 'react-native';

export default class LoginForm extends Component {
  render() {
    return (

  <KeyboardAvoidingView
  behavior="padding"
  style={styles.container}>

    <TextInput
       placeholder = "ваш пароль"
       placeholderTextColor = '#fff'
       underlineColorAndroid = {'transparent'}
       style = {styles.input}
       secureTextEntry>
     </TextInput>

    <TouchableOpacity
      style= {styles.buttonContainer}
      onPress = {() =>
        this
        .props
        .navigation
        .navigate('MainScreen')}>
        <Text  style= {styles.buttonText}>Войти</Text>
    </TouchableOpacity>
</KeyboardAvoidingView>

);
  }
}

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  input : {
    backgroundColor : 'rgba(255, 255, 255, 0.2)',
    height : 40,
    marginBottom : 10,
    color : '#FFF',
    fontSize : 16
  },
  buttonContainer : {
    backgroundColor : '#00B241',
    paddingVertical : 10,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom : 30
  },
  buttonText : {
    textAlign : 'center',
    color : '#fff'
  }
});

A: I believe the issue is that LoginForm.js is nested inside of login.js.
So, when you call this.props.navigation.navigate('MainScreen'), loginForm.js has no idea what navigation is, because it belongs to Login.js.
I believe passing the navigation object to loginForm.js from login.js will solve this issue:
<LoginForm screenProps={{ navigation: this.props.navigation }} />

A: Pass navigation props to loginForm. It works for me
<LoginForm navigation={this.props.navigation} />


text:
Q: How to pass cognito confidential app client credentials for creating boto3 cognito-idp client? Context

*

*Created aws cognito userpool

*Created 2 app clients for that user pool first public client (for frontend), second confidential client (for backend)

*Created frontend in react that uses aws cognito, frontend passes idToken to server

*Server is able to verify idToken and able to extract username from that id token.

Problem
I'm trying to update user attributes from backend, using CognitoIdentityProvider.Client.admin_update_user_attributes But getting an error The security token included in the request is invalid..
For aws_access_key_id and aws_secret_access_key I'm passing the values that I got while creating aws cognito confidential app client. IE app client id and app client secret key.
Code
import boto3

user_pool_id = "xxx"

client = boto3.client(
  'cognito-idp',
  aws_access_key_id="xxx",
  aws_secret_access_key="xxx",
  region_name='xxx'
)

print(client.admin_get_user(
  UserPoolId="xxx",
  Username="xxx"
))

Exception thrown
botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the ListUsers operation: The security token included in the request is invalid.

A: What I was doing was completely wrong.
The documentation read Calling this action requires developer credentials.
Which means you cannot use app client id and app client secret for granting access to cognito-idp:Admin* actions. You need to create IAM user with proper permissions.
The solution was to

*

*create IAM policy with cognito-idp:* permissions

*create new IAM user and attach the policy just created.

*use access_key_id and access_key_secret for that user to initialize boto client.


text:
Q: Button animation doesn't work properly in swift I'm making an app in swift using Xcode and I'm having troubles with the animation of some button.
Here's my situation:

I have three buttons in the middle of the screen where i've also added some constraints.
What i need is that when the button is clicked it reaches the top of the screen, like in this second photo with an animation:

I've tried this:
UIView.animateWithDuration(1, delay: 0, options: [], animations: {
        self.Button2.center.y = 18 + self.Button2.frame.height/2

        }, completion: nil)

But what happens is that the button appears from the bottom of the screen slides up to the position of the first photo. It doesn't respect the position I wrote in the animation. Is it possibile that this is due to the constraints? Because I centered it vertically and horizontally.
Can you help me to make it work?

A: When you work with autolayout and constraints you never make changes to the button frame in your animation, like your code: you must work always with constraints.
This is a generic example:
myButtonCenterYConstraint.constant = 200.0
myButton.layoutIfNeeded()
UIView.animateWithDuration(Double(0.5), animations: {
        myButtonCenterYConstraint.constant = 0
        myButton.layoutIfNeeded()
})

So, the first step is to declare the button constraints you will want to change as IBOutlets:

A: First get the center y of the button then reposition the button.
float centerY = self.Button2.center.y;

UIView.animateWithDuration(1, delay: 0, options: [], animations: {
    self.Button2.center.y = centerY + 18 + self.Button2.frame.height/2

    }, completion: nil)

A: You must change the constraint first and then update the UI in animation. Something like this.
yourButton.yourOriginConstraint'sYCoordinate.constant = // Set this to what you want to change.

// yes, you should create an IBOutlet for constraint that you want to modify.

UIView.animateWithDuration(1.0, animations: {
            self.view.layoutIfNeeded()
            }, completion: nil)

Another  way is to not user auto layout.
Here, is the reference


text:
Q: String concatenation with a space In K&R, I saw an example where a string can be concatenated with a space"
char *s = "abc" "foo";
printf("%s", s); // prints "abcfoo"

How is space string concatenation different from using strcpy and strcat?

A: Adjacent string literal are concatenated by the pre-processor. From the draft C99 standard section 5.1.1.2 Translation phases paragraph 6:

Adjacent string literal tokens are concatenated

so it creates one string literal as a result.

A: Try:
    char *s = "abc" " " "foo";
BTW: it is not concatenation per se, it is just a method for initialising a string with a concatenation of a bunch of literals.


text:
Q: Alter SQL Server Column in PDO I am trying to make an existing ID column in a SQL Server
database AUTO_INCREMENT. I do not have access to the GUI.
I am trying this query.
$stmt = $this->conn()->prepare('ALTER TABLE myTable ALTER COLUMN ID int NOT NULL auto_increment');
if($stmt->execute()){

}else{
    echo "<pre>";
    print_r($stmt->errorInfo());
    echo "</pre>";
}

This gives the following error     [2] => Incorrect syntax near 'auto_increment'. [20018] (severity 5) [(null)]
Thanks for the help.

A: Well that code certainly won't work on SQL Server where you can't alter table to add an identity functionality to a field after the table is created.
And it wouldn't work even if it could because Identity is what you use on SQL Server no autoincrement.
You need to add the identity as a separate column or do what SSMS does and create a new table with the identity, move the data and then drop the old table and rename the new one.
I can't speak for how to do it in mysql.
Incidentally ID is a horrible name for a PK field. Please use tablenameID. You will avoid alot of accidental bad joins and make reporting much easier.


text:
Q: Dio's get request returning incomplete data I'm making a get request with the Dio library (https://pub.dev/packages/dio), but apparently it is not getting all the data in the coming json.
Here's the request:

This is the json that comes from it:

But this is the Response object I get from this request:
:
Note how the "headers" field in the json has substantially more values than my headers field in response.data.
Am I doing something wrong here?

A: You are returning response without extract it's content. That's OK, but you need to extract the body from response where you are calling this method:
http.Response response = await _yourApi.getData();

if (response.statusCode == 200) {
    //Do what you want with body
    final body = response.body;
}


text:
Q: TinyMCE browser "fixes" I'm getting a javascript error in Firefox and Opera when I'm using TinyMCE:
j is null
(function(d){var a=/^\s*|\s*$/g,e,c="B...a.selection.onSetContent.add(f)})}});

This error comes up after I save the contents of the textarea for the 2nd time, 3rd etc. First time it gets saved...
Since it's working fine in the other browsers (IE and Chrome), I assume the issue is within the "TinyMCE" fixes which Opera and probably Firefox too are running...
Is there any way I can stop these browsers from applying these fixes? Anyway it seems ridiculous to me for a browser to attempt to fix a 3rd party script

A: it's a tinymce bug. Internally, the tinymce code uses a  to remember the caret-position when pasting. when validating the resulting fragment, after the paste, the span is deemed invalid and removed, thus breaking the code by removing the marker.
This issue will be fixed in the next official tinymce minor release. There are some workarounds for this kind of issue. One is to add id and mce-data-type attribute to spans as valid elements (init setting). Example:
// The valid_elements option defines which elements will remain in the edited text when the editor saves.
    valid_elements: "@[id|class|title|style]," +
    "a[name|href|target|title]," +
    "#p,-ol,-ul,-li,br,img[src],-sub,-sup,-b,-i,-u," +
    "-span[data-mce-type]",


text:
Q: Object does not contain a definition for links and no extension method links accepting first arguments of type links     private void UpdateWebsiteBrowser(string link)
    {
        int i = 0;
        if (MyBrowser.Document != null)
        {
            for (i = 0; i <= MyBrowser.Document.links.length - 1; i++)
            {
                if (string.Compare(HttpUtility.HtmlDecode(MyBrowser.Document.links.Item(i).href), HttpUtility.HtmlDecode(link), true) == 0)
                {
                   MyBrowser.Document.links.Item(i).Style.backgroundColor = "red";
                }
            }
        }
    }

Error in MyBrowser.Document.Links

Object does not contain a definition for links

A: Document is of type object - WebBrowser.Document and hence have no property links or Links.
Depending on what you need you may get away with using dynamic (see How to get the Document's Title from a Web Browser control in wpf for example) or need to select elements yourself (How to get value from any tag in web browser control using wpf) or cast to mshtml.HTMLDocument.


text:
Q: Angular6 rxjs unsubscribing to timer subscription OnDestroy does not work? So I have a timer where I call an api every 60 seconds (it's a digital signage app so there won't be any interaction yet I want it to auto update)
I have various components that load different api calls but the problem is, when I'm trying to unsubscribe to these timer subscriptions ondestroy it simply does not work.
I go in, test by routing to 2 components back and forth 5-6 times. This should normally kil subscription everytime I go to the next one.
After 60 seconds passes, there's as many api calls being made as many times I've switched between those two. so I've created a timer subscription everytime I went on one of the components but did not destroy them.
EDIT, added my full OnInit and OnDestroy code below:
ngOnInit() {

    let mainTimer = timer(0, 60000);

    this.dataSourceSubscription = mainTimer.subscribe(t => {
      this.service.getSection3();
      this.dataSourceSubscription = this.section3.subscribe(data => {
        let countAccepted = data => {
          for (let i = 0; i < data.length; i++) {
            if (
              data[i].DeliveryStatus == "Accepted" &&
              data[i].BookingId == "0"
            ) {
              this.multidropAccepted++;
            }
          }
        };

        let countDepartedSite = data => {
          for (let i = 0; i < data.length; i++) {
            if (
              data[i].DeliveryStatus == "Departed Site" &&
              data[i].BookingId == "0"
            ) {
              this.multidropDepartedSite++;
            }
          }
        };

        let countPending = data => {
          for (let i = 0; i < data.length; i++) {
            if (
              data[i].DeliveryStatus == "Pending" &&
              data[i].BookingId == "0"
            ) {
              this.multidropPending++;
            }
          }
        };

        let countOnSite = data => {
          for (let i = 0; i < data.length; i++) {
            if (
              data[i].DeliveryStatus == "On Site" &&
              data[i].BookingId == "0"
            ) {
              this.multidropOnSite++;
            }
          }
        };

        let countTurnedAway = data => {
          for (let i = 0; i < data.length; i++) {
            if (
              data[i].DeliveryStatus == "Turned Away" &&
              data[i].BookingId == "0"
            ) {
              this.multidropTurnedAway++;
            }
          }
        };

        (this.dataSource = new MatTableDataSource(
          data.filter(
            (value, index, array) =>
              !array.filter(
                (v, i) => JSON.stringify(value) == JSON.stringify(v) && i < index
              ).length
          )
        )),
          (this.dataSource.sort = this.sort),
          (this.dataSource.paginator = this.paginator),
          this.multidropAccepted = 0;
          this.multidropDepartedSite = 0;
          this.multidropPending = 0;
          this.multidropOnSite = 0;
          this.multidropTurnedAway = 0;
          countAccepted(data),
          countDepartedSite(data),
          countPending(data),
          countOnSite(data),
          countTurnedAway(data),
          this.totalDeliveries = data.length;
      });

      this.lastUpdated.subscribe(data => {
        console.log(data);
      })
    })

    let pageTimer = timer(10000, 10000);

    this.pageSubscription = pageTimer.subscribe(t => {
      if (
        this.dataSource.paginator._pageIndex ==
        this.dataSource.paginator.getNumberOfPages()
      ) {
        this.dataSource.paginator.firstPage();
      } else {
        this.dataSource.paginator.nextPage();
      }
    });
  }

  ngOnDestroy() {
    this.dataSourceSubscription.unsubscribe();
    this.pageSubscription.unsubscribe();
  }

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

A: So from what you described in the question, generally speaking, I don't think there is anything wrong with how you subscribe & unsubscribe the observable.
Which means the mistake must be something silly.
To investigate further, please check:

*

*Is there any typo with your code?

*Is ngOnDestroy() really executed? - put a console log there and see if it really gets called when you switch away from your current page. If not, you probably staying the same route rules even if the page seems to be changed.

The subscription gets overwritten so it's no longer pointing to the timer. When you destroy (unsubscribe) it, it's actually unsubscribe the inner observable, not the timer observable.
this.dataSourceSubscription = mainTimer.subscribe(t => {
  this.dataSourceSubscription = this.section3.subscribe(data => {});
});