text:
Q: PureMVC Mediators and views - creation and control I'm making an app with flash AS3 and puremvc, the way to correctly handle view mediators is sort of throwing me a little...
OK - I have 3 or 4 distinct views, each governed by it's own mediator.
Each view is only displayed on its own - ie. when 1 is visible/on stage - the others are invisible/removed from stage (over simplified, but I guess could be thought of as seperate pages, viewed one at a time, a nav bar allows a user to change views when they like)
At first each view mediator I had creating and added to stage it's own view component, and as such, when it was 'turn' to show or hide that view, it was simple - addChild and removeChild for it's view component.
However, I read over at puremvc.org that it's not good practice to
a. pass round the stage (which was the viewComponent for each mediator in my case - where each view was added to - eg. viewComponent.addChild(foo)
b. create its own view - which allowed me to add and remove it in the first place.
So I changed to the recommended way - when I create each mediator, what I pass in is the view component it governs (rather than the stage/main doc class)
eg.
var view:MyView = new MyView();
facade.registerMediator( new MyViewMediator( view ) );
viewComponent.addChild(view);

So - with that the case - I have no idea how I would go about removing/adding each view when needed.
I could easily enough set the visibility from within each mediator, but I sort of wanted to avoid doing that - prefer removing when not in use for resource management...
Anyone got any good ideas either how I am 'meant' to go about this (as in, when a view is no longer needed on stage, remove it - temporarily, and add it later on when it is needed?) - or am I missing some point (quite likely!) and going about this the wrong way? I'm very new to puremvc so not too confident I am approaching it right. Pointers most welcome!

A: I won't pretend to be an expert in PureMVC, but the way I like to work is to only create a Mediator for major areas of the site. For example, a HeaderMediator, FooterMediator and ViewMediator. Then, I have an ApplicationMediator that "onRegister" will create the other mediators just mentioned. This way, I'm not creating a mediator for each individual view and the "ViewMediator" handles switching between views. Here is what my "onRegister" function would look like:
override public function onRegister():void {
    var viewContainer:Sprite = viewComponent.addChild(new Sprite()) as Sprite;
    facade.registerMediator(new ViewMediator(viewContainer));

    var headerContainer:Sprite = viewComponent.addChild(new Sprite()) as Sprite;
    facade.registerMediator(new HeaderMediator(headerContainer));

    var footerContainer:Sprite = viewComponent.addChild(new Sprite()) as Sprite;
    facade.registerMediator(new FooterMediator(footerContainer));
}

Next, I'll have a ViewProxy that has a pool of views sitting and waiting to be called up (in an Array, Dictionary or Vector). When it's time to change or set a view, I use a ChangeViewCommand that retrieves the view from the ViewProxy and sends a notification (like SET_VIEW) with the view object as the body.
Now, the ViewMediator will handle the notification "SET_VIEW". If it's something as simple as removeChild(oldView) and addChild(newView) then I will just handle it in the Mediator itself. If a transition is necessary and involves more code, then I'll use a command to handle the transition.
Hope that makes sense and helps. Of course, I like to change things up and try new things, so if you have any concerns or suggestions I'm open to hearing them.

A: May I ask your motivation for using PureMVC ? I don't want to start a holy war here, but one of the reasons behind the creation of the second generation frameworks  (Mate,Swiz,Robotlegs,Parsely) was because of the absurd amount of difficulty in getting started with RIA application architecture.
Don't feel bad though, the newer frameworks have documentation, so it is easy to understand and figure out the motivation for all of the components, paradigms and actors that come into play.

A: As FlexFiend mentioned, this situation is easier to take care of in second generation frameworks (at least it is in Robotlegs, I can't speak for the others).  This is because, usually, you never explicitly create or destroy a mediator in Robotlegs; instead, you associate a mediator with a view component and Robotlegs constantly watches the stage for view components being added and removed and creates and destroys instances of the appropriate mediators.
Therefore one approach for implementing this kind of thing in PureMVC is to have a StageMediator with the stage itself as its view component, and listen for Event.ADDED_TO_STAGE and Event.REMOVED_FROM_STAGE events.  Finally you will need a system to associate view components with mediators.  Check out https://github.com/robotlegs/robotlegs-framework/blob/master/src/org/robotlegs/base/MediatorMap.as to see how its done in Robotlegs.
I am actually about to implement something like this since I am working on a project which is part of a suite of PureMVC applications, but honestly unless you have no choice I would say the easiest thing to do is simply to use Robotlegs!


text:
Q: How to add new sysadmin account when no sysadmin accounts exist During testing I deselected the sysadmin rights for my login and now can't re-add it (because I don't have sysadmin rights).
There are no other sysadmin accounts for the instance except the [sa] account.
I was set up for just Windows Authentication so I hacked the LoginMode in the registry to 2 so I could login as sa using SQL Authentication. This does indeed set the login mode to Mixed, however the sa user is disabled by default and I can't re-enable it because I don't have sysadmin rights.
How do I enable the sa login so I can get in and reassign the sysadmin to my normal account?  Is there a registry setting for this too or is it stored in the master database?

A: This is a great question and someone will be in this situation and needs a rescue out of it ..
All the credit goes to codykonior

If you're a Windows Administrator on the server then you can use a PowerShell v2 script to obtain access with no outage and no known risk. It does this by duplicating the login token of the SQL Server service even if it's running under an AD service account, virtual account, or protected with a per-service SID

Below script will iterate the SQL Server services and will add you to the sysadmin role wherever you're missing :
#GITHUB Link : https://github.com/codykonior/HackSql
$userName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name

$services = Get-Service | Where { ($_.Name -eq 'MSSQLSERVER' -or $_.Name -like 'MSSQL$*') -and $_.Status -eq "Running" }
foreach ($service in $services) {
    if ($service.Name -eq "MSSQLSERVER") {
        $sqlName = ".\"
    } else {
        $sqlName = ".\$($service.Name.Substring(6))"
    }

    Write-Host "Attempting $sqlName"
    $serviceProcess = Get-WmiObject -Class Win32_Service -Filter "Name = '$($service.Name)'"

    Invoke-TokenManipulation -ProcessId $serviceProcess.ProcessID -ImpersonateUser | Out-Null
    $impersonatedUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
    Write-Host "Service $($service.Name) on PID $($serviceProcess.ProcessID) will connect to $sqlName as $impersonatedUser"

    $sqlConnection = New-Object System.Data.SqlClient.SqlConnection("Data Source=$sqlName;Trusted_Connection=True")
    $sqlConnection.Open()
    $sqlCommand = New-Object System.Data.SqlClient.SqlCommand("If Not Exists (Select Top 1 0 From sys.server_principals Where name = '$userName')
Begin
    Create Login [$userName] From Windows
End

If Not Exists (Select Top 1 0 From master.sys.server_principals sp Join master.sys.server_role_members srp On sp.principal_id = srp.member_principal_id Join master.sys.server_principals spr On srp.role_principal_id = spr.principal_id Where sp.name = '$userName' And spr.name = 'sysadmin')
Begin
    Exec sp_addsrvrolemember '$userName', 'sysadmin'
End", $sqlConnection)
    $sqlCommand.ExecuteNonQuery() | Out-Null
    $sqlConnection.Close()
    Invoke-TokenManipulation -RevToSelf | Out-Null
}

A: You can still create a login with 'sysadmin' access.Thanks to Principal Data Engineer at Microsoft (Saleem Hakani) had authored the below SQL Server Tips & Trick .
I found this while I was stuck in similar state when I forgot the sa password for my test machine.
Link : https://blogs.technet.microsoft.com/sqlman/2011/06/14/tips-tricks-you-have-lost-access-to-sql-server-now-what/
Here are the steps you will need to perform:

*

*Start the SQL Server instance using single user mode (or minimal configuration which will also put SQL Server in single user mode)

From the command prompt type: SQLServr.Exe –m (or SQLServr.exe –f)
Note: If the Binn folder is not in your environmental path, you'll need to navigate to the Binn folder.
(Usually the Binn folder is located at: C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Binn)

*Once SQL Server service has been started in single user mode or with minimal configuration, you can now use the SQLCMD command from command prompt to connect to SQL Server and perform the following operations to add yourself back as an Admin on SQL Server instance.

SQLCMD –S
You will now be logged in to SQL Server as an Admin.

*Once you are logged into the SQL Server using SQLCMD, issue the following commands to create a new account or add an existing login to SYSADMIN server role.

To create a new login and add that login to SYSADMIN server role:
1> CREATE LOGIN '' with PASSWORD=''
2> go
1> SP_ADDSRVROLEMEMBER '','SYSADMIN'
2>go
To add an existing login to SYSADMIN server role, execute the following:
1> SP_ADDSRVROLEMEMBER '','SYSADMIN'
The above operation will take care of granting SYSADMIN privileges to an existing login or to a new login.

*Once the above steps are successfully performed, the next step is to stop and start SQL Server services using regular startup options. (This time you will not need –f or –m)

A: An actual backdoor into SQL Server does exist that does not require restarting and/or rebooting anything into single-user mode. I have done this on systems where I did not have access but needed to check stuff.
Download PSexec tools from here. Place this on the server and then in a command prompt execute this command:psexec -i -s SSMS.exe, or sqlwb.exe

This will open up SSMS as the system account that has sysadmin access to the instance of SQL Server. This is done during installation of SQL Server, however I have heard that this will not be so with SQL 2012.

A: SQL Server 2008 and newer do not automatically add the local administrators Windows Group into the sysadmin fixed server role.
When SQL Server 2008 is installed, it prompts you to designate an account to be added to the sysadmin role.  If you receive the box after the software is installed, however, this doesn't help you very much.
Fortunately, Microsoft preserved the 2005 functionality when SQL Server is running in single user mode.  Here's what you do:

*

*log into the server as windows local admin

*stop sql server

*at the command prompt, in the directory where sqlservr.exe resides, type sqlservr.exe -m, and press enter - this will start SQL Server in single-user mode

*open up SQL Server Enterprise Manager, and add your account to sysadmin fixed server role

*stop sql server, restart (at command line or in SQL Server Enterprise Manager)

A: The details presented in this answer are correct - however other answers do provide workarounds that exist to allow SQL Server to be started in a special mode that allows the server administrator to access SQL Server as a member of the sysadmin role.

Even the most uber-admin type of connection option Dedicated Administrator Connection (DAC), which can only be used as a local connection, and lets you undo all kinds of evil, still requires login credentials. So I don't think there's an official way to do this.
The quickest way to resurrect this system may be to shut down SQL Server, copy the user database files somewhere safe, uninstall, reinstall (making sure to service pack up to at least the level you were previously at), copy the files back and attach the databases. (Not sure the copying out/back is required, but just to be safe...).
You'll still need to manually recover server level objects (e.g. logins)

A: You can do the next:
1) Create a windows user account with administrative privileges
2) Login in windows with the new administrative account
3) Open the Sql Server Mangement Studio using Windows Authentication
4) Now you are logged in SQL Server as sysadmin, so you can create new accounts or update the sa user

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring integration inbound-channel-adapter triggered at post construct? Suppose I have this class:
public class MyClass {
    public String myMethod() {
         //...
    }
}

What I want is when my application starts, to send the result that myMethod() returns to a certain channel in Spring Integration. What I have tried:
<bean id="myClass" class="myPackage.MyClass"/>

<int:inbound-channel-adapter channel="channelINeedToSendTo" ref="myClass" method="myMethod">
    <int:poller cron=""/>  <!-- poller configuration -->
</int:inbound-channel-adapter>

Now what can I configure in poller is to call myMethod() at a certain time, on regularly on a certain scheduling, but I wanted to be run exactly after the application started (something like @PostConstruct). Is there a simple way achieving this, without complicated AOP techniques?

A: You can add an Event Inbound Channel Adapter to capture the ContextRefreshedEvent Application Event; then wire that adapter to a <service-activator/> that invokes myMethod(); the result will be on the output-channel.


text:
Q: Agregar usuarios a un proyecto Git tengo el siguiente problema.. en un servidor tengo un proyecto y esta en un repositorio de Bitbucket.
Si hago git shortlog -sn
Me lista:
36  root
 4  Mi User

Necesito agregar otro usuario autorizado desde Bitbucker para que hagas commits y push

A: Debes de dirigirte a Settings -> User and group access -> Users y agrega el usuario por su correo. Recuerda que el usuario debe de estar registrado en bitbucket para que te aparezca en la lista.
Aqui una imagen para que te puedas guiar:

Tambien comprueba que la url del repositorio no contenga tu usuario. Ejecuta el siguiente comando:
git remote -v

Si en la url aparece tu usuario entonces tienes que editar y cambiarlo por el usuario que va utilizar el repositorio. Eso se hace con el siguiente comando:
git remote set-url origin  https://<nombre_de_tu_cuenta>@bitbucket.org/<la_nueva_cuenta>/<nombre_repositorio>

A: puedes cambiar de usuario
abre git bash y configura el email y el name de tu otro usuario
git config --global user.email "jp@gmail.com"

git config --global user.name 'JuanPerez'

y puedes verificar el usuario con el que estas con
git config --list


text:
Q: How to remove a substring from a string according to data inside I have this string:
 row =   <line>111222<c>333</c></line><line>444<c>555</c></line>

If  has no value I need all the line to be deleted from my string in this case:
  <line>444<c>555</c></line>

Should I split my row to an array and check each line than concat it to a new string without the lines that hold an empty b ?
Is there an easy/ smart way?

A: Using re.sub we can try:
row = '<line>111222<c>333</c></line><line>444<c>555</c></line>'
output = re.sub(r'<line>(?:(?!<line>).)*.*?</line>', '', row)
print(output)  # <line>111222<c>333</c></line>

The (?:(?!<line>).) term in the regex used above will match content without crossing over the ending tag </line>, and is often referred to as "tempered dot."  The idea is that we want to match an empty  tag within <line>.
Note that for a more general solution consider using an XML parser.  Regex happens to work here assuming that all tags below <line> are single level and not nested deeply.


text:
Q: Oracle, how to insert LONG RAW (a hex string is much longer than 32767) into BLOB in a query for the hex strings <= 32767 I do:
DECLARE buf RAW(32767);
BEGIN
buf := hextoraw('3082560E3082488E1B02....');
INSERT INTO FINGERPRINT VALUES ('bff17a2c-49b7-4d6c-9c4e-56cb1d35c8c8', '00003', 2, buf, NULL);
END;

How to do the same way but if a string is longer than 32767? I tried to use LONG RAW instead of RAW(32767) but getting an error:
Error report -
ORA-06502: PL/SQL: numeric or value error
ORA-06512: at line 1
06502. 00000 -  "PL/SQL: numeric or value error%s"
*Cause:    An arithmetic, numeric, string, conversion, or constraint error
           occurred. For example, this error occurs if an attempt is made to
           assign the value NULL to a variable declared NOT NULL, or if an
           attempt is made to assign an integer larger than 99 to a variable
           declared NUMBER(2).
*Action:   Change the data, how it is manipulated, or how it is declared so
           that values do not violate constraints.

A: Citing asktom:

In Oracle8i, releases 8.0 and up, you should not be using LONG RAW. Both LONG and LONG RAW are only provided for backwards compatibility -- they are deprecated datatypes.
You should be using blob

If it still produces error try working with:

*

*dbms_lob.createtemporary

and then

*

*dbms_lob.append


text:
Q: Using expand.grid function with n elements I need to generate all the combinations of 1:n repeated n times. Example with n = 4:
expand.grid(1:4, 1:4, 1:4, 1:4)

This method, however, will require a lot of typing when n is a larger number. Is there an efficient way to do this? I Tried paste and couldn't make it work.

A: We can replicate into a list and apply the expand.grid
n <- 4
expand.grid(rep(list(seq_len(n)), n))

Or use replicate
expand.grid(replicate(n, seq_len(n), simplify = FALSE))

A: First off, you are looking for permutations with repetition, not combinations. Secondly, there are several packages for obtaining this efficiently in R. There is the classical package gtools and there are the two highly efficient compiled libraries arrangements and RcppAlgos (I am the author):
## library(gtools)
gtools::permutations(4, 4, repeats.allowed = TRUE)

## library(arrangements)
arrangements::permutations(4, 4, replace = TRUE)

## library(RcppAlgos)
RcppAlgos::permuteGeneral(4, 4, TRUE)


text:
Q: What is the difference between these two pools in Uniswap? I found the strange pools in Uniswap (for me).
They appear to be liquidity pools for each of the same currencies.
I have two questions there.
(1) I thought there was one currency pair liquidity, but is there more than one?
(2) If first question is Yes,When swapped from the UI,Is it random which liquidity pool is used?
【Uniswap V3: USDC 2】0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8
【Uniswap V3: USDC 3】0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640
Thanks.

A: The pools have different fee tiers, the first one has 0.05% fee, the other one: 0.3% fee.
It is not possible to control which pool is used when swapping from the UI, but it's not random. The pool or the combinations of pools that are most profitable for the swap will be used.


text:
Q: Factoring $x^{15}−1$ into irreducible polynomials over $\mathrm{GF}(2)$
Factorize $x^{15}−1$ into irreducible polynomials over $\mathrm{GF}(2)$

The answer is
$$(x+1)(x^2+x+1)(x^4+x+1)(x^4+x^3+1)(x^4+x^3+x^2+x+1)$$
but how would I find this? Please help.

A: The polynomial $x^{16}-x\in\mathbb{F}_2[x]$ has roots precisely equal to the elements of $\mathbb{F}_{16}$, and the subfields of $\mathbb{F}_{16}$ are $\mathbb{F}_{16}$, $\mathbb{F}_{4}$, and $\mathbb{F}_{2}$, which have degrees
$$[\mathbb{F}_{16}:\mathbb{F}_2]=4\qquad [\mathbb{F}_{4}:\mathbb{F}_2]=2\qquad [\mathbb{F}_{2}:\mathbb{F}_2]=1$$
Therefore $x^{16}-x$ is the product of the irreducible polynomials in $\mathbb{F}_2[x]$ of degrees $1$, $2$, and $4$.
Therefore $x^{15}-1$ is the product of the irreducible polynomials in $\mathbb{F}_2[x]$ of degrees $1$, $2$, and $4$, other than the irreducible polynomial $x$.
To find these irreducible polynomials, you can use Sieve of Eratosthenes (Wikipedia link), adapted to the ring $\mathbb{F}_2[x]$.


text:
Q: Cluster Bootstrap Mixed Model Contrasts So I regularly make use of lme4 and lmerTest to fit Linear Mixed Models. I then do the post ANOVA contrasts via the emmeans (Estimated Marginal Means) package.
However, I understand that for Generalized Linear Mixed Models, the ANOVA (or analysis of deviance) table does not provide any p-values at all. Is it still valid to perform the contrasts without this?
One method I read about is Cluster Bootstrapping the GLMM. I found a nice package called ClusterBoot which seems to perform the cluster bootstrap. It was released recently: https://link.springer.com/article/10.3758/s13428-019-01252-y
I am able to get bootstrap coefficients, SEs, and percentile/parametric intervals for all the coefficients with this. However, this is difficult to interpret since I don't know how to use all of this to get ANOVA contrasts for my pairwise comparisons from this. Emmeans interfaces nicely with lme4 and provides this but can't be used with this.
How would I go about getting contrasts knowing just the Bootstrap Coefficients/SEs? Along with corresponding p-values.


text:
Q: Creating key-value pairs with js reduce() and creating an array as the value I am having a problem with javascript's reduce() function; I have to put arrays as the value. I can sucessfully create an array but can't add new values to it.
There's an array with words and I have to create a 'map' whose keys are the first letters of the words and the values are the words which start with the said letter.
arr = ["Here", "is", "a", "sentence", "with", "a", "lot", "of", "words"];
The expected output should be this:
{ h: [ "here" ],
  i: [ "is" ],
  a: [ "a", "a" ],
  s: [ "sentence", ],
  w: [ "with", "words" ],
  l: [ "lot" ],
  o: [ "of" ]
}

This is my solution to the problem but it overwrites existing values.
function my_func (param)
{
   return param.reduce ( (returnObj, arr) => {
    returnObj[arr.charAt(0)] = new Array(push(arr));
    return returnObj;
  } , {})

}

I tried this but it didn't work because it couldn't deduce the type for valueOf() and it yielded an error.

function my_func (param)
{
   return param.reduce ( (returnObj, arr) => {
    returnObj[arr.charAt(0)] = (new Array(returnObj[arr.charAt(0)].valueOf().push(arr)));
    return returnObj;
  } , {})

}

A: You are overwriting the accumulator object's property every time. Instead, check if an item with the character has already been added using the || operator and create a new array if it doesn't exist yet.

let array = ["Here", "is", "a", "sentence", "with", "a", "lot", "of", "words"]

function my_func(param) {
  return param.reduce((acc, str) => {
    let char = str.charAt(0).toLowerCase();
    acc[char] = acc[char] || [];
    acc[char].push(str.toLowerCase());
    return acc;
  }, {})
}

console.log(my_func(array))

A: Check out my solution below. Hope this helps!

const arr = ["Here", "is", "a", "sentence", "with", "a", "lot", "of", "words"];

const getWordsDict = (array) => array.reduce(
  (acc, word) => {
    const lowerCasedWord = word.toLowerCase()
    const wordIndex = lowerCasedWord.charAt(0)

    return {
      ...acc,
      [wordIndex]: [
        ...(acc[wordIndex] || []),
        lowerCasedWord,
      ],
    }
  },
  {}
)

console.log( getWordsDict(arr) )

A:

var result = ["Here", "is", "a", "sentence", "with", "a", "lot", "of", "words"].reduce(function(map, value) {

  var groupKey = value.charAt(0).toLowerCase();
  var newValue = value.toLowerCase();

  return map[groupKey] = map.hasOwnProperty(groupKey) ? map[groupKey].concat(newValue) : [newValue], map;
}, {});

console.log( result );

A: param.reduce((acc, el) => {
  const key = el[0] // use `el[0].toLowerCase()` for case-insensitive
  if (acc.hasOwnProperty(key)) acc[key].push(el)
  else acc[key] = [el]
  return acc
}, {})


text:
Q: Where can i find sample alogrithms for analyzing historical stock prices? Can anyone direct me in the right direction?
Basically, I'm trying to analyze stock prices and see if I can spot any patterns. I'm using PHP and MySQL to do this. Where can I find sample algorithms like the ones used in MetaStock or thinkorswim? I know they are closed source, but are there any tutorials available for beginners?
Thank you,
P.S. I don't even know what to search for in google :(

A: First you will need a solid math background : statistics in general, correlation analysis, linear algebra... If you really want to push it check out dimensional transposition.  Then you will need solid basis in Data Mining.  Associations can be useful if yo want to link strict numerical data with news headlines and other events.
One thing for sure you will most likely not find pre-digested algorithms out there that will make you rich...
I know someone who is trying just that...  He is somewhat successful (meaning is is not loosing money and is making a bit)  and making his own algorithms...   I should mention he has a doctorate in Actuarial science.
Here are a few more links... hope they help out a bit

*

*http://mathworld.wolfram.com/ActuarialScience.html

*http://www.actuary.com/actuarial-science/

*http://www.actuary.ca/
Best of luck to you

A: Check out algorithms at investopedia and FM Labs has formulas for a lot of technical analysis indicators.

A: Save yourself time and use programs like NinjaTrader and Wealth-Lab. Both of them are great technical analysis platforms and accept C# as a programming language for defining your trading rules. Every possible technical indicator you can imagine is already included and if you need something more advanced you can always write your own indicator. You would also need a lot of data in order for your analysis to be statistically significant. For US stocks and ETFs, visit www.Kibot.com. We have good experience using their data.

A: Here's a pattern for ya
http://ddshankar.files.wordpress.com/2008/02/image001.jpg

A: A basic, educational algorithm to start with is a dual-crossover moving average. Simply chart fast (say, 5-day) and slow (say, 10-day) moving averages of a stock's closing price, and you have a weak predictor of when to buy long (fast line goes above slow) and sell short (slow line goes above the fast). After getting this working, you could implement exponential smoothing (see previously linked wiki article).
That would be a decent start. Take a look at other technical analysis techniques, but do keep in mind that this is quite a perilous method of trading.
Update: As for actually implementing this? You're a PHP programmer, so here is a charting library for PHP. This is the one I used a few years ago for this very project, and it worked out swimmingly. Maybe someone else can recommend a better one. If you need a free source of data, take a look at Yahoo! Finance's historical data. They dispense CSV files containing daily opening prices, closing prices, trading volume, etc. of virtually every indexed corporation.

A: I'd start with a good introduction to time series analysis and go from there. If you're interested in finding patterns then the interesting term is "1D-Pattern Matching". But for that you need nice features, so google for "Feature extraction in time series". Remember GiGo. So make sure you have error-free stock price data for a sufficiently long timeperiod before you start.

A: May I suggest that you do a little reading with respect to the Kalman filter?  Wikipedia is a pretty good place to start:
    http://en.wikipedia.org/wiki/Kalman_filter/
This should give you a little background on the problem of estimating and predicting the variables of some system (the stock market in this case).
But the stock market is not very well behaved so you may want to familiarize yourself with non linear extensions to the KF.  Yes, the wikipedia entry has sections on the extended KF and the unscented KF, but here is an introduction that is just a little more in-depth:
    http://cslu.cse.ogi.edu/nsel/ukf/
I suppose if anyone had ever tried this before then it would have been all over the news and very well known.  So you may very well be on to something.

A: Use TradeStation
It is a platform that lets you write software to analyze historical stock data. You can even write programs that would trade the stock, and you can back test your program on historical data or run it real time through out the day.


text:
Q: How to get content of span tag in div child? I have this:

     0.00286414
     0.0029

-4.95%

How to export innerHTML of class __bolder label-range-fall of parent class real-time-data dark to console.log?

A: You can use querySelector() function.

const element = document.querySelector(".real-time-data span.label-range-fall");
console.log(element.innerHTML);

     0.00286414
     0.0029

-4.95%

A: var element = document.querySelector(".real-time-data>.label-range-fall");
console.log(element.innerHTML);


text:
Q: android - Renderscript to convert NV12 yuv to RGB I write below code to convert NV12 yuv to RGB but the color is not correct.
yuv2rgb.rs
#pragma version(1)
#pragma rs java_package_name(com.example.myexam)
#pragma rs_fp_relaxed

rs_allocation gYUV;
uint32_t gW;
uint32_t gH;

uchar4 __attribute__((kernel)) YUV2RGB(uint32_t x,uint32_t y)
{
    uchar yps = rsGetElementAt_uchar(gYUV, x, y);
    uchar u = rsGetElementAt_uchar(gYUV,(x & ~1),gH + (y>>1));
    uchar v = rsGetElementAt_uchar(gYUV,(x & ~1)+1,gH + (y>>1));
    uchar4 rgb = rsYuvToRGBA_uchar4(yps, u, v);
    return rgb;
}

java code:
public Bitmap NV12_toRGB(byte[] yuv,int W,int H) {
    RenderScript rs = RenderScript.create(this);
    Type.Builder yuvBlder = new Type.Builder(rs, Element.U8(rs))
            .setX(W).setY(H*3/2);
    Allocation allocIn = Allocation.createTyped(rs,yuvBlder.create(),Allocation.USAGE_SCRIPT);
    Type rgbType = Type.createXY(rs, Element.RGBA_8888(rs), W, H);
    Allocation allocOut = Allocation.createTyped(rs,rgbType,Allocation.USAGE_SCRIPT);

    ScriptC_yuv2rgb scriptC_yuv2rgb = new ScriptC_yuv2rgb(rs);
    scriptC_yuv2rgb.set_gW(W);
    scriptC_yuv2rgb.set_gH(H);
    allocIn.copyFrom(yuv);
    scriptC_yuv2rgb.set_gYUV(allocIn);
    scriptC_yuv2rgb.forEach_YUV2RGB(allocOut);

    Bitmap bmp = Bitmap.createBitmap(W, H, Bitmap.Config.ARGB_8888);
    allocOut.copyTo(bmp);

    allocIn.destroy();
    scriptC_yuv2rgb.destroy();
    return bmp;
}

I guess the (x,y) is the matrix coordinate, so y should be at (x,y), u should be at ((x/2)*2,H + y/2),v should be next to u, ((x/2)*2+1,H + y/2). Sounds like this logic is wrong!

A: Two errors need to be fixed:

*

*-1 should be ~1 since x & -1 just equal to x, but x & ~1 will mask out the last bit so keep the value even.

*The yuv matrix size not correct. since uv vector is stored at the end of the y data, so the total matrix size should be W*H*3/2.

After apply these two changes, it works fine.
java:
public Bitmap YUV_toRGB(byte[] yuv,int W,int H) {
        RenderScript rs = RenderScript.create(this);
        Type.Builder yuvBlder = new Type.Builder(rs, Element.U8(rs))
                .setX(W).setY(H*3/2);
        Allocation allocIn = Allocation.createTyped(rs,yuvBlder.create(),Allocation.USAGE_SCRIPT);
        Type rgbType = Type.createXY(rs, Element.RGBA_8888(rs), W, H);
        Allocation allocOut = Allocation.createTyped(rs,rgbType,Allocation.USAGE_SCRIPT);

        ScriptC_yuv2rgb scriptC_yuv2rgb = new ScriptC_yuv2rgb(rs);
        allocIn.copyFrom(yuv);
        scriptC_yuv2rgb.set_gW(W);
        scriptC_yuv2rgb.set_gH(H);
        scriptC_yuv2rgb.set_gYUV(allocIn);
        scriptC_yuv2rgb.forEach_YUV2RGB(allocOut);

        Bitmap bmp = Bitmap.createBitmap(W, H, Bitmap.Config.ARGB_8888);
        allocOut.copyTo(bmp);

        allocIn.destroy();
        scriptC_yuv2rgb.destroy();
        return bmp;
    }

yuv2rgb.rs
#pragma version(1)
#pragma rs java_package_name(com.example.myexam)
#pragma rs_fp_relaxed

rs_allocation gYUV;
uint32_t gW;
uint32_t gH;

uchar4 __attribute__((kernel)) YUV2RGB(uint32_t x,uint32_t y)
{
    uchar yps = rsGetElementAt_uchar(gYUV, x, y);
    uchar u = rsGetElementAt_uchar(gYUV,(x & ~1),gH + (y>>1));
    uchar v = rsGetElementAt_uchar(gYUV,(x & ~1)+1,gH + (y>>1));
    uchar4 rgb = rsYuvToRGBA_uchar4(yps, u, v);
    return rgb;
}


text:
Q: Exim4 copying authenticated outbound email to a specific address I run an Exim 4 mail server for friends and clients. We've just given our 8 year old son an email capable device and he uses this server for outbound and inbound email. All outbound email is sent authenticated.
I have a file called /etc/exim4/authenticated.users which contains username:password pairs. I have lines in my configuration like this:
  accept
    authenticated = *

  myserver_cram:
    driver = cram_md5
    public_name = CRAM-MD5
    server_secret = ${lookup{$1}lsearch{/etc/exim4/authenticated.users}{$value}fail}
    server_set_id = $1

What I would like is to have a file like this:
/etc/exim4/outgoing.copies littlejohnny:daddy@parent.somewhere

So that when someone authenticates to send an outgoing email as littlejohnny, a copy is sent to daddy@parent.somewhere.
Does anyone know how to achieve this?

A: In your authenticator, you should have a line like server_set_id =.  Whatever is on the right hand side of that line will be stored in a variable $authenticated_id.  That variable can then be used in your routers to conditionally copy messages sent by your son's authenticated username.
It looks to me like you are using Debian, or a Debian derivative like Ubuntu.  Please be aware that Debian packages the Exim configuration file in a way that is specific to their distribution.  Because of this, it can be confusing to receive advice for generic exim systems and try to apply it to a Debian system.  That said, if you really want it to work and you read the debian docs on how their packaging system works, you can make it work.
In case it's not obvious, I'm a non-Debian-Exim guy, so my advice is generic, you'll have to translate it to Debian's packaging standards.
First, you need to find the authenticators and make sure that they are using the server_set_id option.  Here is an example authenticator:
auth_plain:
  driver = plaintext
  public_name = PLAIN
  server_condition = ${if eq {$3}{AUTH_STR}{yes}{no}}
  server_advertise_condition = ${if eq{$tls_cipher}{}{no}{yes}}
  server_set_id = $auth2

Because of the vagaries of the different auth types, sometimes $auth1 will hold the username, sometimes it will be $auth2.  If your system hasn't been updated for a while, you might also see $1 and $2, which were used before the auth-specific variables were added.
Now that you have the authenticated user's username being saved into $authenticated_id, you need to add a router that sends a copy of the mail to your address only if $authenticated_id matches your son's username.  Because the order of routers matter, you'll want to add it pretty high in your routers to make sure you get everything, but you'll have to eyeball your own config to judge where exactly to put it.
Here's an example router that does what you want:
copy_jrs_mail:
  driver = redirect
  data = daddy@parent.somewhere
  condition = ${if eq{$authenticated_id}{littlejohnny}{yes}{no}}
  unseen

To do the same thing but look up the information from a file, you can actually drop the condition (because $authenticated_id being in the file will serve the same purpose) and change the data = portion to use a file:
copy_auth_mail:
  driver = redirect
  data = ${if exists{/etc/exim4/outgoing.copies}{\
         ${lookup{${lc:$authenticated_id}}lsearch{/etc/exim4/outgoing.copies}}}}
  unseen

Hopefully that gets you going in the right direction, good luck.


text:
Q: How does mounting (or unmounting) a partition affect the performance of the system? Just curious to know: how does mounting (or unmounting) a partition affect the performance of the system?
I have a fairly large partition where have stored backups, software and old files that I don't need to access unless I rarely happen to. But I have set this partition to auto-mount at start-up along with other partitions. I just wanted to know if keeping this partition unmounted would save some resources in some way.
Thank you for your time in advance!

A: In my opinion, keeping it mounted or unmounted should have negligible if any affect on your system's performance.  I have a 2 TB external that stays mounted all the time and I haven't noticed any ill effects on my system.  I just have it set to spin down when it's not being accessed so it doesn't wear out.  Now if you have search software set to index that drive and things of that nature, then yeah it might have an effect on those services, but overall I don' think it would hurt anything to leave it mounted.


text:
Q: KLT tracker in OpenCV not working properly with Python I am using KLT (Kanade-Lucas-Tomasi Tracking) Tracking algorithm to track the motion of traffic in India. I am tracking flow of one side of traffic properly, but other side of traffic, that is moving in frame is not detected at all.
Algorithm consist of cv2.goodFeaturesToTrack and cv2.calcOpticalFlowPyrLK to achieve the result.

In the image you can see that Red and Silver car have no tracking feature on them. Yellow Auto on left is also not tracked. Any reason for this? Corners are still there.
Feature Parameters for cv2.goodFeaturesToTrack:
feature_params = dict( maxCorners = 500,   # How many pts. to locate
                       qualityLevel = 0.1,  # b/w 0 & 1, min. quality below which everyone is rejected
                       minDistance = 7,   # Min eucledian distance b/w corners detected
                       blockSize = 3 ) # Size of an average block for computing a derivative covariation matrix over each pixel neighborhood

Feature Parameters for cv2.calcOpticalFlowPyrLK:
lk_params = dict( winSize  = (15,15),  # size of the search window at each pyramid level
                  maxLevel = 2,   #  0, pyramids are not used (single level), if set to 1, two levels are used, and so on
                  criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

Video I have to use is 60 min. long and KLT stops tracking after 5 min.. Any suggestions or help would be great. Thanks.

A: Basically you are doing everything right you just need to reinitialize the good points for tracking like this
p0 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params)

after say every 5th frame or whatever you like
Hope it helps !
following is my code:
import cv2
import numpy as np

cap = cv2.VideoCapture('side.avi')
# params for ShiTomasi corner detection
feature_params = dict( maxCorners = 100,
                       qualityLevel = 0.3,
                       minDistance = 7,
                       blockSize = 7 )
# Parameters for lucas kanade optical flow
lk_params = dict( winSize  = (15,15),
                  maxLevel = 2,
                  criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
# Create some random colors
color = np.random.randint(0,255,(100,3))
# Take first frame and find corners in it
ret, old_frame = cap.read()
for i in range(60):
    ret, old_frame = cap.read()
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
p0 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params)
print(p0)
# Create a mask image for drawing purposes
mask = np.zeros_like(old_frame)
while(1):
    ret,frame = cap.read()
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    frame_no = cap.get(cv2.CAP_PROP_POS_FRAMES)
    if int(frame_no)%5 == 0:
        p0 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params)
    # calculate optical flow
    p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)
    # Select good points
    good_new = p1[st==1]
    good_old = p0[st==1]
    # draw the tracks
    for i,(new,old) in enumerate(zip(good_new,good_old)):
        a,b = new.ravel()
        c,d = old.ravel()
        mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
        frame = cv2.circle(frame,(a,b),5,color[i].tolist(),-1)
    img = cv2.add(frame,mask)
    cv2.imshow('frame',img)
    k = cv2.waitKey(2000) & 0xff
    if k == 27:
        break
    # Now update the previous frame and previous points
    old_gray = frame_gray.copy()
    p0 = good_new.reshape(-1,1,2)
cv2.destroyAllWindows()
cap.release()

A: import numpy as np
import cv2

video_path = ''
output_file = ""
cap = cv2.VideoCapture(video_path)

fourcc = cv2.VideoWriter_fourcc(*'DIVX')

# params for ShiTomasi corner detection
feature_params = dict( maxCorners = 500,   # How many pts. to locate
                       qualityLevel = 0.1,  # b/w 0 & 1, min. quality below which everyone is rejected
                       minDistance = 7,   # Min eucledian distance b/w corners detected
                       blockSize = 3 ) # Size of an average block for computing a derivative covariation matrix over each pixel neighborhood

# Parameters for lucas kanade optical flow
lk_params = dict( winSize  = (15,15),  # size of the search window at each pyramid level
                  maxLevel = 2,   #  0, pyramids are not used (single level), if set to 1, two levels are used, and so on
                  criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

''' Criteria : Termination criteria for iterative search algorithm.
    after maxcount { Criteria_Count } : no. of max iterations.
    or after { Criteria Epsilon } : search window moves by less than this epsilon '''

# Take first frame and find corners in it
ret, old_frame = cap.read()
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
p0 = cv2.goodFeaturesToTrack(old_gray, mask=None, **feature_params)  #use goodFeaturesToTrack to find the location of the good corner.

# Create a mask image for drawing purposes filed with zeros
mask = np.zeros_like(old_frame)

y = 0
is_begin = True # To save the output video
count = 1  # for the frame count
n = 50  # Frames refresh rate for feature generation

while True:
    ret,frame = cap.read()
    if frame is None:
        break
    processed = frame

    #Saving the Video
    if is_begin:
        h, w, _ = processed.shape
        out = cv2.VideoWriter(output_file, fourcc, 30, (w, h), True)
        is_begin = False

    # Convert to Grey Frame
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    if count%n == 0:  # Refresh the tracking features after every 50 frames
        cv2.imwrite('img/r{0:05d}.jpg'.format(y), img)
        y += 1
        ret, old_frame = cap.read()
        old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
        p0 = cv2.goodFeaturesToTrack(old_gray, mask=None, **feature_params)
        mask = np.zeros_like(old_frame)

    # calculate optical flow
    p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)

    # Select good points
    good_new = p1[st==1]
    good_old = p0[st==1]

    # draw the tracks
    for i,(new,old) in enumerate(zip(good_new,good_old)):
        a,b = new.ravel() #tmp new value
        c,d = old.ravel() #tmp old value
        #draws a line connecting the old point with the new point
        mask = cv2.line(mask, (a,b),(c,d), (0,255,0), 1)
        #draws the new point
        frame = cv2.circle(frame,(a,b),2,(0,0,255), -1)
    img = cv2.add(frame,mask)

    out.write(img)
    cv2.imshow('frame',img)
    k = cv2.waitKey(30) & 0xff

    #Show the Output
    if k == 27:
        cv2.imshow('', img)
        break

    # Now update the previous frame and previous points
    old_gray = frame_gray.copy()
    p0 = good_new.reshape(-1,1,2)

    count += 1

# release and destroy all windows
cv2.destroyAllWindows()
cap.release()

I added the refresh rate for the GoodFeaturetoTrack and it's working, but we will not get the full trajectory. Working on it now.


text:
Q: How to write the sql query? The table i have is:
lecturer
  lec_name
  s_code
  lec_pass
  ph_no

proposal_info
  metric,stu_name
  p_title
  u_proposal

apply_supervisor
  metric
  lec1
  lec2
  lec3

Now I would like to join this these 3 table tables and display all the data in the table of proposal_info only for that particular lecturer who login.How login. How to write the sql query for it? This is the query that i I have written...
select p.metric,p.stu_name,p.p_title,p.u_proposal
from proposal_info p
    INNER JOIN apply_supervisor a
    ON p.metric = a.metric
        JOIN lecturer s
        ON a.lec1 = s.s_code
        or a.lec2 = s.s_code
        or a.lec3 = s.s_code
where s.s_code = s_code;

A: I didn't understand exctally what you require, but from whatever i understood, i have created this one.
select p.metric,p.stu_name,p.p_title,p.u_proposal from proposal_info p INNER JOIN
apply_supervisor a ON p.metric = a.metric where
lec1 = @s_code or
lec2 = @s_code or
lec3 = @s_code

Check if this can help you.
Where @s_code is the input parameter that you must replace with value.

A: Select P.metric, P.stu_name, P.p_title, P.u_proposal
From proposal_info As P
Where Exists    (
                Select 1
                From apply_supervisor As A
                Where A.metric = P.metric
                    And (
                        A.lec1 = 'some lecturer code'
                        Or A.lec2 = 'some lecturer code'
                        Or A.lec3 = 'some lecturer code'
                        )
                )

In comments, you mentioned that you are using MySQL. Given that MySQL is not great at handling correlated subqueries. However, you can easily rewrite the above query like so:
Select P.metric, P.stu_name, P.p_title, P.u_proposal
From proposal_info As P
Where P.metric In   (
                    Select A.metric
                    From apply_supervisor As A
                    Where A.lec1 = 'some lecturer code'
                        Or A.lec2 = 'some lecturer code'
                        Or A.lec3 = 'some lecturer code'
                    )


text:
Q: Draw convex hull on android I try to draw convex hull on image.For this, I find all contours and select max area contour. drawContours accepts MatOfPoint but convexHull gives me MatOfInt. I read this question and run some codes. Some of them draw convex hull, but they cannot find really convex points.
I use below code, but it has a runtime error on last line m.fromArray(hullpoints.get(i));. hullpoints.get(i) has only one point and the code cannot create MatOfPoint object. How can I convert to MatOfPoint from MatOfInt ?
        // Find the convex hull
        List<MatOfInt> hull = new ArrayList<MatOfInt>();
        for(int j=0; j < contours.size(); j++){
            hull.add(new MatOfInt());
        }
        for(int j=0; j < contours.size(); j++){
            Imgproc.convexHull(contours.get(j), hull.get(j));
        }

        // Convert MatOfInt to MatOfPoint for drawing convex hull
        // Loop over all contours
        List<Point[]> hullpoints = new ArrayList<Point[]>();
        for(int j=0; j < hull.size(); j++){
            Point[] points = new Point[hull.get(j).rows()];

            // Loop over all points that need to be hulled in current contour
            for(int k=0; k < hull.get(j).rows(); k++){
                int index2 = (int)hull.get(j).get(k, 0)[0];
                points[k] = new Point(contours.get(j).get(index2, 0)[0], contours.get(j).get(index2, 0)[1]);
            }
            hullpoints.add(points);
        }

        // Convert Point arrays into MatOfPoint
        List<MatOfPoint> hullmop = new ArrayList<MatOfPoint>();
        for(int j=0; j < hullpoints.size(); j++){
            MatOfPoint m = new MatOfPoint();
            m.fromArray(hullpoints.get(i));
            hullmop.add(m);
        }

A: Fwiw, I've changed FastConvexHull from here to use com.google.android.gms.maps.model.LatLong. Minimally tested, so no guarantees.
Interface:
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;

public interface ConvexHullAlgorithm
{
    ArrayList<LatLng> execute(ArrayList<LatLng> points);
}

Class:
public class FastConvexHull implements ConvexHullAlgorithm {

    @Override
    public ArrayList<LatLng> execute(ArrayList<LatLng> points) {
        ArrayList<LatLng> xSorted = (ArrayList<LatLng>) points.clone();
        Collections.sort(xSorted, new XCompare());

        int n = xSorted.size();

        LatLng[] lUpper = new LatLng[n];

        lUpper[0] = xSorted.get(0);
        lUpper[1] = xSorted.get(1);

        int lUpperSize = 2;

        for (int i = 2; i < n; i++) {
            lUpper[lUpperSize] = xSorted.get(i);
            lUpperSize++;

            while (lUpperSize > 2 && !rightTurn(lUpper[lUpperSize - 3], lUpper[lUpperSize - 2], lUpper[lUpperSize - 1])) {
                // Remove the middle point of the three last
                lUpper[lUpperSize - 2] = lUpper[lUpperSize - 1];
                lUpperSize--;
            }
        }

        LatLng[] lLower = new LatLng[n];

        lLower[0] = xSorted.get(n - 1);
        lLower[1] = xSorted.get(n - 2);

        int lLowerSize = 2;

        for (int i = n - 3; i >= 0; i--) {
            lLower[lLowerSize] = xSorted.get(i);
            lLowerSize++;

            while (lLowerSize > 2 && !rightTurn(lLower[lLowerSize - 3], lLower[lLowerSize - 2], lLower[lLowerSize - 1])) {
                // Remove the middle point of the three last
                lLower[lLowerSize - 2] = lLower[lLowerSize - 1];
                lLowerSize--;
            }
        }

        ArrayList<LatLng> result = new ArrayList<LatLng>();

        for (int i = 0; i < lUpperSize; i++) {
            result.add(lUpper[i]);
        }

        for (int i = 1; i < lLowerSize - 1; i++) {
            result.add(lLower[i]);
        }

        return result;
    }

    private boolean rightTurn(LatLng a, LatLng b, LatLng c) {
        return (b.latitude - a.latitude) * (c.longitude - a.longitude) - (b.longitude - a.longitude) * (c.latitude - a.latitude) > 0;
    }

    private class XCompare implements Comparator<LatLng> {
        @Override
        public int compare(LatLng o1, LatLng o2) {
            return (new Float(o1.latitude)).compareTo(new Float(o2.latitude));
        }
    }
}


text:
Q: Adding promise polyfill to ES6 I have a React project written in ES6. It is compiled using Babel and works quite well. Except for one promise (of many!) that acts up only in IE, for which I already know - has no support for promises. So I immediately thought to add a polyfill to supply promises for IE, but then I was like "Hold up, you're already writing ES6 and isn't that compiled into ES5 anyways?" Who would know better than SO?
So is there any sense in adding a polyfill such as es6-promise to my project? And if there is, how should I use it syntactically? For now I only have the import but I should probably implement it somehow as well?
import Promise from 'es6-promise';

Also here's the promise that causes problems in IE, perhaps I have a syntax error that I haven't noticed myself! :)
new SingleObjectResource(DJ_CONST.API.setLanguage)
    .put(null, {language_code: theLanguage})
    .then(
        function() {
            window.location.reload();
        }
    );

A: I had the same situation & was very frustrated as i had to deploy production app, The problem i had was with Promises from fetchjs. This is what i do to save my life
npm install --save es6-promise //first install as a dependency & then added in broswerify as dependency.

and then in my main JS file, justed called this
   import "es6-promise/auto";

as from here https://github.com/stefanpenner/es6-promise#auto-polyfill
basically, its alternative syntax of
require('es6-promise').polyfill();

Basically, Under the hood The polyfill() method will patch the global environment (in this case to the Promise name) when called.
Note: i was using gulp with browserify.

A: I couldn't edit my previous response earlier as I received the review comment in the night when I was offline... re-posting my response with embedded information per the review feedback. Thanks.
Why not use bluebird everywhere? Its faster than the native promises. And polyfills for IE too. And I don't work for them :).
EDIT:
Using bluebird instead of native promise -
const Promise = require('bluebird');

 1. Added perf comparisons -
results for 10000 parallel executions, 1 ms per I/O op

file                                     time(ms)  memory(MB)
callbacks-baseline.js                         232       35.86
promises-bluebird-generator.js                235       38.04
promises-bluebird.js                          335       52.08
promises-cujojs-when.js                       405       75.77
promises-tildeio-rsvp.js                      468       87.56
promises-dfilatov-vow.js                      578      125.98
callbacks-caolan-async-waterfall.js           634       88.64
promises-lvivski-davy.js                      653      109.64
promises-calvinmetcalf-lie.js                 732      165.41
promises-obvious-kew.js                      1346      261.69
promises-ecmascript6-native.js               1348      189.29
generators-tj-co.js                          1419      164.03
promises-then-promise.js                     1571      294.45
promises-medikoo-deferred.js                 2091      262.18
observables-Reactive-Extensions-RxJS.js      3201      356.76
observables-caolan-highland.js               7429      616.78
promises-kriskowal-q.js                      9952      694.23
observables-baconjs-bacon.js.js             25805      885.55

Platform info:
Windows_NT 6.1.7601 x64
Node.JS 1.1.0
V8 4.1.0.14
Intel(R) Core(TM) i5-2500K CPU @ 3.30GHz × 4

2. IE Polyfill code -
import Bluebird from 'bluebird';
// Node
global.Promise = Bluebird;
// Browser
window.Promise = Bluebird;

A: Although you are using Babel (just traspiling and not adding functionality), polyfills are needed.
All you have to do is installing the package:
npm install --save es6-promise

Inside webpack.config.js (or wherever your webpack configurations are, assuming you are using webpack)
require('es6-promise').polyfill();

The polyfill() method will patch the global environment (in this case to the Promise name) when called. More info at https://github.com/stefanpenner/es6-promise


text:
Q: Generate new column in dataframe, based on group-event in nested groups I have a dataframe with three "main"-groups (x: 1, 2, 3), three groups within the main-groups (v: 2, 3 or 1) and some events within the main-groups (0 and 1 in y):
x <- c(1, 1, 1, 2, 2, 3, 3, 3, 3)
v <- c(2, 3, 3, 2, 2, 1, 1, 2, 2)
y <- c(0, 0, 1, 0, 0, 0, 0, 0, 1)
df <- data.frame(x, v, y)
df

> df
  x v y
1 1 2 0
2 1 3 0
3 1 3 1
4 2 2 0
5 2 2 0
6 3 1 0
7 3 1 0
8 3 2 0
9 3 2 1

For example: In group 1 (x = 1) there are two more groups (v = 2 and v = 3), event y = 1 happens in group x = 1 and v = 3.
Now i want to generate a new column z, based on the events in y: if there is any y = 1 in one group, all cases in group v in x should get a 1 for z; else NA. How can z be generated this way? df should look like:
> df
  x v y  z
1 1 2 0 NA
2 1 3 0  1
3 1 3 1  1
4 2 2 0 NA
5 2 2 0 NA
6 3 1 0  1
7 3 1 1  1
8 3 2 0 NA
9 3 2 0 NA

I am grateful for any help.

A: Try this:
library(dplyr)

df %>%
group_by(x, v) %>%
mutate(
z = ifelse(any(y == 1), 1, NA)
)

A: df %>% group_by(x, v) %>% mutate(z = if(any(y == 1)) 1 else NA)

After grouping by x and y, the new column z is filled with 1's if there are any 1's in y and with NA's otherwise.


text:
Q: matplotlab: plt.figure() creates empty figure I am playing with the example at
https://github.com/seanabu/seanabu.github.io/blob/master/Seasonal_ARIMA_model_Portland_transit.ipynb
However, on my own Jupyter Notebook, the following piece of code creates an empty figure. Any idea? Thanks!

A: You are creating two figures. Simply remove the first creation of the empty figure fig = plt.figure().
Here is a minimal example:
%matplotlib inline
import statsmodels.api as sm
from statsmodels.tsa.seasonal import seasonal_decompose

dat = sm.datasets.co2.load_pandas().data.dropna()
decomposition = seasonal_decompose(dat.co2, freq=12)
fig = decomposition.plot()
fig .set_size_inches(15, 8)

A: Try adding plt.show() at the end.


text:
Q: ant.xslt/Xalan fails referencing namespaced nodes from an external file In an .xsl file I want to use nodes from a separate file ("foo.xsd"). The .xsl file uses an explicit namespace prefix, the external file doesn't but rather relies on a default namespace. Their namespace URIs match up.
Reading in the nodes, with ant.xslt the following XPath expression results in an ArrayIndexOutOfBounds exception later
document('foo.xsd')/xsd:schema/xsd:*

while it works when removing the last reference to the namespace prefix
document('foo.xsd')/xsd:schema/*

Here is a minimal example that reproduces the issue. The transformation input file
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
   <element name="bar"/>
</schema>

and a transformation .xsl file
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  version="1.0">
  <xsl:variable name="nodeSet" select="document('foo.xsd')/xsd:schema/xsd:*[@name]"/>
    <xsl:template match="/xsd:schema/xsd:element">
      <xsl:value-of select="$nodeSet/@name"/>
   </xsl:template>
</xsl:stylesheet>

The referenced foo.xsd is just a copy of the input file, so in this cut down example I'm running over one instance of the file and reading in the other instance in the stylesheet.
Goold ol' xsltproc is extracting the right attribute value ("bar"). ant.xslt with the default processor (Xalan) throws an ArrayIndexOutOfBoundsException (I presume when looking for the colon insided the element name).The problem only arises when referencing nodeSet as in the <xsl:value-of> element.
The <xsl:template> matches in all cases, using prefixes.
My question is: Did I hit a bug in Xalan, or am I doing something generally wrong?
I'm aware of the various work-arounds concerning namespace prefixes, like using [local-name() = 'element'] and such, so please don't post answers in that vein. I'm looking for a general answer whether this should work (like, according to the specs).
Background Material
Stacktrace (part.) that hints at Xalan:
...
Caused by: javax.xml.transform.TransformerException: java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 512
        at java.xml/com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:783)
        at java.xml/com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:370)
        at org.apache.tools.ant.taskdefs.optional.TraXLiaison.transform(TraXLiaison.java:201)
        at org.apache.tools.ant.taskdefs.XSLTProcess.process(XSLTProcess.java:870)
        ... 126 more
Caused by: java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 512
        at java.xml/com.sun.org.apache.xml.internal.utils.SuballocatedIntVector.elementAt(SuballocatedIntVector.java:441)
        at java.xml/com.sun.org.apache.xml.internal.dtm.ref.DTMDefaultBase._firstch(DTMDefaultBase.java:523)
        at java.xml/com.sun.org.apache.xalan.internal.xsltc.dom.SAXImpl.access$200(SAXImpl.java:73)
        at java.xml/com.sun.org.apache.xalan.internal.xsltc.dom.SAXImpl$NamespaceChildrenIterator.next(SAXImpl.java:1431)
        at java.xml/com.sun.org.apache.xalan.internal.xsltc.dom.CurrentNodeListIterator.setStartNode(CurrentNodeListIterator.java:158)
        at java.xml/com.sun.org.apache.xalan.internal.xsltc.dom.StepIterator.setStartNode(StepIterator.java:97)
        at java.xml/com.sun.org.apache.xalan.internal.xsltc.dom.StepIterator.setStartNode(StepIterator.java:97)
        at java.xml/com.sun.org.apache.xalan.internal.xsltc.dom.DupFilterIterator.setStartNode(DupFilterIterator.java:97)
        at java.xml/com.sun.org.apache.xalan.internal.xsltc.dom.CachedNodeListIterator.setStartNode(CachedNodeListIterator.java:57)
        at jdk.translet/die.verwandlung.test.topLevel()
        at jdk.translet/die.verwandlung.test.transform()
        at java.xml/com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet.transform(AbstractTranslet.java:624)
        at java.xml/com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:776)
        ... 129 more

Invokation is through Gradle via shell command gradlew mytask using the Gradle built-in Ant using its built-in ant.xslt task.
build.gradle:
tasks.register('mytask') {
    doLast {
        ant.xslt(
            baseDir: '.',
            in: 'input.xsd',
            out: 'out.xml',
            style: 'stylefile.xsl'
        )
    }
}

A: Your xslt/xml code is fine (works with Saxon). So it's either something in the way you're running the transformation, or it's a bug in the version of Xalan that you're using.
Xalan shouldn't be throwing an ArrayIndexOutOfBounds exception anyway. It's presumably Xalan code on the stack trace?


text:
Q: How to click item on first form while having another form open Example image:

I just want to know how to click something on the parent form while the child is active!
Why I want it: Users may need to access one dialog while looking at another.

A: Displaying a form with call:
new Form2().showDialog();

Will not allows you to click on the form1.
new Form2().show();

Will allow you to click parent form1.

A: Suggested by David Pilkington.
I fixed it by going from:
form.ShowDialog(this);

to:
form.Show(this);

thank you!

A: quite simply (re-factored) you can use this.
//Open as dialog
new Form2().showDialog();
//Open as new instance
f2 = new Form2();
f2.Show();


text:
Q: Python passing file path variable into Applescript using osascript I am trying to pass a file path into n Applescript from Python, not sure how to achieve it. The code below shows the working Applescript code which prompts to open a file, or files, then  re-assigns the audio channels, saves and closes. Instead of prompting for a file or files, I want to pass the file path into the osascript Applescript, I have already set the args, but not sure how to get it to work.
from subprocess import Popen, PIPE

scpt = '''
    on run
        open (choose file with prompt ("Choose movie file(s)") ¬
        with multiple selections allowed)
    end run

    on open aa
        set channel_layouts_map1 to {¬
            {"Sound Track 1", "Sound Track 1", {"Left"}}, ¬
            {"Sound Track 2", "Sound Track 2", {"Right"}}, ¬
            {"Sound Track 3", "Sound Track 3", {"Center"}}, ¬
            {"Sound Track 4", "Sound Track 4", {"LFE Screen"}}, ¬
            {"Sound Track 5", "Sound Track 5", {"Left Surround"}}, ¬
            {"Sound Track 6", "Sound Track 6", {"Right Surround"}}, ¬
            {"Sound Track 7", "Sound Track 7", {"Left Total"}}, ¬
            {"Sound Track 8", "Sound Track 8", {"Right Total"}} ¬
                }
        set channel_layouts_map2 to {¬
            {"Sound Track 1", "Sound Track 1", {"Left"}}, ¬
            {"Sound Track 2", "Sound Track 2", {"Right"}}, ¬
            {"Sound Track 3", "Sound Track 3", {"Center"}}, ¬
            {"Sound Track 4", "Sound Track 4", {"LFE Screen"}}, ¬
            {"Sound Track 5", "Sound Track 5", {"Left Surround"}}, ¬
            {"Sound Track 6", "Sound Track 6", {"Right Surround"}}, ¬
            {"Sound Track 7", "Sound Track 7", {"Left Total", "Right Total"}} ¬
                }
        set channel_layouts_map3 to {¬
            {"Sound Track", "Sound Track", {"Left", "Right"}} ¬
                }
        set channel_layouts_map4 to {¬
            {"Sound Track 1", "Sound Track 1", {"Left"}}, ¬
            {"Sound Track 2", "Sound Track 2", {"Right"}} ¬
                }

        repeat with a in aa
            set f to a's POSIX path
            set k to count_sound_tracks(f, {_close:false})
            if k = 8 then
                remap_audio_channels(f, channel_layouts_map1)
            else if k = 7 then
                remap_audio_channels(f, channel_layouts_map2)
            else if k = 1 then
                remap_audio_channels(f, channel_layouts_map3)
            else if k = 2 then
                remap_audio_channels(f, channel_layouts_map4)
            else
                -- ignore it (just close it)
                close_document(f, {_save:false})
            end if
        end repeat
    end open

    on count_sound_tracks(f, {_close:_close})
        tell application id "com.apple.quicktimeplayer" -- QuickTime Player 7 Pro
            open (f as POSIX file)
            tell (document 1 whose path = f)
                repeat until exists
                    delay 0.2
                end repeat
                set k to count (tracks whose audio channel count > 0)
                if _close then close
            end tell
        end tell
        return k
    end count_sound_tracks

    on close_document(f, {_save:_save})
        tell application id "com.apple.quicktimeplayer" -- QuickTime Player 7 Pro
            tell (document 1 whose path = f)
                if exists then
                    if _save and modified then save
                    close
                end if
            end tell
        end tell
    end close_document

    on remap_audio_channels(f, channel_layouts_map)
        script o
            property map : channel_layouts_map
            property pp : {}
            property qq : {}

            -- get name and id of sound tracks
            tell application id "com.apple.quicktimeplayer" -- QuickTime Player 7 Pro
                activate
                open (f as POSIX file)
                tell (document 1 whose path = f)
                    repeat until exists
                        delay 0.2
                    end repeat
                    tell (tracks whose audio channel count > 0)
                        set {pp, qq} to {name, id} -- name and id of sound tracks
                    end tell
                end tell
            end tell

            -- remap audio channel layouts as specified
            tell application "System Events"
                tell (process 1 whose bundle identifier = "com.apple.quicktimeplayer")
                    -- open movie properties window
                    keystroke "j" using {command down}

                    tell (window 1 whose subrole = "AXDialog") -- properties for movie
                        repeat until exists
                            delay 0.2
                        end repeat
                        repeat with m in my map
                            set {trk, undef, layouts} to m
                            -- [TRK:
                            repeat 1 times
                                if trk's class = integer then
                                    if trk < 1 or trk > (count my pp) then exit repeat -- TRK:
                                    set trk to my pp's item trk
                                end if
                                tell scroll area 1
                                    tell table 1
                                        tell (row 1 whose text field 1's value = trk) -- target sound track whose name = trk
                                            if not (exists) then exit repeat -- TRK:
                                            select
                                        end tell
                                    end tell
                                end tell
                                tell tab group 1
                                    click radio button 3 -- audio settings
                                    tell scroll area 1
                                        tell table 1 -- channel assignment table
                                            set ix to count layouts
                                            repeat with i from 1 to count rows
                                                if i > ix then exit repeat
                                                tell row i -- channel i
                                                    tell pop up button 1
                                                        click
                                                        tell menu 1 -- channel assignment menu
                                                            tell (menu item 1 whose title = layouts's item i)
                                                                if exists then click
                                                            end tell
                                                        end tell
                                                    end tell
                                                end tell
                                            end repeat
                                        end tell
                                    end tell
                                end tell
                            end repeat
                            -- /TRK:]
                        end repeat

                        -- close movie properties window
                        click (button 1 whose subrole = "AXCloseButton")
                    end tell
                end tell
            end tell

            -- rename sound tracks as specified
            tell application id "com.apple.quicktimeplayer"
                tell document 1
                    repeat with m in my map
                        -- [RENAME:
                        repeat 1 times
                            set {x, y} to m's items 1 thru 2 -- {old name or index, new name or index}
                            if x's class = integer then
                                if x < 1 or x > (count my pp) then exit repeat -- RENAME:
                            else
                                set x to my _index_of(pp, x)
                                if x = 0 then exit repeat -- RENAME:
                            end if
                            if y's class = integer then
                                if y < 1 or y > (count my pp) then exit repeat -- RENAME:
                                set y to my pp's item y
                            end if
                            set p to my pp's item x
                            set q to my qq's item x
                            if p ≠ y then set track id q's name to y
                        end repeat
                        -- /RENAME:]
                    end repeat
                    if modified then save
                    close
                end tell
            end tell

        end script
        tell o to run
    end remap_audio_channels

    on _index_of(xx, x) -- renamed _bsearch() v0.1
        script o
            property aa : xx
            local i, j, k
            if {x} is not in my aa then return 0
            set i to 1
            set j to count my aa
            repeat while j > i
                set k to (i + j) div 2
                if {x} is in my aa's items i thru k then
                    set j to k
                else
                    set i to k + 1
                end if
            end repeat
            return i
        end script
        tell o to run
    end _index_of'''

args = ["/Users/me/Desktop/DOWNLOAD/44.mov"]

p = Popen(['osascript', '-'] + args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(scpt)
print (p.returncode, stdout, stderr)

A: Found the answer. Needed to change the on run section to this:
on run argv
    repeat with a in argv
        set a's contents to a as POSIX file as alias
    end repeat
    open argv
end run

A: According to the man page for osascript, arguments get passed to the run handler.
So just like you have "on open aa", you would have "on run filepath", and then use that in the "choose file".
on run filepath
    open (choose file with prompt ("Choose movie file(s)") ¬
    with multiple selections allowed default location filepath)
end run

Literally, that should be the only change you have to make.


text:
Q: Registry Editor - Set Max Idle Time to 14 Days I'm trying to set my 'MaxIdleTime' in the Registry Editor.  I have used the following link to set it up to be 5 Days.  How can I make it 14 days?  I want it longer than 5 days, but less the 'Never'  I'm not sure how to convert seconds into Hexadecimal or Decimal value.  Any help would be awesome!
https://www.sevenforums.com/tutorials/118889-remote-desktop-set-time-limit-idle-sessions.html
Thanks,

A: I found out it was in milliseconds.  I just converted the days I wanted into milliseconds and went from there


text:
Q: Could not load library cudnn_cnn_infer64_8.dll. Error code 126 Please make sure cudnn_cnn_infer64_8.dll is in your library path I am quiet certain I installed everything correctly, and the required file is clearly in my path. I am not sure what I can do at this point. Please Help.
echo %path%
C:\Users\idvin\anaconda3\envs\3.7;C:\Users\idvin\anaconda3\envs\3.7\Library\mingw-w64\bin;C:\Users\idvin\anaconda3\envs\3.7\Library\usr\bin;C:\Users\idvin\anaconda3\envs\3.7\Library\bin;C:\Users\idvin\anaconda3\envs\3.7\Scripts;C:\Users\idvin\anaconda3\envs\3.7\bin;C:\Users\idvin\anaconda3\condabin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\libnvvp;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\iCLS;C:\Program Files\Intel\Intel(R) Management Engine Components\iCLS;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Windows\System32\OpenSSH;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\WiFi\bin;C:\Program Files\Common Files\Intel\WirelessCommon;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\WINDOWS\System32\OpenSSH;C:\Program Files\MATLAB\R2020b\bin;C:\Users\idvin\Downloads\elastix-4.9.0-win64;C:\Program Files\NVIDIA Corporation\Nsight Compute 2022.1.0;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\bin\cudnn_cnn_infer64_8.dll;D:\dll_x64\dll_x64\zlibwapi.dll;C:\Program Files\MySQL\MySQL Shell 8.0\bin;C:\Users\idvin\AppData\Local\Microsoft\WindowsApps;C:\Users\idvin\AppData\Local\Programs\Julia-1.6.4\bin;D:\dll_x64\dll_x64\zlibwapi.dll;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.6\bin\cudnn_cnn_train64_8.dll;.

A: solved it in my path i needed to add the directory of zlibwapi.dll not zlibwapi.dll itself


text:
Q: Lotus Notes Message : "DBD cannot get the list of adress books for the local server" One of my Louts Notes user is getting  as strange message. When he is trying to access the address book by using  any of the Notes applicaitons, Instead of showing up the address book names in the address dialog he is getting the following error message in the dialog window , it is rendering as "DBD cannot get the list of adress books for the local server".
What does this message mean and Why this meesage shows ?

A: There are a few posts about this, pointing to missing spr/apar's.
Check the Preferences-> Local address books and make sure that the user has access to all the databases mentioned there.


text:
Q: Is there a SELF pointer for blocks? I'd like to recursively call a block from within itself. In an obj-c object, we get to use "self", is there something like this to refer to a block instance from inside itself?

A: You have to declare the block variable as __block:
typedef void (^MyBlock)(id);

__block MyBlock block = ^(id param) {
  NSLog(@"%@", param);
  block(param);
};

A: There is no self for blocks (yet). You can build one like this (assuming ARC):
__block void (__weak ^blockSelf)(void);
void (^block)(void) = [^{
        // Use blockSelf here
} copy];
blockSelf = block;
    // Use block here

The __block is needed so we can set blockSelf to the block after creating the block. The __weak is needed because otherwise the block would hold a strong reference to itself, which would cause a strong reference cycle and therefore a memory leak. The copy is needed to make sure that the block is copied to the heap. That may be unnecessary with newer compiler versions, but it won't do any harm.

A: Fun story! Blocks actually are Objective-C objects. That said, there is no exposed API to get the self pointer of blocks.
However, if you declare blocks before using them, you can use them recursively. In a non-garbage-collected environment, you would do something like this:
__weak __block int (^block_self)(int);
int (^fibonacci)(int) = [^(int n) {
    if (n < 2) { return 1; }
    return block_self(n - 1) + block_self(n - 2);
} copy];

block_self = fibonacci;

It is necessary to apply the __block modifier to block_self, because otherwise, the block_self reference inside fibonacci would refer to it before it is assigned (crashing your program on the first recursive call). The __weak is to ensure that the block doesn't capture a strong reference to itself, which would cause a memory leak.

A: The following recursive block code will compile and run using ARC, GC, or manual memory management, without crashing, leaking, or issuing warnings (analyzer or regular):
typedef void (^CountdownBlock)(int currentValue);

- (CountdownBlock) makeRecursiveBlock
{
    CountdownBlock aBlock;
    __block __unsafe_unretained CountdownBlock aBlock_recursive;
    aBlock_recursive = aBlock = [^(int currentValue)
    {
        if(currentValue >= 0)
        {
            NSLog(@"Current value = %d", currentValue);
            aBlock_recursive(currentValue-1);
        }
    } copy];
#if !__has_feature(objc_arc)
    [aBlock autorelease];
#endif

    return aBlock;
}

- (void) callRecursiveBlock
{
    CountdownBlock aBlock = [self makeRecursiveBlock];

    // You don't need to dispatch; I'm doing this to demonstrate
    // calling from beyond the current autorelease pool.
    dispatch_async(dispatch_get_main_queue(), ^
                   {
                       aBlock(10);
                   });
}

Important considerations:

*

*You must copy the block onto the heap manually or else it will try to access a nonexistent stack when you call it from another context (ARC usually does this for you, but not in all cases. Better to play it safe).

*You need TWO references: One to hold the strong reference to the block, and one to hold a weak reference for the recursive block to call (technically, this is only needed for ARC).

*You must use the __block qualifier so that the block doesn't capture the as-yet unassigned value of the block reference.

*If you're doing manual memory management, you'll need to autorelease the copied block yourself.


text:
Q: How to provide class with multiline element gutenberg RichText block? I'm using following code for gutenberg RichText block
el(
    RichText,
    {
        key: 'editable',
        tagName: 'ul',
        multiline: 'li',
        className: 'list-group',
        onChange: onChangeContent,
        value: content,
    }
)

Can anyone help me how to assign a class list-item with multiline li element?

A: I don't think gutenberg supports this out of the box. You can modify the content of the rich text editor by replacing the
 with
 in the save function.
You need to make use of dangerouslySetInnerHTML to render string as html inside

save: function save(props) {
    function createMarkup() {
        return { __html: props.attributes.content.replace(/
/g, '
') };
    }

    return el('ul', { dangerouslySetInnerHTML: createMarkup() });
}

UPDATED
If you need to do this immediately when you add a new
 in the editor itself, then you need to call a function to add the class to the
 elements in the onChange event of the RichText component.
edit: function edit(props) {
    function setCustomClass() {
        $('.list-group li').addClass('list-item');
    }
    return el(RichText, {
        key: 'editable',
        tagName: 'ul',
        multiline: 'li',
        className: 'list-group',
        onChange: function onChangeContent(content) {
            props.setAttributes({ content: content });
            setCustomClass();
        },
        value: props.attributes.content
    });
},


text:
Q: how to capture the string that beginning and ending certain kind of string with Regex in javascript '\u001b[1m\u001b[31m  \u001b[1m● \u001b[1mregister page › register-automated › desktop › CONTROL\u001b[39m\u001b[22m\n\n    Expected image to match or be a close match to snapshot but was 0.009980258828690502% different from snapshot (91 differing pixels).\n    \u001b[1m\u001b[31mSee diff for details:\u001b[39m\u001b[22m \u001b[31m/src/pages/__image_snapshots__/__diff_output__/register-test-js-register-page-register-automated-desktop-control-1-diff.png\u001b[39m\n\u001b[2m\u001b[22m\n\u001b[2m    \u001b[0m \u001b[90m 60 | \u001b[39m\u001b[0m\u001b[22m\n\u001b[2m    \u001b[0m \u001b[90m 61 | \u001b[39m          \u001b[36mconst\u001b[39m image \u001b[33m=\u001b[39m await page\u001b[33m.\u001b[39mscreenshot({ fullPage\u001b[33m:\u001b[39m isFullPage })\u001b[33m;\u001b[39m\u001b[0m\u001b[22m\n\u001b[2m    \u001b[0m\u001b[31m\u001b[1m>\u001b[2m\u001b[39m\u001b[90m 62 | \u001b[39m          expect(image)\u001b[33m.\u001b[39mtoMatchImageSnapshot({threshold\u001b[33m:\u001b[39m \u001b[35m0.3\u001b[39m})\u001b[33m;\u001b[39m\u001b[0m\u001b[22m\n\u001b[2m    \u001b[0m \u001b[90m    | \u001b[39m                        \u001b[31m\u001b[1m^\u001b[2m\u001b[39m\u001b[0m\u001b[22m\n\u001b[2m    \u001b[0m \u001b[90m 63 | \u001b[39m        })\u001b[33m;\u001b[39m\u001b[0m\u001b[22m\n\u001b[2m    \u001b[0m \u001b[90m 64 | \u001b[39m\u001b[0m\u001b[22m\n\u001b[2m    \u001b[0m \u001b[90m 65 | \u001b[39m        \u001b[36mif\u001b[39m(experimentName \u001b[33m||\u001b[39m experiementVariationName) {\u001b[0m\u001b[22m\n\u001b[2m\u001b[22m\n\u001b[2m      \u001b[2mat Object.toMatchImageSnapshot (\u001b[2msrc/command/getPageImageShot.js\u001b[2m:62:25)\u001b[2m\u001b[22m\n'

how to capture /src/pages/__image_snapshots__/__diff_output__/register-test-js-register-page-register-automated-desktop-control-1-diff.png from this gibberish?
I tried .match(/\bdetails\.\w+png\b/) for capture all the string between the end of ...detail: and end of .png string, but it did not went well, just kept return null. I want to do this way, is because everything after See diff for details: and before .png can be different text...

A: You could use a capturing group to get the path and add a colon : after details
\bdetails:.*?(\/.*?\.png\b)

*

*\bdetails: Match word boundary and details:

*.*? Match any char 0+ times non greedy (If there are no forward slashes in between, you could also use a negated character class [^\/]*

*( Capture group

*

*\/.*?\.png\b Match any char non greedy and .png and word boundary

*) Close capturing group

In the replacement use $1/
See a regex demo

const regex = /\bdetails:.*?(\/.*?\.png\b)/;
const str = `'\\u001b[1m\\u001b[31m  \\u001b[1m● \\u001b[1mregister page › register-automated › desktop › CONTROL\\u001b[39m\\u001b[22m\\n\\n    Expected image to match or be a close match to snapshot but was 0.009980258828690502% different from snapshot (91 differing pixels).\\n    \\u001b[1m\\u001b[31mSee diff for details:\\u001b[39m\\u001b[22m \\u001b[31m/src/pages/__image_snapshots__/__diff_output__/register-test-js-register-page-register-automated-desktop-control-1-diff.png\\u001b[39m\\n\\u001b[2m\\u001b[22m\\n\\u001b[2m    \\u001b[0m \\u001b[90m 60 | \\u001b[39m\\u001b[0m\\u001b[22m\\n\\u001b[2m    \\u001b[0m \\u001b[90m 61 | \\u001b[39m          \\u001b[36mconst\\u001b[39m image \\u001b[33m=\\u001b[39m await page\\u001b[33m.\\u001b[39mscreenshot({ fullPage\\u001b[33m:\\u001b[39m isFullPage })\\u001b[33m;\\u001b[39m\\u001b[0m\\u001b[22m\\n\\u001b[2m    \\u001b[0m\\u001b[31m\\u001b[1m>\\u001b[2m\\u001b[39m\\u001b[90m 62 | \\u001b[39m          expect(image)\\u001b[33m.\\u001b[39mtoMatchImageSnapshot({threshold\\u001b[33m:\\u001b[39m \\u001b[35m0.3\\u001b[39m})\\u001b[33m;\\u001b[39m\\u001b[0m\\u001b[22m\\n\\u001b[2m    \\u001b[0m \\u001b[90m    | \\u001b[39m                        \\u001b[31m\\u001b[1m^\\u001b[2m\\u001b[39m\\u001b[0m\\u001b[22m\\n\\u001b[2m    \\u001b[0m \\u001b[90m 63 | \\u001b[39m        })\\u001b[33m;\\u001b[39m\\u001b[0m\\u001b[22m\\n\\u001b[2m    \\u001b[0m \\u001b[90m 64 | \\u001b[39m\\u001b[0m\\u001b[22m\\n\\u001b[2m    \\u001b[0m \\u001b[90m 65 | \\u001b[39m        \\u001b[36mif\\u001b[39m(experimentName \\u001b[33m||\\u001b[39m experiementVariationName) {\\u001b[0m\\u001b[22m\\n\\u001b[2m\\u001b[22m\\n\\u001b[2m      \\u001b[2mat Object.toMatchImageSnapshot (\\u001b[2msrc/command/getPageImageShot.js\\u001b[2m:62:25)\\u001b[2m\\u001b[22m\\n'`;
console.log(str.replace(regex, "$1/"));

Thanks to @VLAZ helping solving the issue.


text:
Q: One App Drawing on Another's NSView This will probably come across as a naive question, but is there anyway possible for one application to have access to an NSView object belonging to another application and draw on it (via IPC or otherwise)?

A: Yes. That's exactly what the IOSurface framework is for. A good example of its use is Safari in Lion, which has a rendering process that is separate to the HTML parsing process.
There's a good article about it here.
Note that if your app is in a Sandbox that you can't use IPC to communicate with an app outside your app's sandbox, but you can communicate with helper tools inside the sandbox.


text:
Q: How do I calculate the wholesale price, if I have the retail price and the wholesale markup %? Given that I have the retail price & desired retail markup % of an item, how do I then calculate the wholesale price?
Say the following is true for a cup:
Retail: $100
Desired Markup: 100%
Wholesale: $???
Instinctively I know that the Wholesale price should be $50, because I know that marking up $50 by 100% would give me $100.
But how do I calculate that in a formula, such that I could enter that formula into a 'Wholesale' field in Excel and have it reference the Retail price and the Desired Markup and then get the correct wholesale price?

A: Applying a markup of $n$% to a base amount is the same as multiplying the base amount by
$$\frac{100 + n}{100}$$
To remove the markup, just multiply the marked up amount by
$$\frac{100}{100+n}$$


text:
Q: Select cells and automatically apply the formula to the right of each Thank you guys. Based on responses, and going little deeper I kept my code like this:
Public Function LowHigh(custo As Integer)
    If custo > 10.99 And custo <> 0 Then
        LowHigh = "1.4"
    Else
    If custo < 11 And custo <> 0 Then
        LowHigh = "1.35"
    Else
    If custo <= 0 Then
        LowHigh = "Valor Inválido"
    End If
    End If
    End If

End Function
Public Sub lorh()
ActiveCell.Formula = "=LowHigh(" & ActiveCell.Offset(0, 0).End(xlToLeft).Address & ")"

End Sub

Example image
On selecting the right value in question and press the button, the forfunção LowHigh runs, the problem is that it needs to be done cell by cell, and I need to select the entire range to the left and click the button cells immediately right interval are filled with the formula as shown below:
Final image
I tried something like this:
Public Function LowHigh (cost As Integer)
     If cost> And cost 10.99 <> 0 Then
         LowHigh = "1.4"
     else
     If cost <11 And cost <> 0 Then
         LowHigh = "1:35"
     else
     If cost <= 0 Then
         LowHigh = "Invalid"
     end If
     end If
     end If

end Function
Public Sub lorh ()
Range ("ActiveCell", "ActiveCell"). FormulaR1C1 = "LowHigh = (" & Range (ActiveCell.Offset (0, 0). End (xlToLeft)). & Address ")"

end Sub

but it did not work, can you help me?

A: No offense, but you really need to read any tutorial at all on using if...else because everything is wrong with how you use them. You are inserting if statements inside other if statements instead of saying else if, let me show you.
if something then
    blah
else
    if something else
        blah else
    end if
end if

This is above is what you are doing, this is what you meant
if something then
    blah
else if something else then
    blah else
else if something else again then
    blah else again
end if

The difference should speak for itself with proper indentation (which your code does not have).
Edit: Oh and I forgot the most obvious:
If cost> And cost 10.99 <> 0 Then

This makes absolutely no sense. You are saying `if cost is greater than and (which is an operator) and cost 10.99 <> 0 (which means nothing) then. If statements in VBA are practically really what you would say in plain english:
If cost > 10.99 and cost <> 0 then

I guess this is what you meant, but that would be a bit unnecessary to have that and cost <> 0 part.


text:
Q: Allow uses to adjust the position of their profile pictures I am building a website and want to include the feature that allows users to adjust the position of their profile picture when uploading (which part of the picture gets displayed by the "img" element). LinkedIn, for example, has this feature. I searched about how to implement the feature but did not find anything helpful. The code below is what I have right now: After the user selects a image file, it will be uploaded to firebase storage, then the web page will be re-rendered and the new image will be displayed on the web page. I am wondering whether anyone can give me a clue about how to add the feature to my existing code. Thanks!
Client-side code that lets users upload profile images
    state = {
      image: "",
      edit: false
    }

    componentDidMount() {
      const { profile } = this.props;
      this.setState({
        image: profile.image
      })
    }

......

handleUpload = (e) => {
      e.preventDefault();
      const image = e.target.files[0];
      const { auth } = this.props;
      this.props.uploadImage(image, auth.uid);
  }

  openFiles = (e) => {
      e.preventDefault();
      const input = document.getElementById("imageinput");
      input.click();
  }

......

    render() {

      return (

......

                  <input type="file" id="imageinput" hidden="hidden" onChange={this.handleUpload}></input>
                  <button onClick={this.openFiles}>Upload Profile Image</button>

......

Redux uploadImage action object
export const uploadImage = ( image, userid ) => (dispatch) => {
    firebase.storage().ref('images/'+userid).put(image)
    .then(() => {
        return firebase.storage().ref(`images/`+userid).getDownloadURL()
    })
    .then((image) => {
        firebase.firestore().collection("users").doc(userid).update({
            image: image
        })
    }).then(() => {
        dispatch({ type: EDIT_SUCCESS });
    })
}


text:
Q: TokenMismatchException in compiled.php line 3314: Добрый день возникла данная ошибка после ввода данных в поле на странице регистрации, вот ошибка https://i.stack.imgur.com/oUl5T.png ,  а вот сам код https://i.stack.imgur.com/HdwAj.png буду благодарен вашей помощи в решении данной проблем) Сайт на laravel, версия 5.3.30  Сайт был на сервере, теперь моя задача восстановить работу хотя бы на локальном сервере, мое мнение проблеме в .env

A: Проблема решена, я изменил УРЛЫ в файле .env, где к APP_URL добавил http://localhost и к SESSION_DOMAIN подставил localhost, далее я очистил кэш php artisan config:cache и сделал ключ php artisan key:generate, далее запустил проект php artisan serve


text:
Q: IOSurface gradually increases memory in iOS 12 and above I am facing memory issue in my app for iOS 12 and above versions. IOSurface gradually increases simultaneously in iOS 12.1.1 where as it works fine in iOS 11 versions. I have attached the issue screenshot below,

Why this issue happens in iOS 12 versions? Can someone help me how to solve this? I cross checked in iOS 11 versions and it works fine.

A: Do you use camera ?
It may depends on camera.

Size of IOSurface bock: 8372224 bytes = 1960*1080*4


text:
Q: Pairs of data to Classify[] Suppose I had the following data
a={1,2,3,4,5}

How would I turn this into
b={{1,2,3}->4,{2,3,4}->5}

That is, transforming the data into rules where each class has a definition as the three before it.

A: a = {1, 2, 3, 4, 5};

(Most[#] -> Last[#]) & /@ Partition[a, 4, 1]

{{1, 2, 3} -> 4, {2, 3, 4} -> 5}

A: Try this solution:
ruleTransformer[from___, to_] := {from} -> to
ruleTransformer @@@ Partition[Range[5], 4, 1]

(* {{1, 2, 3} -> 4, {2, 3, 4} -> 5} *)

Partition breaks the data into groups of 4, with start of each group shifted by 1 from the previous.  We then apply the helper function ruleTransformer, which takes a list of arguments from___ to be put into the beginning of the Rule, and a single argument to_ to be put at the end of the rule.
We can accomplish the same thing (with a slight modification) with an anonymous
Function:
Function[# -> Reverse[{##2}]] @@@ Reverse /@ Partition[Range[5], 4, 1]

A: Developer`PartitionMap[Most@# -> Last@# &, a, 4, 1]
(* {{1, 2, 3} -> 4, {2, 3, 4} -> 5} *)

A: ♃ = {#, #[[0]] @@ (# /. #[[0]] -> (1 + {##} &))} &@(#[[;; 3]] -> #[[4]] &@#) &;

♃ @ {1, 2, 3, 4, 5}
(* {{1, 2, 3} -> 4, {2, 3, 4} -> 5} *)


text:
Q: Module 'websockets' has no attribute 'client' I am running, in Jupyter Notebook with Anaconda Navigator, a code in python that uses the "requests_html" library, and this error has occurred:
"AttributeError: module 'websockets' has no attribute 'client'"
I already have installed the websocks-client package, but still occurs.
from requests_html import AsyncHTMLSession
asession = AsyncHTMLSession()

r = await asession.get('https://python.org/')
await r.html.arender(timeout=15)
resp = r.html.raw_html
print(resp)

A: Explicitly importing the 'client' before running my code fixed this issue for me (I did not test code given in original post).
from websockets import client

A: This was patched in the latest version of pyppeteer, make sure you have the latest version.  There is a pull request that hasn't been merged yet to allow support for websockets 10.  If you simply install the latest version of pyppeteer, then you will be left with websockets 9.  I need websockets 10 for other modules so I installed pyppeteer using the following command and this fixed the requests_html error.
pip install -U git+https://github.com/pyppeteer/pyppeteer@dev

A: If nothing else works, try to delete "websocket" folder from "python/site-packages/" folder.
When I did it, my IDE (PyCharm) asked me if I want to install package "websocket", then "websocket-client" and after I clicked "yes" downloaded them automatically.


text: Q: Is the product of a continuously differentiable function with a test function also a test function? I have $\phi(x)\sin(nx)$ where $\phi(x)$ is a test function. Obviously, the product is continuously differentiable, but I don't know if $\phi(x)\sin(nx)$ has a compact support too?