问:
To Compress my jQuery
How can I compress my jQuery useful? I want to add a function to show an element when I hover another one. The function below is exactly what I want, but I want it more dynamic. Maybe with an data attribute?

```<code>var item_first = $('.item_first');
var item_second = $('.item_second');
var item_third = $('.item_third');
var item_fourth = $('.item_fourth');

var image_first = $('.image_first');
var image_second = $('.image_second');
var image_third = $('.image_third');
var image_fourth = $('.image_fourth');

$(document).ready(function () {
    item_first.hover(function () {
        image_first.addClass('active');
    }, function () {
        image_first.removeClass('active');
    });

    item_second.hover(function () {
        image_second.addClass('active');
    }, function () {
        image_second.removeClass('active');
    });
    item_third.hover(function () {
        image_third.addClass('active');
    }, function () {
        image_third.removeClass('active');
    });

    item_fourth.hover(function () {
        image_fourth.addClass('active');
    }, function () {
        image_fourth.removeClass('active');
    });
});
</code>```

https://jsfiddle.net/gt5kw00q/

Sorry for my bad English. I try to write so that you understand it.

答:
Please find working solution below, enjoy :)

var items = {
  item_first: 'image_first',
  item_second: 'image_second',
  item_third: 'image_third',
  item_fourth: 'image_fourth'
}

$(document).ready(function() {
  function addClass(key) {
    $('.' + items[key]).addClass('active');
  }

  function removeClass(key) {
    $('.' + items[key]).removeClass('active');
  }
  for (var key in items) {
    $('.' + key).hover(addClass.bind(null, key), removeClass.bind(null, key))
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.right__image {
  display: none;
}

.right__image.active {
  display: block;
}</code>```

      Werte

      Team

      Arbeitsweise

      Standort

      IMAGE 1 HERE

      IMAGE 2 HERE

      IMAGE 3 HERE

      IMAGE 4 HERE

```

Title: To Compress my jQuery

Body:
How can I compress my jQuery useful? I want to add a function to show an element when I hover another one. The function below is exactly what I want, but I want it more dynamic. Maybe with an data attribute?

var item_first = $('.item_first');
var item_second = $('.item_second');
var item_third = $('.item_third');
var item_fourth = $('.item_fourth');

var image_first = $('.image_first');
var image_second = $('.image_second');
var image_third = $('.image_third');
var image_fourth = $('.image_fourth');

$(document).ready(function () {
    item_first.hover(function () {
        image_first.addClass('active');
    }, function () {
        image_first.removeClass('active');
    });

    item_second.hover(function () {
        image_second.addClass('active');
    }, function () {
        image_second.removeClass('active');
    });
    item_third.hover(function () {
        image_third.addClass('active');
    }, function () {
        image_third.removeClass('active');
    });

    item_fourth.hover(function () {
        image_fourth.addClass('active');
    }, function () {
        image_fourth.removeClass('active');
    });
});

https://jsfiddle.net/gt5kw00q/

Sorry for my bad English. I try to write so that you understand it.

Body:
Please find working solution below, enjoy :)

var items = {
  item_first: 'image_first',
  item_second: 'image_second',
  item_third: 'image_third',
  item_fourth: 'image_fourth'
}

$(document).ready(function() {
  function addClass(key) {
    $('.' + items[key]).addClass('active');
  }

  function removeClass(key) {
    $('.' + items[key]).removeClass('active');
  }
  for (var key in items) {
    $('.' + key).hover(addClass.bind(null, key), removeClass.bind(null, key))
  }
});

.right__image {
  display: none;
}

.right__image.active {
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="left">
  <ul class="left__inner">
    <li class="left__item item_first active">
      <a href="#" title="Werte" target="_self">Werte</a>
    </li>
    <li class="left__item item_second">
      <a href="#" title="Team" target="_self">Team</a>
    </li>
    <li class="left__item item_third">
      <a href="#" title="Arbeitsweise" target="_self">Arbeitsweise</a>
    </li>
    <li class="left__item item_fourth">
      <a href="#" title="Standort" target="_self">Standort</a>
    </li>
  </ul>
</div>

<div class="right">
  <div class="right__inner">
    <div class="right__image image_first active">
      IMAGE 1 HERE
    </div>
    <div class="right__image image_second">
      IMAGE 2 HERE
    </div>
    <div class="right__image image_third">
      IMAGE 3 HERE
    </div>
    <div class="right__image image_fourth">
      IMAGE 4 HERE
    </div>
  </div>
</div>


来源: stackexchange

问:
How to get information using css selector and store it variable
I want to verify the values from a register by using a css selector

```<code>[FindsBy(How = How.CssSelector, Using = "#grid_cases > table > tbody")]
private IWebElement CaseListGrid;
</code>```

I have to return the WebElements value and store it to string

```<code>public List<CaseListEntry> GetCaseListEntries()
{
    CaseListGrid.
    return null;
}
</code>```

答:
It works</p>

```<code> var CaseGridTrs = CaseListGrid.FindElements(By.XPath(".//tr"));
        var entryList = CaseGridTrs.Select(x =>
        {
            var CaseEntryTds = x.FindElements(By.XPath(".//td"));
            return new CaseListEntry
            {                                     Register = CaseEntryTds.ElementAt(0).FindElement(By.XPath(".//a")).Text,
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to verify the values from a register by using a css selector

[FindsBy(How = How.CssSelector, Using = "#grid_cases > table > tbody")]
private IWebElement CaseListGrid;

I have to return the WebElements value and store it to string

public List<CaseListEntry> GetCaseListEntries()
{
    CaseListGrid.
    return null;
}

Body:
It works

 var CaseGridTrs = CaseListGrid.FindElements(By.XPath(".//tr"));
        var entryList = CaseGridTrs.Select(x =>
        {
            var CaseEntryTds = x.FindElements(By.XPath(".//td"));
            return new CaseListEntry
            {                                     Register = CaseEntryTds.ElementAt(0).FindElement(By.XPath(".//a")).Text,


问:
Primefaces effect on growl only triggered second time
I have this piece of code:

```<code>    <p:growl id="growler" autoUpdate="true">
        <h:outputScript>
                $("#growler_container").effect("slide", { direction: "right" }, 400);
            </h:outputScript>
    </p:growl>
</code>```

Anytime the growl is activated through a message, the first time it is shown the default way. The second time the 'slide' effect is working as should. How to ensure this also works the first time?

答:
Moved the h:outputScript code to the p:button who was triggering the message and it works. </p>

```<code><p:growl id="growler" autoUpdate="true" life="15000"/>

<p:commandButton value="Save" actionListener="#{referenceManagementPage.save}" update="@form">
    <h:outputScript>$("#growler_container").effect("slide", { direction: "right" }, 400);</h:outputScript>
</p:commandButton>
</code>```

Body:
I have this piece of code:

        <h:outputScript>
                $("#growler_container").effect("slide", { direction: "right" }, 400);
            </h:outputScript>

Anytime the growl is activated through a message, the first time it is shown the default way. The second time the 'slide' effect is working as should. How to ensure this also works the first time?

Body:
Moved the h:outputScript code to the p:button who was triggering the message and it works.

<p:growl id="growler" autoUpdate="true" life="15000"/>

<p:commandButton value="Save" actionListener="#{referenceManagementPage.save}" update="@form">
    <h:outputScript>$("#growler_container").effect("slide", { direction: "right" }, 400);</h:outputScript>
</p:commandButton>


问:
How to make Snap.svg responsive in ie?
this.svgCanvas = Snap("#svg");

this.svgCanvas.attr({ viewBox: "0 0 236 236"});

For all other browsers it will be responsive after setting the view box.
 I am using IE11 , it will not be responsive. the height is always fixed to
 some small value. So sometimes the svg image will be clipped.

See example image

答:
Please follow the below steps to make your svg responsive in all browser.

calculate the total width of your svg image.

set view box width and height same, ie, the calculated width earlier(you can change as well as whatever the aspect ratio you needed).

this.svgCanvas.attr({ viewBox: "0 0 236 236", height: innerWidth });

here 236 is my calculated width of svg image.

Title: How to make Snap.svg responsive in ie?


问:
Unique results for SQL command with GROUP, MIN and NULL values
I have a table inquiry with columns job, gender (TRUE for women, FALSE for men) and salary. None of the columns is unique, salary may contain NULL. How to find the minimum salary per job for women (TRUE)? If e.g. there are entries [pilot ; TRUE ; 100], [pilot ; FALSE ; 100], [pilot ; TRUE ; NULL] and [pilot ; FALSE ; 120], the code below returns [pilot ; 100] twice instead of once.

```<code>SELECT TOP (100) PERCENT T.JOB, T.SALARY
FROM INQUIRY AS T INNER JOIN
    (SELECT JOB, MIN(SALARY) AS SL
    FROM INQUIRY AS T
    WHERE (SALARY IS NOT NULL) AND (GENDER = 1)
    GROUP BY JOB) AS x ON x.JOB = T.JOB AND x.SL = T.SALARY
</code>```

答:
Aggregate functions ignore nulls. Lose the join and you should be OK:

```<code>SELECT   job, MIN(salary)
FROM     inquiry
WHERE    gender = 1
GROUP BY job
</code>```

Body:
I have a table inquiry with columns job, gender (TRUE for women, FALSE for men) and salary. None of the columns is unique, salary may contain NULL. How to find the minimum salary per job for women (TRUE)? If e.g. there are entries [pilot ; TRUE ; 100], [pilot ; FALSE ; 100], [pilot ; TRUE ; NULL] and [pilot ; FALSE ; 120], the code below returns [pilot ; 100] twice instead of once.

SELECT TOP (100) PERCENT T.JOB, T.SALARY
FROM INQUIRY AS T INNER JOIN
    (SELECT JOB, MIN(SALARY) AS SL
    FROM INQUIRY AS T
    WHERE (SALARY IS NOT NULL) AND (GENDER = 1)
    GROUP BY JOB) AS x ON x.JOB = T.JOB AND x.SL = T.SALARY

Body:
Aggregate functions ignore nulls. Lose the join and you should be OK:

SELECT   job, MIN(salary)
FROM     inquiry
WHERE    gender = 1
GROUP BY job


问:
Get Previous and day before Previous date in batch file(cmd)
I have the following to determine the date and grab a file based on date. I need to modify this grab a file that has a date of yesterday and day before yesterday, i.e. date-1 and date-2. What do I need to change? Thanks!</p>

```<code>echo @echo off > uploadsp.txt
set mydate=%date:~10,4%%date:~4,2%%date:~7,2%
echo set mydate=%date:~10,4%%date:~4,2%%date:~7,2% >> uploadsp.txt

set myfile=Epic_DSH360144_Drug_Utilization_%mydate%_DU.txt
echo put %myfile% >> uploadsp.txt
exit
</code>```

答:
Something like this should do.

```<code>@echo off
set day=-1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
set "result1=%yyyy%-%mm%-%dd%"

set day=-2
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
set "result2=%yyyy%-%mm%-%dd%"
set yesterdayFile=Epic_DSH360144_Drug_Utilization_%result1%_DU.txt
set previousdayFile=Epic_DSH360144_Drug_Utilization_%result2%_DU.txt
echo Yesterday: "%result1%" - File to delete is %yesterdayFile%
echo Previous: "%result2%" - File to delete is %previousdayFile%
</code>```

so effectively, depending on which file you want to transfer you can then run

```<code>echo put %yesterdayFile% >> uploadsp.txt
</code>```

or

```<code>echo put %prevousdayFile% >> uploadsp.txt
</code>```

Body:
I have the following to determine the date and grab a file based on date. I need to modify this grab a file that has a date of yesterday and day before yesterday, i.e. date-1 and date-2. What do I need to change? Thanks!

echo @echo off > uploadsp.txt
set mydate=%date:~10,4%%date:~4,2%%date:~7,2%
echo set mydate=%date:~10,4%%date:~4,2%%date:~7,2% >> uploadsp.txt

set myfile=Epic_DSH360144_Drug_Utilization_%mydate%_DU.txt
echo put %myfile% >> uploadsp.txt
exit

Body:
Something like this should do.

@echo off
set day=-1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
set "result1=%yyyy%-%mm%-%dd%"

set day=-2
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
set "result2=%yyyy%-%mm%-%dd%"
set yesterdayFile=Epic_DSH360144_Drug_Utilization_%result1%_DU.txt
set previousdayFile=Epic_DSH360144_Drug_Utilization_%result2%_DU.txt
echo Yesterday: "%result1%" - File to delete is %yesterdayFile%
echo Previous: "%result2%" - File to delete is %previousdayFile%

so effectively, depending on which file you want to transfer you can then run

echo put %yesterdayFile% >> uploadsp.txt

or

echo put %prevousdayFile% >> uploadsp.txt


问:
Trouble formatting images in my CSS
community!
I am having trouble getting the formatting down for a few images I have.

HTML

```<code><footer>
    <section class="socialmedia">
        <a href=""><img src="facebook.png" class="sm"></a>
        <a href=""><img src="twitter.png" class="sm"></a>
        <a href=""><img src="instagram.png" class="sm"></a>
    </section>
</footer>
</code>```

CSS

```<code>.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
    float: left;
    width: 2%;
}
</code>```

The images are just lined up vertically to the left of the page, all at the original size. To my understanding the

float: left;

is used to make them horizontal?

Also I would like them to be centered on the page, but margin: auto; is not changing anything either.

EDIT: I would like to have some spacing between each image as well, is there an alternative to

& nbsp;

答:
Try this. I hope this will solve your issue.

.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: flex;
    align-items: center;
    justify-content: center;
}
.socialmedia > a {
display:inline-block;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
    <section class="socialmedia">
        <img src="https://www.wired.com/images/icons/social-facebook-square-blue.svg" class="sm">
        <img src="http://www.persianfootball.com/forums/images/BP-White/misc/icon-twitter.png" class="sm">
        <img src="http://www.downvids.net/images/inslogo.png" class="sm">
    </section>
</footer></code>```

Title: Trouble formatting images in my CSS

Body:
community!
I am having trouble getting the formatting down for a few images I have.

HTML

CSS

.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
    float: left;
    width: 2%;
}

The images are just lined up vertically to the left of the page, all at the original size. To my understanding the

float: left;

is used to make them horizontal?

Also I would like them to be centered on the page, but margin: auto; is not changing anything either.

EDIT: I would like to have some spacing between each image as well, is there an alternative to

& nbsp;

Body:
Try this. I hope this will solve your issue.

.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: flex;
    align-items: center;
    justify-content: center;
}
.socialmedia > a {
display:inline-block;

}

<footer>
    <section class="socialmedia">
        <a href=""><img src="https://www.wired.com/images/icons/social-facebook-square-blue.svg" class="sm"></a>
        <a href=""><img src="http://www.persianfootball.com/forums/images/BP-White/misc/icon-twitter.png" class="sm"></a>
        <a href=""><img src="http://www.downvids.net/images/inslogo.png" class="sm"></a>
    </section>
</footer>


问:
OFN_ENABLEHOOK modifies the look of GetOpenFileName()
Why does adding a hook procedure (with the OFN_ENABLEHOOK and OFN_EXPLORER flags) to GetOpenFileName() causes a different dialog to be displayed in Windows 7, if the hook procedure just returns FALSE without doing anything?

Update:

Apparently getting the Vista/Windows 7 look with a hook is impossible... can someone confirm or counter this?

答:
The reason for this is that MS completely re-organised the file dialogs for Vista. Hooks are used to extend a file dialog by supplying a resource file. This gives the customiser too much power. They can all too easily modify standard elements of the dialog and indeed many apps did so. The reorganisation of the dialogs would have broken many apps that used hooks. Those would have tried to manipulate elements of the dialog that were not there, or were implemented differently. Legacy versions of the dialogs remain for such apps to "get their hooks into".

You are correct that it is impossible to get the new look when you use a hook.  Instead you need to use the IFileDialogCustomize interface to customise the dialog.  This is less powerful but does result in appearance and behaviour that is more consistent with the standard part of the dialog.

ContentLicense: CC BY-SA 2.5


问:
PowerShell Get-Content with basic manipulations so slow
I am merging a lot of large CSV files, e.g. while skipping the leading junk and appending the filename to each line:

```<code>Get-ChildItem . | Where Name -match "Q[0-4]20[0-1][0-9].csv" |
Foreach-Object {
    $file = $_.BaseName
    Get-Content $_.FullName | select-object -skip 3 | % {
        "$_,${file}" | Out-File -Append temp.csv -Encoding ASCII
    }
}
</code>```

In PowerShell this is incredibly slow even on an i7/16GB machine (~5 megabyte/minute).  Can I make it more efficient or should I just switch to e.g. Python?

答:
Get-Content / Set-Content are terrible with larger files. Streams are a good alternative when performance is key. So with that in mind lets use one to read in each file and another to write out the results.

$rootPath = "C:\temp"
$outputPath = "C:\test\somewherenotintemp.csv"
$streamWriter = [System.IO.StreamWriter]$outputPath
Get-ChildItem $rootPath -Filter "*.csv" -File  | ForEach-Object{
    $file = $_.BaseName
    [System.IO.File]::ReadAllLines($_.FullName) |
        Select-Object -Skip 3 | ForEach-Object{
            $streamWriter.WriteLine(('{0},"{1}"' -f $_,$file))
    }
}
$streamWriter.Close(); $streamWriter.Dispose()
```

Create a writing stream $streamWriter to output the edited lines in each file. We could read in the file and write the file in larger batches, which would be faster, but we need to ignore a few lines and make changes to each one so processing line by line is simpler. Avoid writing anything to console during this time as it will just slow everything down.

What '{0},"{1}"' -f $_,$file does is quote that last "column" that is added in case the basename contains spaces.

Body:
I am merging a lot of large CSV files, e.g. while skipping the leading junk and appending the filename to each line:

Get-ChildItem . | Where Name -match "Q[0-4]20[0-1][0-9].csv" |
Foreach-Object {
    $file = $_.BaseName
    Get-Content $_.FullName | select-object -skip 3 | % {
        "$_,${file}" | Out-File -Append temp.csv -Encoding ASCII
    }
}

In PowerShell this is incredibly slow even on an i7/16GB machine (~5 megabyte/minute).  Can I make it more efficient or should I just switch to e.g. Python?

Body:
Get-Content / Set-Content are terrible with larger files. Streams are a good alternative when performance is key. So with that in mind lets use one to read in each file and another to write out the results.

$rootPath = "C:\temp"
$outputPath = "C:\test\somewherenotintemp.csv"
$streamWriter = [System.IO.StreamWriter]$outputPath
Get-ChildItem $rootPath -Filter "*.csv" -File  | ForEach-Object{
    $file = $_.BaseName
    [System.IO.File]::ReadAllLines($_.FullName) |
        Select-Object -Skip 3 | ForEach-Object{
            $streamWriter.WriteLine(('{0},"{1}"' -f $_,$file))
    }
}
$streamWriter.Close(); $streamWriter.Dispose()

Create a writing stream $streamWriter to output the edited lines in each file. We could read in the file and write the file in larger batches, which would be faster, but we need to ignore a few lines and make changes to each one so processing line by line is simpler. Avoid writing anything to console during this time as it will just slow everything down.

What '{0},"{1}"' -f $_,$file does is quote that last "column" that is added in case the basename contains spaces.

ContentLicense: CC BY-SA 4.0


问:
how to new DMatrix for XGBoost4J in Spark
I have a RDD, which element is ml.dmlc.xgboost4j.LabeledPoint, like

```<code>org.apache.spark.rdd.RDD[ml.dmlc.xgboost4j.LabeledPoint]
</code>```

The function XGBoost.train needs DMatrix for training Data, I check out the xgboost source code and find a constructor function for DMatrix, likes that DMatrix(Iterator iter, String cacheInfo).
DMatrix API

However, I have no idea to construct Iterator for DMatrix.

Any solutions?

Besides: I can only use xgboost4j -v0.5 in spark1.5, so some functions in new versions can not use.

答:
you can find a usage example on the xgboost github: https://github.com/dmlc/xgboost/blob/master/jvm-packages/xgboost4j-example/src/main/scala/ml/dmlc/xgboost4j/scala/example/spark/SparkWithRDD.scala

the relevant parts are:

```<code>import org.apache.spark.ml.feature.{LabeledPoint => MLLabeledPoint}
import org.apache.spark.ml.linalg.{DenseVector => MLDenseVector}

 val trainRDD = MLUtils.loadLibSVMFile(sc, inputTrainPath).map(lp =>
      MLLabeledPoint(lp.label, new MLDenseVector(lp.features.toArray)))
    val testSet = MLUtils.loadLibSVMFile(sc, inputTestPath)
        .map(lp => new MLDenseVector(lp.features.toArray))
    // training parameters
    val paramMap = List(
      "eta" -> 0.1f,
      "max_depth" -> 2,
      "objective" -> "binary:logistic").toMap
    val xgboostModel = XGBoost.trainWithRDD(trainRDD, paramMap, numRound, nWorkers = args(1).toInt,
      useExternalMemory = true)
    xgboostModel.predict(testSet, missingValue = Float.NaN)
</code>```

Body:
I have a RDD, which element is ml.dmlc.xgboost4j.LabeledPoint, like

org.apache.spark.rdd.RDD[ml.dmlc.xgboost4j.LabeledPoint]

The function XGBoost.train needs DMatrix for training Data, I check out the xgboost source code and find a constructor function for DMatrix, likes that DMatrix(Iterator iter, String cacheInfo).
DMatrix API

However, I have no idea to construct Iterator for DMatrix.

Any solutions?

Besides: I can only use xgboost4j -v0.5 in spark1.5, so some functions in new versions can not use.

Body:
you can find a usage example on the xgboost github: https://github.com/dmlc/xgboost/blob/master/jvm-packages/xgboost4j-example/src/main/scala/ml/dmlc/xgboost4j/scala/example/spark/SparkWithRDD.scala

the relevant parts are:

import org.apache.spark.ml.feature.{LabeledPoint => MLLabeledPoint}
import org.apache.spark.ml.linalg.{DenseVector => MLDenseVector}

 val trainRDD = MLUtils.loadLibSVMFile(sc, inputTrainPath).map(lp =>
      MLLabeledPoint(lp.label, new MLDenseVector(lp.features.toArray)))
    val testSet = MLUtils.loadLibSVMFile(sc, inputTestPath)
        .map(lp => new MLDenseVector(lp.features.toArray))
    // training parameters
    val paramMap = List(
      "eta" -> 0.1f,
      "max_depth" -> 2,
      "objective" -> "binary:logistic").toMap
    val xgboostModel = XGBoost.trainWithRDD(trainRDD, paramMap, numRound, nWorkers = args(1).toInt,
      useExternalMemory = true)
    xgboostModel.predict(testSet, missingValue = Float.NaN)


问:
Files under /var/www behaving in a case-insensitive way on Ubuntu 14.04
I'm having trouble understanding what is going on here.  Under /var or ~/ or anywhere else in the file system I cannot access a file unless I am case sensitive (as expected).  However when I go into the /var/www directory (or  every other directory down from there) I can access the file in a case-insensitive way.

I can not reproduce this on my other systems so I'm thinking it must be a configuration that has been made on this box.  I just don't know where to look for it.

Can someone please help me track down why this is happening?

```<code>vagrant@vagrant-ubuntu-trusty-64:/var$ ls -l
total 48
drwxr-xr-x  2 root    root    4096 Apr 10  2014 backups
drwxr-xr-x 13 root    root    4096 Nov  8 03:20 cache
drwxr-xr-x  3 root    root    4096 Nov  8 03:18 chef
drwxrwxrwt  2 root    root    4096 Nov  6 20:42 crash
drwxr-xr-x 53 root    root    4096 Nov  8 03:20 lib
drwxrwsr-x  2 root    staff   4096 Apr 10  2014 local
lrwxrwxrwx  1 root    root       9 Nov  6 20:40 lock -> /run/lock
drwxrwxr-x 13 root    syslog  4096 Nov  8 12:56 log
drwxrwsr-x  2 root    mail    4096 Nov  6 20:40 mail
drwxr-xr-x  2 root    root    4096 Nov  6 20:40 opt
lrwxrwxrwx  1 root    root       4 Nov  6 20:40 run -> /run
drwxr-xr-x  5 root    root    4096 Nov  6 20:41 spool
-rw-r--r--  1 vagrant vagrant   28 Nov 17 13:22 thisIsATestFile.txt
drwxrwxrwt  2 root    root    4096 Nov  6 20:43 tmp
drwxr-xr-x  1 vagrant vagrant  204 Nov 17 13:22 www
vagrant@vagrant-ubuntu-trusty-64:/var$ cat thisIsATestFile.txt
Lorem ipsum dolor sit amet.
vagrant@vagrant-ubuntu-trusty-64:/var$ cat THISISATESTFILE.txt
cat: THISISATESTFILE.txt: No such file or directory
vagrant@vagrant-ubuntu-trusty-64:/var$ cd www
vagrant@vagrant-ubuntu-trusty-64:/var/www$ ls -l
total 8
drwxr-xr-x 1 vagrant vagrant 1394 Nov 17 13:08 html
-rw-r--r-- 1 vagrant vagrant   81 Nov  8 02:28 index.php
-rw-r--r-- 1 vagrant vagrant   28 Nov 17 13:21 thisIsATestFile.txt
vagrant@vagrant-ubuntu-trusty-64:/var/www$ cat thisIsATestFile.txt
Lorem ipsum dolor sit amet.
vagrant@vagrant-ubuntu-trusty-64:/var/www$ cat THISISATESTFILE.txt
Lorem ipsum dolor sit amet.
vagrant@vagrant-ubuntu-trusty-64:/var/www$
</code>```

Here is the distribution info:

```<code>vagrant@vagrant-ubuntu-trusty-64:/var/www$ uname -r
3.13.0-135-generic
vagrant@vagrant-ubuntu-trusty-64:/var/www$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.5 LTS
Release:    14.04
Codename:   trusty
vagrant@vagrant-ubuntu-trusty-64:/var/www$
</code>```

答:
You pointed out that you are using vboxsf file system for /var/www mount point.

This file system is not case sensitive by default.

Mabye see https://forums.virtualbox.org/viewtopic.php?f=9&t=40423 if you want to mount it in a case sensitive way.

Body:
I'm having trouble understanding what is going on here.  Under /var or ~/ or anywhere else in the file system I cannot access a file unless I am case sensitive (as expected).  However when I go into the /var/www directory (or  every other directory down from there) I can access the file in a case-insensitive way.

I can not reproduce this on my other systems so I'm thinking it must be a configuration that has been made on this box.  I just don't know where to look for it.

Can someone please help me track down why this is happening?

vagrant@vagrant-ubuntu-trusty-64:/var$ ls -l
total 48
drwxr-xr-x  2 root    root    4096 Apr 10  2014 backups
drwxr-xr-x 13 root    root    4096 Nov  8 03:20 cache
drwxr-xr-x  3 root    root    4096 Nov  8 03:18 chef
drwxrwxrwt  2 root    root    4096 Nov  6 20:42 crash
drwxr-xr-x 53 root    root    4096 Nov  8 03:20 lib
drwxrwsr-x  2 root    staff   4096 Apr 10  2014 local
lrwxrwxrwx  1 root    root       9 Nov  6 20:40 lock -> /run/lock
drwxrwxr-x 13 root    syslog  4096 Nov  8 12:56 log
drwxrwsr-x  2 root    mail    4096 Nov  6 20:40 mail
drwxr-xr-x  2 root    root    4096 Nov  6 20:40 opt
lrwxrwxrwx  1 root    root       4 Nov  6 20:40 run -> /run
drwxr-xr-x  5 root    root    4096 Nov  6 20:41 spool
-rw-r--r--  1 vagrant vagrant   28 Nov 17 13:22 thisIsATestFile.txt
drwxrwxrwt  2 root    root    4096 Nov  6 20:43 tmp
drwxr-xr-x  1 vagrant vagrant  204 Nov 17 13:22 www
vagrant@vagrant-ubuntu-trusty-64:/var$ cat thisIsATestFile.txt
Lorem ipsum dolor sit amet.
vagrant@vagrant-ubuntu-trusty-64:/var$ cat THISISATESTFILE.txt
cat: THISISATESTFILE.txt: No such file or directory
vagrant@vagrant-ubuntu-trusty-64:/var$ cd www
vagrant@vagrant-ubuntu-trusty-64:/var/www$ ls -l
total 8
drwxr-xr-x 1 vagrant vagrant 1394 Nov 17 13:08 html
-rw-r--r-- 1 vagrant vagrant   81 Nov  8 02:28 index.php
-rw-r--r-- 1 vagrant vagrant   28 Nov 17 13:21 thisIsATestFile.txt
vagrant@vagrant-ubuntu-trusty-64:/var/www$ cat thisIsATestFile.txt
Lorem ipsum dolor sit amet.
vagrant@vagrant-ubuntu-trusty-64:/var/www$ cat THISISATESTFILE.txt
Lorem ipsum dolor sit amet.
vagrant@vagrant-ubuntu-trusty-64:/var/www$

Here is the distribution info:

vagrant@vagrant-ubuntu-trusty-64:/var/www$ uname -r
3.13.0-135-generic
vagrant@vagrant-ubuntu-trusty-64:/var/www$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.5 LTS
Release:    14.04
Codename:   trusty
vagrant@vagrant-ubuntu-trusty-64:/var/www$


问:
How to make certain values in dictionary add up to 100?
I have a dictionary with varying number of items. Each item can have a value of either a 1 or 0. Those with a value of 1 are stored in a list and counted. This is then used to calculate a percentage which would then be used to replace the value 1.

For example: if I have 10 items and only 7 contain a value of 1, the calculated percentage would be 100 / 7 = 14. Therefore those 7 items will have a new value of 14.

But there is a remainder left over and what I would like is for some items to gain this remainder (so 5 items would have a value of 14, 2 items would have a value of 15 so that (5 * 14) + (2 * 15) = 100.

How could this be done?

This is the code I used which gets the percentage value but I am unsure how to implement the remainder part (I would like to only show integers in the dictionary):

```<code>someDict = {
        'item_01': 0,
        'item_02': 0,
        'item_03': 0,
        'item_04': 1,
        'item_05': 1,
        'item_06': 1,
        'item_07': 1,
        'item_08': 1,
        'item_09': 1,
        'item_010': 1
        }

percentage_list = []
for key, value in someDict.items():
    if value == 1:
        percentage_list.append(value)

percentage_value = int(100) / int(len(percentage_list))
# =98

# Replace all 1's in someDict with percentage value
for key, value in someDict.items():
    if value == 1:
        someDict[key] = percentage_value
</code>```

答:
If for some reason your remainder left over is such that each element may gain more than 1, just after calculating percentage_value:

```<code>num_divisions = len(percentage_list)

remainder = 100 - percentage_value * num_divisions

# Replace all 1's in someDict with percentage value
for i, key in enumerate(filter(lambda k: someDict[k] == 1, someDict)):
    extra = int(remainder/(num_divisions - i))

    someDict[key] = percentage_value + extra

    remainder -= extra
</code>```

Body:
I have a dictionary with varying number of items. Each item can have a value of either a 1 or 0. Those with a value of 1 are stored in a list and counted. This is then used to calculate a percentage which would then be used to replace the value 1.

For example: if I have 10 items and only 7 contain a value of 1, the calculated percentage would be 100 / 7 = 14. Therefore those 7 items will have a new value of 14.

But there is a remainder left over and what I would like is for some items to gain this remainder (so 5 items would have a value of 14, 2 items would have a value of 15 so that (5 * 14) + (2 * 15) = 100.

How could this be done?

This is the code I used which gets the percentage value but I am unsure how to implement the remainder part (I would like to only show integers in the dictionary):

someDict = {
        'item_01': 0,
        'item_02': 0,
        'item_03': 0,
        'item_04': 1,
        'item_05': 1,
        'item_06': 1,
        'item_07': 1,
        'item_08': 1,
        'item_09': 1,
        'item_010': 1
        }

percentage_list = []
for key, value in someDict.items():
    if value == 1:
        percentage_list.append(value)

percentage_value = int(100) / int(len(percentage_list))
# =98

# Replace all 1's in someDict with percentage value
for key, value in someDict.items():
    if value == 1:
        someDict[key] = percentage_value

Body:
If for some reason your remainder left over is such that each element may gain more than 1, just after calculating percentage_value:

num_divisions = len(percentage_list)

remainder = 100 - percentage_value * num_divisions

# Replace all 1's in someDict with percentage value
for i, key in enumerate(filter(lambda k: someDict[k] == 1, someDict)):
    extra = int(remainder/(num_divisions - i))

    someDict[key] = percentage_value + extra

    remainder -= extra


答:
What about changing your styles to this:

```<code>/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    text-align: center;
}
</code>```

You are applying the wrong properties on the wrong classes.

Title: Trouble formatting images in my CSS

Body:
What about changing your styles to this:

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    text-align: center;
}

You are applying the wrong properties on the wrong classes.


问:
how to use parameter in viewmodel ins xamarin.forms
Im trying to pass parameter to viewmodel in Xamarin.Forms.But Also I want to use it while loading the page ,to call a rest service with that parameter.But In load event parameter is null always.(I can see that parameter if I bind it to a label or etc...)
How can I make it work properly and use that parameter inside the load event of viewmodel? Any help is appreciated,thanks

here is the button click event and navigate to Samplepage.

```<code> private void OntaptedBildirimItem(string param)
    {
      this._navigationService.NavigateTo(nameof(Views.SamplePage), param);
    }
</code>```

this is the Sample Page Viewmodel

```<code>      private string _id;
    public string id
    {
        get
        {
            return _id;
        }
        set
        {
            Set(() => id, ref _id, value);
        }
    }
public SamplePageViewModel(INavigationService navigationService) : base(navigationService)
    {
        this._navigationService = navigationService;
        this.Title = "Sample Page=" + id; // here the id is always null,but if I use it to bind a label in xaml ,it has a value.
    }
</code>```

This is the SamplePage Code

```<code>     public SamplePage(string parameter)
    {
        InitializeComponent();
        var viewModel = this.BindingContext as ViewModels.SamplePageViewModel;
        if(viewModel != null && parameter != null)
        {
            viewModel.bildirimid = parameter;
        }
    }
</code>```

答:
We need see NavigationService .

You should add bindingContext in NavigationService not in SamplePage.

In This Sample uses NavigationService with a parameter and a better NavigationService structure. You should see it.

Send feedback please.

Body:
Im trying to pass parameter to viewmodel in Xamarin.Forms.But Also I want to use it while loading the page ,to call a rest service with that parameter.But In load event parameter is null always.(I can see that parameter if I bind it to a label or etc...)
How can I make it work properly and use that parameter inside the load event of viewmodel? Any help is appreciated,thanks

here is the button click event and navigate to Samplepage.

 private void OntaptedBildirimItem(string param)
    {
      this._navigationService.NavigateTo(nameof(Views.SamplePage), param);
    }

this is the Sample Page Viewmodel

      private string _id;
    public string id
    {
        get
        {
            return _id;
        }
        set
        {
            Set(() => id, ref _id, value);
        }
    }
public SamplePageViewModel(INavigationService navigationService) : base(navigationService)
    {
        this._navigationService = navigationService;
        this.Title = "Sample Page=" + id; // here the id is always null,but if I use it to bind a label in xaml ,it has a value.
    }

This is the SamplePage Code

     public SamplePage(string parameter)
    {
        InitializeComponent();
        var viewModel = this.BindingContext as ViewModels.SamplePageViewModel;
        if(viewModel != null && parameter != null)
        {
            viewModel.bildirimid = parameter;
        }
    }


问:
Javascript chunky monkey algorithm code break down?
I need a help on breaking how does this code works?

```<code>    function chunkArrayInGroups(arr, size) {
      var newArr = [];
      while (arr.length) {
        newArr.push(arr.splice(0,size));
      }
      return newArr;
    }
chunkArrayInGroups(["a","b","c","d"],2);
</code>```

I dont understand how while(arr.length) gets stop and what this whole code is doing. Please break this down.

答: while (arr.length) executes until the array is empty, because when it's empty, arr.length equals 0 and it's treated as false.

Body:
I need a help on breaking how does this code works?

    function chunkArrayInGroups(arr, size) {
      var newArr = [];
      while (arr.length) {
        newArr.push(arr.splice(0,size));
      }
      return newArr;
    }
chunkArrayInGroups(["a","b","c","d"],2);

I dont understand how while(arr.length) gets stop and what this whole code is doing. Please break this down.


问:
How to display following response using vue js?
This is my response.. How to display the error message? passwords do not match

```<code> {"errors": {"password": ["Passwords donot match"]}, "status": false, "msg": "Validation erro", "error-type": 0}
</code>```

Currently my code is

```<code><script>
regBox = new Vue({
el: "#regBox",
  data: {
   ..........
    response: {
        message: '',
        status: '',
        state: '',
        errors: '',
    }
  },
methods: {
     handelSubmit: function(e) {
           var vm = this;
           data = {};
         ..............
            $.ajax({
              url: '',
              data: data,
              type: "POST",
              dataType: 'json',
              success: function(e) {
              if (e.status)
              {
               alert(" Success")

            }
              else {
                vm.response = e;
               alert(" Failed")
              }
          }
            });
            return false;
}
},
});
</script>
</code>```

My html code to display the same is

```<code> <p class="error">{{response.errors.password}}</p>
</code>```

Currently i am getting error message as
["Passwords donot match"]

How to get only message as

Passwords donot match.. so, how can i able to get it.. can anybody help

答:
Get the first element</p>

```<code><p class="error">{{response.errors.password[0]}}</p>
</code>```

Body:
This is my response.. How to display the error message? passwords do not match

 {"errors": {"password": ["Passwords donot match"]}, "status": false, "msg": "Validation erro", "error-type": 0}

Currently my code is

My html code to display the same is

{{response.errors.password}}

Currently i am getting error message as
["Passwords donot match"]

How to get only message as

Passwords donot match.. so, how can i able to get it.. can anybody help

Body:
Get the first element

<p class="error">{{response.errors.password[0]}}</p>


问:
Preserve function context in Python
I'm having a function in Python that when being called first, reads the content of a file to a list and checks whether or not an element is within that list.

```<code>def is_in_file(element, path):
    with open(path, 'r') as f:
        lines = [line.strip() for line in f.readlines()]
    return element in lines
</code>```

When the function is being called again, however, the content of the file should not be read again; the function should instead remember the value of lines from the first call.

Is there a way to preserve the context of a function when calling the function again? I don't want to make lines global to not litter the above namespace. I guess it's quite similar to the use of a generator and the yield statement...

答:
My opinion is that the correct way is to encapsulate this in a class. The path is set at instance creation, and method calls use the list of lines. That way you can even have different files at the same time:

```<code>class finder:
   def __init__(self, path):
       with open(path, 'r') as f:
           self.lines = [line.strip() for line in f]
   def is_in_file(self, element):
       return element in lines
</code>```

That is not exactly what you have asked for, but is much more OO.

Title: Preserve function context in Python

Body:
I'm having a function in Python that when being called first, reads the content of a file to a list and checks whether or not an element is within that list.

def is_in_file(element, path):
    with open(path, 'r') as f:
        lines = [line.strip() for line in f.readlines()]
    return element in lines

When the function is being called again, however, the content of the file should not be read again; the function should instead remember the value of lines from the first call.

Is there a way to preserve the context of a function when calling the function again? I don't want to make lines global to not litter the above namespace. I guess it's quite similar to the use of a generator and the yield statement...

Body:
My opinion is that the correct way is to encapsulate this in a class. The path is set at instance creation, and method calls use the list of lines. That way you can even have different files at the same time:

class finder:
   def __init__(self, path):
       with open(path, 'r') as f:
           self.lines = [line.strip() for line in f]
   def is_in_file(self, element):
       return element in lines

That is not exactly what you have asked for, but is much more OO.


问:
How do I store a custom user selected CSS template style (like wordpress visual editor)?
I am making a diary app. I want users to be able to customize/style the skin of their journal e.g. covers/backgrounds/fonts/colors etc.

I want to create something like the wordpress theme editor that allows users to update the background color in real time:

Here is how style editor would look.

For example if a user wants to set the writing area of the diary to a light yellow, how do I save that color into a custom CSS template and then render it again? Would I need to create a MySQL table just for style templates and have a row for color, background-color, etc... ?

答:
I've got a working prototype here in case anyone is interested.

How it works

I am storing my template data as an array of JSON objects:

```<code>template: [
    {selector: '.notepad-container', property: 'background-image', value: null},
    {selector: '.notepad', property: 'background-image', value: null},
    {selector: '.notepad', property: 'font-size', value: null},
    {selector: '.notepad', property: 'font-family', value: null},
]
</code>```

When a user wants to customise the style of the page they open the style editor. The selector and property that will be changed is stored in data attributes:

```<code><div class="swatch render" data-selector=".notepad-container" data-property="background-image" style="background-image: url(img/background/asphalt.jpg);"></div>
</code>```

So clicking this button will change the background-image of the .notepad-container class.

When they click to change a background the saveTemplate function is called and the selector and property is stored in the JSON object along with the background-image value:

```<code>saveTemplate: function(e){
    // get data-property and className attribute
    var selector = $(e.target).data('selector');
    var property = $(e.target).data('property');
    // where selector and property are same change model value
    var template = model.template;
    for (var i = 0; i < template.length; i++) {
        if (template[i].selector === selector && template[i].property === property) {
            template[i].property = $(e.target).data('property');
            model.template[i].value = $(e.target).css(property);
            view.renderTemplate(model.template); // render json template
            return;
        }
    }
},
</code>```

The template json data is passed to the renderTemplate(model.template) method which renders the changes.

```<code>renderTemplate: function(template){
    // json
    for (var i = 0; i < template.length; i++) {
        if (template[i].value !== null) {
            $(template[i].selector).css(template[i].property, template[i].value);
        }
    }
}
</code>```

When the save button is pressed the template is stored in the associated 'table' in a text field called template.

here is a working demo: https://codepen.io/jethazelhurst/pen/vWWrrv

Body:
I've got a working prototype here in case anyone is interested.

How it works

I am storing my template data as an array of JSON objects:

template: [
    {selector: '.notepad-container', property: 'background-image', value: null},
    {selector: '.notepad', property: 'background-image', value: null},
    {selector: '.notepad', property: 'font-size', value: null},
    {selector: '.notepad', property: 'font-family', value: null},
]

When a user wants to customise the style of the page they open the style editor. The selector and property that will be changed is stored in data attributes:

<div class="swatch render" data-selector=".notepad-container" data-property="background-image" style="background-image: url(img/background/asphalt.jpg);"></div>

So clicking this button will change the background-image of the .notepad-container class.

When they click to change a background the saveTemplate function is called and the selector and property is stored in the JSON object along with the background-image value:

saveTemplate: function(e){
    // get data-property and className attribute
    var selector = $(e.target).data('selector');
    var property = $(e.target).data('property');
    // where selector and property are same change model value
    var template = model.template;
    for (var i = 0; i < template.length; i++) {
        if (template[i].selector === selector && template[i].property === property) {
            template[i].property = $(e.target).data('property');
            model.template[i].value = $(e.target).css(property);
            view.renderTemplate(model.template); // render json template
            return;
        }
    }
},

The template json data is passed to the renderTemplate(model.template) method which renders the changes.

renderTemplate: function(template){
    // json
    for (var i = 0; i < template.length; i++) {
        if (template[i].value !== null) {
            $(template[i].selector).css(template[i].property, template[i].value);
        }
    }
}

When the save button is pressed the template is stored in the associated 'table' in a text field called template.

here is a working demo: https://codepen.io/jethazelhurst/pen/vWWrrv


问:
Softlayer API: How to specify an account ID in an order?
I have multiple accounts in SoftLayer and I'm ordering hardware using "placeOrder()" function from the API. The problem is that, even though that I'm using different credentials to connect to SoftLayer, it seems that the hardware is ordered always to the default account.

So there must be a place in the order JSON blob where the "accountId" can be specified. I have tried it on each element of the "hardware" field (as I saw that "verifyOrder()" returned it empty). But it didn't work. I can't find any documentation about this. Is there any way to specify the account ID where I want to order hardware? Thanks!

答:
No, there is not way to specify the account id, you must to use an userName and apiKey of each account.

Account A:

userName: A889_userA

apiKey: 4S5DF46S5DFS656SF......

Account B:

userName: B898_userB

apiKey: 2S16WE5RT4S32DF1......

So if you send a placeOrder request by using the user account A889_userA the created hardware should be listed in the "Account A".

```<code>https://A889_userA:4S5DF46S5DFS656F@api.softlayer.com/rest/v3/SoftLayer_Product_Order/placeOrder
</code>```

The same idea when using credentials of user B898_userB in account B

```<code>https://B898_userB:2S16WE5RT4S2DF5F@api.softlayer.com/rest/v3/SoftLayer_Product_Order/placeOrder
</code>```

Body:
No, there is not way to specify the account id, you must to use an userName and apiKey of each account.

Account A:

userName: A889_userA

apiKey: 4S5DF46S5DFS656SF......

Account B:

userName: B898_userB

apiKey: 2S16WE5RT4S32DF1......

So if you send a placeOrder request by using the user account A889_userA the created hardware should be listed in the "Account A".

https://A889_userA:4S5DF46S5DFS656F@api.softlayer.com/rest/v3/SoftLayer_Product_Order/placeOrder

The same idea when using credentials of user B898_userB in account B

https://B898_userB:2S16WE5RT4S2DF5F@api.softlayer.com/rest/v3/SoftLayer_Product_Order/placeOrder


问:
Reshaping a broadcasted expression
I would like to make the following broadcasted expression work:

```<code>J = rand(4,4)
fx1 = rand(2,2)
fx2 = rand(2,2)
@. J[:,1] = fx1 + fx2
</code>```

I really want some kind of:

```<code>@. J[:,1] = vec(fx1 + fx2)
</code>```

where this vec is saying it should reshape to be 4x1, but I don't want to have to make this allocating. How could this be generically handled (i.e. no indexing on the fx)?

答:
Since vecs are views, the following works:

```<code>J = rand(4,4)
fx1 = rand(2,2)
fx2 = rand(2,2)
vfx1,vfx2 = vec(fx1),vec(fx2)
@. J[:,1] = vfx1 + vfx2
</code>```

I don't think there's a way to do it in one line like I wanted, but this is fine.

Title: Reshaping a broadcasted expression

Body:
I would like to make the following broadcasted expression work:

J = rand(4,4)
fx1 = rand(2,2)
fx2 = rand(2,2)
@. J[:,1] = fx1 + fx2

I really want some kind of:

@. J[:,1] = vec(fx1 + fx2)

where this vec is saying it should reshape to be 4x1, but I don't want to have to make this allocating. How could this be generically handled (i.e. no indexing on the fx)?

Body:
Since vecs are views, the following works:

J = rand(4,4)
fx1 = rand(2,2)
fx2 = rand(2,2)
vfx1,vfx2 = vec(fx1),vec(fx2)
@. J[:,1] = vfx1 + vfx2

I don't think there's a way to do it in one line like I wanted, but this is fine.


答: while array count is "available" push into newArr (and also remove the certain item of it from the root array) when all is done, return it</p>

Title: Javascript chunky monkey algorithm code break down?


答:
No need to use a float :) https://jsfiddle.net/L5eyd4bv/1/

```<code>.sm {
     display: inline-block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    text-align: center;
}
</code>```

Using text-align on the parent element allows you to simply use display: inline-block;.

I have also put the class .sm on your  elements to facilitate this.

Title: Trouble formatting images in my CSS

Body:
community!
I am having trouble getting the formatting down for a few images I have.

HTML

CSS

.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
    float: left;
    width: 2%;
}

The images are just lined up vertically to the left of the page, all at the original size. To my understanding the

float: left;

is used to make them horizontal?

Also I would like them to be centered on the page, but margin: auto; is not changing anything either.

EDIT: I would like to have some spacing between each image as well, is there an alternative to

& nbsp;

Body:
No need to use a float :) https://jsfiddle.net/L5eyd4bv/1/

.sm {
     display: inline-block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    text-align: center;
}

Using text-align on the parent element allows you to simply use display: inline-block;.

I have also put the class .sm on your <a> elements to facilitate this.


问:
The Eclipse plugin cannot communicate with the GlassFish server
I need use Glassfish in a project we're currently working on in Eclipse IDE.
My problem is after installing Glassfish Tools in Eclipse I manage to correctly create a new glassfish server en SERVERS tab but when I try to start it the following error message pop up:

The Eclipse plugin cannot communicate with the GlassFish server....
  The Eclipse plugin cannot communicate with the GlassFish server. A
  GlassFish Enterprise Server may be running on the same admin or HTTP
  port, but with a different root installation.Please also check for
  antivirus software, firewall configuration, or VPN setup which might
  block some ports.

Actually the problem looks more complex since not only I'm not able to start server but I cannot execute any action on server. Neither deploying, nor clean or whaterever else do work resulting in popping up the above message.

In the internet developers communities I only find clues about CREDENTIAL ERROR but this is not the case.
Looking in the Glassfish log folder there is no trace of any access attempt.
Everythings points at Eclipse plug-in neither be able to communicate with glassfish by any circumstance.

This issue occours either with  Glassfish 3.1 (using jdk1.7) and 4.1 (using jdk1.8) and in Eclipse Luna and Mars.

I already tried to create, delete and manage glassfish domains (as suggested in other questions here at StackOverflow) to get over potential "credential-related" issues but no result.

Tried to uninstall and reinstall Glassfish Tools from Eclipse too but still no way.

Both Glasshfish 3.1 an 4.1 start flawlessly manually and NetBeans manage to start them without any problem but, as said, I need to work with eclipse so switching to NetBeans is not the solution (and, please, don't suggest me a manual deploy and server start).

As a last attempt, since I work in Windows, in a console window I tried this:

```<code>netstat -a -b
</code>```

to verify no other service is "taking" port 8080 (although it doesn't seem to be a port problem but a "plug-in communication" one) but it resulted free.

I'm into this mess by days.
Please help.

Thank you

答: I just set the proxy configuration in Eclipse menu Window -> Preferences -> General -> Network Connections (changing the Active Provider value from "Native" to "Manual" and inserting all the needed values for HTTP and HTTPS rows) and added "localhost" and "127.0.0.1" to the section "Proxy bypass". </p>

Body:
I need use Glassfish in a project we're currently working on in Eclipse IDE.
My problem is after installing Glassfish Tools in Eclipse I manage to correctly create a new glassfish server en SERVERS tab but when I try to start it the following error message pop up:

The Eclipse plugin cannot communicate with the GlassFish server....
  The Eclipse plugin cannot communicate with the GlassFish server. A
  GlassFish Enterprise Server may be running on the same admin or HTTP
  port, but with a different root installation.Please also check for
  antivirus software, firewall configuration, or VPN setup which might
  block some ports.

Actually the problem looks more complex since not only I'm not able to start server but I cannot execute any action on server. Neither deploying, nor clean or whaterever else do work resulting in popping up the above message.

In the internet developers communities I only find clues about CREDENTIAL ERROR but this is not the case.
Looking in the Glassfish log folder there is no trace of any access attempt.
Everythings points at Eclipse plug-in neither be able to communicate with glassfish by any circumstance.

This issue occours either with  Glassfish 3.1 (using jdk1.7) and 4.1 (using jdk1.8) and in Eclipse Luna and Mars.

I already tried to create, delete and manage glassfish domains (as suggested in other questions here at StackOverflow) to get over potential "credential-related" issues but no result.

Tried to uninstall and reinstall Glassfish Tools from Eclipse too but still no way.

Both Glasshfish 3.1 an 4.1 start flawlessly manually and NetBeans manage to start them without any problem but, as said, I need to work with eclipse so switching to NetBeans is not the solution (and, please, don't suggest me a manual deploy and server start).

As a last attempt, since I work in Windows, in a console window I tried this:

netstat -a -b

to verify no other service is "taking" port 8080 (although it doesn't seem to be a port problem but a "plug-in communication" one) but it resulted free.

I'm into this mess by days.
Please help.

Thank you


问:
How can I print something in the same line as the user input?
I wrote this code:

```<code>import java.util.Scanner;
public static void main (String[] args){
   Scanner scan = new Scanner (System.in);
   String inp;
   int m;
   System.out.println ("Please enter some characters.");
   inp = scan.nextLine();
   m = inp.length();
   System.out.println(" = " + m);
}
</code>```

If I run that, I get something like this:

Please enter some characters.
12345
 = 5
```

<p>But how can I get the <code>= 5</code> to be printed on the same line as the characters entered by the user, like below?</p>

<pre class="lang-none prettyprint-override"><code>Please enter some characters.
12345 = 5
</code>```

答:
just write like this:

```<code>System.out.print(" = " + m);
</code>```

println  prints to a new line.
hope it works

Body:
I wrote this code:

import java.util.Scanner;
public static void main (String[] args){
   Scanner scan = new Scanner (System.in);
   String inp;
   int m;
   System.out.println ("Please enter some characters.");
   inp = scan.nextLine();
   m = inp.length();
   System.out.println(" = " + m);
}

If I run that, I get something like this:

Please enter some characters.
12345
 = 5

But how can I get the = 5 to be printed on the same line as the characters entered by the user, like below?

Please enter some characters.
12345 = 5

Body:
just write like this:

System.out.print(" = " + m);

println  prints to a new line.
hope it works


问:
Function property example explanation
I was going through a JS tutorial, and came across this example:

```<code>function makeCounter() {
  function counter() {
    return counter.count++;
  };
  counter.count = 0;

  return counter;
}

let counter = makeCounter();
counter.count = 10;
console.log(counter()) // logs 10
</code>```

What I don't understand is why it didn't log 11 instead of 10? If we have set the count property to 10 and stored the function counter that increments count property, why the property is not incremented then to 11?

答:
You understand the function property well. This has to do with how ++ works.

return counter.count++; will return counter.count at its current value, THEN increment it, not the other way around.

Title: Function property example explanation

Body:
I was going through a JS tutorial, and came across this example:

function makeCounter() {
  function counter() {
    return counter.count++;
  };
  counter.count = 0;

  return counter;
}

let counter = makeCounter();
counter.count = 10;
console.log(counter()) // logs 10

What I don't understand is why it didn't log 11 instead of 10? If we have set the count property to 10 and stored the function counter that increments count property, why the property is not incremented then to 11?


问:
is there any way to redirect domain to two different ips
In my friend's office he has 2 public ips and its configured in fortigate with load balancing. Also he has 1 web server and his clients accessing the portal with isp1 primarily and clients sometimes accessing the portal using isp2 also if isp1 goes down. but every time he is informing the clients to use alternate 1 if any 1 isp goes down. if we buy 1 domain from registrar, can we redirect that domain to these isp1 ip or isp2 ip if any 1 goes down.
Or any other way to switch the ip to reach webserver without informing clients.

Thanks in advance.
Kumar B

答:
Buying a Domain and redirecting to isp1 or isp2 is a good idea but there will be a little downtime till you switch the isp.  </p>

<p>If you are serving static content try using a CDN to cache all your server files so that it will be serving to the clients even if your isp1 or isp2 id down. </p>

Body:
Buying a Domain and redirecting to isp1 or isp2 is a good idea but there will be a little downtime till you switch the isp.

If you are serving static content try using a CDN to cache all your server files so that it will be serving to the clients even if your isp1 or isp2 id down.


问:
Is there a grapichal tool for mvn release for IntelliJ?
I am developing Java in IntelliJ and we use Maven to release our project into sub version. We have to write

```<code>mvn release:prepare -DreleaseVersion=X.Y.Z
mvn release:perform
mvn clean release:clean
</code>```

in a terminal to release the project.

Is there not a better way to do this? Is there a tool in IntelliJ to do this?

I use Ubuntu 17.10

答:
IDEA has a built in maven plugin with graphical interface:
https://www.jetbrains.com/help/idea/maven.html#d369633e1000 </p>

Body:
I am developing Java in IntelliJ and we use Maven to release our project into sub version. We have to write

mvn release:prepare -DreleaseVersion=X.Y.Z
mvn release:perform
mvn clean release:clean

in a terminal to release the project.

Is there not a better way to do this? Is there a tool in IntelliJ to do this?

I use Ubuntu 17.10


问:
Why I've got Exception of type 'System.StackOverflowException' was thrown. in my own htmlhelper?
I've written htmlhelper for checkbox in asp.net mvc but when I want to use it.It shows me a exception.System.StackOverflowException' was thrownHow to solve it.and I also how to submit checkbox value to htmlhelper in fact,I want to submit value checkbox to my htmlhelper.

```<code> public static class HelperUI
    {
        public static MvcHtmlString CheckBoxSimple(this HtmlHelper htmlHelper, bool IsCheck, string name, object htmlAttributes)
        {
            string checkBoxWithHidden = htmlHelper.CheckBoxSimple(IsCheck, name, htmlAttributes).ToHtmlString();
            string pureCheckBox = checkBoxWithHidden.Substring(0, checkBoxWithHidden.IndexOf("<input", 1));
            return new MvcHtmlString(pureCheckBox);
        }
    }

<div class="col-md-6">
    <div class="form-group row">
        status
        <div class="col-md-9">
            @Html.CheckBoxSimple(true, "Status", new { @class = "form-control", placeholder = "status" })

        </div>
    </div>
</div>
</code>```

答:
StackOverflowExceptions are often caused by an infinite loop or infinite recursion.

In your case CheckBoxSimple is calling itself indefinitely : the first line calls CheckBoxSimple instead of CheckBox.

Body:
I've written htmlhelper for checkbox in asp.net mvc but when I want to use it.It shows me a exception.System.StackOverflowException' was thrownHow to solve it.and I also how to submit checkbox value to htmlhelper in fact,I want to submit value checkbox to my htmlhelper.

 public static class HelperUI
    {
        public static MvcHtmlString CheckBoxSimple(this HtmlHelper htmlHelper, bool IsCheck, string name, object htmlAttributes)
        {
            string checkBoxWithHidden = htmlHelper.CheckBoxSimple(IsCheck, name, htmlAttributes).ToHtmlString();
            string pureCheckBox = checkBoxWithHidden.Substring(0, checkBoxWithHidden.IndexOf("<input", 1));
            return new MvcHtmlString(pureCheckBox);
        }
    }

        status

            @Html.CheckBoxSimple(true, "Status", new { @class = "form-control", placeholder = "status" })


答: Array.splice modifies the original Array. When it is called inside while loop, It keeps shortening the original array and after a few iterations, arr.length becomes 0 and evaluates to false.

Body:
I need a help on breaking how does this code works?

    function chunkArrayInGroups(arr, size) {
      var newArr = [];
      while (arr.length) {
        newArr.push(arr.splice(0,size));
      }
      return newArr;
    }
chunkArrayInGroups(["a","b","c","d"],2);

I dont understand how while(arr.length) gets stop and what this whole code is doing. Please break this down.


问:
jQuery: how to get the id of a div (with a class named "hidden")
can you help me please ?

I'm searching for a solution to get an id from a hidden div and interact the id in an AJAX query when a click is happened

PHP code :

```<code>while ( $contents_print = mysqli_fetch_array( $req_print ) ) {
echo '
        <div class="post print" id="staggered-test">
            <img src="../00_sources/images/upload/pic_min/' . $contents_print[ 'pic_min' ] . '" alt="' . $contents_print[ 'pic_min' ] . '"/>
                <div class="post-content">
                    <a href="#modal" class="modal-action modal-trigger">Détail</a>
                    <div class="row"><blockquote>' . $contents_print[ 'detail_projet' ] . '</blockquote></div>
                </div>
            <div class="post-content valign-wrapper"><h4 class="header center">' . $contents_print[ 'nom_projet' ] . '</h4></div>
        </div>
    ';

echo '<div class="hidden" id="'.$contents_print[ 'id_projet' ].'"></div>';
}
</code>```

jQuery

```<code>$( document ).ready( function () {
  $(".post").siblings('div:hidden').attr("id").click(function() {
    var url_id = $(this).attr('id');
    //alert(url_id);
  });

  $.ajax({
    url: 'core/libs/contents-services.php?action=getFilterContent&id='+url_id,
    type: "get",
    dataType: "html",
    success: function ( reponse ) {
      $( '#modal' ).html( reponse );
      url_id = reponse.url_id;
    }
  });

  // the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
  $( '.modal' ).modal();
});
</code>```

May be I'm missing something, my code doesn't work

Please help me. Thanks a lot !

答:
You have a line that assigns event handlers, which is currently broken:

```<code>$(".post").siblings('div:hidden').attr("id").click(function() {
</code>```

simply remove .attr('id') as it makes no sense there.

```<code>$(".post").siblings('div:hidden').click(function() {
</code>```

The second problem is now you have assigned a bunch of click handlers to hidden divs, so how is the user going to click them?

Body:
can you help me please ?

I'm searching for a solution to get an id from a hidden div and interact the id in an AJAX query when a click is happened

PHP code :

while ( $contents_print = mysqli_fetch_array( $req_print ) ) {
echo '

                    Détail

' . $contents_print[ 'detail_projet' ] . '

' . $contents_print[ 'nom_projet' ] . '

    ';

echo '

';
}

jQuery

$( document ).ready( function () {
  $(".post").siblings('div:hidden').attr("id").click(function() {
    var url_id = $(this).attr('id');
    //alert(url_id);
  });

  $.ajax({
    url: 'core/libs/contents-services.php?action=getFilterContent&id='+url_id,
    type: "get",
    dataType: "html",
    success: function ( reponse ) {
      $( '#modal' ).html( reponse );
      url_id = reponse.url_id;
    }
  });

  // the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
  $( '.modal' ).modal();
});

May be I'm missing something, my code doesn't work

Please help me. Thanks a lot !

Body:
You have a line that assigns event handlers, which is currently broken:

$(".post").siblings('div:hidden').attr("id").click(function() {

simply remove .attr('id') as it makes no sense there.

$(".post").siblings('div:hidden').click(function() {

The second problem is now you have assigned a bunch of click handlers to hidden divs, so how is the user going to click them?


问:
When printing an image, what determines how large it will appear on a page?
Using Python's Imaging Library I want to create a PNG file.

I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.

Is the resolution encoded in the image?

If so, how do I specify it?

And even if it is, does this have any relevance when it goes to the printer?

答:
As of PIL 1.1.5, there is a way to get the DPI:</p>

```<code>im = ... # get image into PIL image instance
dpi = im.info["dpi"] # retrive the DPI
print dpi # (x-res, y-res)
im.info["dpi"] = new dpi # (x-res, y-res)
im.save("PNG") # uses the new DPI
</code>```

OwnerDisplayName: carrier

Body:
As of PIL 1.1.5, there is a way to get the DPI:

im = ... # get image into PIL image instance
dpi = im.info["dpi"] # retrive the DPI
print dpi # (x-res, y-res)
im.info["dpi"] = new dpi # (x-res, y-res)
im.save("PNG") # uses the new DPI

OwnerDisplayName: kylebrooks

LastEditorDisplayName: kylebrooks


问:
Does Distinct() method keep original ordering of sequence intact?
I want to remove duplicates from list, without changing order of unique elements in the list.

Jon Skeet & others have suggested to use the following:

```<code>list = list.Distinct().ToList();
</code>```

Reference:

How to remove duplicates from a List<T>?

Remove duplicates from a List<T> in C#

Is it guaranteed that the order of unique elements would be same as before? If yes, please give a reference that confirms this as I couldn't find anything on it in documentation.

答: According to the documentation the sequence is unordered.</p>

Body:
I want to remove duplicates from list, without changing order of unique elements in the list.

Jon Skeet & others have suggested to use the following:

list = list.Distinct().ToList();

Reference:

How to remove duplicates from a List<T>?

Remove duplicates from a List<T> in C#

Is it guaranteed that the order of unique elements would be same as before? If yes, please give a reference that confirms this as I couldn't find anything on it in documentation.


问:
OpenRefine: Fill down with increasing counter
Is it possible in OpenRefine to fill down blank cells with a counter instead of copying the top non-blank value?

In this example image:

Or here the same example as typed text - image this as a column from top to bottom:

```<code>1
1
blank
1
blank
blank
blank
blank
blank
1
</code>```

I would like to see the column filled as follows (again, imagine top to bottom):

```<code>1
1
2
1
2
3
4
5
6
1
</code>```

Thanks, help is very much appreciated.

答:
It's not really simple. You have to:

1 Replace the blanks with something else, such as an "x"

2 Create a unique record for the entire dataset

3 Use this Jython script:

```<code>import itertools
data = row['record']['cells']['YOUR COLUMN NAME']['value']
x = itertools.count(2)

liste = []
for i, el in enumerate(data):
    if data[i] == "x":
        liste.append(x.next())
    else:
        x = itertools.count(2)
        liste.append(el)

return ",".join([str(x) for x in liste])
</code>```

4 Use Blank down to clear duplicates

5 Split the first multivalued cell.

Here is a screencast of the operations described above.

If you know a little Python, you can also transform your file using pandas. I do not know what is the most elegant way to do it, but this script should work.

```<code>import itertools
import pandas as pd

x = itertools.count(2)

def set_x():
    global x
    x = itertools.count(2)

set_x()

def increase(value):

    if not value:
        return next(x)
    else:
        set_x()
        return value

data = pd.read_csv("your_file.csv", na_values=['nan'], keep_default_na=False)

data['column 1'] = data['column 1'].apply(lambda row: increase(row))

print(data)

data.to_csv("final_file.csv")
</code>```

Body:
Is it possible in OpenRefine to fill down blank cells with a counter instead of copying the top non-blank value?

In this example image:

Or here the same example as typed text - image this as a column from top to bottom:

1
1
blank
1
blank
blank
blank
blank
blank
1

I would like to see the column filled as follows (again, imagine top to bottom):

1
1
2
1
2
3
4
5
6
1

Thanks, help is very much appreciated.

Body:
It's not really simple. You have to:

1 Replace the blanks with something else, such as an "x"

2 Create a unique record for the entire dataset

3 Use this Jython script:

import itertools
data = row['record']['cells']['YOUR COLUMN NAME']['value']
x = itertools.count(2)

liste = []
for i, el in enumerate(data):
    if data[i] == "x":
        liste.append(x.next())
    else:
        x = itertools.count(2)
        liste.append(el)

return ",".join([str(x) for x in liste])

4 Use Blank down to clear duplicates

5 Split the first multivalued cell.

Here is a screencast of the operations described above.

If you know a little Python, you can also transform your file using pandas. I do not know what is the most elegant way to do it, but this script should work.

import itertools
import pandas as pd

x = itertools.count(2)

def set_x():
    global x
    x = itertools.count(2)

set_x()

def increase(value):

    if not value:
        return next(x)
    else:
        set_x()
        return value

data = pd.read_csv("your_file.csv", na_values=['nan'], keep_default_na=False)

data['column 1'] = data['column 1'].apply(lambda row: increase(row))

print(data)

data.to_csv("final_file.csv")


问:
Remove focus from EditView
I have EditText in which the user inputs some name then he clicks a button and I want the EditText to stop being focused and if the user taps with his finger I want it to be focusable again. I've tried all things on first page of Google results but nothing worked. Does anyone have some short solution, for example of one line. I can't believe Xamarin team didn't create this so important feature of removing focus from an element.</p>

答:
You can remove focus from edittext like this:

```<code>yourParentLayout.requestFocus();
</code>```

and inside xml

```<code><yourParentLayout
   android:focusableInTouchMode="true"
   android:focusable="true" />
</code>```

Title: Remove focus from EditView

Body:
You can remove focus from edittext like this:

yourParentLayout.requestFocus();

and inside xml

<yourParentLayout
   android:focusableInTouchMode="true"
   android:focusable="true" />


问:
Angular 4, typescript Assign interface property to variable
Im learning Angular and I'm creating a cryptocurrency exchange app. I created a service and an interface to get the data from an API. Now I can bind it to the DOM but I also want to use this data in my component.ts so I can write for example:

Bid2 = Bid * 2;

and then bind that variable to the DOM like this: {{ Bid2 }}

Thanks for your help. Here is my code:

Component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { BittrexService } from '../../bittrex/bittrex.service';
import {Observable} from "rxjs";
import { MarketListObject } from '../datosmoneda';
import { MarketPrices } from '../datosmoneda';

@Component({
  selector: 'app-comprarzec',
  templateUrl: './comprarzec.component.html',
  styleUrls: ['./comprarzec.component.scss']
})
export class ComprarzecComponent implements OnInit {

  private prices = [];

  constructor(private bittrexService: BittrexService) {
    this.bittrexService = bittrexService;
  }

ngOnInit(){
  this.bittrexService.getPrices()
  .subscribe(
    data => this.prices = data.result
  );
}
 }
</code>```

Service.ts

```<code>import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from "rxjs";
import 'rxjs/Rx';
import 'rxjs/add/operator/catch';
import { MarketViewModel } from '../comprarmonedas/datosmoneda'

@Injectable()
export class BittrexService {

  constructor(private http: Http, private marketModel : MarketViewModel) { }

  public getPrices() :Observable<MarketViewModel> {
    return this.http.get('https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-zec')
    .map((response: Response) => response.json());
  }

}
</code>```

interface.ts (datosmoneda.ts);

```<code>export class MarketViewModel {
  public success : boolean;
  public message : string;
  public result : MarketListObject[];
}

export class MarketListObject {
    public MarketName : string;
    public High : number;
    public Low : number;
    public Volume : number;
    public Last : number;
    public BaseVolume : number;
    public TimeStamp : number;
    public Bid : number;
    public Ask : number;
    public OpenBuyOrders : number;
    public OpenSellOrders : number;
    public PrevDay : number;
    public Created : number;

}
</code>```

Thanks for your help again!

答:
Maybe my github could answer some of your questions.

Ng-CC-Exchange : CryptoCurrencies Exchanges Module for Angular(2+)

An example of how I implement the order book service

Component

```<code>getBittrexOrderBook(market) {
if (market !== '') {
  this._bittrexService.getOrderBook(market).subscribe(
    response => {
      if (response.success && response.result) {
        this._tempCurrencyBuy = response.result;
      } else {
        this.handleError(response.message);
      }
    },
    error => this.handleError(error)
  );
}}
</code>```

Models

```<code>export interface BittrexOrderBook{
    success: boolean;
    message: string;
    result: BittrexOrder[];
}

export interface BittrexOrder{
    Quantity: number;
    Rate: number;
}
</code>```

Html

```<code><div class="bittrex-currencies-container">
<div class="bittrex-currencies-sub-container">
    <div class="bittrex-currencies-title">
        <h3 class="bittrex-currencies-title"><strong> Bittrex order book</strong></h3>
    </div>
    <form #form="ngForm" name="form" (ngSubmit)="submit()">
        <input type="text" class="search-input" placeholder="search engine" [(ngModel)]="filter" name="ngModel">
        <button type="submit" class="btn">submit</button>
    </form>
    <div class="scroll-bar">
        <div class="row" *ngIf="_tempCurrencyBuy.length">
            <div class="col-md-6">
                <label class="label label-default" for="bittrex-info-content">Buy orders</label>
                <div class="bittrex-currencies" *ngFor="let currency of _tempCurrencyBuy">
                    <div class="bittrex-info" *ngIf="currency.Quantity">
                        <label class="label label-info" for="bittrex-info-content">Quantity</label>
                        <span id="bittrex-info-content">{{currency.Quantity}}</span>
                    </div>
                    <div class="bittrex-info" *ngIf="currency.Rate">
                        <label class="label label-info" for="bittrex-info-content">Rate</label>
                        <span id="bittrex-info-content">{{currency.Rate}}</span>
                    </div>
                    <br>
                </div>
            </div>
            <div class="col-md-6">
                <label class="label label-default" for="bittrex-info-content">Sell orders</label>
                <div class="bittrex-currencies" *ngFor="let currency of _tempCurrencySell">
                    <div class="bittrex-info" *ngIf="currency.Quantity">
                        <label class="label label-info" for="bittrex-info-content">Quantity</label>
                        <span id="bittrex-info-content">{{currency.Quantity}}</span>
                    </div>
                    <div class="bittrex-info" *ngIf="currency.Rate">
                        <label class="label label-info" for="bittrex-info-content">Rate</label>
                        <span id="bittrex-info-content">{{currency.Rate}}</span>
                    </div>
                    <br>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Using api can become confusing when the api has a CORS problem and that's why there is a Backend with NodeJs and Nodemon to avoid this problem.
With Electron for example the problem is normally solved but for web app it's another story.

Angular without backend

```<code>getOrderBook(market, type = 'both', depth = 50) {
if (market) {
    return this._http.get(this._BASE_URL + `/getorderbook?market=${market}&type=${type}&depth${depth}`)
        .map(response => response.json() as BittrexOrderBook)
        .timeout(this._timeOut);
    }}
</code>```

If you choose a backend solution here is an example on nodeJS side

```<code>_api.get(_BITTREX_BASEURL + '/getorderbook', (request, response) => {
console.time("getorderbook");
const market = request.query.market;
const type = request.query.type;
const depth = request.query.depth;
const url = `https://bittrex.com/api/v1.1/public/getorderbook?market=${market}&type=${type}&depth${depth}`;
httpGet(url, response);
console.timeEnd("getorderbook");});

function httpGet(url, response) {
    _client.get(url, (data, resp) => {
        response.json(data);
    });
}
</code>```

Another solution may be to use a proxy service as described in this article
Access-Control-Allow-Origin: Dealing with CORS Errors in Angular

Another point to remember if you want to use something other than the public api of Bittrex. You will need the api keys generated by Bittrex, use post and HMAC-SHA512 (eg: Crypto-js).

Crypto-js : JavaScript library of crypto standards.

Body:
Im learning Angular and I'm creating a cryptocurrency exchange app. I created a service and an interface to get the data from an API. Now I can bind it to the DOM but I also want to use this data in my component.ts so I can write for example:

Bid2 = Bid * 2;

and then bind that variable to the DOM like this: {{ Bid2 }}

Thanks for your help. Here is my code:

Component.ts

import { Component, OnInit } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { BittrexService } from '../../bittrex/bittrex.service';
import {Observable} from "rxjs";
import { MarketListObject } from '../datosmoneda';
import { MarketPrices } from '../datosmoneda';

@Component({
  selector: 'app-comprarzec',
  templateUrl: './comprarzec.component.html',
  styleUrls: ['./comprarzec.component.scss']
})
export class ComprarzecComponent implements OnInit {

  private prices = [];

  constructor(private bittrexService: BittrexService) {
    this.bittrexService = bittrexService;
  }

ngOnInit(){
  this.bittrexService.getPrices()
  .subscribe(
    data => this.prices = data.result
  );
}
 }

Service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from "rxjs";
import 'rxjs/Rx';
import 'rxjs/add/operator/catch';
import { MarketViewModel } from '../comprarmonedas/datosmoneda'

@Injectable()
export class BittrexService {

  constructor(private http: Http, private marketModel : MarketViewModel) { }

  public getPrices() :Observable<MarketViewModel> {
    return this.http.get('https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-zec')
    .map((response: Response) => response.json());
  }

}

interface.ts (datosmoneda.ts);

export class MarketViewModel {
  public success : boolean;
  public message : string;
  public result : MarketListObject[];
}

export class MarketListObject {
    public MarketName : string;
    public High : number;
    public Low : number;
    public Volume : number;
    public Last : number;
    public BaseVolume : number;
    public TimeStamp : number;
    public Bid : number;
    public Ask : number;
    public OpenBuyOrders : number;
    public OpenSellOrders : number;
    public PrevDay : number;
    public Created : number;

}

Thanks for your help again!

Body:
Maybe my github could answer some of your questions.

Ng-CC-Exchange : CryptoCurrencies Exchanges Module for Angular(2+)

An example of how I implement the order book service

Component

getBittrexOrderBook(market) {
if (market !== '') {
  this._bittrexService.getOrderBook(market).subscribe(
    response => {
      if (response.success && response.result) {
        this._tempCurrencyBuy = response.result;
      } else {
        this.handleError(response.message);
      }
    },
    error => this.handleError(error)
  );
}}

Models

export interface BittrexOrderBook{
    success: boolean;
    message: string;
    result: BittrexOrder[];
}

export interface BittrexOrder{
    Quantity: number;
    Rate: number;
}

Html

<div class="bittrex-currencies-container">
<div class="bittrex-currencies-sub-container">
    <div class="bittrex-currencies-title">
        <h3 class="bittrex-currencies-title"><strong> Bittrex order book</strong></h3>
    </div>
    <form #form="ngForm" name="form" (ngSubmit)="submit()">
        <input type="text" class="search-input" placeholder="search engine" [(ngModel)]="filter" name="ngModel">
        <button type="submit" class="btn">submit</button>
    </form>
    <div class="scroll-bar">
        <div class="row" *ngIf="_tempCurrencyBuy.length">
            <div class="col-md-6">
                <label class="label label-default" for="bittrex-info-content">Buy orders</label>
                <div class="bittrex-currencies" *ngFor="let currency of _tempCurrencyBuy">
                    <div class="bittrex-info" *ngIf="currency.Quantity">
                        <label class="label label-info" for="bittrex-info-content">Quantity</label>
                        <span id="bittrex-info-content">{{currency.Quantity}}</span>
                    </div>
                    <div class="bittrex-info" *ngIf="currency.Rate">
                        <label class="label label-info" for="bittrex-info-content">Rate</label>
                        <span id="bittrex-info-content">{{currency.Rate}}</span>
                    </div>
                    <br>
                </div>
            </div>
            <div class="col-md-6">
                <label class="label label-default" for="bittrex-info-content">Sell orders</label>
                <div class="bittrex-currencies" *ngFor="let currency of _tempCurrencySell">
                    <div class="bittrex-info" *ngIf="currency.Quantity">
                        <label class="label label-info" for="bittrex-info-content">Quantity</label>
                        <span id="bittrex-info-content">{{currency.Quantity}}</span>
                    </div>
                    <div class="bittrex-info" *ngIf="currency.Rate">
                        <label class="label label-info" for="bittrex-info-content">Rate</label>
                        <span id="bittrex-info-content">{{currency.Rate}}</span>
                    </div>
                    <br>
                </div>
            </div>
        </div>
    </div>
</div>

Using api can become confusing when the api has a CORS problem and that's why there is a Backend with NodeJs and Nodemon to avoid this problem.
With Electron for example the problem is normally solved but for web app it's another story.

Angular without backend

getOrderBook(market, type = 'both', depth = 50) {
if (market) {
    return this._http.get(this._BASE_URL + `/getorderbook?market=${market}&type=${type}&depth${depth}`)
        .map(response => response.json() as BittrexOrderBook)
        .timeout(this._timeOut);
    }}

If you choose a backend solution here is an example on nodeJS side

_api.get(_BITTREX_BASEURL + '/getorderbook', (request, response) => {
console.time("getorderbook");
const market = request.query.market;
const type = request.query.type;
const depth = request.query.depth;
const url = `https://bittrex.com/api/v1.1/public/getorderbook?market=${market}&type=${type}&depth${depth}`;
httpGet(url, response);
console.timeEnd("getorderbook");});

function httpGet(url, response) {
    _client.get(url, (data, resp) => {
        response.json(data);
    });
}

Another solution may be to use a proxy service as described in this article
Access-Control-Allow-Origin: Dealing with CORS Errors in Angular

Another point to remember if you want to use something other than the public api of Bittrex. You will need the api keys generated by Bittrex, use post and HMAC-SHA512 (eg: Crypto-js).

Crypto-js : JavaScript library of crypto standards.


问:
question about jredis performance
I want to use Redis RPUSH and LPOP as message queue in my project, and now I encountered a performance problem:

When I simply rpush a random Double nubmer using Jredis with a single thread from my java client, I notice that the throughout is just 4000 request/secs, which is much lower than what I expected.

Here is my redis Configuration:

timeout 300
save 900 1
save 300 10
save 60 10000

no memory limit with 4G memory.

and Java snippet:

```<code>    jredis = new JRedisClient(ip,6379);
    long bytesTransfered = 0;
    Date start = new Date();
    for(int i = 0; i < 100000 ; i ++){
        String s = Math.random()+"";
        jredis.lpush("testqueue", s);
        bytesTransfered += s.length();
    }
    Date end = new Date();
    double seconds = (end.getTime() - start.getTime())/1000f;
    System.out.println("REDIS:\t"+  (bytesTransfered/seconds)+"bytes/second,\t"+100000/seconds+"request/second");
</code>```

Is there any other java client better than jredis?  Thanks for your help!.

答:
Try some tests without java - the client included with redis should do. There may be some overhead in the java client, but your issue is most likely the network connection. The network may be able to transfer large amounts of data fast, but lots of small keys gets you worst case performance for overhead and latency.

Your test has each operation happening synchronously, waiting for a response before sending the next command. Both client and server can handle more in normal usage - start another thread/connection and you will probably get much better numbers.

Title: question about jredis performance

Body:
I want to use Redis RPUSH and LPOP as message queue in my project, and now I encountered a performance problem:

When I simply rpush a random Double nubmer using Jredis with a single thread from my java client, I notice that the throughout is just 4000 request/secs, which is much lower than what I expected.

Here is my redis Configuration:

timeout 300
save 900 1
save 300 10
save 60 10000

no memory limit with 4G memory.

and Java snippet:

    jredis = new JRedisClient(ip,6379);
    long bytesTransfered = 0;
    Date start = new Date();
    for(int i = 0; i < 100000 ; i ++){
        String s = Math.random()+"";
        jredis.lpush("testqueue", s);
        bytesTransfered += s.length();
    }
    Date end = new Date();
    double seconds = (end.getTime() - start.getTime())/1000f;
    System.out.println("REDIS:\t"+  (bytesTransfered/seconds)+"bytes/second,\t"+100000/seconds+"request/second");

Is there any other java client better than jredis?  Thanks for your help!.


问:
Groupby for the specific type of record
I am little confused about a query. I have a posts table with the field {type}.type field has different values. Now the requirement is that, I want to fetch use groupBy {Date} for the specific type of post.

```<code>    Collection {#832 ▼
  #items: array:5 [▼
    0 => Post {#833 ▶}
    1 => Post {#834 ▶}
    2 => Post {#835 ▶}
    3 => Post {#836 ▶}
    4 => Post {#837 ▼
      Post: array:5 [▼
      0 => Post {#833 ▶}
      1 => Post {#834 ▶}
      2 => Post {#835 ▶}
      3 => Post {#836 ▶}
      ]
    }
  ]
}
</code>```

in this first array 4th key is groupBy.
I hope you can understand my requirements
Thanks In advance

答:
Try something like:

```<code>$type = "example"; //whatever a valid value for type would by, based on your code.
Post::where('type', $type)->groupBy('date')->get();
</code>```

By placing the where() before the groupBy() you can filter results a bit more.

Title: Groupby for the specific type of record

Body:
I am little confused about a query. I have a posts table with the field {type}.type field has different values. Now the requirement is that, I want to fetch use groupBy {Date} for the specific type of post.

    Collection {#832 ▼
  #items: array:5 [▼
    0 => Post {#833 ▶}
    1 => Post {#834 ▶}
    2 => Post {#835 ▶}
    3 => Post {#836 ▶}
    4 => Post {#837 ▼
      Post: array:5 [▼
      0 => Post {#833 ▶}
      1 => Post {#834 ▶}
      2 => Post {#835 ▶}
      3 => Post {#836 ▶}
      ]
    }
  ]
}

in this first array 4th key is groupBy.
I hope you can understand my requirements
Thanks In advance

Body:
Try something like:

$type = "example"; //whatever a valid value for type would by, based on your code.
Post::where('type', $type)->groupBy('date')->get();

By placing the where() before the groupBy() you can filter results a bit more.


答:
Cause you are using the postfix increase operator, which firstly returns its current value, then it increases it. You could change that to a prefix increase:

```<code>   return ++counter.count;
</code>```

Title: Function property example explanation

Body:
I was going through a JS tutorial, and came across this example:

function makeCounter() {
  function counter() {
    return counter.count++;
  };
  counter.count = 0;

  return counter;
}

let counter = makeCounter();
counter.count = 10;
console.log(counter()) // logs 10

What I don't understand is why it didn't log 11 instead of 10? If we have set the count property to 10 and stored the function counter that increments count property, why the property is not incremented then to 11?

Body:
Cause you are using the postfix increase operator, which firstly returns its current value, then it increases it. You could change that to a prefix increase:

   return ++counter.count;


问:
How to define properties in spring dsl in apache camel
How can I define the properties with Spring DSL in Apache Camel ? With Blueprint you can do it via:

```<code> <cm:property-placeholder persistent-id="org.apache.servicemix.examples.cxf.receive" update-strategy="reload">
        <cm:default-properties>
            <cm:property name="CXFserver" value="http://localhost:8989/"/>
            <cm:property name="service" value="soap" />
        </cm:default-properties>
    </cm:property-placeholder>

    <camelcxf:cxfEndpoint id="personService"
                          address="${CXFserver}${service}"
                          serviceClass="org.apache.servicemix.examples.camel.soap.PersonService"
                          />
</code>```

But with Spring DSL what should I do like the example above? Below my camel-cxf.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://camel.apache.org/schema/cxf"
    xsi:schemaLocation="
         http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://camel.apache.org/schema/cxf
         http://camel.apache.org/schema/cxf/camel-cxf.xsd">

    <!-- setting up a Camel CXF web-service -->
    <cxf:cxfEndpoint id="orderEndpoint"
        loggingFeatureEnabled="true" address="http://localhost:9000/order/"
        serviceClass="com.aa.kk.service.OrderService" />

</beans>
</code>```

答:
You are trying get your properties in a server, I've never tryed do it. But you can try do something like when the properties file is local, like this.

```<code><bean
    class="org.apache.camel.component.properties.PropertiesComponent" id="properties">
    <property name="location" value="classpath:application.properties"/>
</bean>
</code>```

And in your classpath, you can try change your classpath to your server address.

Body:
How can I define the properties with Spring DSL in Apache Camel ? With Blueprint you can do it via:

 <cm:property-placeholder persistent-id="org.apache.servicemix.examples.cxf.receive" update-strategy="reload">
        <cm:default-properties>
            <cm:property name="CXFserver" value="http://localhost:8989/"/>
            <cm:property name="service" value="soap" />
        </cm:default-properties>
    </cm:property-placeholder>

    <camelcxf:cxfEndpoint id="personService"
                          address="${CXFserver}${service}"
                          serviceClass="org.apache.servicemix.examples.camel.soap.PersonService"
                          />

But with Spring DSL what should I do like the example above? Below my camel-cxf.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://camel.apache.org/schema/cxf"
    xsi:schemaLocation="
         http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://camel.apache.org/schema/cxf
         http://camel.apache.org/schema/cxf/camel-cxf.xsd">

    <cxf:cxfEndpoint id="orderEndpoint"
        loggingFeatureEnabled="true" address="http://localhost:9000/order/"
        serviceClass="com.aa.kk.service.OrderService" />

</beans>

Body:
You are trying get your properties in a server, I've never tryed do it. But you can try do something like when the properties file is local, like this.

<bean
    class="org.apache.camel.component.properties.PropertiesComponent" id="properties">
    <property name="location" value="classpath:application.properties"/>
</bean>

And in your classpath, you can try change your classpath to your server address.


问:
How to create checkboxes and radiobuttons with only html and css
I'm currently working on a school-project where a big part of my idea is based on radio-buttons and checkboxes. I've found a lot of codes out there on how to create them, the only problem is that I'm only allowed to use certain html-tags and no jQuery.

The tags I can use:

• html, head, body, title, meta, link

• header, section, article, footer

• div

• h1-h6

• p

• span

• ul, ol, li

• a

• img

• audio

Is there any way to create checkboxes and radio-buttons with these tags?

答:
To input data from users in HTML your only option is the input's tag. Take a look official documentation at:

https://www.w3schools.com/html/html_form_input_types.asp

Only with allowed tags your can't create radio-buttons and checkboxes.


答:
Your function makeCounter is returning a function, which has access to the  [[scope]] . It's using  closure. so It  is obvious it works like that.

Closure : ' When a function memorizes the data from the place where he was called from' .

Further information ;  What is a 'Closure'?

Title: Function property example explanation