text:
Q: XSLT: Insert nodes at root of svg file My goal is to add the two nodes <style> and <whatever> to my SVG file using the XSLT below, but I'm facing two problems. First, when adding <style>, it's including three xmlns attributes I don't want:
<style xmlns=""
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:svg="http://www.w3.org/2000/svg">.val{--valence: #4599a3}</style>

Then, it's not adding my second node <whatever>.
How can I fix it ?
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:svg="http://www.w3.org/2000/svg" version='1.0'>

    <!-- this template is applied by default to all nodes and attributes -->
    <xsl:template match="@*|node()">
        <!-- just copy all my attributes and child nodes, except if there's a better template for some of them -->
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

   <xsl:template match="svg:title">
      <xsl:copy-of select="."/>
      <style>.val{--valence: #4599a3}</style>
   </xsl:template>

    <xsl:template match="svg:title">
        <xsl:copy-of select="."/>
        <whatever>foo</whatever>
    </xsl:template>

    <xsl:template match="svg:defs/svg:circle">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:attribute name="style">fill: var(--valence, #47565b)</xsl:attribute>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

A: *

*Namespaces are inherited. To get rid of them, you need to set another namespace or an empty namespace (creating the xmlns="" which means no namespace/empty namespace).  To remove the
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:svg="http://www.w3.org/2000/svg"

One way you can solve this is by explicitly defining the element with an xsl:element:
<xsl:element name="whatever" namespace="">foo</xsl:element>

Now you only have the xmlns="" left on the element. To also remove this, set the namespace to the default namespace - here probably http://www.w3.org/2000/svg
<xsl:element name="whatever" namespace="http://www.w3.org/2000/svg">foo</xsl:element>

Now the element appears as <whatever>foo</whatever>, but remember that it actually has the inherited default namespace.

*
Then, it's not adding my second node <whatever>.

This happens because you have two templates with the same matching rule match="svg:title". Make the matching rules unique and it will work.

A: If you want to add elements in the SVG namespace then you need to use it, so if the whole stylesheet is supposed to create SVG elements and you have it already declared on the root element as you have with
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:svg="http://www.w3.org/2000/svg" version='1.0'>

you can create an SVG style element using svg:style:
   <xsl:template match="svg:title">
      <xsl:copy-of select="."/>
      <svg:style>.val{--valence: #4599a3}</svg:style>
   </xsl:template>

As an alternative, you can put a default namespace declaration xmlns="http://www.w3.org/2000/svg" on the root element of the stylesheet e.g.
<xsl:stylesheet
  xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
  xmlns:svg="http://www.w3.org/2000/svg"
  xmlns="http://www.w3.org/2000/svg"
  version='1.0'>

  ..
   <xsl:template match="svg:title">
      <xsl:copy-of select="."/>
      <style>.val{--valence: #4599a3}</style>
   </xsl:template>

xsl:element is not needed.
As for the other namespace declarations you declare on the root element for XPath expressions or XSLT match patterns but you don't want to be used for result elements, you can use the exclude-result-prefixes attribute on xsl:stylesheet/xsl:transform e.g. exclude-result-prefixes="xsi svg"
<xsl:stylesheet
      xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
      xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
      xmlns:svg="http://www.w3.org/2000/svg"
      xmlns="http://www.w3.org/2000/svg"
      exclude-result-prefixes="xsi svg"
      version='1.0'>

    <!-- this template is applied by default to all nodes and attributes -->
    <xsl:template match="@*|node()">
        <!-- just copy all my attributes and child nodes, except if there's a better template for some of them -->
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

   <xsl:template match="svg:title">
      <xsl:copy-of select="."/>
      <style>.val{--valence: #4599a3}</style>
   </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/gWvjQeY


text:
Q: Calc function with vh and px does not work in safari I am trying to set the height of a section using calc function as follows -
{
    min-height: calc(100vh - 291px);
    min-height: -webkit-calc(100vh - 291px);
}

This works in all browsers but Safari. Safari does not show any error. It reads this property but the calculation it makes is not accurate and breaks the layout. Can anyone explain what's going on and how can this be fixed?
Please note -  I am aware of the JS workarounds but I cannot use JS here.
Thanks in Advance

A: See Caniuse, also look at this SO question

Safari & iOS Safari (both 6 and 7) does not support viewport units for
  border widths, column gaps, transform values, box shadows or in
  calc().

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python: Find index of minimum item in list of floats How can I find the index of the minimum item in a Python list of floats? If they were integers, I would simply do:
minIndex = myList.index(min(myList))

However, with a list of floats I get the following error, I assume because float equality comparison is rather iffy.
ValueError: 0.13417985135 is not in list

Now, I know that I could simply scroll through the list and compare each item to see whether it is < (min + 0.0000000000001) and > (min - 0.0000000000001), but that is kinda messy. Is there a more elegant (preferably built-in) way to find the index of the smallest item in a list of floats?

A: You're effectively scanning the list once to find the min value, then scanning it again to find the index, you can do both in one go:
from operator import itemgetter
min(enumerate(a), key=itemgetter(1))[0]

A: Use of the argmin method for numpy arrays.
import numpy as np
np.argmin(myList)

However, it is not the fastest method: it is 3 times slower than OP's answer on my computer. It may be the most concise one though.

A: I think it's worth putting a few timings up here for some perspective.
All timings done on OS-X 10.5.8 with python2.7
John Clement's answer:
python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop

David Wolever's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop

OP's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop

Note that I'm purposefully putting the smallest item last in the list to make .index as slow as it could possibly be.  It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.
Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).

A: I would use:
val, idx = min((val, idx) for (idx, val) in enumerate(my_list))

Then val will be the minimum value and idx will be its index.


text:
Q: Refactoring an existing abstract class and its parameters I have an abstract class A which declares an abstract method doStuff.  Currently there are many classes that inherit from A and implement doStuff.
The class' instances are initialized at run-time via AFactory based on user input.
Originally all the classes had the same single parameter (the user input). But now I have an additional parameter that only a new class that inherits A needs.
So breaking it down I though of the following logic:

*

*The interpreter class that generates instances based on user input(using AFactory of course) was not aware of this extra parameter.

*

*Trying to push it into the class interpreter class would be really awkward because then I would have to know when to pass it to the factory which defeats the whole purpose of having a factory in the first place.

*Sending it blindly into the Factory hoping it might do something with it seems quite ugly as well.

*My current solution: Meanwhile I've decided to refactor A.doStuff(Param param) into A.doStuff(AParams params).
AParams can hold what ever parameters needed and doStuff can ignore then if they're not interested in them. This also seems a bit awkward to me , and remids me of sending structs in WIN32API that can hold a lot of ugly useless parameters and I'm not fond of it.
Is there a more elegant way to approach this problem ? Or some design pattern that I've overlooked and solves this?
Notes :

*

*We're using Java 1.7

*The class' names are silly in order to emphasize the theoretical design issue they do have normal indicative, meaningful names in reality :)

*I did search quite a lot but having figured out that it's quite hard to search the web for specific abstract theoretical issues (as opposed to why is X throwing Exception in this code) I've decided to ask anyway so I'm sorry if this is a duplicate.

Edit 1:

*

*Clarification: I need to pass a subclass-specific argument to the doStuff method.

EDIT 2:

*

*I did not fully understand Kilian Foth's intention so I've written some Java-pseudo-code to help me better explain the problem/understand your solution. So:
This is a skeleton of my problem.
This is a skeleton of my solution.
This is what I think  might be Kilian Foth's solution, but I'm not sure.

A: The point of a factory is to hide the fact that you may get objects from slightly different classes. Therefore, if some of these objects need certain data and others don't...

*

*Either they aren't similar enough to be produced by the same factory. Then you need to have more than one factory and make the decision way earlier than you are currently doing.

*Or they are similar enough that the client isn't supposed to care which one they get. Then you can't expect the client to care about whether to send the extra data or not. It follows that they must always be passed, but the factory will sometimes ignore them without bothering the client with that implementation detail. Anything else would burden the client with the very distinction that the factory was supposed to conceal.

A: I handle this by using something like a Builder that contains various factories. The Builder is given hashes that contain the factories to make various types of objects, and it will look into the hash and retrieve the correct factory based on whatever criteria.
For example, I have multiple question types, and all of these can be made by some implementation of an IQuestionFactory. Most of the IQuestionFactory implementations are subclasses of BaseQuestionFactory, and they receive XML that represents one question and parse it according to the rules of the question, returning back some subclass of BaseQuestion.
Some questions need more information, such as if it is a form-filling question there might be a section of the XML that contains the questions that defines the fields that are used in the form. The Factories that make these questions implement IEnhancedQuestionFactory, and the builder will check the Factory that it retrieves from the QuestionFactoryRegistry and check to see if it implements this Interface. If it does, it passes the full XML of the file that contained the questions in addition to the individual XML that goes to the createQuestion method.
To show you how flexible this can get, some of the IQuestionFactory implementations are simply shells that contain multiple question factories, and they can look at the incoming XML and then call an internal factory and return whatever that makes. We use this when an XML file contains multiple question types.
However, it sounds like you need something more like the way we build Exercises (which are essentially Controllers wrapped around a collection of Questions), where the hash (ExerciseFactoryMap) is set up to return a default factory most of the time, but in cases where it has a specific Factory registered, it will return that. And we do have one specific Factory that will create an Exercise subclass that has an additional property, and it has the additionall capability to look at the XML and find the information that it needs to populate that property.
So, I'd agree with Killian Foth that the point of a factory is to hide the implementation details of how the object is being constructed, but there's nothing that says you can't combine multiple Factories in creative ways (for example, a Factory that contains other Factories that do the real work).

A: *

*The usual approach in cases like this (Command patternish) is passing additional parameters in the constructor. In your case, that means adding otherArgument to B during construction.

*Turning the logic around might open up some options. For instance moving doStuff to AParams:
for (String arg : listOfArgs) {
    AParams p = AParams.create(arg, otherArgument));
    for (A a : listOfA) {
        p.doStuff(a); // Let AParams to the lifting depending on type of A
    }
}

*Alternatively you can swallow your pride and check with instanceof in the loop and set otherArgument manually before calling doStuff.
If the above is not possible, then you have no choice except doing what you're doing (broadening the parameter argument). Don't overanalyze this stuff.


text:
Q: i want to merge array having one unique value like id and other are different values and key also     Array(
        [0] => Array(
            [billing_first_name] => pp
            [user_id] => 1
        )
        [1] => Array(
            [billing_last_name] => pp
            [user_id] => 1
        )
        [2] => Array(
            [billing_city] => Nagpur
            [user_id] => 1
        )
        [3] => Array(
            [billing_first_name] => gaurav
            [user_id] => 6
        )
        [4] => Array(
            [billing_last_name] => bokade
            [user_id] => 6
        )
    )

and I want Result As :
    Array(
        [0] => Array(
            [user_id] => 1
            [billing_first_name] => pp
            [billing_last_name] => pp
            [billing_city] => Nagpur
        )
        [1] => Array(
            [user_id] => 6
            [billing_first_name] => gaurav
            [billing_last_name] => bokade
            [billing_city] =>
        )
    )

A: <?php
    $array = array(
                array('billing_first_name' => 'pp','user_id' => 1),
                array('billing_last_name' => 'pp','user_id' => 1),
                array('billing_city' => 'Nagpur','user_id' => 1),
                array('billing_first_name' => 'gaurav','user_id' => 6),
                array('billing_last_name' => 'bokade','user_id' => 6)
            );

    foreach($array as $r){
        foreach($r as $key => $s){
            $new[$r['user_id']][$key] = $s;
        }
    }
    echo "<pre>";print_r($new);
?>

Result
Array
(
    [1] => Array
        (
            [billing_first_name] => pp
            [user_id] => 1
            [billing_last_name] => pp
            [billing_city] => Nagpur
        )

    [6] => Array
        (
            [billing_first_name] => gaurav
            [user_id] => 6
            [billing_last_name] => bokade
        )

)


text:
Q: Reference request: indefinite orthogonal groups $O(p,q)$, spin groups $\mathrm{Spin}(p,q)$, and projective orthogonal groups $PO(p,q)$ The indefinite orthogonal group $O(p,q)$ is the orthogonal group preserving the standard scalar product of signature $(p,q)$ on $\mathbb{R}^{p+q}$.
Are there any good references that discuss the properties of these indefinite orthogonal groups and related groups such as indefinite spin groups and projective orthogonal groups? Some things that I'm looking for include:

*

*the representation theory of $O(p,q)$ and its orbits in the standard representation

*the spin groups $\mathrm{Spin}(p,q)$ and their representation theory

*the universal cover of the identity component $O_0(p,q)$

*the projective groups $PGO(p,q)$ and $PSO(p,q)$, and their representation theory

A: References or  addressing some of your points are given in answers to this question.


text:
Q: Get all rows from SQLite I have been trying to get all rows from the SQLite database. But I got only last row from the following codes.
FileChooser class:
public ArrayList<String> readFileFromSQLite() {

  fileName = new ArrayList<String>();

  fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
  fileSQLiteAdapter.openToRead();
  cursor = fileSQLiteAdapter.queueAll();

  if (cursor != null) {
    if (cursor.moveToFirst()) {
      do {
        fileName.add(cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1)));
      } while (cursor.moveToNext());

    }
    cursor.close();
  }

  fileSQLiteAdapter.close();
  return fileName;
}

FileSQLiteAdapter class:
public Cursor queueAll() {
  String[] columns = new String[] { KEY_ID, KEY_CONTENT1 };

  Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns, null,
                null, null, null, null);
  return cursor;
}

Please tell me where is my incorrect. Appreciate.

A: try:
Cursor  cursor = db.rawQuery("select * from table",null);

AND  for List<String>:
if (cursor.moveToFirst()) {
  while (!cursor.isAfterLast()) {
    String name = cursor.getString(cursor.getColumnIndex(countyname));

    list.add(name);
    cursor.moveToNext();
  }
}

A: Using Android's built in method
If you want every column and every row, then just pass in null for the SQLiteDatabase column and selection parameters.
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null, null);

More details
The other answers use rawQuery, but you can use Android's built in SQLiteDatabase. The documentation for query says that you can just pass in null to the selection parameter to get all the rows.

selection Passing null will return all rows for the given table.

And while you can also pass in null for the column parameter to get all of the columns (as in the one-liner above), it is better to only return the columns that you need. The documentation says

columns  Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.

Example
SQLiteDatabase db = mHelper.getReadableDatabase();
String[] columns = {
        MyDatabaseHelper.COLUMN_1,
        MyDatabaseHelper.COLUMN_2,
        MyDatabaseHelper.COLUMN_3};
String selection = null; // this will select all rows
Cursor cursor = db.query(MyDatabaseHelper.MY_TABLE, columns, selection,
        null, null, null, null, null);

A: This is almost the same solution as the others, but I thought it might be good to look at different ways of achieving the same result and explain a little bit:
Probably you have the table name String variable initialized at the time you called the DBHandler so it would be something like;
private static final String MYDATABASE_TABLE = "anyTableName";

Then, wherever you are trying to retrieve all table rows;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + MYDATABASE_TABLE, null);

List<String> fileName = new ArrayList<>();
if (cursor.moveToFirst()){
   fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
   while(cursor.moveToNext()){
      fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
   }
}
cursor.close();
db.close();

Honestly, there are many ways about doing this,

A: I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:
String name;
if (cursor.moveToFirst()) {

        while (cursor.isAfterLast() == false) {
            name = cursor.getString(cursor
                    .getColumnIndex(countyname));

            list.add(name);
            cursor.moveToNext();
        }
}

A: Update queueAll() method as below:
public Cursor queueAll() {

     String selectQuery = "SELECT * FROM " + MYDATABASE_TABLE;
     Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);

     return cursor;
}

Update readFileFromSQLite() method as below:
public ArrayList<String> readFileFromSQLite() {

    fileName = new ArrayList<String>();

    fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
    fileSQLiteAdapter.openToRead();

    cursor = fileSQLiteAdapter.queueAll();

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do
            {
                String name = cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1));
                fileName.add(name);
            } while (cursor.moveToNext());
        }
        cursor.close();
    }

    fileSQLiteAdapter.close();

    return fileName;
}

A: Cursor cursor = myDb.viewData();

        if (cursor.moveToFirst()){
              do {
                 String itemname=cursor.getString(cursor.getColumnIndex(myDb.col_2));
                 String price=cursor.getString(cursor.getColumnIndex(myDb.col_3));
                 String quantity=cursor.getString(cursor.getColumnIndex(myDb.col_4));
                 String table_no=cursor.getString(cursor.getColumnIndex(myDb.col_5));

                 }while (cursor.moveToNext());

                }

                cursor.requery();

A: public List<String> getAllData(String email)
{

    db = this.getReadableDatabase();
    String[] projection={email};

    List<String> list=new ArrayList<>();

    Cursor cursor = db.query(TABLE_USER, //Table to query
            null,    //columns to return
            "user_email=?",        //columns for the WHERE clause
            projection,        //The values for the WHERE clause
            null,       //group the rows
            null,       //filter by row groups
            null);
    //  cursor.moveToFirst();

    if (cursor.moveToFirst()) {
        do {

            list.add(cursor.getString(cursor.getColumnIndex("user_id")));
            list.add(cursor.getString(cursor.getColumnIndex("user_name")));
            list.add(cursor.getString(cursor.getColumnIndex("user_email")));
            list.add(cursor.getString(cursor.getColumnIndex("user_password")));
            // cursor.moveToNext();

        } while (cursor.moveToNext());
    }
    return list;
}

A: a concise solution can be used for accessing the cursor rows.
while(cursor.isAfterLast)
{
    cursor.getString(0)
    cursor.getString(1)
}

These records can be manipulated with a loop


text:
Q: PHP SOAP wsdl Fatal Error & Xdebug I really don't understand what's happening with PHP SOAP library
I use a SOAP service, it's working well but sometimes i have the well-know
"Fatal error:  SOAP-ERROR: Parsing WSDL: ........"
I have read that this error was uncatchable because Xdebug was on and that the solution is to disable it to be able to catch the error,...
but i doesn't work ! the error is displayed with the orange and red colors
do you have an idea ??
(I use the last version of wamp, i don't know how to check if i choosed 64 or 32bits but it's apache 2.2.22, php 5.3.13)
thanks in advance for your help ! :)
<?php
xdebug_disable();
try {
  $sc = new SoapClient("some-wrong.wsdl", array('exceptions' => true));
} catch (Exception $e) {
  echo 'Error Caught :-)';
}
?>

I want to add that :
sometimes I have 2 warning and 1 error
 - Warning: SoapClient::SoapClient -> "failed to open stream ..."
 - Warning: SoapClient::SoapClient -> "failed to load external entity ..."
 - Fatal error: SOAP-ERROR: Parsing WSDL -> "Couldn't load from ..."

and sometimes, just the fatal error
I have placed an echo just after the line new SoapClient(.....
and when there's an uncatched error, the echo is not displayed
I have to add that I call SoapClient with
'trace'      => 1,                                                      'exceptions' => 1,
and i have this in apache error log (** used to hide)
[Thu Jan 31 16:16:02 2013] [error] [client 127.0.0.1] PHP Fatal error:  SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://******?wsdl' : Start tag expected, '<' not found\n in D:\\Programmes\\wamp\\www\\******.php on line 144, referer: http://localhost/******.php
[Thu Jan 31 16:16:04 2013] [error] [client 127.0.0.1] PHP Warning:  ||| faultcode: WSDL ||| faultstring: SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://******?wsdl' : Start tag expected, '<' not found\n ||| in D:\\******.php on line 201, referer: http://localhost/******.php
[Thu Jan 31 16:16:04 2013] [error] [client 127.0.0.1] PHP Fatal error:  Call to a member function __getLastRequestHeaders() on a non-object in D:\\Programmes\\wamp\\www\\******.php on line 204, referer: http://localhost/******.php

I edit my first message because i am new memebr and can t answer to my own message before 8 hours
so this morning, I have change the default stack size of apache because apache was craching with just this line in the apache error log : [notice] Parent: child process exited with status 255 -- Restarting.

*

*I have installed visual basic 2012 (evaluation ;) )

*used the visual basic command console (start > Micrososft Visual Studio 2012 > Visual studio tools)

*checked the sire typing "cd ***my_path_containing_apache_bin_directory**\bin
dumpbin /all httpd.exe | find "stack"" (is was " 40000 size of stack reserve " )

*increase the size typing editbin /stack:1048576 httpd.exe

*And don't forgot to PUT ADMINISTRATOR RIGHT on the httpd.exe file + exit WANP !!! (I lost a morning because of this !, editbin was returning a LINK error !!)

-> It s strange because after to have done this, I had WSDL uncaught errors but since few hours I have not this kind of error, may be it s just the proxy list that I use that are able to connect correctly,..  ??

A: The SOAP extension does some strange things and overrides an internal PHP errorhandler. This conflicts a little with Xdebug's error overriding mechanisms. Do include the full error message though, and I can perhaps update my answer from there on.

A: Here s the detailed error message Xdebug I get (** to hide)
( ! ) Warning: SoapClient::SoapClient(http://****?wsdl) [soapclient.soapclient]: failed to open stream: Une tentative de connexion a �chou� car le parti connect� n�a pas r�pondu convenablement au-del� d�une certaine dur�e ou une connexion �tablie a �chou� car l�h�te de connexion n�a pas r�pondu. in D:\Programmes\wamp\www\****.php on line 146
Call Stack
#   Time    Memory  Function    Location
1   0.0013  497672  {main}( )   ..\script gepir3-1.php:0
2   0.6920  695896  SoapClient->SoapClient( )   ..\script gepir3-1.php:146

( ! ) Warning: SoapClient::SoapClient() [soapclient.soapclient]: I/O warning : failed to load external entity "http://****?wsdl" in D:\Programmes\wamp\www\****.php on line 146
Call Stack
#   Time    Memory  Function    Location
1   0.0013  497672  {main}( )   ..\script gepir3-1.php:0
2   0.6920  695896  SoapClient->SoapClient( )   ..\script gepir3-1.php:146

( ! ) Fatal error: SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://*****.asmx?wsdl' : failed to load external entity "http://****asmx?wsdl" in D:\Programmes\wamp\www\****.php on line 146
Call Stack
#   Time    Memory  Function    Location
1   0.0013  497672  {main}( )   ..\script gepir3-1.php:0
2   0.6920  695896  SoapClient->SoapClient( )   ..\script gepir3-1.php:146

And i don't understand why my php.ini contains this parameter turned to off (the autostart is missing too
; XDEBUG Extension

zend_extension = "D:/Programmes/wamp/bin/php/php5.3.13/zend_ext/php_xdebug-2.2.0-5.3-vc9.dll"

[xdebug]
xdebug.remote_enable = off
xdebug.profiler_enable = off
xdebug.profiler_enable_trigger = off
xdebug.profiler_output_name = cachegrind.out.%t.%p
xdebug.profiler_output_dir = "D:/Programmes/wamp/tmp"

A: Maybe it's a bit late but Opcache module also interferes with XDebug : https://xdebug.org/docs/compat
It must be disabled in order to work with NetbeansIDE


text:
Q: suppose $A=[a_{ij}]$ is symmetric and positive definite. How can I show that $B=[|a_{ij}|]$ is symmetric and positive definite? For $n\le 3$ suppose $A=[a_{ij}]$ is symmetric and postive definite. How can I show that $B=[|a_{ij}|]$ is symmetric and positive definite?
I know these statements:

*

*A symmetric $n \times n$ matrix is positive definite if and only if all its eigenvalues are positive

*A symmetric matrix $A$ is positive definite if and only if all its leading principal minors are positive; that is $\det A (1 : i, 1 : i) >
0, 1 ≤ i ≤ n$. This called Sylvester's criterion.

*If $A = (a_{ij})$ is positive definite, then $a_{ii}> 0$ for all $i$

*If $A = (a_{ij})$ is positive definite, then the largest element in magnitude of all matrix entries must lie on the diagonal.

*The sum of two positive definite matrices is positive definite

I guess for $n=1$ I can use statement number $2$.
But what about $n=2$ and $n=3$?

A: This follows easily from Sylvester's criterion. I will consider only $n=3$, as this is the only interesting case. As $A$ and $B$ share identical diagonal elements as well as principal $2\times2$ minors, it suffices to prove that $\det(B)\ge\det(A)$ (so that $\det(B)>0$). Let
$$
A=\pmatrix{p&s_1a&s_2b\\ s_1a&q&s_3c\\ s_2b&s_3c&r}
\ \text{ and }\ B=\pmatrix{p&a&b\\ a&q&c\\ b&c&r}
$$
where $p,q,r>0,\,a,b,c\ge0$ and $s_1,s_2,s_3\in\{1,-1\}$. Then
\begin{aligned}
\det(A)
&=pqr+2s_1s_2s_3abc-(pc^2+qb^2+ra^2)\\
&\le pqr+2abc-(pc^2+qb^2+ra^2)\\
&=\det(B).
\end{aligned}


text:
Q: How to write contains expression - Java Selenium I have two paths :
 driver.findElement(By.xpath("//tr[@id='"+variable+"']/td[5]/span")).click();
 driver.findElement(By.xpath("//tr[@id='"+variable+"']/td[5]")).click();

How can I handle both via contains so that the first or second version will be searched - with one constancy.

A: WebElement thingie = driver.findElement(By.xpath("//tr[contains(@id,'" + variable + "')]/td[5]"))

if (thingie.findElements(By.tagName("span")).size() != 0) {
    thingie.findElement(By.tagName("span")).click();
} else {
    thingie.click();
}

Create a starting point WebElement, then check to see if the <span> exists. If so, click on the span version, otherwise, click the td directly.

A: You can use the pipeline sign |. The pipeline sign acts as a union of the elements that are returned from each part of the expression
driver.findElement(By.xpath("//tr[contains(@id,'"+variable+"')]/td[5] | //tr[contains(@id,'"+variable+"')]/td[5]/span")).click();

The contains looks not necessary, the expression could be:
driver.findElement(By.xpath("//tr[@id='"+variable+"']/td[5]/span | //tr[@id='"+variable+"']/td[5]")).click();

Reference:
Two conditions using OR in XPATH

A: To rewrite the xpaths including the contains keyword along with a variable expression you can use the following lines of code :
 driver.findElement(By.xpath("//tr[contains(@id,'" + variable + "')]/td[5]/span")).click();
 driver.findElement(By.xpath("//tr[contains(@id,'" + variable + "')]/td[5]")).click()

A: You can use REGEX like this:
driver.findElement(By.xpath("[@value='<REGEX>']")).click();

So the REGEX for your xPath will be (as String):
"^[//tr\[@id='" + variable + "\]/td\[5\]][/span]?$"

So you need to paste this into  and should work.


text:
Q: I am making a Discord SelfBot in Python and getting an error for a mute command I am making a Discord SelfBot in Python and I am getting this one error for a mute command that is confusing to me.
This is the code for the mute command
@commands.command(name="mute", description="Mute a user from the command server.", usage=" [@member] (reason)")
    async def mute(self, ctx, member: discord.Member, *, reason="Undefined"):
        if ctx.author.guild_permissions.mute_members:
            mutedRole = get(ctx.guild.roles, name="Muted")
            await member.add_roles(mutedRole)

This is where the error is and I can't seem to fix it
mutedRole = get(ctx.guild.roles, name="Muted")

This is what it says when I hover over the error part
[pyflakes] undefined name 'get'

And when I take "get" away it gives me an error under
name="Muted")

Saying
[pyflakes] invalid syntax

Error With 'get'
Error without 'get'

A: Based on the comment of Ceres here is a possbile answer:
You want to use get but it seems like you never "imported" it. To overcome the errors you get you have to import the following:
from discord.utils import get

I also noticed that you are usingreason but don't insert it in your code.
A possible complete code would be:
from discord.utils import get # Import get to get the role

@commands.command(name="mute", description="Mute a user from the command server.", usage=" [@member] (reason)")
    async def mute(self, ctx, member: discord.Member, *, reason="Undefined"):
        if ctx.author.guild_permissions.mute_members:
            mutedRole = get(ctx.guild.roles, name="Muted")
            await member.add_roles(mutedRole, reason=reason) # Add reason

For more information look at the docs


text:
Q: Introduction to $L^2$ space. Equivalence class concept
Given a probability space $\left(\Omega\text{, }\mathcal{F}\text{, }\mathbb{P}\right)$, let $L^2$ denote all (equivalence classes for a.s. equality of) random variables $X$ such that $\mathbb{E}\{X^2\}<\infty$. We henceforth identify all random variables $X$, $Y$ in $L^2$ that are equal a.s. and consider them to be representatives of the same random variable. This has the consequence that if $E\{X^2\}=0$, we can conclude that $X=0$ (and not only that $X=0$ a.s.).

I am not sure I am correctly interpreting the above-quoted statements.
What I understand is that, since $E\{X^2\}=0$, given that $\text{Var}(X)=E\{X^2\}-E\{X\}^2\geq0$, it must hold that $E\{X\}=0$. So, at this point one can say that, since $E\{X\}=0$ and $\text{Var}(X)=0$, $X$ follows a degenerate distribution, that is that $X=0$ a.s..
Now, pretending that what I have said so far is ok, does the statement "we can conclude that $X=0$ (and not only that $X=0$ a.s.)" follow from the fact that (see part in bold) "$L^2$ denotes all (equivalence classes for a.s. equality of) random variables $X$ such that $\mathbb{E}\{X^2\}<\infty$"?
If my reasoning was totally wrong, could you please clarify the meaning of the paragraph above?

A: This is actually way more fundamental and only a matter of perspective. $X = 0$ in $L^2$ has a different meaning than $X = 0$ in the space of random variables.
Before introducing $L^2$ we knew that $E\lbrace X^2 \rbrace = 0 \iff X = 0$ a.s..
Now things have changed as $L^2$ only contains equivalence classes (i.e. sets) and is a completely different Vector space than the space of random variables.
Now, what does it mean for $[X] \in L^2$ to be $0 \in L^2$ ($[X]$ denotes the equivalence class of some random variable $X$)? It means that $Y = 0$ a.s. for all $Y \in [X]$ by definition of $L^2$. So: The zero element in $L^2$ is just not a random variable anymore, it's a completely different object.
Remark: We can still write down integrals of equivalence classes as the integral of an arbitrary representant, because every random variable in an equivalence class has the same integral (because they only differ on sets with measure zero). Often the goal of this new perspective is to introduce a norm $\lVert X \rVert_{L^2} := \sqrt{E\lbrace X^2 \rbrace}$ on $L^2$ which requires $\lVert x \rVert_{L^2} = 0 \iff x = 0$ in $L^2$.
This is the concept of so called quotient spaces about which you can learn in a good Linear Algebra book.


text:
Q: How to fix 'SyntaxError: Cannot use import statement outside a module'? I have this error a couple of days ago. There are several similar questions but no answer solved my problem.
It happens when I run npm run start, after running npm run build
Why does npm run start run files with a .ts extension like ormconfig.ts? Is it correct behavior? Shouldn't ormconfig.js run?

*

*Full error message
C:\Users\franc\Code\f5\server\ormconfig.ts:1
import { Booking } from "./src/entities/Booking"
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1031:15)
at Module._compile (node:internal/modules/cjs/loader:1065:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at ConnectionOptionsReader. (C:\Users\franc\Code\f5\server\node_modules\typeorm\connection\ConnectionOptionsReader.js:120:46)
at step (C:\Users\franc\Code\f5\server\node_modules\tslib\tslib.js:143:27)
at Object.next (C:\Users\franc\Code\f5\server\node_modules\tslib\tslib.js:124:57)
at C:\Users\franc\Code\f5\server\node_modules\tslib\tslib.js:117:75
at new Promise ()
at __awaiter (C:\Users\franc\Code\f5\server\node_modules\tslib\tslib.js:113:16)
at ConnectionOptionsReader.load (C:\Users\franc\Code\f5\server\node_modules\typeorm\connection\ConnectionOptionsReader.js:92:38)
at ConnectionOptionsReader. (C:\Users\franc\Code\f5\server\node_modules\typeorm\connection\ConnectionOptionsReader.js:34:55)

*

*package.json

*

*tsconfig.json

*

*Project strcture

PS: this is my first question on the platform, if there is missing data tell me! and sorry for my english :)

A: Move ormconfig.ts to your src folder (change imports if necessary), and add the include after compilerOptions to include everything in the src. It's also a good idea to use exclude node_modules and tests:
{
    "compilerOptions": { ... },
    "include": ["src/**/*.ts"],
    "exclude": ["node_modules", "tests"]
}

It might be because TypeScript is including ormconfig.ts in the compilation output: as you can see in the build folder there is an index.js and ormconfig.js AND duplicate src folder.


text:
Q: Disable Accept-encoding:gzip for specific website firefox There is a website which right now is failing when using gzip encoding.
The site works fine when using Accept-encoding: deflate, I found that this can be done by using the global setting: network.http.accept-encoding, but would not like to disable it globally.

*

*It seems like it was possible by installing Modify Headers extension, but the extension is not available anymore.

Is there any way to disable gzip encoding for specific site without installing an extension?


text:
Q: understand the relation between orientation , in circle test and determinant i come from a software engineering background and I'm new to computational geometry ,
I found this picture online and can't manage to understand from where the logic comes from .
I know that determinants are used to know how a transform squishes space but i don't see the link here .

A: $$\begin{vmatrix}
a_x - c_x & a_y -c_y\\
b_x - c_x & b_y -c_y
\end{vmatrix}$$ is equal to $\Vert ca \Vert \Vert cb \Vert \sin(ca, cb)$ where $\Vert \cdot \Vert$ stands for the norm. The sign of $\sin(ca, cb)$ depends on the fact that $c$ is on one side or the other of the line $ab$. This explains why the sign of the determinant enables to decide on the position of $c$ relatively to the line.
Similar considerations regarding the distance of $d$ vs. the radius of the circle defined by the three points $a,b,c$ enables to explain the second determinant. Have a look to this question.

A: When a continuous curve has the implicit equation of the form $f(x,y)=0$, the sign of the LHS tells you on what side of the curve you are (by continuity, you cannot cross the curve without making the sign change).
Here the determinants enter into play because they form the implicit equations of a line by two points or a circle by three. (Cancelling a determinant expresses lineary dependency.)
$$\begin{vmatrix}x&y&1\\x_0&y_0&1\\x_1&y_1&1\end{vmatrix}=0$$
$$\begin{vmatrix}x^2+y^2&x&y&1\\x_0^2+y_0^2&x_0&y_0&1\\x_1^2+y_1^2&x_1&y_1&1\\x_2^2+y_2^2&x_2&y_2&1\end{vmatrix}=0$$


text:
Q: How does a string pulls pulley at both the ends?
For an Atwood's machine, why does the string exert a downwards force on the pulley that is twice its tension? I'm neither able to understand nor imagine this scenario.
How does a wrapped string with tension $T$ pull a pulley downwards with a force of $T$ at each end?
In short I want to understand that how does tension T in rope pulls pulley ( please open the link, I was not able to upload image here)?
https://linksharing.samsungcloud.com/cdbxRTLOi3d2

A: At one level the answer is trivial- the pulley is subject to two parallel forces T, so the resultant force is 2T.
If, however, your question is exactly how is the force applied to the pulley, the answer is that it is the vertical component of the normal force integrated over the surface of the pulley.
To see that, imagine the pulley is replaced by a square. You will easily see that a normal force exists at the top left and top right corners of the square, where the rope changes direction, and that the vertical components of those normal forces add to 2T.
If you replace the square by a hexagon, you can repeat the calculation of normal forces at each of the corners where the rope changes direction, and you will see again that the vertical components add to 2T. if you like, you can repeat it for an octagon, or any polygon with an increasing number of sides, and you will find the vertical components of the normal forces at the corners always sum to 2T. The case of a circular pulley is the same arrangement taken to an infinite number of corners of infinitely short line segments.


text:
Q: apex trigger (error :UpdateCaseCount: execution of AfterInsert caused by: System.StringException: Invalid id: GC1040 External entry point) trigger UpdateCaseCount on Case(after insert, after update) {

    Set<Id> AccIdUpd = new Set<Id>();
    Map<Id, Id> AccPrd = new Map<Id, Id>();
    set<id> ContactId = new set<id>();

    //Create a master list to hold the emails we'll send
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();

    for (Case cs:Trigger.new) {
        if(Trigger.IsInsert || (cs.IsClosed && Trigger.OldMap.get(cs.Id).IsClosed != cs.IsClosed)) {
            AccIdUpd.add(cs.AccountId);
            AccPrd.put(cs.AccountId, cs.Product__c);
        }
    }

    List<AggregateResult> ARListCurrIssue = [
        select AccountId, Product__c, Count(Id) CaseCount
        from Case
        where AccountId IN :AccIdUpd and IsClosed != true group by AccountId, Product__c
    ];

    // Logic to update curernt Issues
    List<Account> UpdAccList = new List<Account>();
    for (AggregateResult AR : ARListCurrIssue) {
        String CurrCount = AR.get('CaseCount') + ', ' +  AccPrd.get((Id) AR.get('Product__c'));
        UpdAccList.add(new Account(Id = (ID)AR.get('AccountId'), Current_Issues__c = CurrCount));
        Integer iCount = Integer.valueOf(AR.get('CaseCount'));
        if (iCount == 5) {
            //write logic to sendMail

            Contact con = [Select firstname,lastname,email,id,name,MobilePhone from Contact where id in :ContactId];
            // Step 1: Create a new Email
            Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();

            // Step 2: Set list of people who should get the email
            List<String> sendTo = new List<String>();
            sendTo.add(con.email);
            mail.setToAddresses(sendTo);

            // Step 3: Set who the email is sent from
            mail.setReplyTo('lateshpatil97@gmail.com');
            mail.setSenderDisplayName('latesh patil');

            // (Optional) Set list of people who should be CC'ed
            List<String> ccTo = new List<String>();
            ccTo.add('lateshpatil@icloud.com');
            mail.setCcAddresses(ccTo);

            // Step 4. Set email contents - you can use variables
            mail.setSubject('Get in touch with the service team');
            String body = 'Dear ' + con.FirstName;

            mail.setHtmlBody(body);

            // Step 5. Add your email to the master list
            mails.add(mail);
            Messaging.sendEmail(mails);
        }
    }

    if(UpdAccList.size()>0){
        update UpdAccList;
    }

    // Logic to update Past Issues
    ARListCurrIssue = [
        select AccountId, Count(Id) CaseCount
        from Case
        where AccountId In :AccIdUpd and IsClosed = True group By AccountId
    ];

    UpdAccList = new List<Account>();
    for(AggregateResult AR : ARListCurrIssue) {
        String PastCount = AR.get('CaseCount') + ', ' +  AccPrd.get((ID)AR.get('AccountId'));
        UpdAccList.add(new Account(Id = (ID)AR.get('AccountId'), Past_Issues__c = PastCount));
    }

    if (UpdAccList.size()>0) {
        update UpdAccList;
    }
}

A: Your code is failing at the following line:
String CurrCount = AR.get('CaseCount') + ', ' +  AccPrd.get((Id) AR.get('Product__c'));

You are using AccPrd map to store a mapping between AccountId => Product__c. On the above line of code, you are trying to retrieve entry from the AccPrd map using the value of AR.get('Product__c') which is incorrect. You should be using AR.get('AccountId'). Once you make that change, this error will go away.
There are other things which you might want to look into while writing triggers. I would recommend you to please watch this video for basic Apex pattern to use while writing triggers.


text:
Q: Expresión regular en PHP para números entre comillas Necesito extraer con una expresión regular sólo el número dentro de las comillas simples del texto:
onclick="javascript:Cargar('502235593');">

Condiciones:

*

*Siempre aparece como Cargar('502235593');">, y

*el número siempre tiene 9 dígitos.

El resultado debe ser un array con 502235593.
La web posee muchos números que no sirven, por lo tanto la expresión regular que vengo intentando:
preg_match_all('/\d+/', $web, $match);

No sirve, y necesito otra que sea más restrictiva para este caso en particular.

A: Ver Demo
preg_match_all("/^.*'([0-9]+)'.*$/", $web, $match);

Ver en regex101.com

A: Expresión Regular:
Personalmente, me olvidaría del ;"> final, que probablemente tenga más chances de cambiar. Esta expresión coincide con 9 dígitos dentro de la función:
/Cargar\('(\d{9})'\)/

Descripción:

*

*Cargar\(' Coincide con el texto literal. El paréntesis se tiene que escapar porque es un metacaracter para regex.

*(\d{9}) Es un grupo, que captura todo lo que coincide con el patrón que está entre paréntesis y lo devuelve como un item independiente en el array de resultados. Coincide con:

*

*\d{9} Exactamente nueve dígitos consecutivos. Si se quiere otra cantidad, se puede usar \d{8,11} (entre 8 y 11), \d{9,} (9 o más), \d{0,} (0 o más, lo mismo que \d*), \d{1,} (1 o más, lo mismo que \d+), o cualquier cuantificador.

*'\) Las comillas simples y el paréntesis de cierre del final literales.

Código:
$tiene_un_numero = preg_match( "/Cargar\('(\d{9})'\)/", $texto, $coincidencias);

if ($tiene_un_numero) {
    echo "Se encontró: " . $coincidencias[1];
}

Al usar paréntesis en la expresión regular, el grupo define una captura extra. De esta forma, $coincidencias[0] devuelve todo el texto con el que coincidió, y $coincidencias[1] devuelve los 9 dígitos.

Si se busca más de un resultado, en vez de preg_match(), usamos preg_match_all().
$texto = 'onclick="javascript:Cargar(\'502235593\'); Cargar(\'123456789\');">';

$cant = preg_match_all( "/Cargar\('(\d{9})'\)/", $texto, $coincidencias);

echo "Se encontraron " . $cant . " coincidencias.";
foreach ($coincidencias[1] as $valor) {
    echo "\nSe encontró: " . $valor;
}

Se encontraron 2 coincidencias.
Se encontró: 502235593
Se encontró: 123456789

En este caso devuelve un array bidimensional. De nuevo, captura lo que coincide entre paréntesis, pero $coincidencias[1] es un array que contiene todos los resultados que coincidieron con el primer grupo.
Una página que me parece muy práctica para ver cómo queda el array de resultados es phpliveregex.com, que ayuda a entender/recordar en qué orden devuelve cada item.

Por último, sabiendo que podría haber espacios opcionales en el texto antes y después de cada paréntesis, podríamos usar:
/Cargar\s*\(\s*'(\d{9})'\s*\)/

Consideraciones extra:
El caso descripto era relativamente sencillo. Sin embargo, al procesar HTML, las expresiones regulares fallan apenas se modifica levemente el código, o incluso no te permitirían distinguir entre el texto dentro de onclick=, de un texto que podría estar en cualquier otro lado del HTML. Por ese motivo, no recomiendo de ninguna manera usar regex para capturar texto dentro de un HTML en cualquier caso que sea apenas más complejo.
En cambio, accedería al DOM (Document Object Model). Existen muchas formas desde PHP. Para nombrar una, se puede usar la clase DOMDocument. Viendo los ejemplos del manual de PHP, se nota que es muy sencillo y prácticamente igual a como se accede desde JavaScript.


text:
Q: Implementing Session I have a piece of code which loads either french or english text and 2 link buttons that allow to switch between.
<%
if publierFR = 0 Then
    if publierEN = 0 Then
        response.write("
Aucun texte n'est disponible.
")
    else
        response.write(texteEN)
    end if
else
    if publierEN = 1 or Session("lang") = "EN" then
%>
        <asp:LinkButton OnClick="makeVisibleEN" ID="makeEN" runat="server" visible="false">Version Française</asp:LinkButton>
        <asp:LinkButton OnClick ="makeVisibleFR" ID="makeFR" runat="server" visible="true">Version Anglaise</asp:LinkButton>
<%
        if makeEN.visible = true then
            response.write(texteEN)
        else
            response.write(texteFR)
        end if
    elseif publierEN = 0 or Session("lang") = "FR" then
        Response.write(texteFR)
    end if
end if
%>

What would be an efficient way of displaying the link buttons and text if both English and French exist and the session exists in either EN or FR.
I've thought of using panels to hide the buttons or text, but the main problem is having the page refresh to set the Session variable. Response.redirect(URL) to refresh the page i suppose and i can't find a better way to display the text other than to Response.write it since then i'd need a ton of labels.

A: You should use .NET (and ASP.NET) native localization feature, and just change the culture of the thread that's executing the page. You can still store that culture in the Session if you want (or somewhere else: in a database, in a cookie, in the rendered page, in view state, etc.).
Here are some links on ASP.NET localization:
Best practices for ASP.NET web application localization
Asp.net multilingual web application - localization


text:
Q: Microchip PIC18 matrix routines I'm using a Microchip PIC18 and I need to use matrices in my code. I know DSPIC do have matrix libraries, that simplifies the implementation.
Does anybody know whether any is available also for the 18 family (my present PIC18 embeds an hw multiplier)?
Thank you all!

A: Microchip themselves doesn't have any suitable libraries for the PIC18. Someone on the Microchip forums might have written some routines you can use, though.
I'd be inclined to use a 16-bit PIC, it would make things much easier.

A: If you're just using simple, fixed size matrices like 2x2 or 3x3 affine transforms, it's not very difficult to implement them yourself. That link shows how to compute the determinant and inverse of a matrix. Multiplication, addition, etc. are much easier. In fact, the Cairo source code, a drawing library, has GPL/LGPL/MPL licensed code for dealing with matrices (2D affine only):  cairo-matrix.c


text:
Q: Allocating UIDatePicker in a background thread? I am trying to allocate a UIDatePicker in a separate thread (performance gains for an iPhone 4), and for some reason the following code draws a black frame (where the date picker is supposed to go), and after about 20-30 seconds the date picker is shown.
@property (nonatomic, strong) dispatch_queue_t backgroundQueue;

    dispatch_async(self.backgroundQueue, ^{
        self.datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, self.deviceRect.size.width, self.datePicker.frame.size.height)];
        [self.datePicker addTarget:self action:@selector(didSelectDate:) forControlEvents:UIControlEventValueChanged];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.view addSubview:self.datePicker];
    });

});

I know the threading code works because I added a lengthy process and added a UIView when it was finished and everything shows up as expected. The reason I want to do this is because on an iPhone 4 the UIDatePicker lags when being displayed for the first time. You can see this by going to the Apple Calendar app and adding a date, there is noticeable delay before displaying the UIDatePicker.


text:
Q: I am interested/ keen on/ enjoy writing blog posts I am trying to express my interest of writing blog posts.
So basically I want to say something like that.
Furthermore, I enjoy sharing my experience in a form of blog posts, so visit my blog
It sounds inaccurate to me, especially I am not sure about in a form of
The idea is to start with I like to write blog posts and end with so visit my blog
I want to express this more elegantly. And also if it is possible to replace enjoy\keen on\like with a synonym.
Please help to construct a sentence.
I would be grateful for any help.
Thank you.

A: There is nothing wrong with "enjoy". In fact, the only changes I would suggest are: ".. in the form of..", and I would try to avoid repeating "blog". Maybe "...visit my website".
If you need to avoid "enjoy" you can describe why you have found it enjoyable for example: "I've found recording my experiences in this blog to be both rewarding and educational." This is the "show, don't tell" principle that writers use. Explain why it is enjoyable, rather than just stating it.
Your suggested alternative "I like to write blog posts, so visit my website." is also quite acceptable. But "I am keen to" suggests that it is something that you want to do, but haven't done yet, which isn't your meaning.


text:
Q: RapidMiner: Can I use a wildcard as an attribute value for training a decision tree model? I am working on a fairly simple process in RapidMiner 5.3.013, which reads a CSV file and uses it as a training set to train the decision tree classifier. The result of the process is the model. A second CSV is read and used as the unlabeled set. The model (calculated earlier) is applied to the unlabeled test set, in an effort to label it properly.
Each line of the CSVs contains a few attributes, for example:
15, 0, 1555, abc*15, label1
but some lines of the training set may be like this:
15, 0, *, abc*15, label2
This is done because the third value may take various values, so the creator of the training set used a star as a wildcard in the place of the value.
What I would like to do is let the decision tree know that the star there means "match anything", so that it does not literally only match a star.
Notes:

*

*the star in the 4th field (abc*15) should be matched literally and not as a wildcard.

*if the 3rd field always contained stars, I could just not include it in the attributes, but that's not the case. Sometimes the 3rd field contains integer values, which should be matched literally.

*I tried leaving the field blank, but it doesn't work

So, is there a way to use regular expressions, or at least a simple wildcard while training the classifier or using the model?
A different way to put it is: Can I instruct the classifier to not use some of the attributes in some of the entries (lines in the CSV)?
Thanks!

A: I would process the data so the missing value is valid in its own right and I would discretize the valid numbers to be in ranges.
In more detail, what I meant by missing is the situation where the value of an attribute is something like *. I would simply allow this to be one valid value that the attribute takes. For all the other values of this attribute, these are numerical so they need to be converted to a nominal value to be compatible with the now valid *.
It's fairly fiddly to do this and I haven't tried this but I would start with the operator Declare Missing Value to detect the * and make them missing. From there, I would use the operator Discretize by Binning to convert numbers into nominal values. Finally, I would use Replace Missing Values to change the missing values to a nominal value like Missing. You might ask why bother with the first Declare Missing step above? The reason is that it will allow the Discretizing operation to work because it will be working on numbers alone given that non-numbers are marked as missing.
The resulting example set then be passed to a model in the normal way. Obviously, the model has to be able to cope with nominal attributes (Decision trees does).
It occurred to me that some modelling operators are more tolerant of missing data. I think k-nearest-neighbours may be one. In this case, you could simply mark the missing ones as above and not bother with the discretizing step.
The whole area of missing data does need care because it's important to understand the source of missingness. If missing data is correlated with other attributes or with the label itself, handling it inappropriately can skew results.


text:
Q: Running ASP.NET app in VS 2015 debugger with firefox throws login failed for user: NT AUTHORITY/ANONYMOUS LOGON The debug session with VS2015 on my developer workstation works with chrome and connects to the external SQL Server 2012 database from my web app.  I cannot figure out why firefox causes this error while in the debugger in the attempt to make a db connection.
Firefox works otherwise with this web app in IIS from the webserver which by the way also contains the database on the same server when running outside of VS 2015.
What am I missing and why would chrome work but not firefox while debugging in VS 2015 in connecting to the database with integrated security turned on
Everything I see on the internet has to do with this issue when running the web app in IIS and the database on an external server with double hop issues.  My problem is running from the debugger and only firefox not working!  We need to have firefox working for reasons beyond the scope of my question in the debugger.
Has anyone seen anything like this before? Thanks!
Here is my connection string from my web.config  (I also tried with Integrated Security=true)

Here is a code snippet where the cmd.Connection.Open() throws the exception
Dim cmd As SqlCommand = GetSqlCommand(GetSelectForBlackPearlPersonal(whereClause, orderBy))
Try
    Using cmd.Connection
    cmd.Connection.Open()
.
.
.
     End Using
 Catch ex As Exception
 Throw New Exception("Database issue: " & ex.ToString)

End Try

A: I found in another post that someone set impersonation to false in their web.config.
I just changed the impersonate setting from true to false and now its working on firefox in the debugger

I am baffled....Does anyone know why this would be the case?  thanks! Kevin

A: Your connection string states:"Integrated Security=SSPI". This means that you are using Windows Integrated Authentication.
It allows your Windows users' account credentials (or Active Directory in corporate domains) to pass through their browser to a web server and to SQL Server.
Windows Integrated Authentication is enabled by default for Internet Explorer but not for Mozilla Firefox.
To configure Firefox to use Windows Integrated Authentication:

*

*Open Firefox.

*In the address bar type about:config

*You will receive a security warning. To continue, click I'll be careful, I promise.

*You will see a list of preferences listed. Find the settings below by browsing through the list or searching for them in the search box. Once you have located each setting, update the value to the following:

*

*network.negotiate-auth.delegation-uris MyIISServer.domain.com

*network.automatic-ntlm-auth.trusted-uris MyIISServer.domain.com

*network.automatic-ntlm-auth.allow-proxies True

*network.negotiate-auth.allow-proxies True

MyIISServer.domain.com should be the fully qualified name of your IIS server

Here are some older posts that provide explanation and, hopefully, an answer to your question.

*

*Configuring Chrome and Firefox for Windows Integrated Authentication

*Enabling NTLM Authentication (Single Sign-On) in Firefox

*Integrated Windows Authentication with IIS, Firefox and SQL Server


text:
Q: Using VSPerf.exe instead of VSPerfCmd.exe I would like to prepare a number of Visual Studio Profiler (VSP) reports using a batch script. On Windows 7 I used VSPerfCmd.exe in the following way:
VSPerfCmd /start:sample /output:%OUTPUT_FILE% /launch:%APP% /args:"..."
VSPerfCmd /shutdown

VSPerfCmd /shutdown waits until the application has finished its execution, closes data collection and only then the VSP report is generated. This is what I need.
I switched to Windows Server 2012 and now VSPerfCmd does not work; I need to use VSPerf instead. The problem is that I cannot get the same behavior as VSPerfCmd.
Specifically, the /shutdown option is no longer available. Available options do not wait until the application has finished but stop or detach from the process right after execution. This means I can't use them in a batch script, where I run several processes one after another. Any ideas how to get the desired behavior?

A: You don't have to manually shutdown vsperf. You can simply do:
vsperf /launch:YourApp.exe

And vsperf will stop automatically after your application finishes.
See: https://msdn.microsoft.com/en-us/library/hh977161.aspx#BKMK_Windows_8_classic_applications_and_Windows_Server_2012_applications_only


text:
Q: Reverse engineer DDL from JPA entities I'm playing around with some JPA stuff, changing the mappings to see how they're supposed to be etc. It's basic experimentation. However I can't find a tool that will simply read my entities and then generate the table schema for me. I tried to find something like this in JBoss tools but nada. Eclipse integration will be a huge plus but i'll take a command line tool or an ant task.
Any ideas?

A: I don't think there is an universal way of doing this with JPA, you have to directly use the underlying JPA implementation to achieve this.
For Hibernate, there are several possibilities:

*

*Use the method duffymo posted earlier, that makes Hibernate update the database schema automatically.

*If you do not want that, you can use the hbm2ddl tool from Hibernate Tools (note: link sucks, but apparently their home page is a bit broken right now). You can use that to automatically generate database creation scripts from your JPA entities; there are also plugins for Maven and Ant that invoke hbm2ddl automatically.

For EclipseLink (formerly Oracle TopLink, the JPA 2.0 RI) see Using EclipseLink JPA Extensions for Schema Generation. In principle it is very similar to Hibernate, although at first glance I don't see anything that could be used as a stand-alone utility for creating a DB script.
Other JPA implementations (BEA/Oracle Kodo, Apache OpenJPA) probably have their own specific methods of achieving this.

A: When I use Hibernate I simply add this to my config file:
      <property name="hbm2ddl.auto">update</property>

Takes care of everything.  I'm not sure what the equivalent is for JPA, but it's so heavily influenced by Hibernate that I'd be surprised if you couldn't find something similar.
No tool needed.  I usually just run a simple JUnit test and the database is created for me.

A: By maven plugin:
        <plugin>
            <!-- run "mvn hibernate3:hbm2ddl" to generate a schema -->
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>hibernate3-maven-plugin</artifactId>
            <version>3.0</version>
            <configuration>
                <hibernatetool>
                    <classpath>
                        <path location="${project.build.directory}/classes" />
                        <path location="${project.basedir}/src/main/resources/META-INF/" />
                    </classpath>

                    <jpaconfiguration persistenceunit="galleryPersistenceUnit" />
                    <hbm2ddl create="true" export="false" destdir="${project.basedir}/target" drop="true" outputfilename="mysql.sql" format="true" console="true"/>
                </hibernatetool>
            </configuration>
        </plugin>

A: I use Hibernate's org.hibernate.tool.hbm2ddl.SchemaExport class and this small method to
generate the schema in the database:
 public static void rebuildSchema()
 {
     configuration = new Configuration();
     configuration.configure();

     new SchemaExport(configuration)
         .setHaltOnError(true)
         .execute(false, true, false, false);
 }

to create the DDL in an external file, use this call to execute.
     new SchemaExport(configuration)
         .setHaltOnError(true)
         .setOutputFile(outputFile)
         .setImportFile("")
         .setDelimiter(";")
         .setFormat(true)
         .execute(false, false, false, true);

It's considered bad form to set "hibernate.hbm2ddl.auto" to "update", since automatically changing the production database may break it.  For an explanation, see Hibernate hbm2ddl.auto possible values and what they do?.

A: DataNucleus has its own SchemaTool capable of generating the schema for you, or generating the required DDL statements for you to adapt and apply yourself.
--Andy (DataNucleus)

A: Adding to the list of James McMahon:
For OpenJPA:
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>

A: Try adding the following to your persistence.xml
For Hibernate:
To create:
<property name="hibernate.hbm2ddl.auto" value="update"/>

To drop and create:
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>

For Toplink:
To create:
<property name="toplink.ddl-generation" value="create-tables"/>

To drop and create:
<property name="toplink.ddl-generation" value="drop-and-create-tables"/>

For EclipseLink:
To create:
<property name="eclipselink.ddl-generation" value="create-tables"/>

To drop and create:
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>

A: Antonio Goncalves says in his blog about API to generate the schema.
In JPA 2.1 generateSchema method was introduced for this purpose.
Example from blog:
public class Main {
    public static void main(String[] args) {
        Persistence.generateSchema("samplePU", null);
    }
}


text:
Q: How to find parent div a selection range belong to My code is in following format

       lot of other divs are inside this

       lot of other divs are inside this

       lot of other divs are inside this

What i want is whenever a text selection happens on the page i want to fetch the "pageContiner" div it is in .

A: you mean this
function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

$(document).ready(function (){
    $('#viewer div *').mouseup(function (e){
      alert($(this).closest('[id^="pageContainer"]').attr('id'));
    })
});


text:
Q: unknown type name on defining object of another class from same file in C++ In my one c++ file named "two_elements.cpp", I am defining two classes within same file, and the code goes like below:

#include <iostream>
#include <cstream>

class A{
    public:
        void methodA(){
            //do something
        }
};

class B{
    public:
        A a_obj;
        a_obj.methodA();
};

This throws the following error:
error: unknown type name 'a_obj'

I folowed the following stack overflow links comprehensively, but could not find a work around:
Unknown type name class
unknown type name 'class'
C++ - 2 classes 1 file
Please note most of these questions had classes in the individual header files.

A: I found the solution:
#include <iostream>
#include <cstream>

class A{
    public:
        void methodA(){
            //do something
        }
};

class B{
    public:
        A a_obj;
        B(){
            a_obj.methodA();
        }
};

An instance needs to be called inside a constructor or a function in c++.


text:
Q: Access Find Previous Record using a SubQuery in a calculated field I have a sheet in excel that I converted into a table in MS Access. I need to find the previous value of a field (job) to compare to the current value and do the following calculation in my calculated field (TotalCost)

All I'm doing is adding the cost of previous operations to determine the total cost for a job at that operation.
How can I do this in access?

A: You can calculate totalcost using a correlated subquery:
select t.*;
       (select sum(t2.cost)
        from t as t2
        where t2.job = t.job and t2.operation <= t.operation
       ) as totalcost
from t;


text:
Q: How to create Event on facebook through iphone app I want to create event on facebook in my app. I am using FBGraph Api.
Here is the code:
NSString *strGetProfil=[NSString stringWithFormat:
                       @"https://graph.facebook.com/%@/events?access_token=%@&name=%@&start_time=%@&end_time=%@&description=%@&location=%@&location_id=
                       %@&privacy_type=%@",[getAllInfo objectAtIndex:4],[getAllInfo objectAtIndex:7],@"teing",@"2010-03-14T14:00:00",@"2010-03-14T17:30:00",@"",@"",@"",@""];

NSURL *url = [NSURL URLWithString:strGetProfil];

Please guide me for right path.
Thanks in Advance.


text:
Q: Should I use T-score or Z-score for this problem? The farmer decides to try out a new type of pumpkin. A small sample crop with $10$ plants is grown. We first assume that the 10 weight measurements $Y_1, Y_2,. . . , Y_{10}$ are independent and normally distributed with unknown expectation $\mu_Y$ and known standard deviation $\sigma_Y = 0.8$.
The results of the measurements are given in the list below:
$$3.7 , 2.2 , 1.8 , 4.5 , 2.4 , 2.5 , 2.6 , 2.1 , 2.5 , 2.2$$
Find a $90$% confidence interval for $\mu_Y$.
So I am wondering if I should use t-score or z-score for this problem?


text:
Q: How to change secure_file_priv on mac osX for MySQL 5.7.16 When I try to use LOAD DATA INFILE, I got the following error: The MySQL server is running with the --secure-file-priv option so it cannot execute this statement. Which means I need to change the secure-file-priv value from NULL to empty. How can I change this secure-file-priv value? Where is it located?
There is a post related MySQL ERROR 1290 (HY000) --secure-file-priv option, however it does not answer my problem. I want to change secure_file_priv value on mac osX and that post just tells how to do it in CentOS and Windows. I have checked and there is no 'my.cnf' file in Mac osX.


text:
Q: Django model.parameters I'm going through a tough time trying to understand a part of the code I was given to review:
model.parameters.first()

It's a Django model,and though I know what the outcome is, I can't seem to find any word on "parameters" part.
I would be so grateful if you could either explain what does the "parameter" function do, or drop a link with the explanation.
I couldn't find it anywhere in django documentation.
Thanks!

A: Django adds a Manager with the name "objects" to every Django model class. However, if you want to use a name  other than "objects" for the Manager, you can rename it on a your-model as :
class YourModel(models.Model):
 ....
 # custom manager replaces objects manager
  parameters= models.Manager() # in your case
 .....

So now i can do something like this :
YourModel.parameters.first()

Now YourModel.objects will generate an AttributeError.

A: It looks like it is a custom manager.
Model.objects is the default manager provided by django, but we are allowed to create our own, so, if for instance, I had the model Post with the attribute published, I can create the PublishedManager.
class PublishedManager(models.Manager):
    def unpublished(self):
        return self.filter(published=False)

class Post(models.Model):
    title = models.CharField(max_length=30)
    published = models.BooleanField(default=True)
    objects = PublishedManager()

I could easily do:
 Post.objects.unpublished

Even though unpublished is not an attribute of Post.
This is a silly example but I hope you get the idea.


text:
Q: WordPress is_tags not detecting tag clicked I have a simple if statement that should show something different depending if tag, archive or something else.
they all work apart from is_tag, for some reason when I click on a tag it shows the archive condition.
I have tried multiple solutions and look around the internet, nothing seems to work..
Am i doing something wrong ?

            <?php
            $current_tag = single_tag_title("", false);
            $archive_year = get_the_time('Y');
            if (is_archive()) {
                ?>

<?php echo 'Archive ', $archive_year?>

                <?php
            } elseif (is_tag()) {
               ?>

tag working <?php the_title(); ?>

Tag: <?php single_tag_title(); ?>

                <?php
            } else {
                ?>

<?php the_title();?>

                <?php
            }
            ?>

one again, my aim when I load this template from clicking on a tag I was for the statement the tag statement to run.
Thank you

A: is_archive() is very general, and will return true for category, tag, author, date, custom post type, and custom taxonomy based archives - which is why it's catching your tag pages
https://developer.wordpress.org/reference/functions/is_archive/
You might instead try using is_post_type_archive() which applies specifically to post type archive pages.
https://developer.wordpress.org/reference/functions/is_post_type_archive/
OR simply reverse your conditions - test for is_tag() first, then is_archive() second.


text:
Q: Função equivalente ao Chr$ no C# Estou migrando um trecho de código em Visual Basic 6 e me deparei com a seguinte chamada:
variavel = Chr$(27) & Chr(15)

1 - Qual seriam as funções equivalente no C#?
2 - Qual a diferença entre Chr$ e Chr?

A: Basta fazer um cast do número para char, algo assim:
(char)27

Mas provavelmente deveria fazer alguma coisa diferente, a semântica da linguagem muda então não costuma ser só traduzir uma expressão, deve ter outra forma de fazer isso em C#, quem sabe até mesmo em VB6 já era errado fazer isto. Um dos motivos que acho isto é que não faz sentido usar as duas formas da função chr(), uma que retorna String e outra que retorna uma Variant.
Em C# provavelmente usar isto:
"\u0027\u0015"

Coloquei no GitHub para referência futura.


text:
Q: Parallelize data preparation with tensorflow and keras I'm training an LSTM model on GPU using Tensorflow Keras. Before training starts when calling model.fit() it takes about 30 minutes to start training process. I think in this period its preparing data using one core of CPU. Am I correct? and if yes how can I parallelize this data preparation process, using multiple cores?

A: If you use tf.data.Dataset() for preparing your data, you can exploit  some parameters while preparing the dataset.

*

*For example, in your .map() function, set the num_parallel_calls parameter to num_parallel_calls=tf.data.experimental.AUTOTUNE; in this way it will allow your program to automatically choose the number of CPU cores for the dataset preparation.

*The speed can also be improved if you use the .batch().shuffle()
in this order, rather than shuffle().batch() in this order. In the first situation, you take a batch of your dataset and shuffle the elements inside it; in the second case, you batch() on your dataset after the entire dataset is shuffled. One can easily see that shuffling an enormous dataset would lead to much more time spent rather than batching and shuffling in this order.

*Let us see another case(related to the actual training process)(not your case as the dataset preparation is
very time-consuming in your situation): the prefetch() operation.
In this case, the GPU is not idling while waiting for the CPU to
fetch another batch of data. Practically, when the backpropagation
has finished updating the weights after a batch, the GPU immediately
consumes another batch of data. For simplicity purposes, also set its value to tf.data.experimental.AUTOTUNE.


text:
Q: Two sided Rayleigh Ritz Let $A$ be a symmetric matrix.
Then from Rayleigh Ritz,
$\sup_{x\neq 0} \frac{x^TAx}{x^Tx}=\lambda_\max$.
My question is, for a symmetric and positive semi definite matrix, is the following true?
$$\sup_{x,y\neq 0} \frac{y^TAx}{\sqrt{y^Ty\cdot x^Tx}}=\lambda_\max$$
I'm seeking a reference or a counterexample, or related theorems.

A: Let $(\lambda_k,v_k)$ denote the eigenpairs with $\lambda_1\ge ...\lambda_n\ge0$ and $v_i^T v_j =\delta_{ij}$. Write $x =\sum_i c_i v_i$ and $y=\sum_j d_jv_j$. Thus
$$ \sup_{x,y\neq0} y^TAx/(||x||\cdot||y||) = \sup_{||x||=||y||=1}  y^TAx = \sup_{...} \sum_{i,j} c_j d_i \lambda_j v_j^Tv_i= \sup_{...} \sum_j c_jd_j \lambda_j $$
Now it is clear that $x,y$ cannot be such that $x^Ty<0$ for the supremum. So
$$ \sum_i \lambda_i c_id_i\le \lambda_1\sum_i c_i d_i \le \lambda_1$$
where the last inequality is due to Cauchy-Schwarz. By choosing $x=y=v_1$ we have the desired equality.


text:
Q: How do I pronounce $10^{-12}$? I am aware that $10^{12} = 1,000,000,000,000$, which is called a Trillion.
$10^{-12} = \frac{1}{1,000,000,000,000}$, which means 1 divided by a Trillion.
The question is how do I pronounce it. Would I speak it as "ten to the power of negative twelfth", "ten to the power of negative twelve" or something else better? Could someone please give a hint? Thanks in advance.

A: I agree with Sujit's comment that there are many acceptable pronunciations and you shouldn't stress too much about picking the "best" one. As a native speaker all of the following sound fine to me:

*

*ten to the negative twelfth

*ten to the negative twelfth power

*ten to the negative twelve

*ten to the power of negative twelve

*ten to the minus twelve

*one ee negative twelve (ok, maybe avoid this one around the pure mathematicians ;))

and I'm sure there are many other perfectly fine variations and permutations of the above.

A: I would say: "ten to the negative twelfth". Or, to be more precisley, you can add the "pico" prefix before the unit of measure.


text:
Q: Batch - how to copy file by minimum size and date modification? I have this simple batch script which copies the newest file in some dir to another place.
I want this script to also ignore all files (in the DIR command section) under 1GB of size.
FOR /F "delims=|" %%I IN ('DIR "Y:\DEVL\*.*" /B /A-D') DO SET NewestFile=%%I

copy "Y:\DEVL\%NewestFile%" "F:\DEVL\%NewestFile%"

Any help would be very appreciated.

A: Option 1: If you want to copy the newest file, but only if it's greater than 1GB, just replace your copy command with:
robocopy "Y:\DEVL" "F:\DEVL\" "%NewestFile%" /min:1073741824

/min:n defines the minimum size in bytes.
Option 2: If you want to copy the newest file of all files that are greater than 1GB, it's more complicated.
@echo off

Set CopyResult=0
FOR /F "delims=|" %%I IN ('DIR "Y:\DEVL\*.*" /B /O:-d /T:w /A-D') DO Call :DoCopy "%%I"
Goto :EOF

:DoCopy
  IF %CopyResult%==1 Goto :EOF
  set CurrentFile=%1
  robocopy "Y:\DEVL" "F:\DEVL" %CurrentFile% /njs /njh /is /min:107374182
  Set CopyResult=%errorlevel%

/min:n defines the minimum size in bytes.


text:
Q: From array of objects, map values in specific order without repeating the order I'm using map to get the values of these object properties in the specified order (amount, then user, then date) in an array for each object:

const data = [
  {
    amount: '100',
    user: 'admin',
    date: 'March 6, 2019'
  },
  {
    amount: '120',
    user: 'admin',
    date: 'March 6, 2019'
  },
  {
    amount: '80',
    user: 'admin',
    date: 'March 7, 2019'
  },
  {
    amount: '200',
    user: 'admin',
    date: 'March 7, 2019'
  }
];
const result = data.map(({ amount, user, date }) => [ amount, user, date ]);

console.log(result);

Is it possible to get the same result by not repeating amount, user, date? I.e. is there some syntax akin to saving amount, user, date into keys as shown here?
const keys = "amount, user, date"
const result = data.map(({ keys }) => [keys]);

A: Just pass each object through Object.values to get the values array.  Beware!  If the object properties vary in their order per object, this will produce weird results.

const data = [
  {
    amount: '100',
    user: 'admin',
    date: 'March 6, 2019'
  },
  {
    amount: '120',
    user: 'admin',
    date: 'March 6, 2019'
  },
  {
    amount: '80',
    user: 'admin',
    date: 'March 7, 2019'
  },
  {
    amount: '200',
    user: 'admin',
    date: 'March 7, 2019'
  }
];

const result = data.map(Object.values);

console.log(result);

A: It looks like you're trying to dynamically destructure based on the string, but that doesn't work. If you need to do this you will need to map over each 'key' in the passed string and access the property individually, but this offers little benefit over simply destructuring as you already are, unless you have to receive a dynamic list of properties from an outside source, or as @sebastionsimon points out, you want to repeatedly access these properties. If the latter, an array would be a more efficient means of storing them than a string.
const keys = "amount, user, date"
const result = data.map((o) => keys.split(', ').map((key) => o[key]));

If the reason is repeated refactoring, you can declare a helper function.
const Transaction = ({ amount, user, date }) => [amount, user, date];
const result = data.map(Transaction);

const data = [
  { amount: '100', user: 'admin', date: 'March 6, 2019' },
  { amount: '120', user: 'admin', date: 'March 6, 2019' },
  { amount: '80', user: 'admin', date: 'March 7, 2019' },
  { amount: '200', user: 'admin', date: 'March 7, 2019' },
];

const result = data.map(({ amount, user, date }) => [amount, user, date]);

const keys = 'amount, user, date';
const string_result = data.map((o) => keys.split(', ').map((key) => o[key]));

const Transaction = ({ amount, user, date }) => [amount, user, date];

const transaction_result = data.map(Transaction);

console.log('Destructure: \n', result);
console.log('From string: \n', string_result);
console.log('Transaction: \n', transaction_result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Custom TabViewController - navigationItem.rightBarButtonItem doesn't show up in nav bar I'm using a custom TabViewController. I want to change the right bar button item ONLY in CompanyViewController. However, changing the self.navigationItem.rightBarButtonItem doesn't work - the button doesn't show up on the navigation bar. How can I fix this?
CompanyViewController.swift
let filterButton = UIBarButtonItem(title: "Filters Off", style: .plain, target: self, action: #selector(filterButtonTapped))

self.navigationController?.navigationBar.topItem?.rightBarButtonItem = filterButton // Works
self.navigationItem.rightBarButtonItem = filterButton //Doesn't work

Resource

A: Please use this code:
//Create custom UIButton with image.

let filterButton = UIButton(type: .custom)
filterButton.setImage(UIImage(named: "imagename"), for: .normal)
filterButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
filterButton.addTarget(self, action: #selector(Class.Methodname), for: .touchUpInside)

//Assign that UIButton to UIBarButtonItem
let item1 = UIBarButtonItem(customView: filterButton)

//set UIBarButtonItem to navigationItem
self.navigationItem.setRightBarButtonItems([item1], animated: true)


text:
Q: duplicates rows while fetching the data I have 3 tables:  product, subscription and customer
SELECT id_product, product_sku

FROM product

JOIN (select fk_product_subscribed, fk_customer from subscription

            where subscription.status = 'active')S

    ON S.fk_product_subscribed = product.id_product

JOIN (select id_customer from customer

            where email = 'ashutosh@gmail.com')C

    ON C.id_customer = S.fk_customer;

The result which I'm getting is:
+ ---------- + ----------------------- +
| id_product | product_sku             |
+ ---------- + ----------------------- +
| 100        | veggie for 3 happy meal |
| 100        | veggie for 3 happy meal |
+ ---------- + ----------------------- +

Why I am getting 2 rows instead of one ?

A: Cause there are multiple matches present while you JOIN. In this particular case you can use distinct saying SELECT distinct id_product, product_sku instead. Moreover, don't see any reason for the column selection in your subquery; you can probably perform a direct join there.
Your query can be like
SELECT distinct id_product, product_sku

FROM product p

JOIN subscription s

    ON s.fk_product_subscribed = p.id_product

JOIN customer c ON c.id_customer = s.fk_customer

where s.status = 'active'
and c.email = 'ashutosh@gmail.com';

A: You could eliminate duplicates by adding distinct to Select
SELECT DISTINCT id_product, product_sku
FROM product  ....
that way if customer has ordered product more than once, you will only get result once


text:
Q: Which pair is exchangeable, "besides" and "aside from" or "except for" and "aside from"? This is one of the examples from cambridge dict.

Do you play any other sports besides basketball?

Oxford dict consider "besides", "except for" and "aside from" are synonyms.
To simplify the discussion, assume there are 2 options, basketball and baseball. Are "aside from" and "besides" exchangeable in the example sentence? If yes, then "aside from" and "except for" are not exchangeable. Here is the inference
Let set_A (mathematically) denote the group of sports the guy loves.
"besides" implies that both of basketball and baseball belong to set_A while "except for" indicates that the guy only loves baseball in the scope of available options.
Is my understanding right?

A: First of all, the question isn't what sports the person addressed loves, it is what sports the person plays. One may love a sport without playing it, and play a sport without loving it.
Secondly, these questions implicitly ask about any other sport, so it does not (IMO) make sense to limit the possible pool of answers, particularly not to only 2.
Thirdly, no, you have not understood correctly. In this example, "except for" does not significantly change the meaning from "aside from". To put it in set theory terms, all three are asking what the members of the set "sports person plays" are, other than 'basketball" All ask for a total enumeration of all other members of the set, All assume that "basketball" is a member of the set, and none make any assumptions about whether there are other members, and if so how many. (Technically they assume the set is finite, because it does not make sense to ask for the enumeration of an infinite set. But an infinite set of sports doesn't make sense anyway.)


text:
Q: How to make a popup in ASP.Net and pass information to it using a query string? I have all the code I need to response.redirect a page and pass the information I need to the other page. But I don't want it to redirect the page but rather create a popup in the page.
I have code for the popup also but I can't manage to pass information to it.
This is the code for the popup and it's not passing any information:
<asp:LinkButton ID="lb_viewstudenttimetable" runat="server" OnClick="lb_viewstudenttimetable_Click"
     OnClientClick="window.open('Timetable_User.aspx','Timetable','width=640,height=360,scrollbars=yes');">

This is the code for the OnClick button where it passing information to the other page
protected void lb_viewstudenttimetable_Click(object sender, EventArgs e)
{
    GridViewRow row = gv_classlist.SelectedRow;
    Response.Redirect("Timetable_User.aspx?UserID=" + row.Cells[1].Text + "");
    //my attempt of trying to pass the following to the popup
    //Response.Write("window.open('Timetable_User.aspx?UserID="+row.Cells[1].Text+"','Timetable','width=640,height=360,scrollbars=yes');");
}

So I wanna use OnClientClick to do what that OnClick does.

A: Just pass the query string:
<asp:LinkButton ID="lb_viewstudenttimetable" runat="server"
    OnClick="lb_viewstudenttimetable_Click"
    OnClientClick="window.open('Timetable_User.aspx?UserID=x', 'Timetable', 'width=640,height=360,scrollbars=yes');">

The question is then how to get "x" into the query string when "x" comes from the server. What you need to do is, in the Databinding event of the GridView, build the JavaScript string to be used OnClientClick, then set it. That way, the LinkButton in each grid row will already be prepared for when it is clicked.

A: Do you want a pop-up or a new browser tab? If you want a pop up, I generally use iframe like this.
<a rel="#popupinit" href="#" uniqenum='<%= serversideUniquenum %>'>Open popup

A:     GridViewRow row = gv_classlist.SelectedRow;
    lbl_timetableuserid.Text = row.Cells[1].Text;

    ScriptManager.RegisterStartupScript(this, typeof(string), "New_Window", "window.open('Timetable_User.aspx?UserID=" + row.Cells[1].Text + "', null, 'height=360,width=640,status=yes,toolbar=yes,menubar=yes,location=no' );", true);


text:
Q: Magento catalog price rules I have configured magento with only catalogus price rules, no shopping cart price rules exist.
The catalogus price rules define different percentage discount for different categories, for different user groups. All price rules say 'stop further processing'.
Now I have a conflict in the price calculations in shopping cart when adding multiple products.
For example:
I add a product (1) which has catalog price rule A, price is fine
I add a product (2) which has catalog price rule B, price is wrong. The discount from catalog price rule A is applied (because product (1) has price rule A).
When I remove product (1) from shopping cart, the price for product (2) is adjusted to the correct price
Demonstrated in the following screenshots: http://www.phpworks.nl/magento-catalog-price-rules.png
Now my question is: is this behaviour a bug in magento ? Catalog price rules should be calculated per product, not per shopping cart, if im right ?

A: I think you've enabled the option, "Stop Further Rules Processing"
So if the first rule applies, it will never reach the second rule..


text:
Q: Suggestions for optimization of code to pass TLE on java I have written a code that take two integer arrays as input and create two treemaps with their frequencys(number of occurences of integers) and writtens the values which is not present in both or there frequencys differ it is failing a test case when the array size is 10^6 due to TLE(time limit exceeded).
import java.util.*;
//import java.util.stream.Collectors;
public class Solution {

public static void main(String args[])
{
    Scanner s = new Scanner(System.in);
    int x=s.nextInt();
    int[] arr=new int[x];
    int i,j,count=0;
    for(i=0;i<x;i++)
    {
    arr[i]=s.nextInt();
    }
    Map<Integer, Integer> check=new TreeMap<Integer, Integer>();
    for(i=0;i<x;i++)
    {
        for(j=0;j<x;j++)
        {
            if(arr[i]==arr[j])
            {
                count++;
            }
        }
        check.put(arr[i], count);
        count=0;
    }
    int y=s.nextInt();
    int[] brr=new int[y];
    for(i=0;i<y;i++)
    {
    brr[i]=s.nextInt();
    }
    Map<Integer, Integer> check1=new TreeMap<Integer, Integer>();
    int count1=0;
    for(i=0;i<y;i++)
    {
        for(j=0;j<y;j++)
        {
            if(brr[i]==brr[j])
            {
                count1++;
            }
        }
        check1.put(brr[i], count1);
        count1=0;
    }
    //System.out.println(check);
    //System.out.println(check1);
    ArrayList<Integer> store=new ArrayList<Integer>();
    for(int key:check1.keySet())
    {
        if(check.containsKey(key))
        {
            int valb=check.get(key);
            int vala=check1.get(key);
            if(vala-valb!=0)
            {
                store.add(key);
            }
        }
        else
        {
            store.add(key);
        }
    }
    //Collections.sort(store);
    for(i=0;i<store.size();i++)
    {
        System.out.print(store.get(i)+" ");
    }
}

}

A: Instead of going over the same array in nested loops (O(n^2) time) calculating duplicates like this
    for(i=0;i<x;i++)
    {
        for(j=0;j<x;j++)
        {
            if(arr[i]==arr[j])
            {
                count++;
            }
        }
        check.put(arr[i], count);
        count=0;
    }

you can increment map value for each number in array. Something like this:
    for (int item: arr) {
      if (check.containsKey(item)) {
          check.put(item, check.get(item) + 1);
      } else {
          check.put(item, 1);
      }
    }

In the end, this produces the map where each key is a number from array and each value for the key is the counter for how many times this number appears in array. For example for array
[1, 2, 3, 4, 2, 3, 4, 5]

the map will look like
{1 -> 1, 2 -> 2, 3 -> 2, 4 -> 2, 5 -> 1}

This also runs in O(n) time if you're using HashMap instead of TreeMap.
To sort output you can use TreeSet instead of ArrayList.


text:
Q: Access violation at address 005D3653 in module 'Project1.exe I face the following error when I try to debug. I am just newbie with Delphi, please guide how to correct this error.

First chance exception at $73B1A9F2. Exception class EAccessViolation with message 'Access violation at address 005D3653 in module 'Project1.exe'. Read of address 000003AC'. Process Project1.exe (34780)

When break this source code is shown:
  if fsCreating in FFormState then
    if Value then
      Include(FFormState, fsVisible) else
      Exclude(FFormState, fsVisible)

A: You are calling a method on an invalid reference. For instance something like
Obj.DoSomething;

where Obj is not valid. Because the attempted read address is 000003AC, close to zero, almost certainly the reference is nil.
Track back up your call stack until you find the call with the nil reference.


text:
Q: How can I run a MySQL Administration statement with Eloquent and check results? I'd like to perfrom a query like
"SHOW SLAVE STATUS"
with Laravel5/Eloquent ORM
What I tried is:
$select = DB::select("SHOW SLAVE STATUS");

But when I dump $select it's an empty array. Instead I expect all the data:
https://dev.mysql.com/doc/refman/5.0/en/show-slave-status.html


text:
Q: Docker tagging without 'latest' tag? We've been discussing tagging strategies for our docker ECR repos and what we've landed on doesn't involve use of the latest tag at all.
I know latest isn't anything automatic. It's just a regular tag. But it's also a convention. Is it expected that latest exists? Are there tooling problems or things that may break if our repos don't have it at all?

A: You should be fine without the latest tag - there should be no tooling problems as long as you are using other tags and / or sha256 digests explicitly for pulling images.
That said, usually there is no good reason to avoid latest tag completely. Conventional approach is to push your latest acceptable build to its own tag AND the latest tag. It is hard to find an argument against this approach, since using latest is convenient in many non-scripted cases (i.e., a developer pulling the image locally and just using latest) - and at the same time you get this image with its proper tag.
Final thing I want to mention - since tags may be mutable, scripted pipelines and especially production instances should use explicit sha256 digests when pulling images.


text:
Q: WebRTC RtpDataChannels Deprecated
201 [Deprecation] RTP data channels are no longer supported. The "RtpDataChannels" constraint is currently ignored, and may cause an error at a later date.

But what is the migration path? I did a search and can only find info telling us to migrate to SCTP, without any details.
Remove WebRTC RTP data channels (removed)
I am thinking if we shall use the WebSocket channel (the one we used to establish the WebRTC Connection) to replace RtpDataChnanels.

A: If you're doing a peer-to-peer application: Use the standard WebRTC data channels; if in Javascript, just remove the constraint saying "I want to use RTP data channels", and most or all of your applications will work just like before, only better.
Why would anyone want to use that old relic?