text:
Q: force:createrecord event is not working in stand alone app force:createrecord event is not working in stand alone app despite registering the event.Please provide inputs on it
Component 1
<aura:component implements="force:appHostable,forceCommunity:availableForAllPageTypes" access="global">

 <ltng:require styles="{!$Resource.SLDS +
             '/assets/styles/salesforce-lightning-design-system.css'}"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

        <aura:handler name="change" action="{!c.createRecord}" value="{!v.options}"/>
    <aura:registerEvent name="ModalEvent" type="c.ModalEvent"/>

                            Close

Modal Header

                      <ui:inputSelect class="single" aura:id="InputSelectSingle" change="{!c.selection}">
                        </ui:inputSelect>

                    <button class="slds-button slds-button--neutral" onclick="{!c.removecss}">Cancel</button>
                    <button class="slds-button slds-button--neutral slds-button--brand" onclick="{!c.openRecord}">Continue</button>

        <button class="slds-button slds-button--neutral" onclick="{!c.applycss}">Open Modal</button>

</aura:component>

comp 1 controller code
({
    doInit : function(cmp) {
        // Initialize input select options
        var opts = [
            { "class": "optionClass", label: "Select a Record Type", value: "Select"},
            { "class": "optionClass", label: "Adverse Event", value: "012n00000008hxo"},
            { "class": "optionClass", label: "Free of Charge", value: "012n00000008hxp" },
            { "class": "optionClass", label: "Lab Exam", value: "012n00000008hxq" },
            { "class": "optionClass", label: "Nurse Visit", value: "012n00000008hxr" },
            { "class": "optionClass", label: "Quality Report", value: "012n00000008hxs" },
            { "class": "optionClass", label: "Welcome Kit", value: "012n00000008hxt" }

        ];
        cmp.find("InputSelectSingle").set("v.options", opts);

    },
     applycss:function(cmp,event){
        var cmpTarget = cmp.find('Modalbox');
        var cmpBack = cmp.find('MB-Back');
        $A.util.addClass(cmpTarget, 'slds-fade-in-open');
        $A.util.addClass(cmpBack, 'slds-backdrop--open');
    },
    removecss:function(cmp,event){
        var cmpTarget = cmp.find('Modalbox');
        var cmpBack = cmp.find('MB-Back');
        $A.util.removeClass(cmpBack,'slds-backdrop--open');
        $A.util.removeClass(cmpTarget, 'slds-fade-in-open');
    },
    selection: function(cmp,event) {
         var selectCmp = cmp.find("InputSelectSingle").get("v.value");
        console.log('selectCmp modal-->'+selectCmp);
         if(selectCmp !='Select')
         {
           //cmp.PassRecordTypeId(selectCmp);

         }

     },
      openRecord : function (component, event, helper) {
           debugger;
          var evt = $A.get("e.c:ModalEvent");
          //var evt = component.getEvent("ModalEvent");
           evt.setParams({"result":'012n00000008hxp'});
            evt.fire();

        }
})

Event
<aura:event type="Application" description="Event template">
     <aura:attribute name="result" type="String"/>

</aura:event>

Component 2
<aura:component implements="force:appHostable,forceCommunity:availableForAllPageTypes" access="global">
<aura:handler event="c:ModalEvent" action="{!c.openRecord2}"/>
<aura:dependency resource="force:createRecord" type="EVENT"/>

</aura:component>

component 2 code
({

      openRecord2 : function (component,event) {
          try
          {
        debugger;
        console.log('entry inside');
        var item = event.getParam("result");
           console.log('entry1-->'+item);
       var createRecordEvent = $A.get("e.force:createRecord");
       createRecordEvent.setParams({
        "entityApiName": "Service_Request__c"

        });
        createRecordEvent.fire();
          }
          catch(err)
          {
              console.log(err);
          }

      }
})

In component 2 code create record event is not working.

A: force:createRecord This event is handled by the one.app container. It's supported in Lightning Experience and Salesforce1 only.


text:
Q: What is the difference between "mov (%rax),%eax" and "mov %rax,%eax"? What is the difference between mov (%rax),%eax and mov %rax,%eax? I'm sure this is a simple question, but I can't find the answer anywhere.
Here is the original code that prompted my question:
mov    -0x8(%rbp),%rax
mov    (%rax),%eax
lea    (%rax,%rax,1),%edx
mov    -0x8(%rbp),%rax
mov    %edx,(%rax)
mov    -0x8(%rbp),%rax
mov    (%rax),%eax

A: In AT&T syntax, the instruction:

mov (%rax), %eax                  # AT&T syntax

or, equivalently in Intel syntax:

mov eax, DWORD PTR [rax]          ; Intel syntax

dereferences the memory address stored in rax, reads a 32-bit value from that memory address, and stores it in the eax register.
Because the memory address being dereferenced is stored in rax, it can be a 64-bit address, which is necessary when running on a 64-bit operating system.
However, the data pointed to by that memory address is only 32 bits in size, so it can be stored in the 32-bit eax register.
Note that this instruction will implicitly zero the upper 32 bits of the rax register, so that the lower 32-bit half (called eax) will contain the loaded data, and the upper 32-bit half will be empty.
The parentheses in AT&T syntax (or the square brackets in Intel syntax) are your clue that this instruction treats the contents of the register as if they were a pointer.
This is what makes it different from, for example:

mov %rcx, %rax                    # AT&T syntax

mov rax, rcx                      ; Intel syntax

This simply copies the contents of the rcx register into the rax register. There is no dereferencing being done. The values in the register(s) are acted on directly.
Note that the above example was similar to the other example from your question:

mov %rax, %eax                    # AT&T syntax (INVALID!)

mov eax, rax                      ; Intel syntax (INVALID!)

but not identical. This last case is actually an invalid instruction because there is an operand-size mismatch. If it were valid, the instruction would be copying the contents of the 64-bit rax register into the 32-bit eax register. Of course, this is impossible. Narrowing conversions are not allowed, so it will not assemble.
If you really wanted to do this, you would have to decide which half of the 64-bit value in rax that you wanted to throw away. If you decided to throw away the upper bits and copy only the lower bits to eax, you wouldn't need to do anything—just use eax directly. If, however, you wanted to throw away the lower bits and use only the upper bits, you would first do a right-shift by 32.

Note that this is a fairly simple, general-reference question. You could have looked up the answer in any book on x86 assembly language, and a tutorial should have taught you about the significance of the parentheses/brackets syntax. Please see the x86 tag wiki for some tutorials and other general-reference information.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to define a new algebra using TagSet? For example, I would like to define the algebra of quaternions. I coded something like
Unprotect[i, j, k]; ClearAll[i, j, k]
i /: i ** i := -1;
i /: i ** j := k;
i /: j ** i = -k;
i /: i ** k := -j;
i /: k ** i = j;
j /: j ** j := -1;
j /: j ** k := i;
j /: k ** j := -i;
k /: k ** k := -1;
Protect[i, j, k];
ExpandNCM[(h : NonCommutativeMultiply)[a___, b_Plus, c___]] :=
  Distribute[h[a, b, c], Plus, h, Plus, ExpandNCM[h[##]] &];
ExpandNCM[(h : NonCommutativeMultiply)[a___, b_Times, c___]] :=
  Most[b] ExpandNCM[h[a, Last[b], c]];
ExpandNCM[a_] := ExpandAll[a];
QQ = Collect[ExpandNCM[#], {i, j, k}] &;

However, I got two different results when calculating
(a i + b j + c k) ** (d i + e j + f k) // QQ
(a i + b j + c k) ** (l i + m j + n k) // QQ

The first one gave the expected result
k (a e-b d)+j (c d-a f)-a d+i (b f-c e)-b e-c f

while the second one gave a weird answer
i (a i**l+b j**l+c k**l)+j (a i**m+b j**m+c k**m)+k (a i**n+b j**n+c k**n)

I hope the NonCommutativeMultiply ** only operates on those i,j,k. I don't know where the problem is.
I also want to know if there is a handy way to define a new algebra?
Updated
Now the algebra has been set up for +, *, ** but not Power.
Here is the code
Unprotect[i, j, k]; ClearAll[i, j, k, ijkQ, ExpandNCM, Qconj, Qreal, \
Qimag]
i /: i ** i := -1;
i /: i*i := -1;
i /: i ** j := k;
i /: j ** i = -k;
i /: i ** k := -j;
i /: k ** i = j;
j /: j ** j := -1;
j /: j*j := -1;
j /: j ** k := i;
j /: k ** j := -i;
k /: k ** k := -1;
k /: k*k := -1;

i /: Qconj[i] := -i;
j /: Qconj[j] := -j;
k /: Qconj[k] := -k;
Protect[i, j, k];

Qconj[a_: 0] := a /; FreeQ[a, i | j | k];
Qconj[(b_: 1)*(q : i | j | k)] := b*Qconj[q] /; FreeQ[b, i | j | k];
Qconj[a_ + b_] := Qconj[a] + Qconj[b];

Qreal := Select[# + i, (FreeQ[#, i | j | k] &)] &;
Subscript[Qimag, x_] := ({0}~Join~
     Cases[{#}, (a : (_?(FreeQ[#, i | j | k] &)) : 1)*x :> a,
      Infinity])[[-1]] &

ExpandNCM[(h : NonCommutativeMultiply)[a___, b_Plus, c___]] :=
  Distribute[h[a, b, c], Plus, h, Plus, ExpandNCM[h[##]] &];

ExpandNCM[(h : NonCommutativeMultiply)[a___,
    b_?(FreeQ[#, i | j | k] &)*(q : i | j | k), c___]] :=
  b*ExpandNCM[h[a, q, c]];
ExpandNCM[(h : NonCommutativeMultiply)[a___,
    b_?(FreeQ[#, i | j | k] &), c___]] := b*ExpandNCM[h[a, c]];

ExpandNCM[(h : (Times | Plus))[a___, b_NonCommutativeMultiply,
    c___]] := h[a, c, ExpandNCM[b]];
ExpandNCM[(h : NonCommutativeMultiply)[a_: 1]] := a;

ExpandNCM[a_] := ExpandAll[a];

QQ = Collect[ExpandNCM[#], {i, j, k}] &;

Now the problem is how to set up the rules for Power, such as Exp[] , Log[] and Power[]. For example, I want to define Power[q,n] as q**q** ... **q and then use it to define Exp[q]. How should I do?
Note that the algebra of quaternions here is just an example. What I want is to define the rules for the algebra and let the Mathematica do the calculations. These rules will be changed.

A: UPDATE
Just found out that there's a Quaternions package: http://reference.wolfram.com/language/Quaternions/tutorial/Quaternions.html
ORIGINAL ANSWER
Here's a start:
(* some basic helpers *)
Quaternion[a_] := Quaternion[a, 0, 0, 0];
Quaternion[a_, b_] := Quaternion[a, b, 0, 0];
Quaternion[a_, b_, c_] := Quaternion[a, b, c, 0];
QI = Quaternion[0, 1];
QJ = Quaternion[0, 0, 1];
QK = Quaternion[0, 0, 0, 1];

Now a bit of meat:
Quaternion /:
  NonCommutativeMultiply[Quaternion[a1_, b1_, c1_, d1_], Quaternion[a2_, b2_, c2_, d2_]] :=
    Quaternion[
      a1 a2 - b1 b2 - c1 c2 - d1 d2,
      a1 b2 + b1 a2 + c1 d2 - d1 c2,
      a1 c2 - b1 d2 + c1 a2 + d1 b2,
      a1 d2 + b1 c2 - c1 b2 + d1 a2]

Some checks:
Quaternion[3, 0, 0, 0] ** Quaternion[7, 0, 0, 0]
(* Quaternion[21, 0, 0, 0] *)

QJ ** QK
(* Quaternion[0, 1, 0, 0] *)

QI ** QK
(* Quaternion[0, 0, -1, 0] *)

QI ** QJ ** QK
(* Quaternion[-1, 0, 0, 0] *)

Here's a simplistic formatting rule. This is just for demonstration--you should make this more robust.
Format[Quaternion[a_, b_, c_, d_]] := a + b i + c j + d k

Which gives,
Quaternion[1, 1, 1, 1] ** Quaternion[1, 2, 3, 4]
(* dispays as -8 + 4 i + 2 j + 6 k *)

Quaternion[1, 1, 1, 1] ** Quaternion[1, 2, 3, 4] // FullForm
(* Quaternion[-8, 4, 2, 6] *)

Note
I'm only vaguely familiar with quaternions and non-commutative multiplication, so there may be semantic errors above. It should all be made robust and then tested.

A: This is an answer for the "I don't know where the problem is" question.
The problem is this definition
ExpandNCM[(h:NonCommutativeMultiply)[a___,b_Times,c___]]:=Most[b]*ExpandNCM[h[a,Last[b],c]];

and more precisely the pattern b. To understand the problem, enter
d*i
(* d * i *)

m*i
(* i * m *)

In the second case, Times has reordered the variables and put i before m. This is because Times is Orderless and i comes before m in the canonical order.
Therefore, if the b_Times in the definition above is matched with m*i then
Most[b] == i
Last[b] == m

and the i is moved out of the NoncommutativeMultiply.
One possible fix is to replace the definition above by (but please clear old definitions before doing this):
ExpandNCM[(h:NonCommutativeMultiply)[a___,b_*(q:i|j|k),c___]]:=b*ExpandNCM[h[a,q,c]];

Now
(a i+b j+c k)**(l i+m j+n k) // QQ
(* -a l-b m+k (-b l+a m)-c n+j (c l-a n)+i (-c m+b n) *)


text:
Q: Gitlab-CI: Dockerized Spring Boot with gradle failed on docker build I'm trying to get into gitlab-ci, unfortunately the stage docker build fails. Here is the link to my repo:
https://gitlab.com/systemxy/actuator-sample/-/jobs/131454962

A: You have your repository set as private, please paste logs or make it public so we can have a look at this.


text:
Q: Consistent ontology can not be materialized using HERMIT For my experiment, I need to materialize a dbpedia ontology which consists of the TBox/schema and ABox/data.
To do so, I merge the dbpedia ontology/TBox/schema (http://downloads.dbpedia.org/2016-04/dbpedia_2016-04.owl) with the ABox/data part from the DBPedia knowledge graph (I just took 2% of the data in http://downloads.dbpedia.org/2016-04/core-i18n/en/mappingbased_objects_en.ttl.bz2).
Before materialized this merged file, I ran the consistency checking first using HerMit reasoner. The merged file was consistent.
But when I ran the materialization service using HerMit reasoner (I used the code from https://github.com/owlcs/owlapi/issues/643), I found this error  : comparison method violates its general contract!
When I debugged the code, the error was raised when the compiler invoked this process : manager.saveOntology(inferredAxiomsOntology,outputStream)
It's quite strange that a consistent ontology can not be materialized by the reasoner.
Any idea how to solve this error? (The merged file can be downloaded from https://www.dropbox.com/s/l689hejgyv2xn7l/DBPRule1Ite1.owl.zip?dl=0 )
Thank you very much.

A: You need to use a more recent version of the libraries. The bug you found was fixed at the beginning of the V4 series, in 2014.
You can use HermiT 1.3.8.413 (which uses OWLAPI 4.1.3) or HermiT 1.4.1.513 (which uses OWLAPI 5.1.3). Both are available on Maven Central:
http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22net.sourceforge.owlapi%22%20AND%20a%3A%22org.semanticweb.hermit%22


text:
Q: Datatables inline editing with datepicker Ok so I have this datatable with around 90 fields being populated from a dbContext (Visual Studio MVC4). I added the .makeEditable() to enjoy inline editing...
Most of my fields are of a type string (but a user CAN input a date if he opts to....even though its a text type field, the date will be input as simple text..)
The problem I have is that even though I'm successfully being able to get the class of the edit form to become "datepicker", the calender isn't popping up and on other simple non-datatable pages, it runs just fine.
I want to be able to set certain column cells to have inline datepicking ability..
I want my table to look like this thing http://jquery-datatables-editable.googlecode.com/svn/trunk/inline-edit-extra.html
I tried mimic-ing the code there but with no success....its always a textbox for editing instead of a calender view..
UPDATE: I noticed that if I change the "type:" field in
$.fn.editable.defaults = {
        name: 'value',
        id: 'id',
        type: 'datepicker',
        width: 'auto',
        height: 'auto',
        event: 'click.editable',
        onblur: 'cancel',
        loadtype: 'GET',
        loadtext: 'Loading...',
        placeholder: 'Double-Click to edit',
        loaddata: {},
        submitdata: {},
        ajaxoptions: {}
    };

My entire table gets a datepicker on editing mode...
Apparently the intializing code to give certain columns datepicker options doesn't work as it should ....or at least I guess so
**UPDATE END****
This is my datatable initialization code:


text:
Q: MySQL root access from all hosts I've installed MySQL server on a remote Ubuntu machine. The root user is defined in the mysql.user table this way:
mysql> SELECT host, user, password FROM user WHERE user = 'root';
+------------------+------+-------------------------------------------+
| host             | user | password                                  |
+------------------+------+-------------------------------------------+
| localhost        | root | *xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx |
| ip-10-48-110-188 | root | *xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx |
| 127.0.0.1        | root | *xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx |
| ::1              | root | *xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx |
+------------------+------+-------------------------------------------+

I can access with user root from the same remote machine command-line interface using the standard mysql client. Now I want to allow root access from every host on the internet, so I tried adding following row (it's an exact duplicate of the first row from previous dump, except for the host column):
mysql> SELECT host, user, password FROM user WHERE host = '%';
+------------------+------+-------------------------------------------+
| host             | user | password                                  |
+------------------+------+-------------------------------------------+
| %                | root | *xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx |
+------------------+------+-------------------------------------------+

But my client on my personal PC continues to tell me (I obscured the server IP):

SQL Error (2003): Can't connect to MySQL server on '46.x.x.x' (10061)

I can't tell if it's a authentication error or a network error. On the server firewall I enabled port 3306/TCP for 0.0.0.0/0, and that's ok for me...

A: MariaDB running on Raspbian - the file containing bind-address is hard to pinpoint. MariaDB have some not-very-helpful-info on the subject.
I used
# sudo grep -R bind-address /etc

to locate where the damn thing is.
I also had to set the privileges and hosts in the mysql like everyone above pointed out.
And also had some fun time opening the 3306 port for remote connections to my Raspberry Pi - finally used iptables-persistent.
All works great now.

A: Run the following query:
use mysql;
update user set host='%' where host='localhost'

NOTE: Not recommended for production use.

A: Update:
As mentioned in the comments, since MySql 8 you need to first explicitly create the user, so the command will look like:
CREATE USER 'root'@'%' IDENTIFIED BY 'password'; GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;

Original answer:
There's two steps in that process:
a) Grant privileges. As root user execute with this substituting 'password' with your current root password :
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password';

b) bind to all addresses:
The easiest way is to comment out the line in your my.cnf file:
#bind-address = 127.0.0.1

and restart mysql
service mysql restart

By default it binds only to localhost, but if you comment the line it binds to all interfaces it finds. Commenting out the line is equivalent to bind-address=*.
To check where mysql service has binded execute as root:
netstat -tupan | grep mysql

Update For Ubuntu 16:
Config file is (now)
/etc/mysql/mysql.conf.d/mysqld.cnf

(at least on standard Ubuntu 16)

A: MYSQL 8.0 - open mysql command line client
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';

use mysql
UPDATE mysql.user SET host='%' WHERE user='root';

Restart mysql service

A: I'm using AWS LightSail and for my instance to work, I had to change:
bind-address = 127.0.0.1

to
bind-address = <Private IP Assigned by Amazon>

Then I was able to connect remotely.

A: Sometimes

bind-address = 127.0.0.1

should be

bind-address = *

A: if you have many networks attached to you OS, yo must especify one of this network in the bind-addres from my.conf file.
 an example:
[mysqld]
bind-address = 127.100.10.234

this ip is from a ethX configuration.

A: In my case the "bind-address" setting was the problem. Commenting this setting in my.cnf did not help, because in my case mysql set the default to 127.0.0.1 for some reason.
To verify what setting MySql is currently using, open the command line on your local box:
mysql -h localhost -u myname -pmypass mydb

Read out the current setting:
Show variables where variable_name like "bind%"

You should see 0.0.0.0 here if you want to allow access from all hosts. If this is not the case, edit your /etc/mysql/my.cnf and set bind-address under the [mysqld] section:
bind-address=0.0.0.0

Finally restart your MySql server to pick up the new setting:
sudo service mysql restart

Try again and check if the new setting has been picked up.

A: Update the bind-address = 0.0.0.0 in the /etc/mysql/mysql.conf.d/mysqld.cnf and from the mysql command line allow the root user to connect from any Ip.
Below was the only commands worked for mysql-8.0 as other were failing with error syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY 'abcd'' at line 1
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
UPDATE mysql.user SET host='%' WHERE user='root';

Restart the mysql client
sudo service mysql restart

A: mysql_update is what you need.
I don't know why anyone would follow the more complex ways of correcting this issue, when MySql graciously built a tool that already does this...


text:
Q: Local outlier factor (LOF) software / demo? Is there any software that enables me to perform LOF outlier detection towards a 2D dataset? I just implemented LOF from the original paper and want to check whether my results are correct. So far I couldn't find any tool or online service.

A: Did you check the Wikipedia article on Local Outlier Factor? It mentions ELKI, which has a LOF implementation (with index support, so O(n log n) for large data sets).
Note that many people overlook the reachability-distance in LOF, and only approximate it. The ELKI implementation supposedly is correct, so it can help you well for testing your results.

A: You should check rapidminer application. And add anomaly detection plugin.

A: Rapid Miner considers the IP address attribute of DARPA 1998 dataset as polynomial type data ! But LOF is not optimized for that. Interestingly RAPID MINER cannot handle such huge network traffic datasets. Any other implementation available ?


text:
Q: WordPress Can't Connect to MySQL DB While Test Code Can I'm trying to set up a new WordPress site and can't get it to connect to the database.
To to try isolate the problem, I created a php file in the same directory as the WordPress app with the following code:
<?php
$mysqli = new mysqli('localhost:3306', 'root', 'somepassword', 'gazos');

if ($mysqli->connect_error)
    die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);
else
   echo 'Good connection to gazos';
?>

When I execute it from the browser, it returns Good connection to gazos.
This the first part of my wp-config.php file:
<?php
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'gazos');

/** MySQL database username */
define('DB_USER', 'root');

/** MySQL database password */
define('DB_PASSWORD', 'somepassword');

/** MySQL hostname */
define('DB_HOST', 'localhost:3306');

Calling the supplied WordPress index.php file results in the following error:
Error establishing a database connection

I get the same error when I remove the port from localhost.
Could the php version be too new for WordPress?

A: Replace localhost:3306 with 127.0.0.1.
When I asked this question on a wordpress forum, I was told my MySQL configuration was bad. When I asked about that problem on this forum, it was suggested that I try 127.0.0.1 in place of localhost:3306. That fixed the problem. I still don't know if my configuration is bad.

A: leave the port out on DB_HOST.
define('DB_HOST', 'localhost');
Edit:
Try changing your mysql password and updating your wp-config.php.
Saw that here.


text: Q: Detecting HTML modification I'm not even sure if this is in the realm of possibility.  Is there a way to detect a change in a webpage's HTML content?  For example, I have a webpage with an image in the center, if someone decides to remove the image element from the page's HTML source, is there a way to detect the removal?  Or do I need to use something that loops and checks the page every second or so (Using JS)?


text:
Q: Setting cwd in modern C++ I am playing around with MSVC's <experimental/filesystem> library, trying to reset my current working directory to be the executable directory.
This is because when building and running my project in VS2017, the cwd is actually $(ProjectDir), rather than $(OutputDir), as I would expect. I am aware that I could change this in Visual Studio, but I'd like to dummy-proof my code as well.
To that end, I have this snippet of code I am using to reset my path at the beginning of main:
int main(int argc, char *argv[])
{
    Utils::resetcwd(argc, argv);
...

I would like to know if there is anything that I am doing that is "evil" or would not be cross-platform compatible (assuming the filesystem library does not undergo any major changes).
I know that on *nix systems, using argv[0] to find the cwd is not guaranteed to return an absolute path, but I can't find much on what are valid constructors for the Path class. In fact, I'm surprised that the following works:
namespace Utils
{
    using namespace std::experimental;

    static void resetcwd(int argc, char *argv[])
    {
        std::string execution(argv[0]);
        auto basePath = execution.substr(0, execution.find_last_of("/"));

        if (basePath.length() == execution.length())
        {
            basePath = execution.substr(0, execution.find_last_of("\\"));
        }

        filesystem::current_path(basePath);
    }
}

Basically, have I done the right thing, according to C++ 2017?


text:
Q: How to get dialog name or dialog class of MFC dialog? I have big,old MFC source code. It is very difficult to debug the code. I am using Spy++ to examine one of the dialog. Following is snapshot of Spy++ of the dialog of MFC application.
Is there any way to find name of class of Dialog, or dialog ID?
Secondly, is there any tool in Visual Studio (using 2008) which can map button callback with correct method of source code.
I know second question sounds greedy, but just trying to see if this type of tool exists?

A: *

*Launch the Debugger.

*Run the application.

*Hit Break All

*Look into the call stack

You should find the code location that calls DoModal. And there you find the appropriate class that is used.


text:
Q: Delete a page cover photo via open graph I am trying to delete a cover photo of a page via open graph.
Is this even possible?
The cover was set with:
https://graph.facebook.com/PAGE_ID?cover=IMAGE_ID&method=POST&access_token=ACCESS_TOKEN&no_feed_story=true

And deleted with:
https://graph.facebook.com/IMAGE_ID?method=DELETE&access_token=ACCESS_TOKEN

You dont have the permission to do so:
{
  "error": {
    "message": "(#200) Permissions error",
    "type": "OAuthException",
    "code": 200
  }
}

When I set the cover, Facebook saves a new photo into the cover-album of the page.
This cover photo is not created by the app.
So it looks like I am unable to delete the cover photos of a page.
Because you can only delete photos that were created by the same app.
Can someone verify this?

A: There is no API which provides that functionality - if you found documentation suggesting otherwise please comment here and i'll get it corrected

A: I actually got it working, but it more seems a bug on FB side than anything else.
I did the same as initial post, and I would say I managed to have cover deleted in about 20% of my tests (sometimes by entering url directly in my browser, sometimes using PHP/CURL)
But in ALL my recent tests, it's NOT WORKING anymore.
Got "#200 Permissions Error" message when it's not working, and simply "true" when it does.
Seems that has difficulties handling page access token permissions.
Too bad, since I wanted to display my office's webcam capture as my FB cover, but I need to delete my old covers from time to time automatically to avoid my Covers folder to be filled with screen caps every minute or so, and only keep the 10 latest.


text:
Q: ArrayOutOfBoundException runtime error I am trying to run this code, to learn java, but I encountered a runtime error:
import java.util.*;

public class ArrayStack<E> implements StackInterface<E>{
    private E[] theStack;
    private int capacity;
    public static final int CAPACITY = 1000;
    private int top = -1;

    public ArrayStack() {
        top = -1;       // empty stack
        theStack = (E[])(new Object[10]);  // make room for at least 10 items
    }

    public ArrayStack(int initialCapacity) throws IllegalArgumentException {
    /*The constructor creates a new stack with the specified capacity, and throws an IllegalArgumentException
     if the specified capacity is less than zero.*/
        if (initialCapacity < 1)
            throw new IllegalArgumentException
                  ("initialCapacity must be >= 1");
        theStack = (E[]) new Object [capacity];
        capacity = initialCapacity;
        top = -1;

    }

    public void push(E element) throws NullPointerException,IllegalStateException {
        if (size() == capacity)
            throw new IllegalStateException("Stack is full.");
        if (element == null) {
            throw new NullPointerException("Can't push a null element");
        }

        if (theStack.length == top + 1) {
            theStack = java.util.Arrays.copyOf(theStack, theStack.length * 2);
        } // else, there already is room for one new element
        top++;
        theStack[top] = element;
    }
    public int size() { return top+1; }
    public boolean isEmpty() {
        return (top < 0);
    }
    public E pop() throws EmptyStackException{
        E element;
        if(isEmpty()) {
            throw new EmptyStackException();
        }
        element = theStack[top];
        theStack[--top] = null;
        return element;
    }

    public int depth() {
        return size();
    }

    public int capacity() {
        return capacity;
    }

    public void flip() {
        reverse(theStack, 0, size() -1);
    }

    public void reverse(E[] x, int i, int j){
        if(i<j){
            E tmp = x[i];
            x[i] = x[j];
            x[j] = tmp;
            reverse(x, ++i, --j);
        }
    }

    public void transferTop(ArrayStack<E> s) throws EmptyStackException {
    /*The transferTop method transfers the element from the top of stack s to the top of the current stack (this).*/
        if(isEmpty()) {
            throw new EmptyStackException();
        }
        E x;
        x = s.pop();
        this.push(x);

    }

    public E replaceTop(E element) throws NullPointerException {
    /*The replaceTop method replaces the top element of the stack with the specified element and returns the original top element.*/
        if(element == null) throw new NullPointerException("Can't push a null element");
        theStack[top] = element;
        return theStack[top];
    }

    public String toString() {
        String s;
        s = "[";
        if (size() > 0)
            s += theStack[0];
        if (size() > 1)
            for (int i = 1; i <= size() - 1; i++) {
                s += ", " + theStack[i];
            }
        return s + "]";
    }

    public void status(String op, Object element) {
        System.out.print("------> " + op); // print this operation
        System.out.println(", returns " + element); // what was returned
        System.out.print("result: size = " + size() + ", isEmpty = "
                + isEmpty());
        System.out.println(", stack: " + this); // contents of the stack
    }

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        Object o;
        //ArrayStack(int initialCapacity)
        StackInterface<Integer> A = new ArrayStack<Integer>(100);
        A.status("new ArrayStack<Integer> A", null);

        A.push(7);
        A.status("A.push(7)", null);
        o = A.pop();
        A.status("A.pop()", o);
        A.push(9);
        A.status("A.push(9)", null);
        o = A.pop();
        A.status("A.pop()", o);
        ArrayStack<String> B = new ArrayStack<String>();
        B.status("new ArrayStack<String> B", null);
        B.push("Bob");
        B.status("B.push(\"Bob\")", null);
        B.push("Alice");
        B.status("B.push(\"Alice\")", null);
        o = B.pop();
        B.status("B.pop()", o);
        B.push("Eve");
        B.status("B.push(\"Eve\")", null);
    }
}

The A.push(7) operation generated the ArrayIndexOutOfBoundsException. I was wondering what needs to be changed in my push() method. Thanks in advance.

A: theStack = (E[]) new Object [capacity];
capacity = initialCapacity;

You allocate a zero-sized array because you use capacity when it's set to deafult 0 and not the correct value.


text:
Q: Авторизация на сайте при помощи сертификата У меня есть пользовательский сертификат. sert.cer. Мне нужно авторизоваться на сайте и скачать файлы.  я его при помощи операции openssl x509 -inform der -in sert.cer -out certificate.pem  преобразовал  в .pem (в примерах везде pem поключают).  так же у меня есть корневой сертификат D:\br.so-ups.ru(GOST-2012).cer. Но при запросе Get
zHTTP.Get('https://br.so-ups.ru:444/webapi/public/ssl/LoginByCert.aspx');
Вылетает ошибка

Project LisTLoad.exe raised exception class EIdOSSLLoadingCertError with message 'Could not load certificate.
error:0609E09C:digital envelope routines:PKEY_SET_TYPE:unsupported algorithm'.

  zHandler := TIdSSLIOHandlerSocketOpenSSL.Create(aHTTP);

  zHandler.SSLOptions.Method := sslvSSLv23;
  zHandler.SSLOptions.SSLVersions := [sslvSSLv2, sslvSSLv3, sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2];
  zHandler.SSLOptions.CertFile := 'D:\certificate.pem';
  zHandler.SSLOptions.KeyFile := 'D:\certificate.pem';
  zHandler.SSLOptions.RootCertFile := 'D:\br.so-ups.ru(GOST-2012).cer';
  zHandler.SSLOptions.Mode := sslmClient;
  with aHTTP do
  begin
    Request.UserAgent := 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0';
    Request.CustomHeaders.AddValue('Accept', 'text/html,application/xhtml+xml,application/xml');
    Request.CustomHeaders.AddValue('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64;Trident/7.0 rv:11.0) like Gecko');
    Request.CustomHeaders.AddValue('Connection', 'Keep-Alive');
    Request.CustomHeaders.AddValue('DNT', '1');
    Request.CustomHeaders.AddValue('Referer', 'https://br.so-ups.ru/signin');
    Request.CustomHeaders.AddValue('Host', 'https://br.so-ups.ru');
    Request.BasicAuthentication := False;

    CookieManager := IdCookie1;
    AllowCookies := True;
    HandleRedirects := True;
    IOHandler := zHandler;
    if CheckBox2.Checked = True then
    begin
      ProxyParams.ProxyPort := proxy_port;
      ProxyParams.ProxyServer := proxy_server;
      ProxyParams.ProxyUsername := proxy_login;
      ProxyParams.ProxyPassword := proxy_password;
    end;
    ReadTimeout := 100000000;
  end;

В браузере авторизация через пользовательский сертификат проходит нормалотно


text:
Q: Multiple select with single Group By query I have these 3 fields in the table.

trans_date |  transaction_type | client_id

What I need is a count of entries by transaction_types for each date. For example,

Date : 07/07/2015  total count : 6 transaction_type 1 count : 3 ,
  transaction_type 2 count : 1,   transaction_type 3 count : 2 etc....

And I need this for all the dates grouped by each date.
Here's my current query,
SELECT count(id) as total_count,
    (select count(id) where transaction_type=1) as type1_count,
    (select count(id) where transaction_type=2) as type2_count,
    (select count(id) where transaction_type=3) as type3_count
FROM tblTransactions
where client_id=1
GROUP BY date(trans_date/1000, 'unixepoch')

This returns weird numbers that doesn't match. What am I doing wrong?

A: The reason that you are getting weird values is that your sub queries are not filtered by date so you will get the total count for each transaction type. What you need is a correlated subquery that will get a paremeter from outer query:
SELECT count(id) as total_count,
    (select count(id) where transaction_type=1 and trans_date=t.trans_date) as type1_count,
    (select count(id) where transaction_type=2 and trans_date=t.trans_date) as type2_count,
    (select count(id) where transaction_type=3 and trans_date=t.trans_date) as type3_count
FROM tblTransactions t
where client_id=1
GROUP BY date(trans_date/1000, 'unixepoch')

A: You can use sum function instead of subqueries
select date(trans_date/1000, 'unixepoch') d,
       sum(case when transaction_type = 1 then 1 else 0 end) type1_count,
       sum(case when transaction_type = 2 then 1 else 0 end) type2_count,
       sum(case when transaction_type = 3 then 1 else 0 end) type3_count
    from tblTransactions
  where client_id=1
  group by d


text:
Q: Configurable product quantity not shown on invoice or order When a user purchase a configural product from my store, he goes to the checkout cart and in that it shows the basic details of the product and the price and quantity. After purchasing a configurable product, My cart looks something like this and also the invoice bottom and order bottom part looks the same as below
 Product Name Unit Price Qty Subtotal

Associate Support $825.00 1 $825.00

Hour
15

I want to add Quantity below Hour i.e.
Product Name Unit Price Qty Subtotal

Associate Support $825.00 1 $825.00

Hour
Quantity: 15

Can anyone please tell me how to add that text "Quantity" in My cart, in invoice and in order.

A: For the Admin
Enable Template Path hints as follows
INSERT INTO `core_config_data` (`scope`, `scope_id`, `path`, `value`)
       VALUES ('websites', '0', 'dev/debug/template_hints', '1');

Clear cache. With this enabled you would be able to know the templates/blocks in admin section
For FrontEnd
You can find templates for email here.You can follow the same path in your theme also
app/design/frontend/base/default/template/email/order/invoice


text:
Q: Using Babel to convert ES6 modules to ES5 AMD modules, not working as expected I hope someone can help.
I'm using grunt-babel to convert my ES6 module code to ES5 AMD module code. Here's my ES6 code:
multiply.js
export default function (x,y) {
    return x * y;
};

square.js
import multiply from 'multiply';
export default function (x) {
   return multiply(x,x);
};

app.js
import square from 'square';

var myValue = square(2);
console.log(myValue);

As you can see, all I'm doing is creating a module 'multiply', importing that into another module 'square', and then finally using 'square' in my main js file. The above 3 files then gets converted to the following:
multiply.js
define("multiply", ["exports", "module"], function (exports, module) {
    module.exports = function (x, y) {
        return x * y;
    };
});

square.js
define("square", ["exports", "module", "multiply"], function (exports, module, _resourcesJsEs6moduleExampleMultiply) {
    var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };

    var multiply = _interopRequire(_resourcesJsEs6moduleExampleMultiply);

    module.exports = function (x) {
        return multiply(x, x);
    };
});

app.js
define("app", ["exports", "square"], function (exports, _resourcesJsEs6moduleExampleSquare) {
    var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };

    var square = _interopRequire(_resourcesJsEs6moduleExampleSquare);

    var myValue = square(2);
    console.log(myValue);
});

The problem I have is that I expected the 'app.js' file to be converted to something more like this:
requirejs(['square'],
    function (square) {
        var myValue = square(2);
        console.log(myValue);
    }
);

In my gruntfile.js my config is pretty simple:
options: {
    moduleIds: true,
    modules: 'amd',
    blacklist: ['strict']
}

Am I doing something wrong?

A: After some further digging I finally realised where I went wrong.
In my current stack I'm forced to use Almond, instead of RequireJS. Because of this, Almond expects there to be a file to initialise the modules, hence why I was expecting Babel to generate one for me. But as it turns out, the code generated by Babel will work fine within RequireJS, but for it to work with Almond, I need to create a seperate es5 js file, just to initialise the files generated by Babel.
Something like this:
requirejs(['app'],
    function (app) {
        app();
    }
);


text:
Q: how to make VBA Class method return an object I wrote a Class representing a geometric Vector (defined by x and y coordinates) and I would like to make one of its method return an object of similar type by performing a simple translation
The Cass would be named Vxy and its code is:
Option Explicit
''+------------------------------------------------------------------+
''| Class Vector defined by x and y                                  |
''+------------------------------------------------------------------+
Private px As Double: Private py As Double
Public Property Get x() As Double:    x = px:            End Property
Public Property Let x(d As Double):  px = d:             End Property
Public Property Get y() As Double:    y = py:            End Property
Public Property Let y(d As Double):  py = d:             End Property
''+------------------------------------------------------------------+
''| Method Translation                                               |
''|                                                                  |
''+------------------------------------------------------------------+
Function Ts(V As Vxy) As Vxy
 Set Ts = CreateObject("Vxy")
 Ts.x = Me.x + V.x
 Ts.y = Me.y + V.y
End Function

The code that tries to create objects of above class is as follows:
Option Explicit
''+------------------------------------------------------------------+
''| Testing Vectors                                                  |
''|                                                                  |
''+------------------------------------------------------------------+
Sub test_Vectors()
Dim V As New Vxy
 V.x = 3
 V.y = 4:
MsgBox V.a:
MsgBox V.l: ' Ok
Dim V_translated As New Vxy: V_translated = V.Ts(V) 'ERROR HERE
MsgBox V_translated.x: MsgBox V_translated.y:
End Sub

The error is: Run-time error 429: ActiveX component can't create object

A: You cant late bind to a local class with CreateObject("Vxy") (which raises your 429 error) instead:
Set Ts = new Vxy

You also need to Set object references so:
Set V_translated = V.Ts(V)

A: CreateObject("Vxy") will attempt to look up the CSLID of your object in the registry to instantiate a late-bound instance of it. It's running in VBA, so it will obviously never get registered.  Simply replace that with the early-bound version:
Set Ts = New Vxy


text:
Q: How to set progressbar max value other than setting it on the event form load? im having problem setting the max progressbar value. the program will ask the user how much is the max progressbar value and then the program sets it.
using ProgressBar1.Maximum = val dosent seem to work when outside of Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Help

A: Do the following:
Add a ProgressBar, Textbox, and Button on a new form.
Next, double-click on the Button, and add the following code:
Dim pb1max As Int64
pb1max = TextBox1.Text
ProgressBar1.Maximum = CInt(pb1max)
For j As Integer = 1 To pb1max
    ProgressBar1.Value = j
Next

Then, at run-time, type for example 100000 into the Textbox, then click the Button.  You are grabbing the integer value from the Textbox (which the user types in), and then setting ProgressBa1.Max = pb1max.  The loop also goes up to the max value, and ProgressBar1.Value is used to set the progress bar level (percent completion).


text:
Q: Flutter - Create a countdown widget I am trying to build a countdown widget. Currently, I got the structure to work. I only struggle with the countdown itself. I tried this approach using the countdown plugin:
class _Countdown extends State<Countdown> {

  int val = 3;

  void countdown(){
    CountDown cd = new CountDown(new Duration(seconds: 4));

    cd.stream.listen((Duration d) {
      setState((){
        val = d.inSeconds;
      });
    });

  }

  @override
  build(BuildContext context){
    countdown();
    return new Scaffold(
      body: new Container(
        child: new Center(
          child: new Text(val.toString(), style: new TextStyle(fontSize: 150.0)),
        ),
      ),
    );
  }
}

However, the value changes very weirdly and not smooth at all. It start twitching. Any other approach or fixes?

A: It sounds like you are trying to show an animated text widget that changes over time. I would use an AnimatedWidget with a StepTween to ensure that the countdown only shows integer values.

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyApp(),
  ));
}

class Countdown extends AnimatedWidget {
  Countdown({ Key key, this.animation }) : super(key: key, listenable: animation);
  Animation<int> animation;

  @override
  build(BuildContext context){
    return new Text(
      animation.value.toString(),
      style: new TextStyle(fontSize: 150.0),
    );
  }
}

class MyApp extends StatefulWidget {
  State createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> with TickerProviderStateMixin {
  AnimationController _controller;

  static const int kStartValue = 4;

  @override
  void initState() {
    super.initState();
    _controller = new AnimationController(
      vsync: this,
      duration: new Duration(seconds: kStartValue),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.play_arrow),
        onPressed: () => _controller.forward(from: 0.0),
      ),
      body: new Container(
        child: new Center(
          child: new Countdown(
            animation: new StepTween(
              begin: kStartValue,
              end: 0,
            ).animate(_controller),
          ),
        ),
      ),
    );
  }
}

A: The countdown() method should be called from the initState() method of the State object.
class _CountdownState extends State<CountdownWidget> {

  int val = 3;
  CountDown cd;

  @override
  void initState() {
    super.initState();
    countdown();
  }
...

Description of initState() from the Flutter docs:

The framework calls initState. Subclasses of State should override
  initState to perform one-time initialization that depends on the
  BuildContext or the widget, which are available as the context and
  widget properties, respectively, when the initState method is called.

Here is a full working example:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:countdown/countdown.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Countdown Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new CountdownWidget();
  }
}

class _CountdownState extends State<CountdownWidget> {

  int val = 3;
  CountDown cd;

  @override
  void initState() {
    super.initState();
    countdown();
  }

  void countdown(){
    print("countdown() called");
    cd = new CountDown(new Duration(seconds: 4));
    StreamSubscription sub = cd.stream.listen(null);
    sub.onDone(() {
      print("Done");
    });
    sub.onData((Duration d) {
      if (val == d.inSeconds) return;
      print("onData: d.inSeconds=${d.inSeconds}");
      setState((){
        val = d.inSeconds;
      });
    });
  }

  @override
  build(BuildContext context){
    return new Scaffold(
      body: new Container(
        child: new Center(
          child: new Text(val.toString(), style: new TextStyle(fontSize: 150.0)),
        ),
      ),
    );
  }
}

class CountdownWidget extends StatefulWidget {

  @override
  _CountdownState createState() => new _CountdownState();
}

A: based on @raju-bitter answer, alternative to use async/await on countdown stream
  void countdown() async {
    cd = new CountDown(new Duration(seconds:4));
    await for (var v in cd.stream) {
      setState(() => val = v.inSeconds);
    }
  }

A: Why not use a simple TweenAnimationBuilder its easy to use and you don't need to manage any stream controllers or worry about using streams and disposing them off etc;
TweenAnimationBuilder<double>(
                duration: Duration(seconds: 10),
                tween: Tween(begin: 100.0, end: 0.0),
                onEnd: () {
                  print('Countdown ended');
                },
                builder: (BuildContext context, double value, Widget child) {
                  return Padding(
                      padding: const EdgeInsets.symmetric(vertical: 5),
                      child: Text('${value.toInt()}',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              color: Colors.black,
                              fontWeight: FontWeight.bold,
                              fontSize: 40)));
                }),

here's the dartpad example to playaround
output:

originally answered here

A: Countdown example using stream, not using setState(...) therefore its all stateless.
this borrow idea from example flutter_stream_friends
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:countdown/countdown.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  static String appTitle = "Count down";

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: appTitle,
      theme: new ThemeData(
        primarySwatch: Colors.purple,
      ),
      home: new StreamBuilder(
          stream: new CounterScreenStream(5),
          builder: (context, snapshot) => buildHome(
              context,
              snapshot.hasData
                  // If our stream has delivered data, build our Widget properly
                  ? snapshot.data
                  // If not, we pass through a dummy model to kick things off
                  : new Duration(seconds: 5),
              appTitle)),
    );
  }

  // The latest value of the CounterScreenModel from the CounterScreenStream is
  // passed into the this version of the build function!
  Widget buildHome(BuildContext context, Duration duration, String title) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(title),
      ),
      body: new Center(
        child: new Text(
          'Count down ${ duration.inSeconds }',
        ),
      ),
    );
  }
}

class CounterScreenStream extends Stream<Duration> {
  final Stream<Duration> _stream;

  CounterScreenStream(int initialValue)
      : this._stream = createStream(initialValue);

  @override
  StreamSubscription<Duration> listen(
          void onData(Duration event),
          {Function onError,
          void onDone(),
          bool cancelOnError}) =>
      _stream.listen(onData,
          onError: onError, onDone: onDone, cancelOnError: cancelOnError);

  // The method we use to create the stream that will continually deliver data
  // to the `buildHome` method.
  static Stream<Duration> createStream(int initialValue) {
    var cd = new CountDown(new Duration(seconds: initialValue));
    return cd.stream;
  }
}

The difference from stateful is that reload the app will restart counting. When using stateful, in some cases, it may not restart when reload.


text:
Q: How to add multiple target columns in google sheets script when wanting to add a date to certain column I have columns B-E where information will be entered and column A to add the date/timestamp for when all information in columns B-E has been entered. I have got it coded where if just column B is entered but am struggling to get it for when columns B-E are entered and not just column B.
I would also like the date and time format to be MM/DD/YYYY HH:MM:SS:AM/PM
Here is the code I have so far:
function onEdit(e) {

  var row = e.range.getRow();
  var col = e.range.getColumn();
  var targetColumn = 2;

  if(targetColumn  && row >1 && e.source.getActiveSheet().getName() === "HHAM"){
  e.source.getActiveSheet().getRange(row,1).setValue(new Date());
}
}

Here is the document: https://docs.google.com/spreadsheets/d/1KDywZKPUpbPImnnN-X9GeVLL_VUzu16vTwEGXwCHKQ0/edit?usp=sharing

A: You can use Regex to check if the edited cell belongs to columns B,C,D and E.
Try this:
function onEdit(e) {
  var row = e.range.getRow();
  var range = e.range.getA1Notation();
  if(range.match(/[B,C,D,E]\d/) && row > 1 && e.source.getActiveSheet().getName() === "HHAM"){
    var data = e.range.getValues();
    var filtered = data.filter(e => {
      return e[0] != ''
    });
    if(filtered.length == 0){
      e.source.getActiveSheet().getRange(row,1).setValue(""); // this will remove the date to any deletion happen to cells
    }else{
      e.source.getActiveSheet().getRange(row,1).setValue(new Date());
    }
  }
}

Sample Data:
Edit/Insert to a single cell:

Edit/Insert multiple data at once:

To change the format to MM/DD/YYYY HH:MM:SS:AM/PM:

*

*Highlight column A

*Click Format Tab -> Number -> More Formats -> Custom number format

*Paste this string: mm"/"dd"/"yyyy" "hh":"mm":"ss" "AM/PM
References:

*

*Regular Expression


text:
Q: Search values in string with separator The following code will search for val1. How to find val2?
x = "[val1][val2]"
section = x[x.find("[")+1:x.find("]")]
print(section)

>> val1

How find val2 ? eg. return to array section[0] and section[1]
edited.

A: How about this?
x = "[val1][val2]"
values = x[1:-1].split("][")
print(values)

*

*x[1:-1] removes the two [] characters on each end ("[val1][val2]" -> "val1][val2")

*.split("][") splits the string into a list of two ("val1][val2" -> ["val1", "val2"]

*print(values) print out the values!

Hope this helps explain this code!
NOTE: This works for any number of values (try "[val1][val2][val3]")!

A: Here is how you can use re to list all the strings that are between two square brackets, non-greedy:
import re
x = "[val1][val2]"
section = re.findall('(?<=\[).*?(?=\])',x)
print(section)

Output:
['val1', 'val2']

A: x = "[val1][val2]"

section = x.replace('[',' ').replace(']',' ').split()
print(section[0], section[1])

Prints:
val1 val2

A: You can do something like this:
def extract(inp):
    tmp=inp
    while len(tmp):
        start=tmp.find('[')
        end=tmp.find(']')
        if start==-1 or end==-1:
            break
        val=tmp[start+1:end]
        yield val
        tmp=tmp[end+1:]

x = "[val1][val2]"
for i in extract(x):
    print(i)


text:
Q: laravel queue not working from custom class Im use database for queue.
php artisan queue:work not runned.
If I add to queue from App\Models\Mail: ProcessMail::dispatch(['test' => 'test'); auto_increment value changed, but row does not exists in database, no errors in logs and no exception. If I try ProcessMail::dispatch(['test' => 'test'); in controller that's work fine: row creates to database.
This is code of ProcessMail:
<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Log;

class ProcessMail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $mailData;

    /**
     * Create a new job instance.
     *
     * @param [] $mailData
     * @return void
     */
    public function __construct($mailData)
    {
        $this->mailData = $mailData;
        Log::info('job constructor');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Log::info('job handle');
    }
}

Queue table structure:
CREATE TABLE `jobs` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `queue` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
  `attempts` tinyint(3) UNSIGNED NOT NULL,
  `reserved_at` int(10) UNSIGNED DEFAULT NULL,
  `available_at` int(10) UNSIGNED NOT NULL,
  `created_at` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

How can I fix this problem?

A: I found problem. I call ProcessMail::dispatch(['test' => 'test'); after DB::beginTransaction(); and because I debug - I run DB::rollback(); So created job removed from table. This is solely my fault. Perhaps someone will save time.


text:
Q: SQL Join tables based on Id in Stored Procedure I need to pull all the policies' cols for a claiment's ID with a JOIN stored Procedure.
pseudocode : select * from policies(tbl) where parties.id = policy.policyNumber.
Here's what I have so far...
CREATE PROCEDURE [dbo].[usp_GetPolicyForClaimentByPolicyIdNumber]
(
    @IdNumber varchar(255) = null
)
AS
BEGIN
SELECT *
    FROM [BinderCurrent].[Policy]
    LEFT JOIN [BinderCurrent].[Policy] ON ([BinderCurrent].[Parties].Id = [BinderCurrent].[PolicyRoles].PolicyId)
    WHERE   [BinderCurrent].[PolicyRoles].PolicyRoleTypeId = 40
    AND (@IdNumber IS NULL OR [BinderCurrent].[Parties].IdNumber LIKE ''+@IdNumber+'%')
    ORDER BY Id DESC

END

A: Filter with ON clause :
SELECT *
FROM [BinderCurrent].[Policy] LEFT JOIN
     [BinderCurrent].[Policy]
     ON ([BinderCurrent].[Parties].Id = [BinderCurrent].[PolicyRoles].PolicyId AND
         [BinderCurrent].[PolicyRoles].PolicyRoleTypeId = 40
WHERE (@IdNumber IS NULL OR [BinderCurrent].[Parties].IdNumber LIKE ''+@IdNumber+'%')
ORDER BY Id DESC;

Note : Table [BinderCurrent].[PolicyRoles] should also appeared with JOINs. This assumes that is part of your query.


text:
Q: TextMeshPro font doesn't change I'm using TMP in my project. I have downloaded font - Quanelas. I'm creating font prefab via Font Asset Creator. When I'm trying to switch my font it staying default.
It's how numbers, for example, look like:

But must be like:

I also noticed, that in SubMesh font still staying default:

I think that is thre reason, but I can't change font in SubMesh
Help and Sorry for my English :D


text:
Q: How do I connect multiple databases in rails I am trying to connect multiple databases in my rails app one as a primary and the other as a secondary. This is what I have in my database.yml
# SQLite version 3.x
# gem install sqlite3
#
# Ensure the SQLite 3 gem is defined in your Gemfile
# gem 'sqlite3'
#
# development:
# adapter: postgresql
# database: martin_development
# username:
# password:
# pool: 5
# timeout: 5000

development:
adapter: sqlserver
host:
port: 1433
database:
username:
password:

I left out some data for obvious reasons but the sqlserver is connected but I lost all my data from the postgresql database and I need it as well because it holds separate data for the blog and author logins et cetera. How would I accomplish this?


text:
Q: ElasticSearch cluster always auto-balancing I have an issue with ES auto balancing shards in my cluster:

*

*I've seen it moving shards from nodes with more free disk space to nodes with less free disk space

*It has been moving shards non-stop for days, which I thought was ok until I realized it was moving them across AZs (AWS availability zones, which means: that costs money)

*I checked our nodes and they looked already quite balanced: similar shard counts and similar free disk space.

Why is ES taking the decision of moving shards then?
Is there a way to look into why ES decides to balance a shard in a certain way?
Thanks.
Edit:
Some maybe-relevant configuration values we have set in our cluster:
Shard allocation settings
   cluster.routing.allocation.enable => all
   cluster.routing.allocation.node_concurrent_incoming_recoveries => 2
   cluster.routing.allocation.node_concurrent_outgoing_recoveries => 2
   cluster.routing.allocation.node_concurrent_recoveries => 8
   cluster.routing.allocation.node_initial_primaries_recoveries => 4
   cluster.routing.allocation.same_shard.host => false

Shard rebalancing settings
   cluster.routing.allocation.allow_rebalance => indices_all_active
   cluster.routing.allocation.cluster_concurrent_rebalance => 2

Shard balancing heuristics
   cluster.routing.allocation.balance.shard => 0.45
   cluster.routing.allocation.balance.index => 0.99f
   cluster.routing.allocation.balance.threshold => 1.0

BTW:

*

*I'm using ElasticSearch 6.8

*My data nodes already have cluster.routing.allocation.awareness.attributes' set to 'aws_availability_zone'

*I had posted two similar questions in ES' blog: "Discuss the Elastic Stack" as I didn't get answers there:

*

*ES cluster always auto-balancing.

*Cluster rebalancing across AZs

*There is a similar SO question here but it didn't get any answers. Also, the version they were using at the start of 2017 is likely different  from the one I'm using now.


text:
Q: AWS IoT + Cognito Connection Flow Based on the documentation, I understand how to create IoT things and also how to create authenticated users using AWS IoT. My question is geared towards how to effectively combine these services so that each user can access several of his or her devices securely.
Let's say Jane has just signed up for the platform and wants to connect her lightbulb device to her account. Let's also assume that her lightbulb device already has a certificate on it and a policy in IoT so that it can connect to the IoT platform and then publish and subscribe to a few topics. For the sake of simplicity, let's say that Jane can create this connection by simply making an API call named pairDevice  which takes in a cognito identity (i.e. 59700b18-94c7-XXXX-857a-d820a68c0ec6) and a device serial number.
Basically I envision this function doing two things:

*

*It will call "AttachPrincipalPolicy" that will link the policy associated with that lightbulb to the cognito user. Which I would assume at this point the cognito user would be able to publish and subscribe to topics for that particular lightbulb and only that lightbulb.

*It would add a DynamoDB entry in the users account of the thing ARN so that way it can be easily referenced and queried later.
So if my understanding is correct I would have a policy like this for each of my devices in IoT (should they also publish and subscribe to topics with the the serial number too? I want to make sure that users cannot connect to devices they aren't allowed to obviously):

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-west-1:123456789012:client/SerialNumber",
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish",
                "iot:Subscribe",
                "iot:Receive"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}

And then I would simply attach this policy using AttachPrincipalPolicy to the cognito user? Do I need to have an explicit policy in Amazon Cognito identity pool for IoT Access, or is that linkage done specifically through AttachPrincipalPolicy?

A: In order to authenticate an Amazon Cognito identity to publish MQTT messages over HTTP, you must specify two policies. The first policy must be attached to an Amazon Cognito identity pool role. This first policy is most likely the managed policy AWSIoTDataAccess.
The second policy must be attached to an Amazon Cognito user using the AWS IoT AttachPrincipalPolicy API.
An example application demonstrating this is:
https://github.com/awslabs/aws-iot-chat-example
For explicit instructions, you can read:
https://github.com/awslabs/aws-iot-chat-example/blob/master/docs/authentication.md


text:
Q: Puzzle: Recursive generator without loops/imports It is generators today. I saw a question today that wanted to find a way to flatten a list recursively without using loops and imports. tobias_k answered it with a following code:
def flatten(test_list):
    if isinstance(test_list, list):
        if len(test_list) == 0:
            return []
        first, rest = test_list[0], test_list[1:]
        return flatten(first) + flatten(rest)
    else:
        return [test_list]

Is there a way of creating a generator (with keeping the rules: no imports,loops)?
NOTE: it is purely educational. i know it is not the best idea, but coulnd't figure out how to do it.

A: In Python 3.3 (development version), you can use the yield from construct to avoid explicit loops:
def flatten(x):
    if isinstance(x, list):
        if x:
            first, rest = x[0], x[1:]
            yield from flatten(first)
            yield from flatten(rest)
    else:
        yield x

In current versions, I can't think of a solution that does not use itertools.chain.

A: A generator function is a function that contains at least one yield statement and no return statements that take an expression.  When a generator function is invoked it returns a generator iterator, which when iterated (e.g. by a for loop, or explicitly with next) runs through the body of the function, freezing its state and returning control to the caller on each yield statement (and in Python 3.3, yield from statements).
Flow control inside a Python function is always forwards; without hacks like setting the current frames f_lineno (as famously done by the (April Fool's) goto statement), the only way for control to reach an earlier point is to use a loop (for or while).  So without a loop or yield from, the maximum number of times a generator iterator can be invoked is bounded by the number of yield statements within the generator function.
Note that it's easy to write a flatten that returns an iterator; taking the original solution and writing return iter(flatten(first) + flatten(rest)) would do.  But that wouldn't be a generator iterator, and the function wouldn't be a generator function.
Here's an implementation that abuses f_lineno to give loopless iteration.  Unfortunately it has to use import sys:
def current_frame():
    i = None
    def gen():
        yield i.gi_frame.f_back
    i = gen()
    return next(i).f_back

class Loop(object):
    jump = False
    def __call__(self, frame, event, arg):
        if self.jump:
            frame.f_lineno = self.lineno
            self.jump = False
        return None if event == 'call' else self
    def __enter__(self):
        import sys
        sys.settrace(self)
        current_frame().f_back.f_trace = self
        self.lineno = current_frame().f_back.f_lineno
        return self
    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is None:
            self.jump = True
        else:
            import sys
            sys.settrace(None)
            current_frame().f_back.f_trace = None
            return exc_type is StopIteration

def flatten(x):
    if isinstance(x, list):
        if x:
            first, rest = flatten(x[0]), flatten(x[1:])
            with Loop():
                yield next(first)
            with Loop():
                yield next(rest)
            pass
    else:
        yield x

A: Done with a single line list comprehension:
def flatten (test_list):
    return [element for temp in test_list for element in flatten(temp)] if isinstance(test_list, list) else [test_list]

print(flatten([1, [2, 1, [3, 6, 7]], [1, 2, [3, 2, 3], 4, [1, 2, 3, 4, 5]]]))
#[1, 2, 1, 3, 6, 7, 1, 2, 3, 2, 3, 4, 1, 2, 3, 4, 5]


text:
Q: How do I run to the boat without losing the parrot? When I try to walk with the parrot to the boat on the right end of the island, the parrot always flees as soon I try to cross the water underneath the hermit's house.
How can I keep the parrot on my shoulder?

A: You may not jump in the water, but jump carefully down at the right side of the hermits home platform.


text:
Q: What's the evidence supporting 1 singular Big Bang?
Possible Duplicate:
What has been proved about the big bang, and what has not?

I love to dabble with science, I'm by no means a scolar in this field. One thing that haven't seen proven yet (maybe I missed it) is that there was only 1 singular Big Bang where it all started.
As I understand, when Hubble discovered that the universe was expanding, the conclusion was also that it was much smaller in the past. That I follow, but the theories seem to automatically agree on there being 1 Big Bang where everything started.
Couldn't there have been multiple points where matter etc 'flipped' into existence roughly around the same place and time? Is there any evidence for that? Does all the red shift for instance point to 1 spot?
Thanks for your time and knowledge in advance,
Gert-Jan

A: I've answered a series of related questions recently. Do a search of the site for "FLRW metric" to find relevant questions.
Anyhow, the idea of the Big Bang arose from a solution to the Einstein equations called the FLRW metric. If you assume that the universe is homogenous and isotropic (i.e. that it's basically the same everywhere) then you can solve the Einstein equation to give an equation that describes how the universe expands. This solution is called the FLRW metric, and it does seem to be a very good description of the universe as we see it today.
If you take the FLRW description of the universe and you wind time backwards, then as you approach 13.7 billion years ago the density becomes greater and greater and eventually becomes infinite. This point is known as the Big Bang. The Big Bang happens at the same time everywhere. Actually, at the moment of the Big Bang the FLRW metric predicts that the spacing between any two points falls to zero, but the universe remains infinite. This paradoxical situation is why most of think that some theory of quantum gravity will cut in before we reach the Big Bang.
So, to answer your question, the universe today seems to be well described by the FLRW metric, and the FLRW metric predicts that the Big Bang happened everywhere at the same time. To answer your specific question about the red shift, the red shift appears to be the same in all directions so this supports an isotropic universe and a single Big Bang everywhere.
It's possible that our interpretation of the experimental evidence might change as we learn more. For example you might like to have a look at this question, which discusses eternal inflation and the possibility that the Big Bang is different in different parts of the universe. At the moment there is no experimental evidence to support the idea of eternal inflation.

A: It is an explainable confusion when one thinks that the Big Bang happened at one point in space, to extend it to many points in space. But, the Big Bang happened in space time, i.e. in four dimensions, and that one singularity is at the (0,0,0,0) origin of all the space points in all the observable universe. The first  figure shows the balloon analogy, how all the points in a two dimensional surface recede from each other and all start at the origin.


text:
Q: Window.open retorna NULL u OBJECT en Internet Explorer 8 Tengo un sitio web en el cual en un menú creo un link con el objetivo de de abrir una pestaña nueva y mantener mi sitio en la pestaña actual, estoy realizando las pruebas en Internet Explorer 8.
Para realizar lo comentado utilizo el siguiente código:
Test

ERROR:
Cuando doy click en la opción del menú me abre exitosamente la pestaña, sin embargo mi pantalla principal se muestra en blanco y aparece un texto que dice NULL.
Leí que desactivando el Modo Protegido de internet ya no se mostraría el mensaje de NULL, y así fue, solo que ahora me muestra el texto [OBJECT].

NOTA: Tomar en cuenta que me conecto en una VPN para trabajar (no se si influye en esto).
SOLUCIÓN DESEADA:
Abrir una pestaña nueva con la ruta que configuré y conservar mi pantalla principal sin ningún cambio en la pantalla (que no se muestre NULL u OBJECT).
Espero puedan ayudarme, no comprendo aun a que se debe este inconveniente.
Gracias anticipadas.

A: Puedes hacer lo siguiente
link


text:
Q: What does "@" symbol mean in "import { Component } from '@angular/core';" statement? I'm reading Angular 2 "5 Min Quickstart" and there is such a line:
import { Component } from '@angular/core';"

I can't figure out, what does @ symbol make in that import? TypeScript docs also don't say anything about that.
What does it mean?

A: Also of relevance is that you can use the @ symbol scoping for non-npm packages as well. You can use this in your project as a short way of referring to different directories.
i.e.
import { MyService } from '@services/my.service';
import { HelloWorldComponent } from '@components/hello-world.component';

instead of
import { MyService } from '../../../../my.service';
import { HelloWorldComponent } from '../shared/deeply/nested/hello-world/hello-world.component';

To do this, you simply configure your tsconfig.json file (at root of project) like this:
{
  "compileOnSave": false,
  "compilerOptions": {

    // omitted...

    "baseUrl": "src",
    "paths": {
      "@services/*": ["app/path/to/services/*"],
      "@components/*": ["app/somewhere/deeply/nested/*"],
      "@environments/*": ["environments/*"]
    }
  }
}

See the full details at Angular Firebase

A: this is just a naming convention that Angular uses. Since the release they renamed it to @angular/core in stead of angular2/core.
It references the core components of the framework.
(found in post - angularjs 2 with angular-material @angular/core not found)

A: @scope_name/package_name
This is NPM feature, scoped name, anything between @ and slash / will be your scope name.
npm scope document


text:
Q: How to make OpenCV Detect method thread-safe? I invoke the following OpenCV method (Emgu CV wrapper), which detects faces, in several threads simultaneously:
IntPtr objects = CvInvoke.cvHaarDetectObjects(
                   img.Ptr,
                   haarObj.Ptr,
                   stor.Ptr,
                   scaleFactor,
                   minNeighbors,
                   flag,
                   minSize);

I get AccessViolationException. The standard .NET lock is unacceptable here since this method takes almost all a thread lifetime. Any ideas how to make this method work concurrently?

A: The solution is to use an internal multithreading in OpenCV. For that to work, OpenCV must be built with Intel TBB. Then when the Detect method is called, it uses multiple threads internally.


text:
Q: Chart is not defined, chart.js in javascript template I'm having some trouble getting charts to show up. I get the error "chart is not defined" although it seems to be defined when I hover over it in my javascript template. Here's my code:
javascript file
var myChart = new Chart("myChart", {
  type: "bar",
  data: {
    labels: ["Lag 1", "Lag 2"],
    data: [10, 5],
    backgroundColor: ["red", "green"]
  },
  options: {}
});

html file

<link href="{% static 'main/formwrapper.css' %}" rel="stylesheet" />

        <canvas id="myChart" style="width: 60%"></canvas>

    <button class="desktop1-buttondefault">
      Nästa runda
    </button>

the base html file which I extend, and where I have my links to javascript template and chart.js

I'm probably missing something simple, but I can't figure it out, thankful for some advice!
Update. Entire base.html where I link javascript
<!DOCTYPE html>

{% load static %}

    <title>Med Andra Ord</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta charset="utf-8" />
    <meta property="twitter:card" content="summary_large_image" />

    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap"
      data-tag="font"
    />
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Kalam:wght@300;400;700&display=swap"
      data-tag="font"
    />
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Outfit:wght@100;200;300;400;500;600;700;800;900&display=swap"
      data-tag="font"
    />
    <link rel="stylesheet" href="{% static 'main/style.css' %}" />

      <link href="{% static 'main/desktop1.css' %}" rel="stylesheet" />

            MED ANDRA
            ORD

  {% block content %}{% endblock %}

A: This should work.
<!DOCTYPE html>

{% load static %}

    <title>Med Andra Ord</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta charset="utf-8" />
    <meta property="twitter:card" content="summary_large_image" />

    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap"
      data-tag="font"
    />
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Kalam:wght@300;400;700&display=swap"
      data-tag="font"
    />
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Outfit:wght@100;200;300;400;500;600;700;800;900&display=swap"
      data-tag="font"
    />
    <link rel="stylesheet" href="{% static 'main/style.css' %}" />

      <link href="{% static 'main/desktop1.css' %}" rel="stylesheet" />

            MED ANDRA
            ORD

      <link href="{% static 'main/formwrapper.css' %}" rel="stylesheet" />

              <canvas id="myChart" style="width: 60%"></canvas>

          <button class="desktop1-buttondefault">
            Nästa runda
          </button>

  {% block content %}{% endblock %}


text:
Q: Wrong object rotation when I tilt my mobile in landscape orientation in Unity I'm trying to rotate an object with the same tilt as my mobile
I found this thread that is really helpful
http://answers.unity3d.com/questions/139294/match-the-tilted-angle-of-phone-to-object.html
But, when I put the device in landscape orientation and try to tilt the mobile between left and right, the object rotate in Z and Y axis
I would like to lock Y axis when the mobile is in horizontal, but not when it's in vertical
I put an image about I'm trying:

EDIT:
private var sizeFilter: int = 15;
private var filter: Vector3[];
private var filterSum = Vector3.zero;
private var posFilter: int = 0;
private var qSamples: int = 0;

function MovAverage(sample: Vector3): Vector3 {
    if (qSamples==0)
        filter = new Vector3[sizeFilter];

    filterSum += sample - filter[posFilter];
    filter[posFilter++] = sample;

    if (posFilter > qSamples)
        qSamples = posFilter;

    posFilter = posFilter % sizeFilter;
    return filterSum / qSamples;
}

function Update() {
    var temp: Vector3 = -MovAverage(Input.acceleration.normalized);
    temp.x *= -1;
    transform.up = temp.normalized;
}


text:
Q: How to add navigation controls to Web browser control in C# I am using the web browser control in C# project to load html pages.
I can navigate back / forward or refresh the page only after right clicking the web page.
How do I add these navigation controls to the web browser itself, so that user can navigate without right clicking.

A: You can add buttons on your form and wire up their click events to the appropriate actions you need.
//if wb is your WebBrowser instance
wb.GoBack();
wb.Refresh();
wb.GoForward();


text:
Q: Working with stdin So I have to implement a program that works with a text file (.txt), which has been put to stdin like that: ./program [argumets] <textfile.txt without using such functions as fopen, fscanf, malloc, etc. and I have no idea how to do that. I need to work with characters in that text file (print them to screen, print max/min value, print sum, etc.), NOT with the file itself, so, maybe anyone got a hint? Thank you.

A: Reading from text file like this as nearly identical to reading from keyboard. So much so that without doing some special tricks, your program has no way to know if input comes from keyboarad or from file.
When you do need to use a function which requires a file, there is stdin, which is so called "file pointer", and has type FILE*, same as returned by fopen.  File pointer is accepted by functions likes fscanf (but you can just call scanf then) and fgets (do NOT use gets, it's fatally broken, and finally removed from C11 standard).
If you need to use functions which take file descriptor, which is integer, and returned for example by open call, and accepted by functions like read, then the file descriptor number for standard input is 0, but you should usually use the STDIN_FILENO constant. And, do not mix reading from file descriptor (unbuffered), and reading from FILE* (buffered), because buffering will mess up the data you get. Using FILE* is probably better for most applications.
To make this more concrete, you can develop your program so, that instead of using < to redirect the input file, you can open the input file in editor, copy it to clipboard, run your application in a terminal, and paste input file as text to the terminal.


text:
Q: SSO Request.IsAuthenticated is always false after the first Login, however the first SSO login works fine Please forgive me if upfront if I missed something or made a mistake.  I think I've only had to post here a couple of times....
I have googled this situation for two days trying this and that and am no closer to having this solved.  Something in Chrome changed and it broke my app.   The scenario is I have an MVC 5 app that uses SSO.   The first login brings me to the microsoftonline login page, and I can login successfully - upon which I am brought to my application redirectURI page and Request.IsAuthenticated = true.   All is good.   However, if I either close the browser or use the Log Out link (which executes the Logout code below) and try to access my app again, I am brought to microsoftonline login page as expected, enter my password, but the 2nd time Request.IsAuthenticated = false and my app no longer works.  It expects that Request.IsAuthenticated will be true, and because it is false it redirects back to microsoftonline's login page again resulting in a constant loop.   I have found that I can restart the web site and it somehow resets the Request.IsAuthenticated so I can login again.
I have no more ideas how to fix this.   Any help is greatly appreciated.
Here is the SSOAuthConfig:  (it's basically a carbon copy of the Azure App Registration ASP.Net Quick Start example)
internal static class SSOAuthConfig2020
{

    // The Client ID is used by the application to uniquely identify itself to Azure AD.
    static string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];

    // RedirectUri is the URL where the user will be redirected to after they sign in.
   static string  redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];

    // Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
    static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];

    // Authority is the URL for authority, composed by Microsoft identity platform endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0)
    static string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);

    /// <summary>
    /// Configure OWIN to use OpenIdConnect
    /// </summary>
    /// <param name="app"></param>
    public static void Configuration(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        var cookieAuthenticationOptions = new CookieAuthenticationOptions()
        {
            CookieName = "MyFakeCookieName",
            ExpireTimeSpan = TimeSpan.FromDays(1),
            AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
            SlidingExpiration = true,
        };
        app.UseCookieAuthentication(cookieAuthenticationOptions);
        app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            // Sets the ClientId, authority, RedirectUri as obtained from web.config
            ClientId = clientId,
            Authority = authority,
            RedirectUri = redirectUri,
            // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
            PostLogoutRedirectUri = redirectUri,
            Scope = OpenIdConnectScope.OpenIdProfile,
            // ResponseType is set to request the id_token - which contains basic information about the signed-in user
            ResponseType = OpenIdConnectResponseType.IdToken,
            // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
            // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
            // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = true
            },
            // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = OnAuthenticationFailed,
                AuthorizationCodeReceived = async n =>
                {
                    n.AuthenticationTicket.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60);
                    n.AuthenticationTicket.Properties.IsPersistent = true;
                    n.AuthenticationTicket.Properties.AllowRefresh = true;
                    n.AuthenticationTicket.Properties.IssuedUtc = DateTimeOffset.UtcNow;
                }
            }
        }
    );
    }

Here is the Login logic:
  public void SignIn()
    {
        if (!Request.IsAuthenticated)
        {
            HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/Client" },
                OpenIdConnectAuthenticationDefaults.AuthenticationType);
        }
    }

Here is the Log Out:
    public void SignOut()
    {
        try
        {

            HttpContext.GetOwinContext().Authentication.SignOut(
                 OpenIdConnectAuthenticationDefaults.AuthenticationType,
                 CookieAuthenticationDefaults.AuthenticationType);

        }
        catch (Exception ex)
        {

        }

    }

A: I found the answer to my own question several months after asking it.   I posted the answer to help this person and am just linking to it to avoid duplication:
Getting NULL Identity while authenticating user via Azure AD authentication


text:
Q: C++ LibVLC dos it work? I would like to use LibVLC in C++, but looking in the documentation I saw that a version named LibVLCpp existed.
Only impossible to find it. Does LibVLC work in C++ ?

A:
Does LibVLC work in C++ ?

Yes, you can use it like any other c-API in c++.


text:
Q: Rest api call fails in POST API call Hi I have newly created a microservice post API call with STS4 which was build and deployed successfully. the localhost:8080/demo/ link is opening up. but the rest maping underneath it failing with 404 not found. I haved added requestmapping and post mapping and tried still not working. Can anyone fix the code?
PFB the code:-
POM:-
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <maven.test.skip> true</maven.test.skip>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

here is the config for swagger :-
package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
//Enable Swagger
@EnableSwagger2
public class SwaggerConfig {

  @Bean
  public Docket api() {
     //creating constructor of Docket class that accepts parameter DocumentationType
     return new Docket(DocumentationType.SWAGGER_2);
  }
}

here is the rest controller:
package com.example.demo.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.MyResponse;
import com.example.demo.service.dao.DemoServiceDAO;
import com.example.demo.service.impl.DemoServiceImpl;

@RestController
@Validated
@RequestMapping(value ="/newcall", method = RequestMethod.POST)
public class DemoController {
  Logger logger =LoggerFactory.getLogger(DemoController.class);

  @PostMapping(value ="/newResp", headers ="Accept=Application/JSON", produces="Application/JSON")
  public MyResponse newResp(@RequestBody String myInput) {
    MyResponse myResponse = null;
    try {
      DemoServiceDAO demoServiceDAO = new DemoServiceImpl();
      logger.debug("Started getValue() method...");
      myResponse=demoServiceDAO.getValue(myInput);
      logger.debug("Completed getValue() method...");

    }
    catch(Exception e){
      logger.debug("Exception occurs",e);
      e.printStackTrace();
      System.out.println("Exception occurs");
    }
    return myResponse;
  }
}

here is the application:-
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@ComponentScan(basePackages = "com.example.*")
@EnableSwagger2
public class DemoApplication extends SpringBootServletInitializer {

  public static void main(String[] args) {
    Logger logger =LoggerFactory.getLogger(DemoApplication.class);
    SpringApplication.run(DemoApplication.class, args);
  }
}

here is the app.properties:-
    logging.file.name=opt/var/logs/demoService.log
    logging.file.path=opt/var/logs
    logging.level.web=DEBUG
    spring.jmx.default-domain=demo
    server.servlet.context-path=/demo
    management.endpoints.web.exposure.include=*
    management.endpoint.health.show-details=always

    springfox.documentation.swagger-ui.base-url=true
    management.endpoint.info.enabled: true
    springfox.documentation.swagger-ui.enabled=true
    springfox.documentation.open-api.enabled=true
    spring.security.user.name = user
    spring.security.user.password = password

Output from http://localhost:8080/demo/
     "_links" : {
       "profile" : {
          "href" : "http://localhost:8080/demo/profile"
        }
     }

full code is in github with logs:-
https://github.com/Sourav654/tempProject/tree/master/demo

A: Without any logs we can only guess, but looking at your Controller I see some weird things. Can you please try the following?
@RestController
@Validated
@RequestMapping("newcall")
public class DemoController {
  Logger logger =LoggerFactory.getLogger(DemoController.class);

  @PostMapping("/newResp", consumes = "application/json", produces = application/json)
  public MyResponse newResp(@RequestBody String myInput) {
    MyResponse myResponse = null;
    try {
      DemoServiceDAO demoServiceDAO = new DemoServiceImpl();
      logger.debug("Started getValue() method...");
      myResponse=demoServiceDAO.getValue(myInput);
      logger.debug("Completed getValue() method...");

    }
    catch(Exception e){
      logger.debug("Exception occurs",e);
      e.printStackTrace();
      System.out.println("Exception occurs");
    }
    return myResponse;
  }
}


text:
Q: NSView - mouseEntered not called when view created Is there a way to check that the mouse is in the view?

A: Your question is a little unclear but I think you want to detect the position of the mouse when your custom view becomes visible and update it if the mouse position is within the view's bounds.
If so, you need to do something like this:
- (void)viewDidMoveToWindow
{
    if(![self window])
        return;

    NSPoint mouseLocation = [[self window] mouseLocationOutsideOfEventStream];

    if(NSPointInRect(mouseLocation, [self frame]))
    {
        NSLog(@"mouse is over the view");
    }
    else
    {
        NSLog(@"mouse is not over the view");
    }

}


text:
Q: Browser's default CSS hides flash objects? I have an embedded flash object in a Drupal-block, something like this:
<object classid="xxxxxx" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" height="320" width="160"><param name="quality" value="high" /><param name="movie" value="/sites/default/files/flash/xxxxxxx.swf" /><embed height="320" pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" src="/sites/default/files/flash/xxxxxxx.swf" type="application/x-shockwave-flash" width="160"></embed></object>

A few days ago it disappeared misteriously. After some browsing in Firebug, I found out that it's nost likely caused by the following CSS-declaration:
img:-moz-suppressed, input:-moz-suppressed, object:-moz-suppressed, embed:-moz-suppressed, applet:-moz-suppressed {
    display: none !important;
    visibility: hidden !important;
}

It's coming from (as far as I understand) the default css of Firefox. I tried to set the "object" and "embed" tags visible but this declaration always override it.
My questions are: Why is this default CSS-declaration come into effect now? It's not the first flash object I have embedded and they were visible so far. And how can I override it?
Thanks in advance!