text:
Q: How to use filters in a GridPanel? I'm starting in the path of ExtJS 4 and I need to use the GridPanel's filters feature.
Here's the code for my panel:
var panel = Ext.create("Ext.grid.Panel", {
  renderTo : "main"
, store    : store
, title    : "Users"
, columns  : [ /*...*/ ]
, // ...
// Important line --v
, features : [ { ftype : 'filters' } ]
, // ...
});

As I understood from the example, I need to enable Ext.Loader and so I did. After that, however, ExtJS is trying to load a features/filters.js which I can't find anywhere, I have tried to look for it in the src/ folder but have found nothing.
How am I supposed to make this work?

Update
@nscrob pointed me to the example's FiltersFeature.js file. I have successfully loaded the file, but I still lack the features/filter.js file, the one missing from the start.
--
Thanks guys.

A: you are probably trying to create something like http://dev.sencha.com/deploy/ext-4.0.2a/examples/grid-filtering/grid-filter-local.html, if you check the js code for this example you will see that the filter feature is an user extended component... so you will find the filter component defined in examples/ux/grid/FilterFeatures.js
Edit sep 9 , 6pm
As i said above the problem is that the component you are using is user extended if you check the component defined in the filterfeatures.js you will fin that it needs other files like
        'Ext.ux.grid.menu.ListMenu',
        'Ext.ux.grid.menu.RangeMenu',
        'Ext.ux.grid.filter.BooleanFilter',
        'Ext.ux.grid.filter.DateFilter',
        'Ext.ux.grid.filter.ListFilter',
        'Ext.ux.grid.filter.NumericFilter',
        'Ext.ux.grid.filter.StringFilter'

The file this component needs are all in the example/ux/grid folder

A: I found the solution here:
http://www.sencha.com/forum/showthread.php?140370-Getting-404-error-The-requested-resource-(-EmployeeApp-feature-filters.js)-not-avail&p=626408&viewfull=1#post626408
You can just link statically required files in your index.html
<link rel="stylesheet" type="text/css" href="scripts/ext/examples/ux/grid/css/GridFilters.css" />
<link rel="stylesheet" type="text/css" href="scripts/ext/examples/ux/grid/css/RangeMenu.css" />
<script type="text/javascript" src="scripts/ext/examples/ux/grid/FiltersFeature.js"></script>
<script type="text/javascript" src="scripts/ext/examples/ux/grid/filter/Filter.js"></script>
<script type="text/javascript" src="scripts/ext/examples/ux/grid/filter/StringFilter.js"></script>
<script type="text/javascript" src="scripts/ext/examples/ux/grid/filter/ListFilter.js"></script>
<script type="text/javascript" src="scripts/ext/examples/ux/grid/filter/BooleanFilter.js"></script>
<script type="text/javascript" src="scripts/ext/examples/ux/grid/filter/NumericFilter.js"></script>
<script type="text/javascript" src="scripts/ext/examples/ux/grid/filter/DateFilter.js"></script>
<script type="text/javascript" src="scripts/ext/examples/ux/grid/menu/RangeMenu.js"></script>

A: The reason that ExtJS tries to load ".../features/filter.js" is that the object that it is looking for ("features.filter") is not yet defined. ExtJS guesses this must be in a file called "features/filter.js". However, it is actually defined in "grid/FeaturesFilter.js"
(where "features.filter" is defined as an "alias" to "Ext.ux.grid.FiltersFeature").
Most people who have this problem have read the documentation and are trying to load Ext.ux.grid.FiltersFeature (usually at "ux/grid/FiltersFeature.js") but the timing of the
load is such that it is not loaded when it is needed. Therefore, ExtJS tries to load the
non-existent file.
The key to solving this problem is to ensure that the "Ext.ux.grid.FiltersFeature" is
fully loaded (not just the load initiated) by the time the grid is initializing with
the filters feature.
The sensible (and appropriate) thing is to put the "Ext.ux.grid.FiltersFeature"
in the "requires" of the class extending the grid.
This should ensure that the grid/FiltersFeature.js file is loaded before you need it.
// This should work
Ext.define("FrontSuite.view.MyGrid", {
    extend:  'Ext.grid.Panel',
    xtype:   'mygrid',
    requires: [
        'Ext.ux.grid.FiltersFeature'
    ],
    title:   'My Grid',
    ...
    features: [{
        ftype  : 'filters',
        encode : true
    }],
    columns: [
        { dataIndex: 'id', text: 'ID'},
        { dataIndex: 'name', text: 'Name'}
    ]
}

If for some reason, the file does not load in time,
you can put a (seemingly redundant) requires "Ext.ux.grid.FiltersFeature" in
the Ext.application() call (ExtJS 4+).
Ext.application({
    name: 'MyNamespace',
    extend: 'MyNamespace.Application',
    controllers: ['MyController'],
    autoCreateViewport: true,
    paths: {
        'Ext.ux': 'path/to/my/ext/ux'
    },
    requires: [
        'Ext.ux.grid.FiltersFeature'
    ]
});

IMPORTANT NOTES ON CLASS LOAD TIMING:
Putting the required class in the proper "requires" config for the proper requiring class
is important so that when you do a build and create a minified Javascript file, you get only the bits of the ExtJS library code that are truly needed. However, you should watch the Javascript console for messages that say that ExtJS had to load a file synchronously. If it does this, the "correct" location for a "requires" should be supplemented by a "redundant requires" somewhere earlier, such as in Ext.application() as shown above.

A: I ran into the same problem and finally figured it out. You need put Ext.Loader and Ext.require outside Ext.onReady.
Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', '../ux');
Ext.require([
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.ux.grid.FiltersFeature',
    'Ext.toolbar.Paging'
]);

Ext.onReady(function(){
...YOUR CODE HERE
}

A: If you are getting this error:
features/filters.js is not found

it indicates a loading error is the EXTJS libraries.  Make sure to wrap the call that initializes your grid in the Ext.onReady() function that is shown in the example:
http://dev.sencha.com/deploy/ext-4.0.2a/examples/grid-filtering/grid-filter-local.js

A: Works for me by this way for ExtJs 4.2 - for the error of features/filters.js is not found
Ext.application({
......
requires: [
    'Ext.ux.grid.FiltersFeature',
    ..... more required files ....
]});

A: In the file that runs your Ext.application launch function you need to set a path to your user extensions so the application knows how to load these files which reside outside of your app (or similarly named) folder structure. You do that by setting the Ext.Loader config for path using:
Ext.Loader.setConfig({
    enabled: true,
    paths: {
        'Ext.ux':'ext-4.0.6/ux/' /*This should be the path to your top-level ux dir*/
    }
});

The other answers on this are correct, but your issue is the auto-loader behavior. The directory path to the ux dir should be relative to the .js file calling this function.


text:
Q: Adding words to over 4,000 products, does it have to be done manually? I have a magento store that sells products but in the meta description of every single product I want it to be formatted like this.
Product Name 1
Product Name 2
Product Name 3
Is there any possible way I could add automatically do this instead of manually?
Changing it to:
Sell Product Name 1 Here
Sell Product Name 2 Here
Sell Product Name 3 Here
I want to add words to the beginning and the end automatically of every single listing if possible, if anyone knows a way please let me know. Manually doing this would be a two year job.

A: To expand on pspahn's solution, I would do the following:
Create a one-off PHP script in the magento root folder called 'script.php' (or whatever you want).
<?php
require_once 'app/Mage.php';
Mage::app('default');

$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToSelect('meta_title');

foreach ($products as $product) {
    $product->setMetaTitle('Sell '.$product->getMetaTitle().' Here');
    $product->getResource()->saveAttribute($product, 'meta_title');
}

Then from bash (while current directory is magento root folder), run
php script.php

$product->getResource()->saveAttribute() is MUCH faster then calling save() on the original model, so your script would finish in I would guess about a tenth of the time. Also, I doubt the actual attribute is meta_title, probably description, or meta_description, so change the script accordingly.

A: You can do this with the "Update Attributes" feature of the Magento Catalog grid.

*

*Navigate to Catalog > Manage Products

*Select the products you wish to update with the checkbox, select Update Attributes from the dropdown and then click Submit

*Update meta keywords and click Save

A: You can rewrite block catalog-product-view and add the prefix and posfix for metas in the _prepareLayout method.

A: If your intention is to do this just once (since you want to change all the products to the new meta title) you can use something like the following (haven't tested this, and with thousands of products, it'll probably take a bit to finish):
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToSelect('meta_title');

foreach ($products as $product) {
    $oldMeta = $product->getMetaTitle();
    $newMeta = "Buy " . $oldMeta . " Supplements Online"
    $product->setMetaTitle($newMeta);
    $product->save();
}

You could run this from your own module, as an external script, whatever you want.  I've actually run some things like this just from whatever template I happen to have open. You're running it once and then getting rid of it.
Note that there are some spots if you place this code it will run multiple times for a single page load. Leaving you with something like "Buy Buy My Product Supplements Online Supplements Online". Make sure it is run just once.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use trigger to prevent delete on table and update instead? I would like to implement soft-delete in mysql using trigger and doing an update instead of delete. Then I found out that mysql doesn't have instead-of-Triggers.
So I would like to use a Before-Trigger but I couldn't find any way to abort the delete without throwing an error.
I'm looking for something like this:
use testdb;
DELIMITER $$
CREATE TRIGGER `table1_before_delete` BEFORE DELETE ON `table1`
FOR EACH ROW
BEGIN
    call abort_delete_and_dont_raise_error();
    UPDATE table1 SET deleted_at=NOW() where id=old.id;
END$$
DELIMITER ;

I couldn't find anything like this.

A: You can't abort the delete in Mysql without throwing an error. You shouldn't use the trigger of before delete to implement soft-delete mechanism. This is a wrong way. You should implement soft-delete mechanism in your application.


text:
Q: conda installed some package but still ModuleNotFoundError when import this package I've found the solution:anaconda - graphviz - can't import after installation
I want to use graphviz and follow the commend in https://anaconda.org/anaconda/graphviz
run following in terminal
conda install -c anaconda graphviz
However no matter in Jupyter Notebook, python or Pycharm to import graphviz, it always shows
ModuleNotFoundError: No module named 'graphviz'
How to solve this problem? Thank you.
PS:

*

*when run which python in terminal: it return /opt/anaconda3/bin/python, therefore I use anaconda environment by default. And I have only one environment in anaconda that is root.

*when I run conda list in terminal, I can find this line :
graphviz                  2.40.1               hefbbd9a_2

*I found a weird thing:

my pip and conda use the same environment:
run :which pip
get : /opt/anaconda3/bin/pip
run : which conda
get : /opt/anaconda3/bin/conda
However when I run pip list, I cannot find graphviz and many other packages which shows in conda list. For these packages show in conda list but not in pip list, I also cannot import them no matter in Jupyter notebook, python, pycharm etc. Why this happens?

A: After using "conda install attrs", other package installations are working fine without any http connection or ModuleNotFoundError errors. Please try and let me know.


text:
Q: How to copy or import database from mongolab.com to my local mongodb server? I have used some queries for import and export database from mongolab.com to my local mongodb server. Can you please anyone tell me, how to retrieve all data from mongolab.com (clouddb) to local mongodb server.
I have trying these codes in my local mongodb server with command line prompt:
mongodump -h ds040032.mongolab.com:40032 -d mydb -u "<"myname">" -p "<"mypass">" -o "<"D:\2016\LearnMongoDB\NEWDB">"

mongoexport -h ds040032.mongolab.com:40032 -d mydb -c "<"collectionname">" -u "<"myname">" -p "<"mypass">" -o "<"D:\2016\LearnMongoDB\Testingf">"

mongorestore -h ds040032.mongolab.com:40032 -d mydb -u "<"myname">" -p "<"mypass">" "<"input db directory">"

After entering, I am not getting any results with the commandline prompt. Getting Still cursor loading symbol.

A: try db.copyDatabase
    db.copyDatabase('from_mydb','to_mydb','ds040032.mongolab.com:40032',
'<myname>','<mypassword>')

Go to local mongo shell and apply above command with appropriate parameters.

A: In 2017, db.copyDatabase (using shell) works, but the format has changed a bit:
db.copyDatabase('mlab_databse_name', 'local_folder_for_data_name', 'ds000000.mlab.com:00000', 'database_user_name', 'database_user_password')


text:
Q: 100 point moving average filter on MATLAB I need to create a 100 point moving average filter on MATLAB and then convolute it with data to make a graph. How am I supposed to make the filter and keep it at the same length as the data that I need to plot?
I need the filter to cover 686 data points.


text:
Q: Excel: comparing names in two different sheets I have two excel sheets with about 500 rows each. Worksheet A has a name column E) and worksheet B has two name columns for small and large names(H&I). I want to create a loop that goes through and compares these columns and should it find a match paste this match onto a new worksheet.
Further clarification:
On worksheet B the two name columns are akin to Cigna and Cigna Co for example so they are not always the same name repeated, and on Worksheet A the name may be Cigna, so they are not always exact though. But the name of Worksheet A must match 1 or both names on Worksheet B.

A: Something like this is an easy loop and record, then see if anything from the first sheet is on the second.
Not sure what your small and large names situation is, so I checked both columns
In you VBA IDE go to the tools menu and selecte references. Select "Microstoft ActiveX data objects 2.8 Library.  This will be used for the recordset.
Private Sub CommandButton1_Click()
    Dim rs As New ADODB.Recordset
    Dim ws As Excel.Worksheet
    Dim ws2 As Excel.Worksheet
    Dim lRow As Long
    Dim lRowOut As Long

    Set ws = ActiveWorkbook.Sheets("Sheet1")
    ws.Activate

    Set ws2 = ActiveWorkbook.Sheets("Sheet3")

    'Add fields to your recordset for storing data.
    With rs
        .Fields.Append "Row", adInteger
        .Fields.Append "Name", adChar, 25
        .Open
    End With

    'Loop through and record the name
    lRow = 1
    Do While lRow <= ws.UsedRange.Rows.count

        rs.AddNew
        rs.Fields("Row").Value = lRow
        rs.Fields("Name").Value = ws.Range("E" & lRow).Value
        rs.Update

        lRow = lRow + 1
        ws.Range("A" & lRow).Activate
    Loop

    If rs.EOF = False Then
        rs.MoveFirst
    End If

    'Switch to the second worksheet
    Set ws = Nothing
    Set ws = ActiveWorkbook.Sheets("Sheet2")
    ws.Activate

    'Loop through and see if anything on this sheet was on the first sheet.
    lRow = 1
    lRowOut = 1
    Do While lRow <= ws.UsedRange.Rows.count

        'Check if the column H name was recorded from the first sheet
        rs.Filter = ""
        rs.Filter = "Name='" & ws.Range("H" & lRow).Value & "'"
        If rs.RecordCount = 0 Then
            rs.Filter = ""
            rs.Filter = "Name='" & ws.Range("I" & lRow).Value & "'"
            If rs.RecordCount > 0 Then
                'It has a date, delete the current row
                ws2.Range("A" & lRowOut).Value = rs.Fields("Name").Value
                lRowOut = lRowOut + 1
            End If
        ElseIf rs.RecordCount > 0 Then
            'It has a date, delete the current row
            ws2.Range("A" & lRowOut).Value = rs.Fields("Name").Value
            lRowOut = lRowOut + 1
        End If

        lRow = lRow + 1
        ws.Range("A" & lRow).Activate
    Loop
End Sub

If you want to look for a part of the name as you say in your comment, you can use a like.  Change the filter lines to something like this.
rs.Filter = "Name LIKE '%" & ws.Range("I" & lRow).Value & "%'"

A: Doing this with formulas, instead of VBA, I would stick a formula in A1 of your new workbook like the following. Assuming that your "Worksheet A" is in Book1 on Sheet1 and your H and I columns from "Worksheet B" are Book2 on Sheet1:
=if(countif([Book2]Sheet1!H:I, [Book1]Sheet1!E1)>1, [Book1]Sheet1!A1, "")

This says "If, in my columns H and I in Sheet1 of Book2 there is at last one match on the name from Cell E1 in Sheet1 of Book1, then grab the name from Cell E1 on Sheet1 of Book1"
This will leave a good number of blanks, but at that point you can just filter or sort them out.
If the requirements are more complicated than that, like any match across any of three columns, then you can just add the results of multiple CountIf() formulas and test them for > 1, or do a single Countif() for each column and then union the results, sort/filter, and Bob's your uncle.
If this is going to be something you do often, then it may be worth investing in  the VBA route as that will take the little bit of manual work out of it.


text:
Q: Is there a graph with these properties?3 Is there a way to make a graph with these properties:
$i)$ $17$ vertices so that every vertex has a degree of $3$ and
$ii)$ $27$ vertices split into two columns where the first column has $10$ vertices each of them with a degree of $3$ and the second column has $17$ vertices each of them with a degree of $2$.

A: Well, the sum of degrees is two times the number of edges. So it has to be even and the answer to (i) should be immediate.
In the second case, I assume that the graph is meant to to be bipartite. Then the sum of degrees of vertices on the left should equal the sum of degrees of vertices on the right...


text:
Q: VBA select onclick if condition is met
 align = "center" onmouseover = "this.style.cursor='pointer';" onclick = "__doPostBack('ctl01$PortalContent$GridOrderControl1$CILGridViewOrder','Select$0')">
new
Text2
Text3
Text4
Text5

Hi, I need help for the above. What I want:
1) check if first row is new and "text 4" didn't appear before
2) if the above condition is met, click/select on the onclick
3) Select$0 is the first row in the table, there are 10 rows in total, I want to check all rows then click and do something else when the conditions are met
So far i am able to pinpoint the text out, however i cant call this onclick event, any idea on how to do it?
What I have so far
Set Data = IE.Document.getElementsByTagName("tbody")(6).getElementsByTagName("tr")
x = 1
y = 1

For Each eleCollection in Data
  If Instr(1, eleCollection.innerHTML, "Select$0") >0 Then
    For Each ele in eleCollection.getElementsByTagName("td")
       ws.Cells(x,y).Value = ele.innerText
       y = y + 1
       x = x + 1
    Next
  End If
Next elemCollection


text:
Q: Is $f(t,\beta ,\mu , \theta )= e^{\theta(t-\mu)^{\beta}}$ a well known distribution on the unit interval? $\newcommand{\erf}{\operatorname{erf}}$
I have tried out to define a new  distribution lie in [0,1] using my special function which is montioned in this paper, The new special function is defined as:
$$I(a)=\int_{0}^{a}{(e^{-x²})}^{\erf(x)}dx, \tag{01}$$ take $t=\erf(x)$ then $x=\erf^{-1}(t)$ such that $ dx=\dfrac{\sqrt{\pi}}{2}e^{(\erf^{-1}(t))^2 }dt$ by substitution in $\int_{0}^{a}{(e^{-x²})}^{\erf(x)}dx$ yield to get : $$\dfrac{\sqrt{\pi}}{2}\int_{0}^{b}{(e^{(\erf^{-1}(t))^2-t(\erf^{-1}(t))^2})}dt, \tag{02}$$ using this approximation for small $t$ we have :$\erf^{-1}(t) \sim t\dfrac{\sqrt{\pi}}{2}$ , Replace this approixmation gives the following :$$\dfrac{\sqrt{\pi}}{2}\int_{0}^{b}{e^{\dfrac{\pi}{4}(t^2-t^3)}}dt .\tag{03}$$
Now for the latter equality I want to define a new distribution since we are now in [0,1], because the precedent variable change $t$ vary from $0$ to $1$ because $ \erf^{-1}(\infty)=1 $, Then let us define a Unit distribution with $3$ parametre : $\beta$ and $\mu$ and $\theta $ such that:
$$ f(t,\beta ,\mu , \theta )=e^{\theta(t-\mu)^{\beta}} \text{and} f(t,\beta ,\mu , \theta )=0,  \text{for}: t >1 \tag{04}$$ , Now my question here is this a known distribution and if it is what is it ?
Edit: I have edited parameters for generalisation to be clear

A: The distribution seems to be close to a truncated form of the generalized Gaussian distribution which has the same formula (except it has support on entire $\mathbb{R}$ and some parameters are in a different place, for instance  $\theta = -1/\alpha^\beta$ )
$$f(x) \propto e^{-(\vert x-\mu \vert /\alpha)^\beta} $$

One difference is that the function uses the absolute value of $x-\mu $. But , this might be necessary for your distribution as well. In the cases $\mu>0$ and $\beta \notin \mathbb{Z}$ then you the term $(x-\mu)^\beta$ is a non-integer power of a negative number which is problematic. So I guess that your distribution should use the restriction $\mu<0$ in which case the difference with the absolute sign is not relevant.

A: $f$, in your formulation, is not a probability density function as it does not integrate to 1 on the interval $t\in(0,1)$ for all values of the parameters. You would need to normalize it, but then the expression would not be that nice as it will depend on the parameters through some special functions (actually the cdf of the Generalized Normal distribution).
One alternative is to use the logit transformation applied to the Generalized Normal distribution, which leads to
$$f(t;\alpha,\beta,\mu) = {\frac {\beta }{2\alpha \Gamma (1/\beta )}} \frac{1}{t(1-t)}\;e^\left\{-\left(\left\vert\mbox{logit}(t)-\mu \right\vert/\alpha \right)^{\beta }\right\}, $$
$t\in(0,1)$, $\mu\in{\mathbb R}$, $\alpha,\beta>0$.
You can call it the Generalized Logit-Normal distribution, which generalizes the logit normal distribution:
https://en.wikipedia.org/wiki/Logit-normal_distribution


text:
Q: Is it possible to have 2 different classes in a SparseArray? I am currently using a SparseArray and want to have data from 2 different classes in them, is this a possibility?

A: You can make like this.
interface FruitInterface { /* common methods */ }
public class Apple implements FruitInterface { }
public class Pear implements FruitInterface { }

SparseArray<FruitInterface> fruits = new SparseArray<FruitInterface>();

Or you can make like this.
SparseArray<Object> fruits = new SparseArray<Object>();

and then check
if (fruits.get(0) instanceof Apple) {
} else if (fruits.get(0) instanceof Pear) {
}


text:
Q: Explanation of this abstract algebra permutations problem For $m \geq 2$, let $\alpha = (a_0 a_1 \dots a_{m-1}) \in Perm(S_n)$ and
$\beta = (a_ 0 a_{m-1})\cdots (a_0 a_1) = \prod_{i=0}^{m-2} (a_0 a_{(m-1) - i}) \in Perm(S_n)$.
Show that $\alpha = \beta$. Hint: clearly, $\alpha (x) = \beta(x) = x$ for all $x \not \in \{ a_0,a_1,\dots, a_{m-1} \}$. Thus, we must show that $\alpha (x) = \beta (x)$ for every $x \in \{ a_0, a_1, \dots, a_{m-1} \}$. Split this into three cases: $x =a_0$; $x = a_{m-1}$; and $x \in \{ a_1, \dots, a_{m-2} \}$.
Can someone help me out with this problem? Not sure what approach to take.

A: Since $a_1$ only appears in the rightmost transposition, we see that
$$
\beta\colon a_0\mapsto a_1
$$
Similarly $\beta\colon a_{m-1}\mapsto a_0$.
What about $a_i$, with $0<i<m-1$? We have
$$
(a_0a_i)\colon a_i\mapsto a_0
$$
and
$$
(a_0a_{i+1})\colon a_0\mapsto a_{i+1}
$$
so $\beta\colon a_i\mapsto a_{i+1}$, because no other transposition acts on $a_{i+1}$.


text:
Q: vscode with Node 8 - inspect-brk error I've recently upgraded my vscode and now I get this error when I try to run the service:
D:\herokuworkspace\server/node_modules/.bin/babel-node.CMD --inspect-brk=27776 src\index.js

D:\Program Files\nodejs\node.exe: bad option: --inspect-brk=27776

This is my configuration:
{
            "type": "node",
            "request": "launch",
            "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/babel-node",
            "name": "Launch Program",
            "program": "${workspaceFolder}/src/index.js",
            "cwd": "${workspaceRoot}",
            "internalConsoleOptions": "openOnSessionStart"
        }

Please advise what should I change in the configuration in order to make it work again.

A: Your title says Node 8, but it looks like you are using an older version of Node that doesn't support the --inspect-brk flag. You can upgrade to a version after Node 7.6, or you can set the old debug args in your launch config like this (added port and runtimeArgs):
{
    "type": "node",
    "request": "launch",
    "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/babel-node",
    "runtimeArgs": [ "--inspect=1234", "--debug-brk" ],
    "port": 1234,
    "name": "Launch Program",
    "program": "${workspaceFolder}/src/index.js",
    "cwd": "${workspaceRoot}",
    "internalConsoleOptions": "openOnSessionStart"
}


text:
Q: HTML JS assembling array name works fine but then prints as a "string" rather than the actual job I am doing a bit of prelim coding for a game with robots.
I have written a short program in JavaScript to track turns and player in the game.
I can update the turns, return whose turn it is no problem.
I want to use arrays to hold info about players. I'm learning at the moment so for now I'm using an array with only 2 elements.
The names are player1_data, player2_data, etc. I want to find out the content of array element 0, so it becomes player1_data[0], which is fine.
If I type this in all is fine and I get my element returned to me.
However, if I assemble the array info, by going "player" + current_player + "_data[" + element +"]" then it looks fine, but simply doesn't not function.
It just a string of characters, not the actual array element request that I get if I type it in manually!
What is the problem?
<!DOCTYPE HTML>

    <button class="button" onclick="vardisplay(), updateturn() ">SHOW VARIABLES</button>

false

2

2

2

2

2

2

2

A:
I want to use arrays to hold info about players. Im learning at the moment so for now I'm using an array with only 2 elements. The names are player1_data, player2_data etc.

Don't do this.  Instead of grouping similarly named variables whose relationship is based on naming conventions, group values using the collections provided by the language.
var player_data_for_all_players = [player1_data, player2_data];

will allow you to do
player_data_for_all_players[player_index][array_selector]

or
var player_data_by_name = {
  'dave': current_robot,
  ...
};

which allows you to identify players using a (unique) value that is more self-explanatory in a debugging console.

A: You need an array of array. Like this :
var players_data = [];
players_data[1] = ["dave",current_robot];
players_data[2] = ["kim",current_robot];
players_data[3] = ["nigel",current_robot];
players_data[4] = ["bob",current_robot];

Now if you want to display the information for the second player, you just have to do this :
var name = players_data[2][0]

But it should be better to use an array of object to have a more "readable" code :
var players_data = [];
players_data[1] = {
    name : 'dave',
    robot : current_robot
};

// Access to the name of the first player
var name = players_data[1].name


text:
Q: In a social network environment, what would be the easiest way to check for friendships globally? For reference, here is a question on SO that I asked recently that is relevant to this question:  How to model Friendship relationships
On that question, we figured out a way to display news feed items only if posted by friends.  However, what I need is advice on how to check for friendship in a more dynamic way so it can be used throughout several site functions.
For example, I've just installed a comment system, allowing users to post comments on news posts.  However, this isn't restricted to friends, and it should be (and later should be made optional by the author of the post).
Posting news items only by friends was slightly different because I was getting data directly from the database, and using SELECT subqueries to only get posts by friends of the current user.  However, in the example of the commenting, I only want to display the comment post form if the person is a friend.  I'm not actually pulling anything from the database to pick, sort, and display.
Knowing issues like this will arise many times throughout the site, what would be the simplest way to check for friendship?  Could I somehow pull all the friends' user IDs from the database into a session array of some kind and then do an if(in_array($friends)) whenever I needed to determine if the person in question is a friend of the currently logged in user?  Off the top of my head, this sounds like it would work fine, but I'd like your input first.
The question I linked to above explains how my friendship table works, in case that help you help me with this.

A: Actually, it is a very bad idea to stor the friend array in the session. What happens if some you add a new friend after the session variable is created? It does not get updated in the session.
Since you will be checking the list of friends a lot of times on the same page, why not just query it out and store it in a local array that you can keep using on the same page.
When the page finish executing, the array will be discarded.
So basically, you will only query the list out once.
A recommended implementation would be to follow the advise of "pst" in the above comment, and just query for every time you need to find the relationship first, as that is simple to implement. Later, when the speed of the query starts to become a issue, you can just change the internal of that method to cache the friend list in a local array when it is first called to speed things up. (exchange memory usage for processor usage).


text:
Q: How to control spacing in formulas inside a table? I have the following table:
\documentclass[12pt, twoside]{report}
\usepackage[a4paper,width=150mm, top=25mm, bottom=25mm, bindingoffset=6mm]{geometry}
\usepackage[backend=biber,style=numeric,hyperref=true]{biblatex}
\usepackage{tabularx}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{makecell}
\usepackage{multicol}
\usepackage{multirow}
\usepackage{amsmath}
\raggedbottom

\begin{document}
\bgroup
\def\arraystretch{1.5}
\begin{table}[!ht]
    \caption{Definition of $mapToReference()$}
    \label{tab:op_map_read_to_reference}
    {\begin{tabular}{l|p{12cm}}
    \toprule
    Inputs & \hangindent=1em$M_{raw} = \{m_i: m_i = (header, payload)\}$ where $m.payload = r = (s\_id, r\_id, b, q, f_p)$ as in. \\
    \cline{2-2}
    Operation & $mapToReference(r, ref\_id)$\\
    \cline{2-2}
    \multirow{2}{*}{Outputs} & \hangindent=1em$M_{aln} = \{m_i: m_i = (header, r)\} \text{ where } r = (s\_id, ref\_id, r\_id, b, q, f_p, rname, pos, mapq, cigar, flags)$\\
    & \hangindent=1em $M_{unaln} = \{m_i: m_i = (header, r)\} \text{  where } r = (s\_id, r\_id, b, q, f_p, unmapped=true)$\\
    \bottomrule
    \end{tabular}}
\end{table}
\egroup
\end{document}

This is generating an ugly looking table where the formulas, especially in the Output section are stretched out. I'm wondering what the best way is to control the layout of these cells. I don't want arbitrary horizontal spacing, and I want to be able to introduce line breaks wherever I want.
Thanks.

A: Some suggestions:

*

*Use explicit math italics, rather than ordinary math mode, to typeset variable names; in the code below, this is achieved via the \vn ("variable name") macro.

*Use explicit line breaks.

*Use fewer pairs of curly braces: Many of them do absolutely nothing except create code clutter.

\documentclass[12pt, twoside]{report}
\usepackage[a4paper,width=150mm, vmargin=25mm,
            bindingoffset=6mm]{geometry}
\usepackage{array,booktabs,ragged2e,amsmath}
\raggedbottom
\newcommand\vn[1]{\mathit{#1}}

\begin{document}

\begin{table}[!ht]
\def\arraystretch{1.25}
    \caption{Definition of $\vn{mapToReference}()$}
    \label{tab:op_map_read_to_reference}
    \centering
    \begin{tabular}{@{}l>{\RaggedRight}p{12cm}@{}}
    \toprule
    Inputs & $\vn{M_{raw}} = \{m_i: m_i = (\vn{header}, \vn{payload})\}$ where \\
    & \qquad $\vn{m.payload} = r = (s\_id, r\_id, b, q, f_p)$ as in. \\
    \cmidrule(l){2-2}
    Operation & $\vn{mapToReference}(r, \vn{ref\_id})$\\
    \cmidrule(l){2-2}
    Outputs & $\vn{M_{aln}} = \{m_i: m_i = (\vn{header}, r)\}$,
    where \\
    & \qquad $r = (s\_id, \vn{ref}\_id, r\_id, b, q, f_p,
    \vn{rname}, \vn{pos}, \vn{mapq}, \vn{cigar}, \vn{flags})$\\
    & $\vn{M_{unaln}} = \{m_i: m_i = (\vn{header}, r)\}$, where \\
    & \qquad $r = (s\_id, r\_id, b, q, f_p, \vn{unmapped=true})$\\
    \bottomrule
    \end{tabular}
\end{table}

\end{document}


text:
Q: Office Add-in - This app isn't supported by the version of exchange server that your account connects to
*

*I have Exchange on-premises server with version 2013

*I wrote an Office add-on which I can install in Office365 account with manifest file with out any issues

*But, when I try to install the same add-on from my Exchange 2013 OWA > Settings > Manage Add-ins/Apps it says

This app isn't supported by the version of exchange server that your
  account connects to

Searching for this issue showing that the issue might be with the requirement set we use in the manifest. But, I used the same requirement set 1.1 which should support Exchange 2013 as mentioned in the docs.
What else should be done to enable Office add-on in my Exchange 2013?
Any advice/guidance would be greatly appreciated.

A: @user3752326, I'm glad updating to the latest Exchange 2013 CU solved your installation problem.
The reason why your add-in is not showing up in the side bar is because Exchange 2013 does not support Add-In Commands. Only Exchange 2016 or Office365 support Add-In Commands. Exchange 2013 supports legacy add-ins, which show up in the body of the message, as you have it in your screenshot.


text:
Q: Deezer audio player after Sept 1 when Chrome start blocking Flash? From the 1st Sept Chrome will start blocking Flash based ads by default:
https://plus.google.com/+GoogleAds/posts/2PmwKinJ7nj
With Flash on its way out does Deezer have a pure HTML5 based web player in the works and is it possible to start testing it yet?

A: We have a fallback on a HTML5 player for now, but it is not built in order to play full tracks. You can test if you want.Also, this problem will occur only for ads.


text:
Q: Scala - Overloading method in implicit class I currently have an issue where I am trying to overload a method contained within quill using an implicit class, normally this is possible with the simple case, i.e. if you have something like
class Test {
  def rawr(string: String): String = string
}

You can easily overload this definition of rawr using a different type like so
implicit final class RawrExt(val t: Test) {
  def rawr(int: Int): Int = int
}

And this compiles as expected, i.e.
val t = new Test
t.rawr(5)

Even if Test has more complex type parameters, this still works, i.e.
class Test[T <: Number] {
  def rawr(string: String): String = string
}

implicit final class RawrExt[N <: Number](val t: Test[N]) {
  def rawr(int: Int): Int = int
}

val t = new Test[BigDecimal]
t.rawr(5)

Where I am getting a problem is when I am trying to implement the exact same overloading for the quill-monix-jdbc's transaction. When using monix-quill-jdbc, you have a transaction method that has the following signature
def transaction[A](f: Task[A]): Task[A]

The issue is that we are using TaskResult in our application logic which is Monad Transformer of Either and Task using cats, i.e.
type TaskResult[T] = EitherT[Task, GeneralError, T]

What I am trying to do is to provide an override for transaction which takes TaskResult rather than Task, defining this in an implicit class is quite straight forward
object TaskResultSupport {
  implicit final class TaskResultCtxSupport[Dialect <: SqlIdiom, Naming <: NamingStrategy](
      val value: MonixJdbcContext[Dialect, Naming]) {

    def transaction[A](f: TaskResult[A]): TaskResult[A] =
      EitherT(value.transaction(f.value))
  }
}

And then when we try to use it we get a compilation error, it can't seem to pick up the implicit class.
val ctx: PostgresMonixJdbcContext[SnakeCase] =
  new PostgresMonixJdbcContext(SnakeCase, "database")

val taskResult: TaskResult[Unit] = TaskResult(())

ctx.transaction(taskResult) // This doesn't compile

I tried all various permutations of defining the implicit class, i.e. as an example
implicit final class TaskResultCtxSupport(val value: MonixJdbcContext[_, _]) extends AnyVal

And none seem to work. Here is the compilation error
type mismatch;
 found   : Playground.this.Implicits.TaskResult[Unit]
    (which expands to)  cats.data.EitherT[monix.eval.Task,Playground.this.GeneralError,Unit]
 required: monix.eval.Task[?]

A scastie demonstrating the problem can be found here https://scastie.scala-lang.org/pqAn8fUPTbmBqToCVIXDXA. Thanks to Martjin Hoekstra, there is a further minimized example here https://scastie.scala-lang.org/4YrhP0HSRzu7F9numrqAGQ. Scala contributors thread can be found here https://contributors.scala-lang.org/t/scala-compiler-unable-to-overload-methods-with-type-parameters/3761

A: Turns out this was a bug with the current Scala compiler, a solution is slated for 2.13. See https://github.com/scala/scala/pull/7396 for more details.


text:
Q: NgFor only supports binding to Iterables such as Arrays Buenos días, soy nuevo en Angular2 y tengo ciertos problemas con el uso de los Observables y componentes
ERROR a solucionar

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

Tengo un servicio REST que me devuelve un JSON con cierta información,Desde el componente que he creado, llamo a dicho servicio:
Componente.ts
    ngOnInit() {
    this.getSystems();
  }

  getSystems(): void {
    this.systemService.getSystems()
    .subscribe(systems => this.systems = systems);
  }

El problema es que no trato con un Array de información, sino con un objeto, por lo que no puedo usar el comando *ngfor
Componente.html

        {{system.systemId}}
        {{system.host}}
        {{system.password}}
        {{system.port}}
        {{system.rfcDest}}
        {{system.userId}}
        {{system.version}}

Según he leído, la solución sería crear un @Pipe pero no tengo claro como funciona. ¿Alguién podría aclararmelo?
JSON
{
    "test":
    [
        {
            "host": "h265",
            "messagingSystemID": "1",
            "password": "xxx,
            "port": "50000",
            "rfcDest": "testDes",
            "systemID": "PPO",
            "userId": "TestUser",
            "version": "7.5"
        },
        {
            "host": "h455",
            "messagingSystemID": "2",
            "password": "xxx",
            "port": "50000",
            "rfcDest": "testDes2",
            "systemID": "PPO",
            "userId": "TestUser",
            "version": "7.5"
        }
    ]
}

Respuesta esperada
Mi intención es imprimi dichos sistemas en formato texto, tabla, o de cualquier manera posible. Pero todos ellos.
Service - Opción 1
Esta es la primera solución que intenté realizar
   /** GET systems from the server */
  getSystems (): Observable<System[]> {
    var data = this.http.get<System[]>(this.systemsUrl);
    console.log('getSystems service');
    console.log(data);
    return data;
  }

Error mostrado

Service - Solución 2
También he probado a realizar la llamada del servicio de la siguiente manera:
   getSystems(): Observable<System[]> {
       let url = 'http://10.8.0.2:50000/integration.experts~web~mappingtesttool/rest/systems';
        console.log(url);
        return this.http.get(url)
          .map(this.extractData);
  }

    private extractData(res: Response) {
      let body = res.json();
      console.log("extraData");
      return body || { }; // here
    }

Error mostrado

¿Alguno podría decirme en que estoy fallando? Me es indiferente usar la opción 1 o opción 2 del servicio. Saludos

A: Prueba a hacer este cambio:
getSystems(): Observable<System[]> {
   let url = 'http://localhost:50000/...';
    console.log(url);
    return this.http.get(url)
      .map(this.extractData);
}

private extractData(res: Response) {
  let body = res.json();
  console.log("extraData: ");
  if (body && body.test) {
    body=body.test;
  }
  return body || []; // devolvemos un array vacio si la respuesta no tiene un array
}

Explicación: La respuesta es un objeto de la forma
{
  "test": [ ... ]
}

Pero tú quieres el array de systems que viene dentro y que es iterable, no el objeto que lo contiene.

Ten cuidado con las diferencias de Angular 2 y Angular 4 con los HTTP

A: si te devuelve un objeto , normalmente te da error por que son procesos Asincronos cuando muestras el valor muestra que no existe, lo que debes hacer es lo siguiente:

    {{system?.systemId}}
    {{system?.host}}
    {{system?.password}}
    {{system?.port}}
    {{system?.rfcDest}}
    {{system?.userId}}
    {{system?.version}}

puedes verificar mas en la respuesta en ingles

Una variacion de la respuesta de @Pablo Lozano


text:
Q: Building an array of non-sequential variables I have a dataset with ~6000 variables, which are in 82 groups. The variable names are all in the form "a001yr, a001sta, a001tot... a082tot" (in other words, "acyclenumsetsuffix"). Is there a way to cleanly pick out all the numeric variations of one particular set, (e.g. a001yr, a002yr, ... a082yr) to build an array? Or am I stuck writing out the full set of variables by hand?
(I'm using SAS 9.2)

A: Your description is still kinda of vague, what rules to define 'one particular set'? For your example, you could try the following:
 proc sql;
  select name into :varname separated by ' ' from dictionary.columns
where libNAME='WORK' and upcase(memname)='TEST' AND PRXMATCH('/a\d+yr/io',name) > 0 and type='num';
quit;

The code uses PRX functions (which I believe they are available for 9.2) to pick out those variable names from 'WORK' library, 'TEST' table, that are start with 'a', then bunch of numbers, and end with 'yr' and also numeric, then put them into a macro variable varname, so you can use it in your downstream data step code, such as:
data want;
 set test;
 array tst &varname;
 blah blah;
 run;


text:
Q: Agregar Publicidad Admob en app con Android Studio estoy intentando implementar publicidad a una aplicación pero no aparece cuando agrego el id que me da ADMOB y eso que seguí los pasos tal y como están en la pagina
https://developers.google.com/admob/android/quick-start
solo me aparece el banner pero con el id de prueba de ADMOB , por favor ayuda, llevo buscando alguna solución por un largo tiempo y nada...

A: Inicializa AdMob en la actividad principal
    MobileAds.initialize(thisActivity, "xx-xxx-pub-0000000000000000/0000000000"); //
    adView = findViewById(R.id.adView);
    AdRequest adReuest = new AdRequest.Builder().build();
    adView.loadAd(adReuest);

Pero recuerda que también lo tienes que cambiar en AndroidManifest.xml
    <meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="xx-xxx-pub-0000000000000000/0000000000"/>


text:
Q: Static Fix and Audio Mic Recognition So I didn't find any forums for the product, hopefully anyone here can help.
I recently bought this new headset, the Etekcity H5GX Gaming Headset, link is below, and despite the reviews that say they get no static when using the mic, when I record in Audacity or Audition, there is static. When I try to use the mic on Skype, it doesn't even recognize it. I think there may be something wrong within my settings or sound card, or perhaps I changed something within the sound manager panel that I wasn't supposed to change.
Here are my specs:
Windows 10
Description: Speakers (Realtek High Definition Audio)
Default Sound Playback: Yes
Default Voice Playback: Yes
Hardware ID: HDAUDIO\FUNC_01&VEN_10EC&DEV_0269&SUBSYS_17AAC034&REV_1002
Manufacturer ID: 1
Product ID: 100
Type: WDM
Driver Name: RTKVHD64.sys
Driver Version: 6.00.0001.7535 (English)
Driver Attributes: Final Retail
WHQL Logo'd: Yes
Date and Size: 6/24/2015 21:57:00, 4504320 bytes
Driver Provider: Realtek Semiconductor Corp.
HW Accel Level: Basic
Cap Flags: 0xF1F
Min/Max Sample Rate: 100, 200000
http://www.amazon.com/gp/product/B012EQG6ZK?refRID=6QZ33FWHEA2WGD2RX61X&ref_=pd_cart_vw_2_1_p

A: What do you mean by "static"--is it continuous background noise, or is it an intermittent clicking, or more just a distortion of your voice, like choppiness or rapid cutting in/out?
IMHO the first order of business is to get the mic working in Skype, so you can run some tests.  Skype is pretty finicky, so getting it to work there will be a key step.  Go to Skype>Tools>Options>Audio settings.  Click the little blue triangle on the right side of the window, right next to the Speakers selector.  See if that works right.
Then, look up to the Microphone pick list just above it.  You should have at least two options, try them all.  See if the volume indicator shows anything when you talk into the mic.  See if the volume indicator shows the noise you are hearing.
Go to the Control Panel for audio devices.  Depending on the brand of PC, there may be more than one control system for audio (e.g., Beats audio).  You'll have to do some experimentation because each of these proprietary thingies is  different, but buried in those control panels somewhere is the item you want to click.
If you are offered a "bit rate" or other quality indicator, choose "CD Quality" or "44kHz" or "44100" but nothing higher.  That audio quality setting can definitely confuse some apps, even if the hardware can handle it.  If there's a selector for buffer size, choose the largest size on the list.
Sorry I can't be more specific, but there are too many proprietary variables to give you a simple answer.


text:
Q: How to input values automatically in arrays (C++)? so I'm stuck on this little thing that has been causing lots of problems for me. Let's say I have interval of 2 numbers [x,y]. I manually input the values of x and y. The thing is I want to make an array ranging from x to y. For example if x = 1 and y = 5, array would be [1,2,3,4,5].
Here's the code that is supposed to do what I just described:
` for (t=0;t<y;t++){
  for (x=x;x<y;x++){
   q[t] == x;
   cout <<q[t];
  }
}`

Instead it out prints 4259904. Thanks in advance.

A: Hey try out the following code :
cin>>x;
cin>>y;
int a;
if(x>y)
{
  numberofelements=x-y+1;
  a=y;
}
else
{
numberofelements=y-x+1;
a=x;
}
int array1[numberofelements];
for(int i=0;i<numberofelements;i++,a++)
 array1[i]=a;

let me know if it works


text:
Q: Convert integer to array of UInt8 units I have number - 94887253 (in ASCII), it can be represented like:
let data = [UInt8]([0x39, 0x34, 0x38, 0x38, 0x37, 0x32, 0x35, 0x33])
How to write a function that convert number to such array of UInt8 units? Thanks.

A: I would use shifts.
var array: [UInt8] = []
var n = theInputNumber
while n > 0
{
    array.append(UInt8(n & 0xff))
    n >>= 8
}

This is type safe and endian independent (the array is little endian but is easy to reverse) but slower than using an unsafe pointer.
EDIT
Right, so the question wasn't clear. If you want the ASCII represenatation of the number, the easy way is to turn it into a string and take the UTF-8
Array("\(theInputNumber)".utf8)

Or if you need to roll your own, modify my first answer
var array: [UInt8] = []
var n = theInputNumber
while n != 0
{
    array.append(UInt8(n % 10) + 0x30)
    n /= 10
}

The array is in reverse order, but I'll let you figure out how to get it the right way around.
Also will need modification for negative numbers.

A: It seems that what you are looking for is an array with the ASCII
codes of the (decimal) string representation of the number:
let x = 94887253
let a = Array(String(x).utf8)

print(a == [0x39, 0x34, 0x38, 0x38, 0x37, 0x32, 0x35, 0x33]) // true

A: If you want to get an ASCII codes of the decimal String representation of a number, you can write your own function for it like this:
func getAsciiCodesOfDigits(_ n: Int)->[UInt8]{
    return String(n).unicodeScalars.map{UInt8($0.value)}
}

getAsciiCodesOfDigits(numberToConvert)

Above function works, since using an Int as an input ensures that each element of String(n).unicodeScalars will be an ASCII character and hence it can be represented as a UInt8 and for ASCII characters, UnicodeScalar.value returns the ASCII code in a decimal form.


text:
Q: Output and Input at Same Line using IOSTREAM I want to use the iostream input and output operators in the same statement, not to be nicer to the user but the look I was trying not successfully obtained.
Code fragment:
int value = 0;
std::cout << "Number 1: " << std::cin >> value << std::endl;

Is there any way to do this using only cin cout?

A: struct IO {
    template <typename T>
    const IO & operator << (const T & t) const {
        std :: cout << t;
        return *this;
    }

    template <typename T>
    const IO & operator >> (T & t) const {
        std :: cin >> t;
        return *this;
    }
};

IO () << "Number 1: " >> value;

A: a bit messy but I think this is what you wanted
std::cout<<"Data : "<<val<<std::endl<<(std::cin>>val)<<"\r"<<"\t\r\n"<<std::flush;

A: std::cout << "Number 1: ";
std::cin >> value;

Should do the trick.


text:
Q: Amarok 1.4 script: knowing who's running you I've been using Amarok 1.4 for a long time, switching to Bogdan Butnaru's packages when KDE stopped supporting it, and I'm now giving Pana a try.
I realised that a script I wrote in Python for Amarok 1.4 will not immediately run without changes under Pana. But instead of converting my script, which basically comes down to replacing "amarok" with "pana" in the paths I use, I'd rather make it compatible with both the original Amarok 1.4 and Pana, so that I could be able to distribute only a single version of that script (and possibly modifying it later if other forks become popular).
So, is there a (Python(ic)) way for my script, running from within the player, to find out which program launched it?

A: import os

pid = os.getppid()
with open("/proc/%s/cmdline" % pid) as f:
    print f.readline()

Assuming you are running Linux. Not sure if you need getppid() or getpid() here.
Not so pythonic maybe.


text:
Q: Ubuntu Boots, But stays on shell! I have a Dell Optiplex 160L and I'm booting Ubuntu 13.04 from a LinuxLiveKey USB. It loads all the way through the purple Ubuntu loading screen then goes back to shell. then it gets stuck on

ubuntu@ubuntu:~$

Also could it be a problem that I'm using a 1 GB USB?
Is there a reason why it doesn't boot? Or is my hardware to crappy for it?


text:
Q: Рулетка на js html Есть рулетка, как сделать так, чтобы оно корректно останавливалось? Все перепробовал что знаю, не получилось.

Config:

<img src="data:image/jpeg;base64,[encoded data, 10752 characters]" style="display: block; float: left;">

<button id="go" onclick="play()">Go</button>


text:
Q: bootstrap confirm modal box in select item not work I have this code for show confirm delete message before send form data:
$('input[name="submit"]').on('click', function (e) {
    var $form = $(this).closest('form');
    var checked = $("input:checked").length;
    var action = $('select[name="todo"]');

    if (action.val() === "delete" && checked) {

        e.preventDefault();
        $('#confirm').modal({
            backdrop: 'static',
            keyboard: false
        })
            .one('click', '#delete', function (e) {
            $form.trigger('submit');
        });
    }
});

When I try this, it does not work.  After clicking delete in the modal box, the form is not sent/submitted.   How can I fix this?
DEMO

 $('input[name="submit"]').on('click', function(e) {
   var $form = $(this).closest('form');
   var checked = $("input:checked").length;
   var action = $('select[name="todo"]');

   if (action.val() === "delete" && checked) {

     e.preventDefault();
     $('#confirm').modal({
         backdrop: 'static',
         keyboard: false
       })
       .one('click', '#delete', function(e) {
         $form.trigger('submit');
       });
   }
 });

  <form method="POST" role="form" action="#">

        <select name="todo" class="contentgroup">
          <option value="">choose</option>
          <option value="delete">delete</option>
          <option value="mark">mark</option>
          <option value="unmark">unmark</option>
        </select>
        <input type="hidden" name="csrf_token" value="MTQzNjU3MDc3NjZPNXFKUmZWVlJWcE9ZNnd4VUZFbmRiSzMzSTZwMzRD">
        <input type="submit" value="ok" class="btn btn-primary btn-sm" name="submit" />

<input type="checkbox" name="selected[]" class="check" value="4" />
</form>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

delete

        message

        <button type="button" data-dismiss="modal" class="btn btn-danger btn-sm" id="delete">delete</button>
        <button type="button" data-dismiss="modal" class="btn btn-sm">back</button>


text:
Q: Chart.js set time xAxes I'm trying to set xAxes in charset.js from 00:00 to 23:59 with an interval of 15 minutes.And set yAxes from 0 to 16
But it shows up to me every hour and not until 23:59 only until 00:00.
Thanks !
my ts :
   let options = {
      responsive: false,
      scales: {
        xAxes: [{
          type: 'time',
          time: {

            displayFormats: {
              'minute': 'HH:mm',
              'hour': 'HH:mm'
            }
          }
        }],
        yAxes: [{
          type: 'time',
          time: {
            displayFormats: {
              hour: 'HH mm',
              bounds: 'ticks',
            }
          }
        }]
      },
    };

    Chart.Bar(ctx, {
    /*  data: data,*/
      options: options,
    });

data is not set yet.
Thanks.


text:
Q: Why does some of my columns in my HTML table display cells as undefined while other columns display correctly? See screenshot:

I couldn't figure out why some of the cells are undefined even though they have similar data types to some of the cells that are displaying values correctly? What can I try to make them display properly?
The code should take the list of dictionaries and populate the tables with them. I am fairly new to javascript and web development. I usually work in backend with SQL and python.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

        date &#9650
        exposed (mn) &#9650
        displaced (k) &#9650
        killed &#9650
        duration(days) &#9650
        cause &#9650
        Country Name &#9650
        ISO code &#9650

Time Range:  -

A: Change object key names or how you access them
Let us take one of the objects from your array, let's say index 9. It looks like this:
[9] = {
  'Country Name': "Nepal",
  'ISO code': "NPL",
  'cause': "Heavy rain",
  'date': "6/11/2003",
  'displaced (k)': 9500000,
  'duration(days)': 121,
  'exposed': 16822143,
  'killed': 600
};

Do you see some of those columns have spaces and/or brackets?  (k) or (days) is part of the key name.
You have two options here:

*

*You must use exactly those key names. So ${data[i]['duration(days)']}	 and ${data[i]['displaced (k)']}	 with all spaces and case sensitive name, for example

*You could replace  (k) and (days) and names with spaces to key names, which are easier to access

Any solution is valid here. I prefer when I can type the key name with just letters, but that is up to you.


text:
Q: Missing Reference to Navigation Controller in Monotouch I am new to Monotouch and attempting to understand how some of the basics hang together. Hopefully someone out there will be able to assist.
I've created a test project in MonoDevelop based on the Multi-Screened Apps tutorial on the Xamarin site and have extended it to include a tableView. I am having issues with referencing the Navigation Controller in a view that I need to push a detail view onto to display the detail of an item tapped in the table via an accessory button. I know some of the coding is scrappy, just been trying to get it working at this stage rather than the clarity in the code! (I'm using the latest versions of all Mono tools/libraries etc and XCode 4 on Lion). Starting at the beginning here's the code in FinishedLaunching in AppDelegate.
window = new UIWindow (UIScreen.MainScreen.Bounds);
this.rootNavigationController = new UINavigationController();
// Create a new homescreen
HomeScreen homeScreen = new HomeScreen();
// Add the homescreen to the root navigation controller
this.rootNavigationController.PushViewController(homeScreen, false);
// Set the root view controller on the window - the navigation controller
// will handle the rest.
this.window.RootViewController = this.rootNavigationController;
// make the window visible
this.window.MakeKeyAndVisible ();

homeScreen just contains a button which loads a new view containing a table view (OrderList). Here's the button event handler.
void HandleOrdersButtonhandleTouchUpInside (object sender, EventArgs e)
{
    if (orderListScreen == null)
        orderListScreen = new OrderList();
    NavigationController.PushViewController(orderListScreen, true);
}

This all works fine. I've got some dummy data that loads into the table view, which also works fine. OrderData is a simple class for testing which just contains a couple of properties. I've added an AccessoryButton to the cells and am trying to load a detail view when this is tapped. Here's the code that does this - comment in code where issue is! (I'd previously tested the AccessoryButtonTapped functionilty was working by just displaying an alert).
public override void AccessoryButtonTapped (UITableView tableView, NSIndexPath indexPath)
{
    var dataSource = (OrdersTableViewDataSource)tableView.DataSource;
    if (detailScreen == null)
        detailScreen = new OrderDetailScreen();
    OrderData theOrder = dataSource.OrdersData[indexPath.Row];
    detailScreen.currentOrder = theOrder;

    // Cant get a reference to NavigationController here to push the detail view!
    // this.NavigationController is not available
    this.NavigationController.PushViewController(detailScreen, true);
}

My understanding of NavigationControllers from what I've read so far is that this reference should be available through all views that originate from the root ViewController/NavigationController without the need to pass the reference from AppDelegate through the various view constructors?
Can anyone tell me what I might be missing here?
Thanks in advance.
** An update after reviewing Jason's comment: (Please let me know if this is the incorrect way to post updates)
So, I tried the following:
I saved a reference to the NavigationController in the constructor for the ViewController that contains the table view as follows:
public partial class OrderList : UIViewController
{
    UINavigationController navController;

    public OrderList () : base ("OrderList", null)
    {
        this.Title = "Orders";
        navController = this.NavigationController;
    }

Then passed that into the TableViewDelegate, where the AccessoryButtonTapped is handled, in the ViewDidLoad method.
public override void ViewDidLoad ()
{
    orderTableView.DataSource = new OrdersTableViewDataSource();
    orderTableView.Delegate = new OrdersTableViewDelegate(navController);

    base.ViewDidLoad ();
}

Then referenced that in the TableViewDelegate:
public class OrdersTableViewDelegate : UITableViewDelegate
{
    UINavigationController navController;

    public OrdersTableViewDelegate(UINavigationController controller)
    {
        navController = controller;
    }

    // Rest of class definition
}

Then the reference to the NavigationController using navController compiles with the code as previously described using the following in the AccessoryButtonTapped method:
navController.PushViewController(detailScreen, true);

When I run this and tap on the AccessoryButton I get a null reference exception on navController. The reference to this.NavigationController in the ViewController constructor is null. Am I doing something in the wrong place or sequence?
Cheers

A: The NavigationController property is on your table's view controller.  If you are trying to reference it from your table's datasource, you need to pass a reference to the controller when you create the datasource.


text:
Q: Notification if a modal dialog is shown on top of a JFrame What listener should I register in a JFrame instance to be notified if a modal JDialog is shown on top of the frame (the frame is the owner of the dialog)? Thanks in advance.

A: I think JFrame.addWindowListener(...) would work and then pay attention to WindowListener.windowDeactivated(...)
ETA:
jFrame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowDeactivated(WindowEvent e) {
            if(e.getOppositeWindow() instanceof JDialog) {
                JDialog dialog = (JDialog) e.getOppositeWindow();
                if(dialog.isModal()) {
                    // do stuff
                }
            }
        }
    });


text:
Q: How to cross join two tables in sql So I need to cross join 2 tables but I cannot find a way to do so without receiving the error

ORA-01427: single-row subquery returns more than one row ORA-06512: at "SYS.DBMS_SQL", line 1721

Here is my code I am using but I am unaware where my error is coming from, I am new to sql so any help is appreciated:
INSERT INTO Valid_Safety (Area, Course_ID, Course_Name, Personnel_Number, ESA_Name, Section_Leader, Valid, Expire_Date)

Select Safety_Map.Area,
       Course_ID,
       Course_Name,
       _ESA.Personnel_Number,
       _ESA.ESA_Name,
       _ESA.Section_Leader,
    (Select
    COUNT(*) Valid
     From
    SAP_Data
    Where Personnel_Number = TX3_ESA.Personnel_Number
    AND Duplicate1 = 'Valid'
    AND Course_Num = Safety_Map.Course_Num) As Valid,

     (Select
     Expire_Date
     From
      SAP_Data
    Where Personnel_Number = _ESA.Personnel_Number
    AND Duplicate1 = 'Valid'
    AND Course_Num = Safety_Map.Course_Num) As Expire_Date

From Safety_Map CROSS JOIN _ESA;

A: (Select
Expire_Date
From
SAP_Data
Where Personnel_Number = _ESA.Personnel_Number
AND Duplicate1 = 'Valid'
AND Course_Num = Safety_Map.Course_Num)
Is returning more than one rows. If you just need top one then you can use rownum or fetch first 10 rows only
Select Safety_Map.Area,
       Course_ID,
       Course_Name,
       _ESA.Personnel_Number,
       _ESA.ESA_Name,
       _ESA.Section_Leader,
    (Select
    COUNT(*) Valid
     From
    SAP_Data
    Where Personnel_Number = TX3_ESA.Personnel_Number
    AND Duplicate1 = 'Valid'
    AND Course_Num = Safety_Map.Course_Num) As Valid,

     (Select
     Expire_Date
     From
      SAP_Data
    Where Personnel_Number = _ESA.Personnel_Number
    AND Duplicate1 = 'Valid'
    AND Course_Num = Safety_Map.Course_Num
    and rownum=1 ) As Expire_Date

From Safety_Map CROSS JOIN _ESA;

or you can use aggregation (max() or min()):
(Select
     max(Expire_Date)
     From
      SAP_Data
    Where Personnel_Number = _ESA.Personnel_Number
    AND Duplicate1 = 'Valid'
    AND Course_Num = Safety_Map.Course_Num
    and rownum=1 ) As Expire_Date

A: well , seems like subquery for Expire_Date , returns more than one row :
so the solution can be vary depends on the logic but here is one way :
...
    (
        Select max(Expire_Date)
        From SAP_Data
        Where Personnel_Number = _ESA.Personnel_Number
        AND Duplicate1 = 'Valid'
        AND Course_Num = Safety_Map.Course_Num
    ) As Expire_Date
From Safety_Map CROSS JOIN _ESA;


text:
Q: Express cors get origin = 'null' with type string Express CORS is failing for my nodejs application and I need your help fixing it. The reason is that the app is getting null with type string as origin, which is not in my list of whitelisted domain. If I whitelist null, it works but I am not sure it should be that way. The problem occurs in both dev (Windows) and prod (Ubuntu+nginx) mode.
Here is my CORS config:
{
  origin: function (origin, callback) {
    //console.log(typeof origin)
    if (whitelist.indexOf(origin) !== -1 || !origin) {
      return callback(null, true)
    } else {
      logger.warn('origin ' + origin + ' is not whitelisted')
      return callback(new Error('Not allowed by CORS'), false)
    }
  }
}

The problem goes away if I add set the Access-Control-Allow-Origin header like the following but that seems to defeat the purpose of CORS.
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
  res.header('Access-Control-Allow-Headers', 'Content-Type')

One thing to mention, I never had such issue when developing NodeJS API. This project has an integrated view engine. I don't know whether it is related or not.

Thank you in advance

A: Your corsConfig should look something like this;
{
origin: (origin, callback) => {
    if (!origin || origin === 'null') return callback(null, true);
    if (originsURL.indexOf(origin) === -1) {
        logger.warn('origin ' + origin + ' is not whitelisted')
        return callback(new Error('Not allowed by CORS'), false);
    }
    return callback(null, true);
    }
}

*

*If the origin is null or undefined, it should return the callback.

*If the origin is not within the allowed origins, callback returns an error.

*else return the callback.


text:
Q: HTML Form to XML and LocalStorage I'm doing a simple html form and I'd like to be able to save the output that I type in onto the Local Storage of my website.
Is there any way of converting the inputs from a HTML Form using raw Javascript or PHP onto an internal XML on the Local Storage in my browser?

A: It seems that you just want to be able to save data in the form and recover it from localStorage when you need to.
You're going to want to use JavaScript and go through your form inputs and then save them respectively to the localStorage object.
For example if I had an element:
<input type="text" id="fname" name="fname">

I could save the content to the localStorage object by doing
localStorage.setItem("fname", document.getElementById("fname").value);

I could then retrieve the content and put it back in by doing
document.getElementById("fname").value = localStorage.getItem("fname");

Hope this helps


text:
Q: Authorize ShinyApps In Rstudio I am trying to authorize my shinyapps account on my Rstudio console, but when I run the setAccountInfo() , i get the following error
 Failed to connect to api.shinyapps.io port 443: Connection refused

I am under a proxy connection in my college.although i have run the following code to work under proxy and it used to work for installing packages from github etc. but to authorize its still not working
library(httr)
set_config(
use_proxy(url="10.3.100.207", port=8080)
)

i have even enabled internet2. but all the attempts are futile. any help ?

A: If you're running behind a proxy server, you'll want to configure the shinyapps package to use your proxy server. Checkout the docs in ?shinyapps::shinyappsProxies for more information, but in short you'll likely want to do:
Sys.setenv(http_proxy = "http://username:password@proxy.example.com:8080")

It can be helpful to put this command in your .Rprofile so its runs everytime you launch R.


text:
Q: Why can't static member functions be constant? I went through the already existing thread on this topic and wasn't convinced with the explanation.
What I could pick up from there was:
When a non-static member function is declared const, the restriction is imposed on this this pointer. As static member functions donot involve the this pointer, they cannot be declared const.
Is that it? Doesn't sound too convincing to me. I mean, I'm not questioning why it's so. I just want to to the reason why.

A: A const non-static member function is allowed to modify local, static, and global variables; it just isn't allowed to modify members of its class through the this pointer (implicitly or explicitly). A const static member function, therefore, would be allowed to modify local, static, and global variables, just like a non-member function. This would make the const meaningless.
If you want to write a function that isn't allowed to modify any non-local variables at all, you can declare it constexpr, although that also imposes additional restrictions.

A: The reason the const/non-const distinction for functions is important is that there are contexts in which it is not legal to call a non-const function. So the distinction can be used to enforce invariants.
For example, if you pass a non-const reference to a function, if your class is properly designed, you are guaranteed that the function can't change the value of the thing the reference refers to. This allows you to avoid copies.
Also, a non-const reference can't bind to a temporary. This permits functions to signal whether they return values through references or just take a value. You will get an error at compile time if you inadvertently ignore a returned value because a temporary was created unexpectedly.
None of this would apply to static functions because there is no context in which you would be prohibited from calling them. So the entire rationale for the distinction does not exist with static functions.


text:
Q: Building a DOS-feel script. How to make the command line? I always had the idea to make a textarea based program, that gets the last line and uses it as a command. So it looks like some cool DOS-like program.. But in fact is simple textarea -> AJAX -> PHP -> textarea again. Textarea based version works great, but has alot of drawbacks. Mostly related to not getting the right command and possible vulnerabilities to the script.
So, my idea is to use a output container and command line totally separately. I found a good example of what I want, but I cannot figure out, how it is actually made. The main idea is that the hole thing feels like one block of text and you can highlight it:

But you actually cant delete the prompt (c:>) or the already outputted text above.. Since the command line is an actual input.
I don't understand, how this effect is being achieved. You can see the above examples source code, it is basically:

    c:\>
    <input type="text" name="actual_commandline" value="" />

And the JavaScript behind it is: http://pastebin.com/pjbd9Y7k
How can I merge the spans line with the input, so it works like one line, but you cannot manipulate the span#prompt or span#blinker contents?
It is very hard to find any help on www for such localized problems. I can see some CSS in the example-link above..however my knowledge of CSS tells me, that it has nothing to do with that layout.
Also, I drew out exactly what I'm thinking to do, as it is very hard to explain these types of technical questions:

*

*Red = General wrapper, not much function

*Blue = Prompt area, very static

*Green = Writing area, expands its width when typing, pushing the blinker more to the right

*Purple = Blinker container, simple gif animation that looks like this:
Note: I'm not actually ripping-off that example site, but well only that command-line layout. Any hint, link code or idea is welcome. It can be totally alternative, but should achieve the goal, thanks :)
Edit: The question got solved thanks to Joe. However, since the original idea might interest somebody in the future.. I will include a small picture, of what my script looks like. Maybe this inspires some of you someday :)

A: What he's doing is hiding a textbox off-screen. The actual command line is just an element styled to have 1 line's worth of height. When you click this command line, the textbox takes focus.
The C:\> and _ sandwich the textarea, so your text appears in between, thus increasing the width on the command line element as you type, and pushing the _ to the right, giving the illusion that it moved on its own.
http://jsfiddle.net/YeR3L/1/


text:
Q: Python - Calculate Hierarchical clustering of word2vec vectors and plot the results as a dendrogram I've generated a 100D word2vec model using my domain text corpus, merging common phrases, for example (good bye => good_bye). Then I've extracted 1000 vectors of desired words.
So I have a 1000 numpy.array like so:
[[-0.050378,0.855622,1.107467,0.456601,...[100 dimensions],
 [-0.040378,0.755622,1.107467,0.456601,...[100 dimensions],
 ...
 ...[1000 Vectors]
]

And words array like so:
["hello","hi","bye","good_bye"...1000]

I have ran K-Means on my data, and the results I got made sense:
X = np.array(words_vectors)
kmeans = KMeans(n_clusters=20, random_state=0).fit(X)
for idx,l in enumerate(kmeans.labels_):
    print(l,words[idx])

--- Output ---
0 hello
0 hi
1 bye
1 good_bye

0 = greeting 1 = farewell
However, some words made me think that hierarchical clustering is more suitable for the task. I've tried using AgglomerativeClustering, Unfortunately ... for this Python nobee, things got complicated and I got lost.
How can I cluster my vectors, so the output would be a dendrogram, more or less, like the one found on this wiki page?

A: I had the same problem till now!
After finding always your post after searching it online (keyword = hierarchy clustering on word2vec).
I had to give you a perhaps valid solution.
sentences = ['hi', 'hello', 'hi hello', 'goodbye', 'bye', 'goodbye bye']
sentences_split = [s.lower().split(' ') for s in sentences]

import gensim
model = gensim.models.Word2Vec(sentences_split, min_count=2)

from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage

l = linkage(model.wv.syn0, method='complete', metric='seuclidean')

# calculate full dendrogram
plt.figure(figsize=(25, 10))
plt.title('Hierarchical Clustering Dendrogram')
plt.ylabel('word')
plt.xlabel('distance')

dendrogram(
    l,
    leaf_rotation=90.,  # rotates the x axis labels
    leaf_font_size=16.,  # font size for the x axis labels
    orientation='left',
    leaf_label_func=lambda v: str(model.wv.index2word[v])
)
plt.show()


text:
Q: Ruby- accessing elements multidimensional array could you anyone help me with the logic to change/organize log entries
input_array = [
  ["2/6/2014", "13:31:12", "IN", "application1", "user1", "machine1"]
  ["2/6/2014", "13:31:12", "IN", "application2", "user2", "machine2"]
  ["2/6/2014", "13:31:52", "IN", "application3", "user3", "machine3"]
  ["2/6/2014", "13:38:37", "OUT", "application1", "user1", "machine1"]
  ["2/6/2014", "14:46:37", "OUT", "application2", "user2", "machine2"]
  ["2/6/2014", "15:56:37", "OUT", "application3", "user3", "machine3"]
]

How to access individual elements within this array .. such as 2/6/2014 or application1?
when I do input_array[1][4], the desired output is ...
"application1" # and not 6 ... its giving me the 4 character in line 1

appreciate your help!

A: Your proposed code has an error, if you actually defined your array like this:
input_array = [
    ["2/6/2014", "13:31:12", "IN", "application1", "user1", "machine1"],
      ["2/6/2014", "13:31:12", "IN", "application2", "user2", "machine2"],
      ["2/6/2014", "13:31:52", "IN", "application3", "user3", "machine3"],
      ["2/6/2014", "13:38:37", "OUT", "application1", "user1", "machine1"],
      ["2/6/2014", "14:46:37", "OUT", "application2", "user2", "machine2"],
      ["2/6/2014", "15:56:37", "OUT", "application3", "user3", "machine3"]
    ]

You would then be able to access your array like this:
2.0.0p195 :054 > input_array[0][0]
 => "2/6/2014"

A: Perhaps you mean this:
input_line = [
  ["2/6/2014", "13:31:12", "IN", "application1", "user1", "machine1"],
  ["2/6/2014", "13:31:12", "IN", "application2", "user2", "machine2"],
  ["2/6/2014", "13:31:52", "IN", "application3", "user3", "machine3"],
  ["2/6/2014", "13:38:37", "OUT", "application1", "user1", "machine1"],
  ["2/6/2014", "14:46:37", "OUT", "application2", "user2", "machine2"],
  ["2/6/2014", "15:56:37", "OUT", "application3", "user3", "machine3"]]

?
You can then use the syntax input_array[i][j] without issues!


text:
Q: Enum with associated value I have an Enum with operators different operators.
enum OperatorsTypes
    {
        Zero, Division, Equal, If, Minus, Multiplication, One, Plus, RandomNumber, Time
    };

Each operator have different contacts count. For instance Plus - 2 contacts count, Random number - zero.
What is the base way to store and use contacts counts assotiated with opetators.
I considered 3 options:
1) Using array with index ewual to OperatorsTypes and value = contacts count.
2) Using following declaration:
enum OperatorsTypes
    {
        Zero = 0, Division = 12, Equal = 21, If = 32, Minus = 42, Multiplication = 52, One = 60, Plus = 72, RandomNumber = 81, Time = 90,
    };

where first digit is Id number and second - contacts count. Then using % operator in some static method i can find operator's contacts count from OperatorsTypes value.
3) Using switch in some static method
But all this approach has drawbacks... (note - that my code must be top speed).
Is there better way for this task in C++ both beatifull and top-speed?

A: one way to do what you want is inline template functions:
template <OperatorsTypes o>
inline int GetOperatorContacts();

template<>
inline int GetOperatorContacts<Zero>() {return 0;}

template<>
inline int GetOperatorContacts<Minus>() {return 2;}

//...ect

In C++11, you could even make these constexpr, but I don't have a ton of experience with that.
However, this is probably an X vs Y problem. I'd be guessing you want a heck of a lot more information than just the number of contacts, and that a structure or a class is a better fit than an enum.


text:
Q: Maple : polynomial in two variables I have a polynomial f(x,y) with rational coefficients.  I want to rigorously verify that f(x,y) >= 0 for 0 <= x <= 1 and 0 <= y <= 1.
How can I do it (using Maple or otherwise)?
EDIT:  The degree-12 example I had could be written as a sum of 23 terms of the form $x^i(1-x)^jy^k(1-x)^l$ with positive coefficients. I'd be interested in knowing whether a proof like that is always possible and if there is an algorithm or canned Maple code for carrying it out. I used linear programming, which was a pain.


text:
Q: Max sum path in 2D array + double two values to achieve better score I have a 2d array and I need to find the max sum path that can be collected by left bottom and going only top and right until reach an end. I have done it on Java (task very similar to Project Euler: Problem 81):
static int maxSumPath(int[][] data) {
    final int length = data.length;

    final int[][] sumArr = new int[length][length];

    for (int row = length - 1; row >= 0; row--) {
        for (int col = 0; col < length; col++) {
            if (row == length - 1 && col == 0) {
                sumArr[row][col] = data[row][col];
            } else if (row == length - 1) {
                sumArr[row][col] = sumArr[row][col - 1] + data[row][col];
            } else if (col == 0) {
                sumArr[row][col] = sumArr[row + 1][col] + data[row][col];
            } else {
                sumArr[row][col] = Math.max(sumArr[row][col - 1], sumArr[row + 1][col]) + data[row][col];
            }
        }
    }
    return sumArr[0][length - 1];
}

Example

3, 0, 2
2, 0, 0
0, 3, 0

Result 7.
But now I need to implement opportunity to double any value of that array to achieve better score and I can do it only twice and double certain value only once.
Example (in this matrix numbers with * must be doubled)

3*, 0, 2
2*, 0, 0
0*, 3, 0

Result 12.

A: You can solve this by adding a third dimension to your 2-D array, with exactly three layers:
final int[][][] sumArr = new int[3][length][length]

*

*Layer zero represents the best sum you can get without doubling any elements

*Layer one represents the best sum you can get with doubling only one number

*Layer two represents the best sum you can get with doubling two numbers

The algorithm is a simple extension of what you already have, except now you need to set three partial sums in each branch of your if condition.
Here is your code modified according to the above:
static int maxSumPath(int[][] data) {
    final int length = data.length;
    final int[][][] sumArr = new int[3][length][length];
    for (int row = length - 1; row >= 0; row--) {
        for (int col = 0; col < length; col++) {
            int val = data[row][col];
            int val2 = data[row][col] * 2;
            if (row == length - 1 && col == 0) {
                sumArr[0][row][col] = val;
                sumArr[1][row][col] = val2;
            } else if (row == length - 1) {
                sumArr[0][row][col] = sumArr[0][row][col - 1] + val;
                sumArr[1][row][col] = Math.max(
                    sumArr[1][row][col - 1] + val
                ,   sumArr[0][row][col - 1] + val2
                );
                sumArr[2][row][col] = Math.max(
                    sumArr[1][row][col - 1] + val2
                ,   sumArr[2][row][col - 1] + val
                );
            } else if (col == 0) {
                sumArr[0][row][col] = sumArr[0][row + 1][col] + val;
                sumArr[1][row][col] = Math.max(
                    sumArr[0][row + 1][col] + val2
                ,   sumArr[1][row + 1][col] + val
                );
                sumArr[2][row][col] = Math.max(
                    sumArr[1][row + 1][col] + val2
                ,   sumArr[2][row + 1][col] + val
                );
            } else {
                sumArr[0][row][col] = Math.max(
                    sumArr[0][row][col - 1], sumArr[0][row + 1][col]
                ) + data[row][col];
                sumArr[1][row][col] = Math.max(
                    Math.max(sumArr[0][row][col - 1], sumArr[0][row + 1][col]) + val2
                ,   Math.max(sumArr[1][row][col - 1], sumArr[1][row + 1][col]) + val
                );
                sumArr[2][row][col] = Math.max(
                    Math.max(sumArr[1][row][col - 1], sumArr[1][row + 1][col])+val2
                ,   Math.max(sumArr[2][row][col - 1], sumArr[2][row + 1][col])+val
                );
            }
        }
    }
    return sumArr[2][0][length - 1];
}

Demo


text:
Q: IOS / Swift2 - List all files in remote directory I have a server running nginx. I have a directory in my server where I have several audio files. I replaced my real url by "url".
How can I list all files in that directory in a table.
When I print weContent I get:
403 Forbidden
override func viewDidLoad() {
    super.viewDidLoad()
    let url = NSURL(string: "url")!
    //self.webView.loadRequest(NSURLRequest(URL: url))

    let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in

        // Will happen when task completes
        if let urlContent = data {
            let webContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)
            print(webContent)
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.webView.loadHTMLString(String(webContent!), baseURL: nil)
            })
        } else {
            // Show error message
        }
    }
    task.resume()
}

Thank you

A: A 403 error usually means that the user or group doesn't have permission to access to the resource you are requesting.
You should try changing the permissions on the directory you are trying to access to: o+r or change the owner of the directory to the appropriate user. (I generally use apache servers, the user is www)
Nginx provides it's own documentation on 403 errors here


text:
Q: PHP How to convert strings from DomCrawler to UTF-8 I have some data I collect with DomCrawler and store in an array, but it looks like he fails when it comes to special characters like è,à,ï,etc.
As an example I get è instead of è when I echo the result.
When I store my results in a .json file I get this: \u00c3\u00a8
My goal is to save the special character in the .json file.
I've tried encoding it but doesn't seem to have the result I want.
$html = file_get_contents($url);
$crawler = new Crawler($html);

$h1 = $crawler->filter('h1');
$title = $h1->text();
$title = mb_convert_encoding($title, "HTML-ENTITIES", "UTF-8");

Is there anyway I can have my special characters shown?
Thanks a lot!

A: By using the constructor to add the HTML, the crawler assume that it is in ISO-8859-1. You have to explicitly tell it that your DOM is in UTF-8 with the addHTMLContent method:
$html = file_get_contents($url);
$crawler = new Crawler;
$crawler->addHTMLContent($html, 'UTF-8');


text:
Q: Unity WebGL rendering When running WebGl app on PC browser, there is a rendering problem. Blurry image above the red line and also shadows disappearing above line
Anybody knows what i'm doing wrong?
Thanks

A: Solved blurry image problem by increasing aniso level in texture import settings


text:
Q: Compass Create Options I've installed Compass via Ruby Gems. When I create a new project it creates:

*

*config.rb

*/sass

*/stylesheet

Is it possible to use my existing directories? For example I am using a PHP Framework, that has a /css directory, and ideally I'd like to use that.
Thanks

A: Read the Compass Configuration Reference:
You can change the default CSS directory by changing this in config.rb:
css_dir = "css"


text:
Q: For loop to select a column in Scala I want to achieve the below in scala for a spark dataframe,

*

*For each column, select colname and flag variable ( 0 or 1)

*find mean of column when flag = 0 and then when flag = 1

*std dev of the column

I am not sure how to loop through columns and select each column and flag variable each iteration of the loop. What I tried is :-
 for (a <- colnames) {
      val dat1 = data.filter($"cust_flag".isin("1")).select(a)
      val dat0 = data.filter($"cust_flag".isin("0")).select(a)
      val m0 = dat1.select(avg(a)).asInstanceOf[Double]
      val m1 = dat0.select(avg(a)).asInstanceOf[Float]
      val stdev = data.agg(stddev(a)).asInstanceOf[Float]
      val rpb = ((m1 - m0) / stdev)*p*q
      println(rpb)

Now I am getting an error - Exception in thread "main" java.lang.ClassCastException: org.apache.spark.sql.Dataset cannot be cast to java.lang.Float

A: To create a column with a given name from a string, a simple way is to use:
import org.apache.spark.sql.{functions => sf}

df.select(sf.col(colName))

You can combine this in control logic (your loop) as you see fit.
If you want to know what columns are in the dataframe, use df.columns.

A: We have direct function for mean() and  stddev()
Create two filter data set
ie.
1 for flag =0 and
 2 for flag =1 and
dfcol0= df.filter(df("colname") === "0")
dfcol1= df.filter(df("colname") === "1")

Now using stddev() and mean() function get what is required .
 dfcol0.select(stddev("coname")).show(false)
 dfcol0.select(mean("coname")).show(false)

A: As I understand, you are  trying to get average of each columns according to flag and Standard Deviation of each column irrespective of flag. After it you are applying formula and calculating rpb.
On the basis of same logic, I have taken sample data and written code without loop. It will be faster than the loop logic you are using. Spark does not good with loop logic so try to get all required data into one row (such as avg0, avg1 and StdDev in below example) and after it process horizontally or in batch.

Please note, as I commented above. I didn't understand the value of p
  and q so I have ignored it in final Output dataframe logic. You can
  add directly if these are variables declared before.

scala> import org.apache.spark.sql.types._
scala> val df = Seq(
     |   ("121",  "442",  "512","1"),
     |   ("134",  "434",  "752","0"),
     |   ("423",  "312",  "124","1"),
     |     ("432",  "677",  "752","0"),
     |   ("332",  "424",  "111","1")).
     |   toDF("col1","col2","col3","cust_flag").
     |   withColumn("col1", $"col1".cast(DoubleType)).
     |   withColumn("col2", $"col2".cast(DoubleType)).
     |   withColumn("col3", $"col3".cast(DoubleType))

scala> df.show
+-----+-----+-----+---------+
| col1| col2| col3|cust_flag|
+-----+-----+-----+---------+
|121.0|442.0|512.0|        1|
|134.0|434.0|752.0|        0|
|423.0|312.0|124.0|        1|
|432.0|677.0|752.0|        0|
|332.0|424.0|111.0|        1|
+-----+-----+-----+---------+

scala>val colSeq =  Seq("col1", "col2", "col3")

scala>  val aggdf  = colSeq.map(c => {
     | df.groupBy("cust_flag").agg( lit(c).alias("columnName"), avg(c).cast("Decimal(14,2)").alias("avg"))
     | })

scala> val devdf  = colSeq.map(c => {
     |   df.agg( lit(c).alias("columnName"), stddev(c).cast("Decimal(14,2)").alias("StdDev"))
     |   })

scala> val avgDF = aggdf.reduce(_ union _)

scala> val stdDevDF = devdf.reduce(_ union _)

scala> val finalAvgDF = avgDF.filter(col("cust_flag") === 1).alias("1").join(avgDF.filter(col("cust_flag") === 0).alias("0"), List("columnName")).select(col("columnName"), col("1.avg").alias("avg1"), col("0.avg").alias("avg0"))

scala> val outDF = finalAvgDF.join(stdDevDF, List("columnName"))

scala> outDF.show()
+----------+------+------+------+
|columnName|  avg1|  avg0|StdDev|
+----------+------+------+------+
|      col1|292.00|283.00|152.07|
|      col2|392.67|555.50|133.48|
|      col3|249.00|752.00|319.16|
+----------+------+------+------+

//apply your final formula to ger rpb
scala> outDF.withColumn("rpb", (col("avg1") - col("avg0"))/col("StdDev")).show
+----------+------+------+------+--------------------+
|columnName|  avg1|  avg0|StdDev|                 rpb|
+----------+------+------+------+--------------------+
|      col1|292.00|283.00|152.07| 0.05918327086210298|
|      col2|392.67|555.50|133.48|-1.21988312855858556|
|      col3|249.00|752.00|319.16|-1.57601203158290513|
+----------+------+------+------+--------------------+

A: I would suggest you use df.selectExpr() which can take a sequence of string:
val expressions = Seq("avg(col1) as avg_col1","std_dev(col1) as sd_col1", "...")

df.selectExpr(expressions:_*)

You can do almost everything with that function building the array of expressions as you wish in a for loop.
I suggest anyway that you show us an example of expected input/output (the code you wrote doesn't tell much).


text:
Q: Using ExtractTextPlugin for Webpack, how do you not extract css and create an empty file with a flag? Basically I want to extract css in production, but I want to leave it in the JavaScript file in development mode.
This is so I can have the sourcemap working which shows the sass files used.
I want to be able to have:
<link href="~/dist/css/site.css" rel="stylesheet" />
<script type="text/javascript" src="~/dist/js/manifest.js"></script>
<script type="text/javascript" src="~/dist/js/css.js"></script>

Documentation is a bit thin on the ground.
So in dev mode site.css will be empty and won't cause an error like it would if it didn't exist. css.js will be used for style and source mapping.
In production mode css.js will exist but just not do anything because the css is extracted. This means the css will load nice and quickly and minified in site.css but have no mapping.

A: What I did was this:
Installed and required webpack-create-file-plugin
Created the css directory with a .empty file in it because the directory must exist.
This is generally how I have done it:
const extractSass = new ExtractTextPlugin("css/site.css");
const sassOptions = removeEmpty([
    ifNotProd({
        loader: "style-loader"
    }),
    {
        loader: "css-loader",
        options: {
            sourceMap: ifNotProd()
        }
    }, {
        loader: "sass-loader",
        options: {
            outputStyle: ifProd("compressed", "expanded"),
            sourceMap: ifNotProd()
        }
    }
]);

The sass rule looks like this:
{
    test: /\.scss$/,
    use: ifProd(extractSass.extract({
        use: sassOptions,
        fallback: "style-loader"
    }), sassOptions)
}

Added to plugins ifNotProd(new CreateFilePlugin({files: ["css/site.css"]})) and ifProd(extractSass)


text:
Q: HTML responsive email stacked columns not working I've been trying to get these columns to stack and no solution seems to be working.  There are several layers of nested tables (not all shown here) to keep the structure consistent across clients, but I don't know if this has anything to do with why my columns won't stack. I've tried applying the media queries to td, table, and div elements, but none of the solutions I've read on several sites works.  Below is the gist of my code:

          Advertise

          To advertise in our newsletter, please email:

            email@domain.com

          Newsletter Services

          Interested in reading more?

Click the link below to

            Sign Up for Our Newsletters

          If you no longer wish to receive this newsletter, click here to

            unsubscribe

          To manage your account and Newsletter settings, click here for

            My Account


text:
Q: Import external modules in typescript angular app I am refactoring a large app to use commonjs instead of a gazzilion script tags. I have refactored all the parts where the main app (entry point) imports the different app modules, app modules entry file loads its controllers, service etc. and I am happy with the code.
I am also using tsconfig.json files property (which include tsd.d.ts with external dependencies typings) for reference resolution and both webstorm and vscode seem happy with the code as well.
I have not used any external module imports so far. Trying to compile/bundle my code either using tsc or browserify generates quite a few errors about not finding external modules eg. "Cannot find name 'angular'". So I thought fine, I will require angular in that file:
import * as angular from 'angular';

import {avatarModuleServices} from './services/module';
import {avatarModuleDirectives} from './directives/module';

import {AvatarProcessController} from './avatar-process-controller';
export var avatarModule = angular.module('cv.avatar', [
        avatarModuleServices.name,
        avatarModuleDirectives.name,
        'angularFileUpload'
    ])
    .controller(AvatarProcessController.className, AvatarProcessController);

but then I get error

TS2304: Cannot find name 'angular'.

and I thought, it's probably because I am using bower to get angular and external imports probably look into node_modules directory. So I went ahead and installed angular through npm, but problem remains.
At this point what are my options for bundling my code along with external dependencies both from npm and bower?
btw I am using the latest version of everything (angular 1.4.8, tsc 1.7.3, browserify 12.0.1 etc)


text:
Q: How to search for a string in part of text? I am trying to search multiple text files for the text "1-2","2-3","3-H" which occur in the last field of the lines of text that start with "play".
An example of the text file is show below
id,ARI201803290
version,2
info,visteam,COL
info,hometeam,ARI
info,site,PHO01
play,1,0,lemad001,22,CFBBX,HR/78/F
play,1,0,arenn001,20,BBX,S7/L+
play,1,0,stort001,12,SBCFC,K
play,1,0,gonzc001,02,SS>S,K
play,1,1,perad001,32,BTBBCX,S9/G
play,1,1,polla001,02,CSX,S7/L+.1-2
play,1,1,goldp001,32,SBFBBB,W.2-3;1-2
play,1,1,lambj001,00,X,D9/F+.3-H;2-H;1-3
play,1,1,avila001,31,BC*BBX,31/G.3-H;2-3
play,2,0,grayj003,12,CC*BS,K
play,2,1,dysoj001,31,BBCBX,43/G
play,2,1,corbp001,31,CBBBX,43/G
play,4,1,avila001,02,SC1>X,S8/L.1-2

For the text file above, I would like the output to be '4' since there are 4 occurrences of "1-2","2-3" and "3-H" in total.
The code I have got so far is below, however I'm not sure where to start with writing a line of code to do this function.
import os

input_folder = 'files'  # path of folder containing the multiple text files

# create a list with file names
data_files = [os.path.join(input_folder, file) for file in
os.listdir(input_folder)]

# open csv file for writing
csv = open('myoutput.csv', 'w')
def write_to_csv(line):
    print(line)
    csv.write(line)

j=0 # initialise as 0
count_of_plate_appearances=0 # initialise as 0

for file in data_files:
    with open(file, 'r') as f:  # use context manager to open files
        for line in f:
            lines = f.readlines()
            i=0
            while i < len(lines):
                temp_array = lines[i].rstrip().split(",")
                if temp_array[0] == "id":
                    j=0
                    count_of_plate_appearances=0
                    game_id = temp_array[1]
                    awayteam = lines[i+2].rstrip().split(",")[2]
                    hometeam = lines[i+3].rstrip().split(",")[2]
                    date = lines[i+5].rstrip().split(",")[2]

                    for j in range(i+46,i+120,1): #only check for plate appearances this when temp_array[0] == "id"
                        temp_array2 = lines[j].rstrip().split(",") #create new array to check for plate apperances
                        if temp_array2[0] == "play" and temp_array2[2] == "1": # plate apperance occurs when these are true

count_of_plate_appearances=count_of_plate_appearances+1
                    #print(count_of_plate_appearances)
                    output_for_csv2=(game_id,date,hometeam, awayteam,str(count_of_plate_appearances))
                    print(output_for_csv2)
                    csv.write(','.join(output_for_csv2) + '\n')
                    i=i+1

                else:
                    i=i+1

                    j=0
                    count_of_plate_appearances=0
                #quit()

csv.close()

Any suggestions on how I can do this? Thanks in advance!

A: You can use regex, I put your text in a file called file.txt.
import re
a = ['1-2', '2-3', '3-H'] # What you want to count
find_this = re.compile('|'.join(a)) # Make search string
count = 0
with open('file.txt', 'r') as f:
    for line in f.readlines():
        count += len(find_this.findall(line)) # Each findall returns the list of things found
print(count) # 7

or a shorter solution: (Credit to wjandrea for hinting the use of a generator)
import re
a = ['1-2', '2-3', '3-H'] # What you want to count
find_this = re.compile('|'.join(a)) # Make search string
with open('file.txt', 'r') as f:
    count = sum(len(find_this.findall(line)) for line in f)
print(count) # 7