问:
Transform JSX to JS using babel
I'm new to babel and I'm trying to convert my main.jsx file to main.js. I installed the following babel plugin.

```<code>npm install --save-dev babel-plugin-transform-react-jsx
</code>```

Created a file called .babelrc in the application root directory.

```<code>{
   "plugins": ["transform-react-jsx"]
}
</code>```

My app is using the express server, so on running node app.js I was expecting the babel to transform main.jsx to main.js but nothing happens.
Can any one point out what I'm doing wrong ?

答:
You can configure webpack and use babel as a loader to transpile your jsx

```<code>var webpack = require('webpack');
var path = require('path');

module.exports ={

    context: path.join(__dirname, "src"),
    devtool: "inline-sourcemap",
    entry: "./main.js",
    module: {
        loaders: [
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015','stage-0'],

                }
            }
        ]
    },
    output: {
        path: __dirname+ "/src",
        filename: "client.min.js"
    }
}
</code>```

Tutorials

Title: Transform JSX to JS using babel

Body:
I'm new to babel and I'm trying to convert my main.jsx file to main.js. I installed the following babel plugin.

npm install --save-dev babel-plugin-transform-react-jsx

Created a file called .babelrc in the application root directory.

{
   "plugins": ["transform-react-jsx"]
}

My app is using the express server, so on running node app.js I was expecting the babel to transform main.jsx to main.js but nothing happens.
Can any one point out what I'm doing wrong ?

Body:
You can configure webpack and use babel as a loader to transpile your jsx

var webpack = require('webpack');
var path = require('path');

module.exports ={

    context: path.join(__dirname, "src"),
    devtool: "inline-sourcemap",
    entry: "./main.js",
    module: {
        loaders: [
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015','stage-0'],

                }
            }
        ]
    },
    output: {
        path: __dirname+ "/src",
        filename: "client.min.js"
    }
}

Tutorials


来源: stackexchange

问:
DataReader.GetFieldType returned null
In my db table Layout, there's one column whose type is hierarchyid (column index=4).
When trying to set-up new environment (a virtual web-server, created from XEN server), then running the site, I've met with this issue:

Exception message: DataReader.GetFieldType(4) returned null.
  Exception data: System.Collections.ListDictionaryInternal

I've made some search and found out there are already some topic on it (such as on MSDN).

But even when I added the C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.Types.dll library, it seems like db type in structure SqlHierarchyId doesn't get recognized.

"Exception at DataReader.GetFieldType(4) returned null" is still thrown out.

Note: The issue will be solved if I made installation of C# package in VS2010 onto the environment (Windows Server 2008 RC2), but my boss didn't accept that, because this is purely a simple web-server.

答:
After other solution if you still have error try to delete in web.config

```<code><add assembly="Microsoft.SqlServer.Types, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
</code>```

copy file Microsoft.SqlServer.Types.dll to bin folder (or/and add reference)

or/and add "Type System Version=SQL Server 2012;" in sqlconnectionstring

ContentLicense: CC BY-SA 3.0

Title: DataReader.GetFieldType returned null

Body:
After other solution if you still have error try to delete in web.config

<add assembly="Microsoft.SqlServer.Types, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>

copy file Microsoft.SqlServer.Types.dll to bin folder (or/and add reference)

or/and add "Type System Version=SQL Server 2012;" in sqlconnectionstring


问:
Prevent border clipping my image
Okay so I have an image and I want a border outline around it (which I can get). But even if the border is 'x' far away from my image, the image still gets clipped. ONLY HAPPENS WHEN BORDER-RADIUS PROPERTY IS SET. Hopefully, that made some sense but here's some images to show what I mean. Btw sorry if this is anywhere else it's hard to think of good keywords when there's a border-image-outset property and other crap.

   .slideshow {
   display: none;
   margin-top: -50px;
   font-size: 25px;
   }

.slideshow table {
  width: 100%;
}

.slideshow table tr td {
  text-align: center;
}

.icon_circle {
  overflow: hidden;
}

td span {
  display: block;
  border-radius: 90px;
  padding: 30px;
  border: #000 5px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="slideshow">
    <table>
      <tr>
        <td><img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td><img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td><img class="icon_circle" width="90px"  src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
      </tr>
    </table>
    <p>Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.</p>
  </div></code>```

Images:

No-Clipping

Clipping

Winrar logo

答:
```<code>overflow:none;
</code>```

on the div that's holding your image.

Title: Prevent border clipping my image

Body:
Okay so I have an image and I want a border outline around it (which I can get). But even if the border is 'x' far away from my image, the image still gets clipped. ONLY HAPPENS WHEN BORDER-RADIUS PROPERTY IS SET. Hopefully, that made some sense but here's some images to show what I mean. Btw sorry if this is anywhere else it's hard to think of good keywords when there's a border-image-outset property and other crap.

   .slideshow {
   display: none;
   margin-top: -50px;
   font-size: 25px;
   }

.slideshow table {
  width: 100%;
}

.slideshow table tr td {
  text-align: center;
}

.icon_circle {
  overflow: hidden;
}

td span {
  display: block;
  border-radius: 90px;
  padding: 30px;
  border: #000 5px solid;
}

Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.

Images:

No-Clipping

Clipping

Winrar logo

Body:
overflow:none;

on the div that's holding your image.


问:
Parsing Date Time in C#, Getting wrong output
I am trying to parse the date by using below code

```<code>DateTime mydate = DateTime.ParseExact(datetoconvert,"dd/mm/yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
</code>```

but its output is wrong, the datetoconvert in above code is 30/Mar/2017 but output is 29/Jan/2017

looking forward for your valuable answers...

答:
Lowercase mm means minute, use MM

```<code>DateTime mydate = DateTime.ParseExact(datetoconvert,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
</code>```

If you want to output it as 30/Mar/2017(different topic):

```<code>string result = mydate.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);
</code>```

But note that / has a special meaning too(in Parse and ToString). It will be replaced with your current cultures date-separator which seems to be / but fails with a different. You can avoid it by specifying CultureInfo.InvariantCulture or by masking it by wrapping it with apostrophes:

```<code>DateTime mydate = DateTime.ParseExact(datetoconvert,"dd'/'MM'/'yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
</code>```

Body:
I am trying to parse the date by using below code

DateTime mydate = DateTime.ParseExact(datetoconvert,"dd/mm/yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);

but its output is wrong, the datetoconvert in above code is 30/Mar/2017 but output is 29/Jan/2017

looking forward for your valuable answers...

Body:
Lowercase mm means minute, use MM

DateTime mydate = DateTime.ParseExact(datetoconvert,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);

If you want to output it as 30/Mar/2017(different topic):

string result = mydate.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);

But note that / has a special meaning too(in Parse and ToString). It will be replaced with your current cultures date-separator which seems to be / but fails with a different. You can avoid it by specifying CultureInfo.InvariantCulture or by masking it by wrapping it with apostrophes:

DateTime mydate = DateTime.ParseExact(datetoconvert,"dd'/'MM'/'yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);


问:
Differences between apktool and baksmali
As far as I know, both apktool and baksmali are able to produce smali code out of .apk (.dex) files, and apktool makes use of the dexlib2. They are both APK packing/unpacking tools

But still I am not clear what are the main differences between apktool and smali/baksmali. in temrs of functionality with .dex files and extended features?

PS:
One of the difference that I just found out is that apktool is able to work with multiple dex files inside an apk while baksmali cannot (at least for the time being)

I did try to read the source code but due to the lack of experience, I could not really understand the working flow of both tools. I would really appreciate If anyone could suggest some readings or flow charts, etc.

Thank you!

答:
In short, apktool is for APK files and baksmali is for DEX files.

APK file is a zip archive with specific structure. This represents the Android app. This is what your smart phone or tablet downloads from the market, usually Google Play. The archive consists of the manifest, resources, asserts/data files, native libraries and the DEX file.

DEX file contains the app code. See https://source.android.com/devices/tech/dalvik/dex-format.html for details.

One more thing to say, is that apktool is capable to extract and pack back the resources file. (I believe baksmali doesn't do that, need to check.)


问:
wrap_content larger than actual imageview
I have a simple question, I have a simple RelativeLayout with a single ImageView (soon to add more). However, the width and height of the ImageView are set to wrap_content but when checked, the width is aligned properly (probably because its the max width of the screen) but the height seems to wrap further than the actual image. The images were made via Adobe Illustrator and then exported out as a .png with a DPI of 480.

Example:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    tools:context=".MainActivity"
    android:background="#d1070707">

 <ImageView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:id="@+id/outer_shell"
     android:layout_centerVertical="true"
     android:layout_centerHorizontal="true"
     android:src="@drawable/out_shell" />

</RelativeLayout>
</code>```

[Couldn't post direct images due to rep < 10 but I wanted to show my issue
for a better understanding, links direct to the images]

The issue: http://postimg.org/image/75ijbo1zv/

Show that my image has no larger border: http://postimg.org/image/mog8ijghb/

However, If I were to move the image further down where the wrapped content area would theoretically get cut off, it resizes itself (height) smaller and smaller depending on the margin value I set.
So, if anyone has any idea why it acts like this and can explain, that would be great!

答:
It's an old question but someone may stumble upon it, so I'll leave an answer.

I had the same problem, and setting android:adjustViewBounds="true" helped me. It makes the ImageView resize itself to fit the image.

Body:
I have a simple question, I have a simple RelativeLayout with a single ImageView (soon to add more). However, the width and height of the ImageView are set to wrap_content but when checked, the width is aligned properly (probably because its the max width of the screen) but the height seems to wrap further than the actual image. The images were made via Adobe Illustrator and then exported out as a .png with a DPI of 480.

Example:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    tools:context=".MainActivity"
    android:background="#d1070707">

 <ImageView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:id="@+id/outer_shell"
     android:layout_centerVertical="true"
     android:layout_centerHorizontal="true"
     android:src="@drawable/out_shell" />

</RelativeLayout>

[Couldn't post direct images due to rep < 10 but I wanted to show my issue
for a better understanding, links direct to the images]

The issue: http://postimg.org/image/75ijbo1zv/

Show that my image has no larger border: http://postimg.org/image/mog8ijghb/

However, If I were to move the image further down where the wrapped content area would theoretically get cut off, it resizes itself (height) smaller and smaller depending on the margin value I set.
So, if anyone has any idea why it acts like this and can explain, that would be great!


问:
how to remove numeric characters before any alphabetic characters
I have one variable which has values like this

```<code>VAL1="59809_RH_EA_TEST_1_P1_Q"
</code>```

or

```<code>VAL1="89292-RH_EA_TEST_1_P1_Q"
</code>```

How can I get only RH_EA_TEST_1_P1_Q using sed or any other bash command

答:
With awk</p>

```<code>#!/bin/sh

rnum () { # remove numeric characters before any alphabetic characters
 awk '
 function ch(i) { return substr(ARGV[1], i, 1) } # ith character
 BEGIN {
         a = "[a-zA-Z]" ; d = "[0-9]"
         n = length(ARGV[1]); i = 1
         for ( ; i <= n && ch(i) !~ a; i++) if (ch(i) !~ d) ans = ans ch(i)
         for ( ; i <= n              ; i++)                 ans = ans ch(i)
         print ans
       }
 ' "$1"
}

# usage
rnum 59809_RH_EA_TEST_1_P1_Q
rnum 89292-RH_EA_TEST_1_P1_Q
rnum "123 abc 456 efg"
</code>```

Body:
I have one variable which has values like this

VAL1="59809_RH_EA_TEST_1_P1_Q"

or

VAL1="89292-RH_EA_TEST_1_P1_Q"

How can I get only RH_EA_TEST_1_P1_Q using sed or any other bash command

Body:
With awk

#!/bin/sh

rnum () { # remove numeric characters before any alphabetic characters
 awk '
 function ch(i) { return substr(ARGV[1], i, 1) } # ith character
 BEGIN {
         a = "[a-zA-Z]" ; d = "[0-9]"
         n = length(ARGV[1]); i = 1
         for ( ; i <= n && ch(i) !~ a; i++) if (ch(i) !~ d) ans = ans ch(i)
         for ( ; i <= n              ; i++)                 ans = ans ch(i)
         print ans
       }
 ' "$1"
}

# usage
rnum 59809_RH_EA_TEST_1_P1_Q
rnum 89292-RH_EA_TEST_1_P1_Q
rnum "123 abc 456 efg"


问:
Handle Ajax Auto Suggest Drop List using selenium
I want to enter value to the From field of http://busindia.com/ using the following code

```<code>driver.findElement(By.id("matchFromPlace")).sendKeys("Udupi");
</code>```

while typing udupi in the from input there appears a list of options beneath from which we select to select udupi.

答:
Below code worked for me:</p>

```<code>    Thread.sleep(2000);

    List<WebElement> OptionList = driver.findElements(By.xpath("//ul[contains(@class,'ui-autocomplete')]/li/a"));
    if(OptionList.size()>=1){
        for(int i=0;i<OptionList.size();i++)
        {
            String CurrentOption = OptionList.get(i).getText();
            if(CurrentOption.equalsIgnoreCase("UDUPI")){
                System.out.println("Found the city : "+CurrentOption);
                OptionList.get(i).click();
            }
        }
    }
    else{
        System.out.println("OptionList is empty");
    }
</code>```

Body:
I want to enter value to the From field of http://busindia.com/ using the following code

driver.findElement(By.id("matchFromPlace")).sendKeys("Udupi");

while typing udupi in the from input there appears a list of options beneath from which we select to select udupi.

Body:
Below code worked for me:

    Thread.sleep(2000);

    List<WebElement> OptionList = driver.findElements(By.xpath("//ul[contains(@class,'ui-autocomplete')]/li/a"));
    if(OptionList.size()>=1){
        for(int i=0;i<OptionList.size();i++)
        {
            String CurrentOption = OptionList.get(i).getText();
            if(CurrentOption.equalsIgnoreCase("UDUPI")){
                System.out.println("Found the city : "+CurrentOption);
                OptionList.get(i).click();
            }
        }
    }
    else{
        System.out.println("OptionList is empty");
    }


问:
Simple Math with JS
Hello I need a quick hand, I have this div below

$1500

I need to do some simple math with that amount I need to divide it in half, then divide it by 6 and display the result like below.

Pay as low as $"result here"

I am a graphic designer I need this for a webpage and I know this should be simple but I just can't figure it out I really appreciate any help here.

答:
hope it help.

 /*define a function to Deleting all characters other than numbers. in element*/
  function checkIsInteger(sTr){
  var newstr = "";
  if(typeof sTr !== "undefine" && sTr!=""){
   var indexInt = ['0','1','2','3','4','5','6','7','8','9'];
   for(var i=0;i<sTr.length;i++){
    var cek = sTr.substr(i,1)
    if(indexInt.indexOf(cek)>=0){
     newstr += sTr.substr(i,1);
    }
   }
  }
  return newstr;
 }

$("#res").html((parseInt(checkIsInteger($("#price").html()))/2)/6);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="price" id="price">$1500</div>
<label class="payment" id="pym">Pay as low as $<span id="res">result</span> here </label></code>```

Title: Simple Math with JS

Body:
hope it help.

 /*define a function to Deleting all characters other than numbers. in element*/
  function checkIsInteger(sTr){
  var newstr = "";
  if(typeof sTr !== "undefine" && sTr!=""){
   var indexInt = ['0','1','2','3','4','5','6','7','8','9'];
   for(var i=0;i<sTr.length;i++){
    var cek = sTr.substr(i,1)
    if(indexInt.indexOf(cek)>=0){
     newstr += sTr.substr(i,1);
    }
   }
  }
  return newstr;
 }

$("#res").html((parseInt(checkIsInteger($("#price").html()))/2)/6);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="price" id="price">$1500</div>
<label class="payment" id="pym">Pay as low as $<span id="res">result</span> here </label>


答:
replace

```<code>"dd/mm/yyyy"
</code>```

with

```<code>"dd/MMM/yyyy"
</code>```

because "Jan" is matched by MMM instead of mm (for minutes)

Reference

"MMM" The abbreviated name of the month.

https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Title: Parsing Date Time in C#, Getting wrong output

Body:
replace

"dd/mm/yyyy"

with

"dd/MMM/yyyy"

because "Jan" is matched by MMM instead of mm (for minutes)

Reference

"MMM" The abbreviated name of the month.

https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx


问:
Php days error when calculating -1 month
I surprised when i getting the issue in PHP date calculation.

```<code>$add = '- 30 days';
echo date('Y-m-01', strtotime($add)); // result is 2017-02-01 which is correct as need
</code>```

but in

```<code>$add = '-1 month';
echo date('Y-m-01', strtotime($add)); // result is 2017-03-01 which is in correct
</code>```

please help me in this how could i resolve this issue.

答:
You can have look at : http://php.net/manual/en/function.strtotime.php (explanations and comments)

Note:

Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.

Body:
I surprised when i getting the issue in PHP date calculation.

$add = '- 30 days';
echo date('Y-m-01', strtotime($add)); // result is 2017-02-01 which is correct as need

but in

$add = '-1 month';
echo date('Y-m-01', strtotime($add)); // result is 2017-03-01 which is in correct

please help me in this how could i resolve this issue.


问:
jQuery DataTables: Can I have 3 states for Sort : ASC, DESC and NO_SORT?
jQuery Datatable's sorting order on clicking column header toggles only between asc(Down Arrow) and desc(Up Arrow). i.e.,

```<code>1st-click ascending
2nd-click descending
3rd-click asc
4th-click desc
   ||   ||
   ||   ||
   ||   ||
   ||   ||
odd-click asc
even-click desc.
</code>```

I want to induce something like this :

```<code>1st-click ascending
2nd-click descending
3rd-click no-sorting
4th-click asc
5th-click desc
6th-click no-sort
   ||   ||
   ||   ||
   ||   ||
   ||   ||
(n%3==1)-click asc
(n%3==2)-click desc
(n%3==0)-click no-sort.
</code>```

Is there a way to change this behavior in jQuery dataTables? Please help!
Thanks in advance.

答:
when you load a table, it is sorted in a certain way (maybe by id, name or whatever). So what you call 'no-sorting' is, in fact, a 'sort by initial column'.

An easy approach is to let the sorting mechanism as it is, and place a button somewhere to reload the table deleting the current sort. Or even better, make this button sort the table by the initial column.

Body:
jQuery Datatable's sorting order on clicking column header toggles only between asc(Down Arrow) and desc(Up Arrow). i.e.,

1st-click ascending
2nd-click descending
3rd-click asc
4th-click desc
   ||   ||
   ||   ||
   ||   ||
   ||   ||
odd-click asc
even-click desc.

I want to induce something like this :

1st-click ascending
2nd-click descending
3rd-click no-sorting
4th-click asc
5th-click desc
6th-click no-sort
   ||   ||
   ||   ||
   ||   ||
   ||   ||
(n%3==1)-click asc
(n%3==2)-click desc
(n%3==0)-click no-sort.

Is there a way to change this behavior in jQuery dataTables? Please help!
Thanks in advance.


答:
Just follow the instructions at https://www.npmjs.com/package/babel-plugin-transform-react-jsx

First, create a new folder, test, and from the folder init a new project:

npm init

Install babel CLI

npm install --save-dev babel-cli

Then install babel-plugin-transform-react-jsx

npm i babel-plugin-transform-react-jsx

In the test folder create a sample jsx file index.jsx

```<code>var profile = <div>
  <img src="avatar.png" className="profile" />
  <h3>{[user.firstName, user.lastName].join(' ')}</h3>
</div>;
</code>```

And finally, run the transofmation command in you terminal from the test folder:

.\node_modules\.bin\babel --plugins transform-react-jsx index.jsx

You'll see the output in you terminal window.

Title: Transform JSX to JS using babel

Body:
Just follow the instructions at https://www.npmjs.com/package/babel-plugin-transform-react-jsx

First, create a new folder, test, and from the folder init a new project:

npm init

Install babel CLI

npm install --save-dev babel-cli

Then install babel-plugin-transform-react-jsx

npm i babel-plugin-transform-react-jsx

In the test folder create a sample jsx file index.jsx

var profile = <div>
  <img src="avatar.png" className="profile" />
  <h3>{[user.firstName, user.lastName].join(' ')}</h3>
</div>;

And finally, run the transofmation command in you terminal from the test folder:

.\node_modules\.bin\babel --plugins transform-react-jsx index.jsx

You'll see the output in you terminal window.


问:
ng-bootstrap ngbDropdown not working in angular 4
At my angular 4 application is the ngbDropdown-Element from ng-bootstrap not working.

I have installed the following npm modules for this case:

"@ng-bootstrap/ng-bootstrap": "^1.0.0-alpha.22",
 "bootstrap": "4.0.0-alpha.6",
 "bootstrap-sass": "^3.3.7",

My app.module.ts is looking like this:

```<code>import { BrowserModule } from "@angular/platform-browser"
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { HttpModule } from "@angular/http";

import { AppComponent } from "./app.component";
import { FileitHeaderComponent } from "./fileit-header/fileit-header.component";
import {TranslateModule} from "ng2-translate";
import { CCACampaignComponent } from "./cca-campaign/cca-campaign.component";
import {NgbModule} from "@ng-bootstrap/ng-bootstrap";

@NgModule({
  declarations: [
    AppComponent,
    FileitHeaderComponent,
    CCACampaignComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    TranslateModule.forRoot(),
    NgbModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

And in the CCA Campaign I am trying to use the Demo of ng-bootstrap:

```<code><div ngbDropdown class="d-inline-block">
    <button class="btn btn-outline-primary" id="dropdownMenu1" ngbDropdownToggle>Toggle dropdown</button>
        <div class="dropdown-menu" aria-labelledby="dropdownMenu1">
            <button class="dropdown-item">Action - 1</button>
            <button class="dropdown-item">Another Action</button>
            <button class="dropdown-item">Something else is here</button>
        </div>
</div>
</code>```

But the result of this code is unfortunately very bad:

and nothing happens when I click on it ...

答:
tl;dr; install Bootstrap 4 CSS.

ng-bootstrap requires Bootstrap 4 as documented on the "Getting Started" page. For some reason you've got "bootstrap-sass": "^3.3.7" so it looks like you are mixing Bootstrap versions and might be using Bootstrap 3, effectively.

With the Bootstrap 4 CSS things work perfectly fine as shown on the demo page (and plunkers you can fork from it): https://ng-bootstrap.github.io/#/components/dropdown

Body:
At my angular 4 application is the ngbDropdown-Element from ng-bootstrap not working.

I have installed the following npm modules for this case:

"@ng-bootstrap/ng-bootstrap": "^1.0.0-alpha.22",
 "bootstrap": "4.0.0-alpha.6",
 "bootstrap-sass": "^3.3.7",

My app.module.ts is looking like this:

import { BrowserModule } from "@angular/platform-browser"
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { HttpModule } from "@angular/http";

import { AppComponent } from "./app.component";
import { FileitHeaderComponent } from "./fileit-header/fileit-header.component";
import {TranslateModule} from "ng2-translate";
import { CCACampaignComponent } from "./cca-campaign/cca-campaign.component";
import {NgbModule} from "@ng-bootstrap/ng-bootstrap";

@NgModule({
  declarations: [
    AppComponent,
    FileitHeaderComponent,
    CCACampaignComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    TranslateModule.forRoot(),
    NgbModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And in the CCA Campaign I am trying to use the Demo of ng-bootstrap:

    <button class="btn btn-outline-primary" id="dropdownMenu1" ngbDropdownToggle>Toggle dropdown</button>

            <button class="dropdown-item">Action - 1</button>
            <button class="dropdown-item">Another Action</button>
            <button class="dropdown-item">Something else is here</button>

But the result of this code is unfortunately very bad:

and nothing happens when I click on it ...


问:
How to get each specific value in an array?
I'm looking to be able to extract each 'hire_address' value from the following array and add it to a separate array.

```<code>var addr =
{
   "status":"success",
   "data":[
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Glasgow",
         "offer_oucu":"ac1",
         "offer_address":"Glasgow"
      },
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Poole",
         "offer_oucu":"ac1",
         "offer_address":"Poole"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Hastings",
         "offer_oucu":"ac1",
         "offer_address":"Hastings"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"London",
         "offer_oucu":"ac1",
         "offer_address":"London"
      }
   ]
};
</code>```

I currently have

```<code>var addresses = [];
$.each(addr.data.hire_address, function (index, value) {
addresses.push(value);
</code>```

But not having any luck. Any suggestions?

Thank you for the replies.

I now have

```<code>var addresses = [];
$.each(addr, function (index, value) {
    if (value == "data"){
        addresses.push(value.hire_address);
    }
}
);
</code>```

But can't seem to get it to work. Do I need the if statement? I added this because the first item is 'status' and was running into errors if I tried to add a 'hire_address' property of this because it doesn't exists.

答:
After you fix up your object (see my comment), you can iterate simply without jQuery:

```<code>var addresses=[];
addr.data.forEach(function(a){
    addresses.push(a.hire_address);
});
alert(addresses);
</code>```

The JavaScript .forEach() array method does a similar job to jQuery’s .each() without the overhead.

Alternatively, for older browsers:

```<code>for(var i=0;i<addr.data.length;i++)
    addresses.push(addr.data[i].hire_address);
</code>```

Body:
I'm looking to be able to extract each 'hire_address' value from the following array and add it to a separate array.

var addr =
{
   "status":"success",
   "data":[
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Glasgow",
         "offer_oucu":"ac1",
         "offer_address":"Glasgow"
      },
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Poole",
         "offer_oucu":"ac1",
         "offer_address":"Poole"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"Hastings",
         "offer_oucu":"ac1",
         "offer_address":"Hastings"
      }
      {
         "start":"2017-01-26 12:30:00",
         "hire_oucu":"ac2",
         "hire_address":"London",
         "offer_oucu":"ac1",
         "offer_address":"London"
      }
   ]
};

I currently have

var addresses = [];
$.each(addr.data.hire_address, function (index, value) {
addresses.push(value);

But not having any luck. Any suggestions?

Thank you for the replies.

I now have

var addresses = [];
$.each(addr, function (index, value) {
    if (value == "data"){
        addresses.push(value.hire_address);
    }
}
);

But can't seem to get it to work. Do I need the if statement? I added this because the first item is 'status' and was running into errors if I tried to add a 'hire_address' property of this because it doesn't exists.

Body:
After you fix up your object (see my comment), you can iterate simply without jQuery:

var addresses=[];
addr.data.forEach(function(a){
    addresses.push(a.hire_address);
});
alert(addresses);

The JavaScript .forEach() array method does a similar job to jQuery’s .each() without the overhead.

Alternatively, for older browsers:

for(var i=0;i<addr.data.length;i++)
    addresses.push(addr.data[i].hire_address);


问:
Why global variable is different from local variable in this function?
Here I have a function named max(a,b) to get the max number out of two.
And I found that the value of variable a and b using printf()  are different after executing

```<code>printf("maxab()=%d after max: a=%d b=%d \n",max(a++,b++),a,b);
</code>```

when a and b are Global variables and Local variables. Below is my code:

```<code>#include<stdio.h>

int max(int a,int b)
{

    if(a>b)
    {
        //printf("In func max():%d %d \n",a,b);
        return a;
    }
    else {
        //printf("In func max():%d %d \n",a,b);
        return b;
    }

}
void jubu_test(void)
{
    int a=1;
    int b=2;
    printf("maxab()=%d after max: a=%d b=%d \n",max(a++,b++),a,b);  //a=2,b=3
}
int c=2;
int d=1;
void quanju_test(void)
{
    printf("maxcd()=%d  c=%d d=%d \n",max(c++,d++),c,d);    //c=2,d=1
    c=2;
    d=1;
    int f=max(c++,d++);
    printf("maxcd()=%d after max: c=%d d=%d \n",f,c,d);     //c=3,d=2
}
int main(int argc, char** argv)
{
    jubu_test();
    quanju_test();
}
</code>```

The result I get on my computer is:

```<code>maxab()=2 after max: a=2 b=3
maxcd()=2  c=2 d=1
maxcd()=2 after max: c=3 d=2
</code>```

My question is: Why in the second output a and b is their original value and why the third output is a+1 and b+1? Why when a and b are Global variables, the value of a and b printed out only changes when we execute max(a++,b++) first? Why when a and b are local variables it doesn't matter?

Thanks!
(using gcc 5.3.0 on windows 10)

答:
The expression printf(... max(a++,b++),a,b); is undefined behavior as per Why are these constructs (using ++) undefined behavior?.

The evaluation of a++ is not sequenced in relation to the evaluation of a, same for b++ and b. It doesn't matter that there is a sequence point before the function is called, because the sub-expressions may be evaluated before that, in any order.

Undefined behavior = always a bug. Means that the program could have any kind of behavior, print anything, crash & burn etc.

The reason why it is undefined behavior is this, C11 6.5/2:

If a side effect on a scalar object is unsequenced relative to either
  a different side effect on the same scalar object or a value
  computation using the value of the same scalar object, the behavior is
  undefined.

(a is a scalar object - not an array or struct etc. a++ causes a side-effect of updating the variable. This is unsequenced in relation of the value computation of a elsewhere in the same expression.)

Not to be confused with unspecified behavior, which means that the program will behave deterministically but you can't know in which way. For example, the order of evaluation of function arguments is unspecified behavior:

```<code>int func (void)
{
  static int x=0;
  x++;
  return x;
}

printf("%d %d", func(), func());
</code>```

This may print either 1 2 or 2 1 and we can't know or assume which applies. The compiler does not need to document this, nor does it have to behave consistently throughout the program. It could pick one order in one case and another order in another case.

Code relying on unspecified behavior is bad, but won't behave completely erratically like code containing undefined behavior.

Body:
Here I have a function named max(a,b) to get the max number out of two.
And I found that the value of variable a and b using printf()  are different after executing

printf("maxab()=%d after max: a=%d b=%d \n",max(a++,b++),a,b);

when a and b are Global variables and Local variables. Below is my code:

#include<stdio.h>

int max(int a,int b)
{

    if(a>b)
    {
        //printf("In func max():%d %d \n",a,b);
        return a;
    }
    else {
        //printf("In func max():%d %d \n",a,b);
        return b;
    }

}
void jubu_test(void)
{
    int a=1;
    int b=2;
    printf("maxab()=%d after max: a=%d b=%d \n",max(a++,b++),a,b);  //a=2,b=3
}
int c=2;
int d=1;
void quanju_test(void)
{
    printf("maxcd()=%d  c=%d d=%d \n",max(c++,d++),c,d);    //c=2,d=1
    c=2;
    d=1;
    int f=max(c++,d++);
    printf("maxcd()=%d after max: c=%d d=%d \n",f,c,d);     //c=3,d=2
}
int main(int argc, char** argv)
{
    jubu_test();
    quanju_test();
}

The result I get on my computer is:

maxab()=2 after max: a=2 b=3
maxcd()=2  c=2 d=1
maxcd()=2 after max: c=3 d=2

My question is: Why in the second output a and b is their original value and why the third output is a+1 and b+1? Why when a and b are Global variables, the value of a and b printed out only changes when we execute max(a++,b++) first? Why when a and b are local variables it doesn't matter?

Thanks!
(using gcc 5.3.0 on windows 10)

Body:
The expression printf(... max(a++,b++),a,b); is undefined behavior as per Why are these constructs (using ++) undefined behavior?.

The evaluation of a++ is not sequenced in relation to the evaluation of a, same for b++ and b. It doesn't matter that there is a sequence point before the function is called, because the sub-expressions may be evaluated before that, in any order.

Undefined behavior = always a bug. Means that the program could have any kind of behavior, print anything, crash & burn etc.

The reason why it is undefined behavior is this, C11 6.5/2:

If a side effect on a scalar object is unsequenced relative to either
  a different side effect on the same scalar object or a value
  computation using the value of the same scalar object, the behavior is
  undefined.

(a is a scalar object - not an array or struct etc. a++ causes a side-effect of updating the variable. This is unsequenced in relation of the value computation of a elsewhere in the same expression.)

Not to be confused with unspecified behavior, which means that the program will behave deterministically but you can't know in which way. For example, the order of evaluation of function arguments is unspecified behavior:

int func (void)
{
  static int x=0;
  x++;
  return x;
}

printf("%d %d", func(), func());

This may print either 1 2 or 2 1 and we can't know or assume which applies. The compiler does not need to document this, nor does it have to behave consistently throughout the program. It could pick one order in one case and another order in another case.

Code relying on unspecified behavior is bad, but won't behave completely erratically like code containing undefined behavior.


问:
Redux Thunk Middleware not working
I am implementing a basic login using Redux. When I created my store I did the following:

```<code>const store = createStore(
    reducers,
    applyMiddleware(thunk)
);
</code>```

Then in my actions I mapped to props the handler for login...

```<code>const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        loginRoute: (username,password) => {
            dispatch(loginRoute(username,password));
        },
        dispatch
    }
};
</code>```

The action is then dispatched on submit...

```<code>this.props.loginRoute(username.value,password.value);
</code>```

The login route function looks like this .....

```<code>export function loginRoute(username, password){
    return axios({
      method: 'post',
      url: '/login',
      data: {
        'username': username,
        'password': password
      }
    }).then((response)=>{
        if(response.data === "no username in database"){
          // send action to update state, no username in database
          return{
            type: "ERROR",
            response
          };
        }else if(response.data ==="incorrect password"){
          return{
            type: "ERROR",
            response
          };
        }else{
          return{
            type: 'LOGIN',
            data:response
          };
        }
    }).catch((error)=>{

      return{
        type: "ERROR",
        response: error
      };
    });
}
</code>```

However, with all of this I get the error Actions must be plain objects. Use custom middleware for async actions.

Any ideas as to why? I am using the thunk middleware and the logic seems to be correct.

答:
You need to return a function from your action creator:

```<code>export function loginRoute(username, password) {
    return function(dispatch, getState) {
        axios({...}).then((response) => {
            ...
            dispatch({type: 'LOGIN', data: response})
        }
    }
}
</code>```

You might use the shorthand syntax for this:

```<code>export const loginRoute = (username, password) => (dispatch, getState) => {
    ...
}
</code>```

Alternatively, there is another middleware that you can use, which should make it possible to implement exactly like you did above, https://github.com/acdlite/redux-promise

Title: Redux Thunk Middleware not working

Body:
I am implementing a basic login using Redux. When I created my store I did the following:

const store = createStore(
    reducers,
    applyMiddleware(thunk)
);

Then in my actions I mapped to props the handler for login...

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        loginRoute: (username,password) => {
            dispatch(loginRoute(username,password));
        },
        dispatch
    }
};

The action is then dispatched on submit...

this.props.loginRoute(username.value,password.value);

The login route function looks like this .....

export function loginRoute(username, password){
    return axios({
      method: 'post',
      url: '/login',
      data: {
        'username': username,
        'password': password
      }
    }).then((response)=>{
        if(response.data === "no username in database"){
          // send action to update state, no username in database
          return{
            type: "ERROR",
            response
          };
        }else if(response.data ==="incorrect password"){
          return{
            type: "ERROR",
            response
          };
        }else{
          return{
            type: 'LOGIN',
            data:response
          };
        }
    }).catch((error)=>{

      return{
        type: "ERROR",
        response: error
      };
    });
}

However, with all of this I get the error Actions must be plain objects. Use custom middleware for async actions.

Any ideas as to why? I am using the thunk middleware and the logic seems to be correct.

Body:
You need to return a function from your action creator:

export function loginRoute(username, password) {
    return function(dispatch, getState) {
        axios({...}).then((response) => {
            ...
            dispatch({type: 'LOGIN', data: response})
        }
    }
}

You might use the shorthand syntax for this:

export const loginRoute = (username, password) => (dispatch, getState) => {
    ...
}

Alternatively, there is another middleware that you can use, which should make it possible to implement exactly like you did above, https://github.com/acdlite/redux-promise


问:
How to create an even distribution over multiple sets?
This is for a hobby project and will be implemented with Python, but this is not really important. I'm mostly looking for a good algorithm.

I want to host a racing event with 2 to 30 drivers (num_drivers). The event has 2 to about 12 races (num_races), and I want each driver to have a fair chance according to their position at the start using somewhat random positioning. The problem is, which starting positions do I assign to each driver for each race?

An example: for an event with num_races=3 and num_drivers=4 (named "A" to "D") a pretty good setup would be

```<code>Race 1: A B C D
Race 2: C D B A
Race 3: D B A C
</code>```

The pole position would have a value of 1, the second position 2, and so on. So this setup gives quite equal values to each driver:

```<code>A: 1+4+3 = 8
B: 2+3+2 = 7
C: 3+1+4 = 8
D: 4+2+1 = 7
</code>```

In the end the sum of positions of each driver should ideally be the same as for every other driver. What would be a good generic algorithm (in pseudo code) for my problem when the number of drivers and number of races can vary? Is there even already an algorithm somewhere to look at?

答:
I found a nicely working PHP script on github that solves the problem for me.
So if anyone's interested in the answer to my problem:
https://github.com/FriendlyBaron/GridCreator</p>

Body:
This is for a hobby project and will be implemented with Python, but this is not really important. I'm mostly looking for a good algorithm.

I want to host a racing event with 2 to 30 drivers (num_drivers). The event has 2 to about 12 races (num_races), and I want each driver to have a fair chance according to their position at the start using somewhat random positioning. The problem is, which starting positions do I assign to each driver for each race?

An example: for an event with num_races=3 and num_drivers=4 (named "A" to "D") a pretty good setup would be

Race 1: A B C D
Race 2: C D B A
Race 3: D B A C

The pole position would have a value of 1, the second position 2, and so on. So this setup gives quite equal values to each driver:

A: 1+4+3 = 8
B: 2+3+2 = 7
C: 3+1+4 = 8
D: 4+2+1 = 7

In the end the sum of positions of each driver should ideally be the same as for every other driver. What would be a good generic algorithm (in pseudo code) for my problem when the number of drivers and number of races can vary? Is there even already an algorithm somewhere to look at?


问:
What is the easiest way to install BLAS and LAPACK for scipy?
I would like to run a programme that someone else has prepared and it includes scipy. I have tried to install scipy with

```<code>pip install scipy
</code>```

but it gives me a long error. I know there are ways with Anaconda and Canopy but I think these are long ways. I would like to have a short way. I have also tried

```<code>G:\determinator_Oskar>pip install scipy
Collecting scipy
  Using cached scipy-0.16.1.tar.gz
Building wheels for collected packages: scipy
  Running setup.py bdist_wheel for scipy
  Complete output from command g:\myve\scripts\python.exe -c "import setuptools;
__file__='e:\\temp_n~1\\pip-build-1xigxu\\scipy\\setup.py';exec(compile(open(__f
ile__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d e:\temp_
n~1\tmp07__zrpip-wheel-:
  lapack_opt_info:
  openblas_lapack_info:
    libraries openblas not found in ['g:\\myve\\lib', 'C:\\']
    NOT AVAILABLE

  lapack_mkl_info:
  mkl_info:
    libraries mkl,vml,guide not found in ['g:\\myve\\lib', 'C:\\']
    NOT AVAILABLE

    NOT AVAILABLE

  atlas_3_10_threads_info:
  Setting PTATLAS=ATLAS
    libraries tatlas,tatlas not found in g:\myve\lib
    libraries lapack_atlas not found in g:\myve\lib
    libraries tatlas,tatlas not found in C:\
    libraries lapack_atlas not found in C:\
  <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
    NOT AVAILABLE

  atlas_3_10_info:
    libraries satlas,satlas not found in g:\myve\lib
    libraries lapack_atlas not found in g:\myve\lib
    libraries satlas,satlas not found in C:\
    libraries lapack_atlas not found in C:\
  <class 'numpy.distutils.system_info.atlas_3_10_info'>
    NOT AVAILABLE

  atlas_threads_info:
  Setting PTATLAS=ATLAS
    libraries ptf77blas,ptcblas,atlas not found in g:\myve\lib
    libraries lapack_atlas not found in g:\myve\lib
    libraries ptf77blas,ptcblas,atlas not found in C:\
    libraries lapack_atlas not found in C:\
  <class 'numpy.distutils.system_info.atlas_threads_info'>
    NOT AVAILABLE

  atlas_info:
    libraries f77blas,cblas,atlas not found in g:\myve\lib
    libraries lapack_atlas not found in g:\myve\lib
    libraries f77blas,cblas,atlas not found in C:\
    libraries lapack_atlas not found in C:\
  <class 'numpy.distutils.system_info.atlas_info'>
    NOT AVAILABLE

  lapack_info:
    libraries lapack not found in ['g:\\myve\\lib', 'C:\\']
    NOT AVAILABLE

  lapack_src_info:
    NOT AVAILABLE

    NOT AVAILABLE

  g:\myve\lib\site-packages\numpy\distutils\system_info.py:1552: UserWarning:
      Atlas (http://math-atlas.sourceforge.net/) libraries not found.
      Directories to search for the libraries can be specified in the
      numpy/distutils/site.cfg file (section [atlas]) or by setting
      the ATLAS environment variable.
    warnings.warn(AtlasNotFoundError.__doc__)
  g:\myve\lib\site-packages\numpy\distutils\system_info.py:1563: UserWarning:
      Lapack (http://www.netlib.org/lapack/) libraries not found.
      Directories to search for the libraries can be specified in the
      numpy/distutils/site.cfg file (section [lapack]) or by setting
      the LAPACK environment variable.
    warnings.warn(LapackNotFoundError.__doc__)
  g:\myve\lib\site-packages\numpy\distutils\system_info.py:1566: UserWarning:
      Lapack (http://www.netlib.org/lapack/) sources not found.
      Directories to search for the sources can be specified in the
      numpy/distutils/site.cfg file (section [lapack_src]) or by setting
      the LAPACK_SRC environment variable.
    warnings.warn(LapackSrcNotFoundError.__doc__)
  Running from scipy source directory.
  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "e:\temp_n~1\pip-build-1xigxu\scipy\setup.py", line 253, in <module>
      setup_package()
    File "e:\temp_n~1\pip-build-1xigxu\scipy\setup.py", line 250, in setup_packa
ge
      setup(**metadata)
    File "g:\myve\lib\site-packages\numpy\distutils\core.py", line 135, in setup

      config = configuration()
    File "e:\temp_n~1\pip-build-1xigxu\scipy\setup.py", line 175, in configurati
on
      config.add_subpackage('scipy')
    File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in
 add_subpackage
      caller_level = 2)
    File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 970, in
get_subpackage
      caller_level = caller_level + 1)
    File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 907, in
_get_configuration_from_setup_py
      config = setup_module.configuration(*args)
    File "scipy\setup.py", line 15, in configuration
      config.add_subpackage('linalg')
    File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in
 add_subpackage
      caller_level = 2)
    File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 970, in
get_subpackage
      caller_level = caller_level + 1)
    File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 907, in
_get_configuration_from_setup_py
      config = setup_module.configuration(*args)
    File "scipy\linalg\setup.py", line 20, in configuration
      raise NotFoundError('no lapack/blas resources found')
  numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

  ----------------------------------------
  Failed building wheel for scipy
Failed to build scipy
Installing collected packages: scipy
  Running setup.py install for scipy
    Complete output from command g:\myve\scripts\python.exe -c "import setuptool
s, tokenize;__file__='e:\\temp_n~1\\pip-build-1xigxu\\scipy\\setup.py';exec(comp
ile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __fi
le__, 'exec'))" install --record e:\temp_n~1\pip-3hncqr-record\install-record.tx
t --single-version-externally-managed --compile --install-headers g:\myve\includ
e\site\python2.7\scipy:
    lapack_opt_info:
    openblas_lapack_info:
      libraries openblas not found in ['g:\\myve\\lib', 'C:\\']
      NOT AVAILABLE

    lapack_mkl_info:
    mkl_info:
      libraries mkl,vml,guide not found in ['g:\\myve\\lib', 'C:\\']
      NOT AVAILABLE

      NOT AVAILABLE

    atlas_3_10_threads_info:
    Setting PTATLAS=ATLAS
      libraries tatlas,tatlas not found in g:\myve\lib
      libraries lapack_atlas not found in g:\myve\lib
      libraries tatlas,tatlas not found in C:\
      libraries lapack_atlas not found in C:\
    <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
      NOT AVAILABLE

    atlas_3_10_info:
      libraries satlas,satlas not found in g:\myve\lib
      libraries lapack_atlas not found in g:\myve\lib
      libraries satlas,satlas not found in C:\
      libraries lapack_atlas not found in C:\
    <class 'numpy.distutils.system_info.atlas_3_10_info'>
      NOT AVAILABLE

    atlas_threads_info:
    Setting PTATLAS=ATLAS
      libraries ptf77blas,ptcblas,atlas not found in g:\myve\lib
      libraries lapack_atlas not found in g:\myve\lib
      libraries ptf77blas,ptcblas,atlas not found in C:\
      libraries lapack_atlas not found in C:\
    <class 'numpy.distutils.system_info.atlas_threads_info'>
      NOT AVAILABLE

    atlas_info:
      libraries f77blas,cblas,atlas not found in g:\myve\lib
      libraries lapack_atlas not found in g:\myve\lib
      libraries f77blas,cblas,atlas not found in C:\
      libraries lapack_atlas not found in C:\
    <class 'numpy.distutils.system_info.atlas_info'>
      NOT AVAILABLE

    lapack_info:
      libraries lapack not found in ['g:\\myve\\lib', 'C:\\']
      NOT AVAILABLE

    lapack_src_info:
      NOT AVAILABLE

      NOT AVAILABLE

    g:\myve\lib\site-packages\numpy\distutils\system_info.py:1552: UserWarning:
        Atlas (http://math-atlas.sourceforge.net/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [atlas]) or by setting
        the ATLAS environment variable.
      warnings.warn(AtlasNotFoundError.__doc__)
    g:\myve\lib\site-packages\numpy\distutils\system_info.py:1563: UserWarning:
        Lapack (http://www.netlib.org/lapack/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [lapack]) or by setting
        the LAPACK environment variable.
      warnings.warn(LapackNotFoundError.__doc__)
    g:\myve\lib\site-packages\numpy\distutils\system_info.py:1566: UserWarning:
        Lapack (http://www.netlib.org/lapack/) sources not found.
        Directories to search for the sources can be specified in the
        numpy/distutils/site.cfg file (section [lapack_src]) or by setting
        the LAPACK_SRC environment variable.
      warnings.warn(LapackSrcNotFoundError.__doc__)
    Running from scipy source directory.
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "e:\temp_n~1\pip-build-1xigxu\scipy\setup.py", line 253, in <module>
        setup_package()
      File "e:\temp_n~1\pip-build-1xigxu\scipy\setup.py", line 250, in setup_pac
kage
        setup(**metadata)
      File "g:\myve\lib\site-packages\numpy\distutils\core.py", line 135, in set
up
        config = configuration()
      File "e:\temp_n~1\pip-build-1xigxu\scipy\setup.py", line 175, in configura
tion
        config.add_subpackage('scipy')
      File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 1001,
in add_subpackage
        caller_level = 2)
      File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 970, i
n get_subpackage
        caller_level = caller_level + 1)
      File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 907, i
n _get_configuration_from_setup_py
        config = setup_module.configuration(*args)
      File "scipy\setup.py", line 15, in configuration
        config.add_subpackage('linalg')
      File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 1001,
in add_subpackage
        caller_level = 2)
      File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 970, i
n get_subpackage
        caller_level = caller_level + 1)
      File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 907, i
n _get_configuration_from_setup_py
        config = setup_module.configuration(*args)
      File "scipy\linalg\setup.py", line 20, in configuration
        raise NotFoundError('no lapack/blas resources found')
    numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

    ----------------------------------------
Command "g:\myve\scripts\python.exe -c "import setuptools, tokenize;__file__='e:
\\temp_n~1\\pip-build-1xigxu\\scipy\\setup.py';exec(compile(getattr(tokenize, 'o
pen', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install
--record e:\temp_n~1\pip-3hncqr-record\install-record.txt --single-version-exter
nally-managed --compile --install-headers g:\myve\include\site\python2.7\scipy"
failed with error code 1 in e:\temp_n~1\pip-build-1xigxu\scipy
</code>```

I have also tried

```<code>pip install lapack
</code>```

with this result

```<code>Collecting lapack
  Could not find a version that satisfies the requirement lapack (from versions
 )
No matching distribution found for lapack
</code>```

I have also tried

```<code>pip install blas
</code>```

with similar results

```<code>G:\determinator_Oskar>pip install blas
Collecting blas
  Could not find a version that satisfies the requirement blas (from versions: )

No matching distribution found for blas
</code>```

Why does a scipy get so complicated ?

答:
For windows: Best is to use pre-compiled package available from this site:
http://www.lfd.uci.edu/%7Egohlke/pythonlibs/#scipy</p>

Body:
I would like to run a programme that someone else has prepared and it includes scipy. I have tried to install scipy with

pip install scipy

but it gives me a long error. I know there are ways with Anaconda and Canopy but I think these are long ways. I would like to have a short way. I have also tried

G:\determinator_Oskar>pip install scipy
Collecting scipy
  Using cached scipy-0.16.1.tar.gz
Building wheels for collected packages: scipy
  Running setup.py bdist_wheel for scipy
  Complete output from command g:\myve\scripts\python.exe -c "import setuptools;
__file__='e:\\temp_n~1\\pip-build-1xigxu\\scipy\\setup.py';exec(compile(open(__f
ile__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d e:\temp_
n~1\tmp07__zrpip-wheel-:
  lapack_opt_info:
  openblas_lapack_info:
    libraries openblas not found in ['g:\\myve\\lib', 'C:\\']
    NOT AVAILABLE

  lapack_mkl_info:
  mkl_info:
    libraries mkl,vml,guide not found in ['g:\\myve\\lib', 'C:\\']
    NOT AVAILABLE

    NOT AVAILABLE

  atlas_3_10_threads_info:
  Setting PTATLAS=ATLAS
    libraries tatlas,tatlas not found in g:\myve\lib
    libraries lapack_atlas not found in g:\myve\lib
    libraries tatlas,tatlas not found in C:\
    libraries lapack_atlas not found in C:\
  <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
    NOT AVAILABLE

  atlas_3_10_info:
    libraries satlas,satlas not found in g:\myve\lib
    libraries lapack_atlas not found in g:\myve\lib
    libraries satlas,satlas not found in C:\
    libraries lapack_atlas not found in C:\
  <class 'numpy.distutils.system_info.atlas_3_10_info'>
    NOT AVAILABLE

  atlas_threads_info:
  Setting PTATLAS=ATLAS
    libraries ptf77blas,ptcblas,atlas not found in g:\myve\lib
    libraries lapack_atlas not found in g:\myve\lib
    libraries ptf77blas,ptcblas,atlas not found in C:\
    libraries lapack_atlas not found in C:\
  <class 'numpy.distutils.system_info.atlas_threads_info'>
    NOT AVAILABLE

  atlas_info:
    libraries f77blas,cblas,atlas not found in g:\myve\lib
    libraries lapack_atlas not found in g:\myve\lib
    libraries f77blas,cblas,atlas not found in C:\
    libraries lapack_atlas not found in C:\
  <class 'numpy.distutils.system_info.atlas_info'>
    NOT AVAILABLE

  lapack_info:
    libraries lapack not found in ['g:\\myve\\lib', 'C:\\']
    NOT AVAILABLE

  lapack_src_info:
    NOT AVAILABLE

    NOT AVAILABLE

  g:\myve\lib\site-packages\numpy\distutils\system_info.py:1552: UserWarning:
      Atlas (http://math-atlas.sourceforge.net/) libraries not found.
      Directories to search for the libraries can be specified in the
      numpy/distutils/site.cfg file (section [atlas]) or by setting
      the ATLAS environment variable.
    warnings.warn(AtlasNotFoundError.__doc__)
  g:\myve\lib\site-packages\numpy\distutils\system_info.py:1563: UserWarning:
      Lapack (http://www.netlib.org/lapack/) libraries not found.
      Directories to search for the libraries can be specified in the
      numpy/distutils/site.cfg file (section [lapack]) or by setting
      the LAPACK environment variable.
    warnings.warn(LapackNotFoundError.__doc__)
  g:\myve\lib\site-packages\numpy\distutils\system_info.py:1566: UserWarning:
      Lapack (http://www.netlib.org/lapack/) sources not found.
      Directories to search for the sources can be specified in the
      numpy/distutils/site.cfg file (section [lapack_src]) or by setting
      the LAPACK_SRC environment variable.
    warnings.warn(LapackSrcNotFoundError.__doc__)
  Running from scipy source directory.
  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "e:\temp_n~1\pip-build-1xigxu\scipy\setup.py", line 253, in <module>
      setup_package()
    File "e:\temp_n~1\pip-build-1xigxu\scipy\setup.py", line 250, in setup_packa
ge
      setup(**metadata)
    File "g:\myve\lib\site-packages\numpy\distutils\core.py", line 135, in setup

      config = configuration()
    File "e:\temp_n~1\pip-build-1xigxu\scipy\setup.py", line 175, in configurati
on
      config.add_subpackage('scipy')
    File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in
 add_subpackage
      caller_level = 2)
    File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 970, in
get_subpackage
      caller_level = caller_level + 1)
    File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 907, in
_get_configuration_from_setup_py
      config = setup_module.configuration(*args)
    File "scipy\setup.py", line 15, in configuration
      config.add_subpackage('linalg')
    File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 1001, in
 add_subpackage
      caller_level = 2)
    File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 970, in
get_subpackage
      caller_level = caller_level + 1)
    File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 907, in
_get_configuration_from_setup_py
      config = setup_module.configuration(*args)
    File "scipy\linalg\setup.py", line 20, in configuration
      raise NotFoundError('no lapack/blas resources found')
  numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

  ----------------------------------------
  Failed building wheel for scipy
Failed to build scipy
Installing collected packages: scipy
  Running setup.py install for scipy
    Complete output from command g:\myve\scripts\python.exe -c "import setuptool
s, tokenize;__file__='e:\\temp_n~1\\pip-build-1xigxu\\scipy\\setup.py';exec(comp
ile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __fi
le__, 'exec'))" install --record e:\temp_n~1\pip-3hncqr-record\install-record.tx
t --single-version-externally-managed --compile --install-headers g:\myve\includ
e\site\python2.7\scipy:
    lapack_opt_info:
    openblas_lapack_info:
      libraries openblas not found in ['g:\\myve\\lib', 'C:\\']
      NOT AVAILABLE

    lapack_mkl_info:
    mkl_info:
      libraries mkl,vml,guide not found in ['g:\\myve\\lib', 'C:\\']
      NOT AVAILABLE

      NOT AVAILABLE

    atlas_3_10_threads_info:
    Setting PTATLAS=ATLAS
      libraries tatlas,tatlas not found in g:\myve\lib
      libraries lapack_atlas not found in g:\myve\lib
      libraries tatlas,tatlas not found in C:\
      libraries lapack_atlas not found in C:\
    <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
      NOT AVAILABLE

    atlas_3_10_info:
      libraries satlas,satlas not found in g:\myve\lib
      libraries lapack_atlas not found in g:\myve\lib
      libraries satlas,satlas not found in C:\
      libraries lapack_atlas not found in C:\
    <class 'numpy.distutils.system_info.atlas_3_10_info'>
      NOT AVAILABLE

    atlas_threads_info:
    Setting PTATLAS=ATLAS
      libraries ptf77blas,ptcblas,atlas not found in g:\myve\lib
      libraries lapack_atlas not found in g:\myve\lib
      libraries ptf77blas,ptcblas,atlas not found in C:\
      libraries lapack_atlas not found in C:\
    <class 'numpy.distutils.system_info.atlas_threads_info'>
      NOT AVAILABLE

    atlas_info:
      libraries f77blas,cblas,atlas not found in g:\myve\lib
      libraries lapack_atlas not found in g:\myve\lib
      libraries f77blas,cblas,atlas not found in C:\
      libraries lapack_atlas not found in C:\
    <class 'numpy.distutils.system_info.atlas_info'>
      NOT AVAILABLE

    lapack_info:
      libraries lapack not found in ['g:\\myve\\lib', 'C:\\']
      NOT AVAILABLE

    lapack_src_info:
      NOT AVAILABLE

      NOT AVAILABLE

    g:\myve\lib\site-packages\numpy\distutils\system_info.py:1552: UserWarning:
        Atlas (http://math-atlas.sourceforge.net/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [atlas]) or by setting
        the ATLAS environment variable.
      warnings.warn(AtlasNotFoundError.__doc__)
    g:\myve\lib\site-packages\numpy\distutils\system_info.py:1563: UserWarning:
        Lapack (http://www.netlib.org/lapack/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [lapack]) or by setting
        the LAPACK environment variable.
      warnings.warn(LapackNotFoundError.__doc__)
    g:\myve\lib\site-packages\numpy\distutils\system_info.py:1566: UserWarning:
        Lapack (http://www.netlib.org/lapack/) sources not found.
        Directories to search for the sources can be specified in the
        numpy/distutils/site.cfg file (section [lapack_src]) or by setting
        the LAPACK_SRC environment variable.
      warnings.warn(LapackSrcNotFoundError.__doc__)
    Running from scipy source directory.
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "e:\temp_n~1\pip-build-1xigxu\scipy\setup.py", line 253, in <module>
        setup_package()
      File "e:\temp_n~1\pip-build-1xigxu\scipy\setup.py", line 250, in setup_pac
kage
        setup(**metadata)
      File "g:\myve\lib\site-packages\numpy\distutils\core.py", line 135, in set
up
        config = configuration()
      File "e:\temp_n~1\pip-build-1xigxu\scipy\setup.py", line 175, in configura
tion
        config.add_subpackage('scipy')
      File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 1001,
in add_subpackage
        caller_level = 2)
      File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 970, i
n get_subpackage
        caller_level = caller_level + 1)
      File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 907, i
n _get_configuration_from_setup_py
        config = setup_module.configuration(*args)
      File "scipy\setup.py", line 15, in configuration
        config.add_subpackage('linalg')
      File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 1001,
in add_subpackage
        caller_level = 2)
      File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 970, i
n get_subpackage
        caller_level = caller_level + 1)
      File "g:\myve\lib\site-packages\numpy\distutils\misc_util.py", line 907, i
n _get_configuration_from_setup_py
        config = setup_module.configuration(*args)
      File "scipy\linalg\setup.py", line 20, in configuration
        raise NotFoundError('no lapack/blas resources found')
    numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

    ----------------------------------------
Command "g:\myve\scripts\python.exe -c "import setuptools, tokenize;__file__='e:
\\temp_n~1\\pip-build-1xigxu\\scipy\\setup.py';exec(compile(getattr(tokenize, 'o
pen', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install
--record e:\temp_n~1\pip-3hncqr-record\install-record.txt --single-version-exter
nally-managed --compile --install-headers g:\myve\include\site\python2.7\scipy"
failed with error code 1 in e:\temp_n~1\pip-build-1xigxu\scipy

I have also tried

pip install lapack

with this result

Collecting lapack
  Could not find a version that satisfies the requirement lapack (from versions
 )
No matching distribution found for lapack

I have also tried

pip install blas

with similar results

G:\determinator_Oskar>pip install blas
Collecting blas
  Could not find a version that satisfies the requirement blas (from versions: )

No matching distribution found for blas

Why does a scipy get so complicated ?


问:
Angular 2 - Is there an event, when UI binding is finished
If I change the value of a bounded object in my component, angular automatically updates the value on the UI. This update-process takes some milliseconds (depend on the device). Is there an event when the UI-update-process finished?

At the moment I use following code:

```<code>// refresh binding
boundedItem = newValue;

// wait 100 milliseconds and the open the browsers print view
setTimeout(() => {
    // open browser print view
}, 100);
</code>```

On slow devices (smartphones) the process could be take more than 100 milliseconds, so the code is not really clean.

答:
You can try this Life-cycle hook:</p>

```<code>ngAfterViewInit(){

}
</code>```

Body:
If I change the value of a bounded object in my component, angular automatically updates the value on the UI. This update-process takes some milliseconds (depend on the device). Is there an event when the UI-update-process finished?

At the moment I use following code:

// refresh binding
boundedItem = newValue;

// wait 100 milliseconds and the open the browsers print view
setTimeout(() => {
    // open browser print view
}, 100);

On slow devices (smartphones) the process could be take more than 100 milliseconds, so the code is not really clean.

Body:
You can try this Life-cycle hook:

ngAfterViewInit(){

}


问:
reference & pointers confusing parts(declarations and their types)
I'm studying pointer and reference parts and having very hard time to study them.
I think I understand now some simple usage of reference and pointers in the function, but there is something I cannot totally understand.

Here are some variable declarations:

```<code>int a = 1;
float b = 2;
int* p = &a;
string s = "Hello";
vector<int*> values = {p};
</code>```

What will be the types of the following expressions?

```<code>&a
&b
p
&p
&s
&(s.at(1))
values.at(0)
&(values.at(0))
&values
</code>```

I have no idea what their types exactly are, but I tried it myself.

```<code>&a : pointer to int
&b : pointer float
 p : pointer to int
&p : pointer to pointer to int
&s : pointer to string
&(s.at(1)) : pointer to string
values.at(0) : pointer to int
&(values.at(0)) : pointer to pointer to int
&values : pointer to pointer to int
</code>```

and one more problem >
write the following variable declarations:
a) A pointer to a string
b) A reference to a float
c) An array of pointers-to-ints.
d) A pointer to a pointer to bool
e) A reference to a pointer to an int

and my answers are:

```<code>a: string* s = "Hello"

b: float& f = g;

c: int n =1;
   int*x =&n;
   int arr[] = {*x};

d: bool y = true;
   bool* x = &y;
   bool** qq = &x;

e: int a = 1;
   int* x = &a;
   int& z = *x;
</code>```

I'm not sure about my answers. Please help these confusing parts.

答:
If you need to know the exact type of an expression and if you can use Boost, it provides a great functionality.

```<code>#include <boost/type_index.hpp>
#include <iostream>
#include <string>
#include <vector>

#define TYPE(x) std::cout << "decltype(" << #x << ") == " << type_id_with_cvr<decltype(x)>().pretty_name() << std::endl

int main()
{
    using boost::typeindex::type_id_with_cvr;

    int a;
    TYPE(a);

    int * p = &a;
    TYPE(p);
    TYPE(&p);

    std::vector<int*> values {p};
    TYPE(values.at(0));
    TYPE(&(values.at(0)));
    TYPE(&values);
}
</code>```

If you can't use Boost, you can still deliberately create a template error to force the compiler to show you the type of expressions (from a talk of Scott Meyers, a great expert of C++).

```<code>#include <iostream>
#include <string>
#include <vector>

template <typename T>
    class TD;

template <typename T>
void function(T & param)
{
    TD<T> templateType;
    TD<decltype(param)> paramType;
}

int main()
{
    int a;
    function(a);

    int * p = &a;
    function(p);
    function(&p);

    std::vector<int*> values {p};
    function(&values);
}
</code>```

c) An array of pointers-to-ints

You created an array of int containing a single value, the value to wish the pointer refers to. As said previously, you need a int* [] array.

Body:
I'm studying pointer and reference parts and having very hard time to study them.
I think I understand now some simple usage of reference and pointers in the function, but there is something I cannot totally understand.

Here are some variable declarations:

int a = 1;
float b = 2;
int* p = &a;
string s = "Hello";
vector<int*> values = {p};

What will be the types of the following expressions?

&a
&b
p
&p
&s
&(s.at(1))
values.at(0)
&(values.at(0))
&values

I have no idea what their types exactly are, but I tried it myself.

&a : pointer to int
&b : pointer float
 p : pointer to int
&p : pointer to pointer to int
&s : pointer to string
&(s.at(1)) : pointer to string
values.at(0) : pointer to int
&(values.at(0)) : pointer to pointer to int
&values : pointer to pointer to int

and one more problem >
write the following variable declarations:
a) A pointer to a string
b) A reference to a float
c) An array of pointers-to-ints.
d) A pointer to a pointer to bool
e) A reference to a pointer to an int

and my answers are:

a: string* s = "Hello"

b: float& f = g;

c: int n =1;
   int*x =&n;
   int arr[] = {*x};

d: bool y = true;
   bool* x = &y;
   bool** qq = &x;

e: int a = 1;
   int* x = &a;
   int& z = *x;

I'm not sure about my answers. Please help these confusing parts.

Body:
If you need to know the exact type of an expression and if you can use Boost, it provides a great functionality.

#include <boost/type_index.hpp>
#include <iostream>
#include <string>
#include <vector>

#define TYPE(x) std::cout << "decltype(" << #x << ") == " << type_id_with_cvr<decltype(x)>().pretty_name() << std::endl

int main()
{
    using boost::typeindex::type_id_with_cvr;

    int a;
    TYPE(a);

    int * p = &a;
    TYPE(p);
    TYPE(&p);

    std::vector<int*> values {p};
    TYPE(values.at(0));
    TYPE(&(values.at(0)));
    TYPE(&values);
}

If you can't use Boost, you can still deliberately create a template error to force the compiler to show you the type of expressions (from a talk of Scott Meyers, a great expert of C++).

#include <iostream>
#include <string>
#include <vector>

template <typename T>
    class TD;

template <typename T>
void function(T & param)
{
    TD<T> templateType;
    TD<decltype(param)> paramType;
}

int main()
{
    int a;
    function(a);

    int * p = &a;
    function(p);
    function(&p);

    std::vector<int*> values {p};
    function(&values);
}

c) An array of pointers-to-ints

You created an array of int containing a single value, the value to wish the pointer refers to. As said previously, you need a int* [] array.


问:
java.lang.LinkageError: Failed to link freemarker/core/TemplateElement
My problem is that i have an ejb which internally uses freemarker tool to generate a HTML page, built and deployed to JBoss EAP 6.4.10. When i try to access this functionality (which generates HTML code using freemarker tool), jboss throwing below errors:

java.lang.LinkageError: Failed to link freemarker/core/TemplateElement
  Caused by: java.lang.NoClassDefFoundError: javax/swing/tree/TreeNode

I added freemarker jar in my jboss modules and it's module.xml looks like this:

```<code><module xmlns="urn:jboss:module:1.1" name="org.freemarker">
<resources>
    <resource-root path="freemarker-2.3.25.jar"/>
</resources>

<dependencies>
</dependencies>
</module>
</code>```

答:
The Google App Engine has this same problem, that some classes that are mandatory in Java SE aren't present there. So try to use org.freemarker:freemarker-gae instead of plain org.freemarker:freemarker.

What kind of platform is that anyway, why's that class missing? Is it Google App Engine?

Update: Certainly JBoss EAP's class loader doesn't export the javax.swing package from some reason (see comments). While using freemarker-gae works that around, then you have to be careful to exclude the non-gae FreeMarker-s coming from elsewhere as transitive Maven (or Gradle, etc.) dependencies. So it would be more maintainable to fix the JBoss modules configuration instead. I saw some start JBoss EAP with -Djboss.modules.system.pkgs=javax.swing, though if Swing is available for other modules in the same JVM, then there must be a more elegant solution, such as adding something to deployment-structure.xml, or if you define your own JBoss modules then to its module.xml. Maybe you should check which standard module exports the swing packages ("javax.api"?), and try to declare that module as a dependency.

Body:
My problem is that i have an ejb which internally uses freemarker tool to generate a HTML page, built and deployed to JBoss EAP 6.4.10. When i try to access this functionality (which generates HTML code using freemarker tool), jboss throwing below errors:

java.lang.LinkageError: Failed to link freemarker/core/TemplateElement
  Caused by: java.lang.NoClassDefFoundError: javax/swing/tree/TreeNode

I added freemarker jar in my jboss modules and it's module.xml looks like this:

<module xmlns="urn:jboss:module:1.1" name="org.freemarker">
<resources>
    <resource-root path="freemarker-2.3.25.jar"/>
</resources>

<dependencies>
</dependencies>
</module>


问:
Prevent border clipping my image
Okay so I have an image and I want a border outline around it (which I can get). But even if the border is 'x' far away from my image, the image still gets clipped. ONLY HAPPENS WHEN BORDER-RADIUS PROPERTY IS SET. Hopefully, that made some sense but here's some images to show what I mean. Btw sorry if this is anywhere else it's hard to think of good keywords when there's a border-image-outset property and other crap.

   .slideshow {
   display: none;
   margin-top: -50px;
   font-size: 25px;
   }

.slideshow table {
  width: 100%;
}

.slideshow table tr td {
  text-align: center;
}

.icon_circle {
  overflow: hidden;
}

td span {
  display: block;
  border-radius: 90px;
  padding: 30px;
  border: #000 5px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="slideshow">
    <table>
      <tr>
        <td><img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td><img class="icon_circle" width="90px" src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
        <td><img class="icon_circle" width="90px"  src="https://i.stack.imgur.com/N2SF1.png" alt=""></td>
      </tr>
    </table>
    <p>Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.</p>
  </div></code>```

Images:

No-Clipping

Clipping

Winrar logo

答:
Add padding in the image e.g.</p>

```<code>.image {
   padding: 10px;
}
</code>```

Title: Prevent border clipping my image

Body:
Okay so I have an image and I want a border outline around it (which I can get). But even if the border is 'x' far away from my image, the image still gets clipped. ONLY HAPPENS WHEN BORDER-RADIUS PROPERTY IS SET. Hopefully, that made some sense but here's some images to show what I mean. Btw sorry if this is anywhere else it's hard to think of good keywords when there's a border-image-outset property and other crap.

   .slideshow {
   display: none;
   margin-top: -50px;
   font-size: 25px;
   }

.slideshow table {
  width: 100%;
}

.slideshow table tr td {
  text-align: center;
}

.icon_circle {
  overflow: hidden;
}

td span {
  display: block;
  border-radius: 90px;
  padding: 30px;
  border: #000 5px solid;
}

Lorem ipdrepnt occaecqui officia deserunt mollit anim id est laborum.

Images:

No-Clipping

Clipping

Winrar logo

Body:
Add padding in the image e.g.

.image {
   padding: 10px;
}


答:
You can just iterate over wanted days, then you add nested iteration over wanted hours. For the possibility to compare objects you need to convert strings into datetime objects with strptime function. Finally, you can get output in arbitrary format with .strftime method of datetime object.

```<code>import datetime

start_time = '9:00'
end_time = '18:00'
slot_time = 10

# Start date from today to next 5 day
start_date = datetime.datetime.now().date()
end_date = datetime.datetime.now().date() + datetime.timedelta(days=5)

days = []
date = start_date
while date <= end_date:
    hours = []
    time = datetime.datetime.strptime(start_time, '%H:%M')
    end = datetime.datetime.strptime(end_time, '%H:%M')
    while time <= end:
        hours.append(time.strftime("%H:%M"))
        time += datetime.timedelta(minutes=slot_time)
    date += datetime.timedelta(days=1)
    days.append(hours)

for hours in days:
    print(hours)
</code>```

Title: Python create a list of time slot between start time to end time

Body:
I have start_date, end_date, from time, end time, and slot in min details, I need to create a list of time slot as per following expected

import datetime

start_time = '9:00'
end_time = '18:00'
slot_time = 10

# Start date from today to next 5 day
start_date = datetime.datetime.now().date()
end_date = datetime.datetime.now().date() + datetime.timedelta(days=5)

expected output (start_date to end_date = total 5 days)

['9:00', '9:10', '9:20', '9:30', '9:40', '9:50', '10:00', '10:10', ..., '17.50', '18:00']
['9:00', '9:10', '9:20', '9:30', '9:40', '9:50', '10:00', '10:10', ..., '17.50', '18:00']
['9:00', '9:10', '9:20', '9:30', '9:40', '9:50', '10:00', '10:10', ..., '17.50', '18:00']
['9:00', '9:10', '9:20', '9:30', '9:40', '9:50', '10:00', '10:10', ..., '17.50', '18:00']
['9:00', '9:10', '9:20', '9:30', '9:40', '9:50', '10:00', '10:10', ..., '17.50', '18:00']

My slot time was not fixed it can be 10, 15, 20, 30 minute base on output list of slot create

If my slot time = 15

Expected output (start_date to end_date = total 5 days)

['9:15', '9:30', '9:45', '10:00', '10:15', ..., '17.45', '18:00']
['9:15', '9:30', '9:45', '10:00', '10:15', ..., '17.45', '18:00']
['9:15', '9:30', '9:45', '10:00', '10:15', ..., '17.45', '18:00']
['9:15', '9:30', '9:45', '10:00', '10:15', ..., '17.45', '18:00']
['9:15', '9:30', '9:45', '10:00', '10:15', ..., '17.45', '18:00']

Body:
You can just iterate over wanted days, then you add nested iteration over wanted hours. For the possibility to compare objects you need to convert strings into datetime objects with strptime function. Finally, you can get output in arbitrary format with .strftime method of datetime object.

import datetime

start_time = '9:00'
end_time = '18:00'
slot_time = 10

# Start date from today to next 5 day
start_date = datetime.datetime.now().date()
end_date = datetime.datetime.now().date() + datetime.timedelta(days=5)

days = []
date = start_date
while date <= end_date:
    hours = []
    time = datetime.datetime.strptime(start_time, '%H:%M')
    end = datetime.datetime.strptime(end_time, '%H:%M')
    while time <= end:
        hours.append(time.strftime("%H:%M"))
        time += datetime.timedelta(minutes=slot_time)
    date += datetime.timedelta(days=1)
    days.append(hours)

for hours in days:
    print(hours)


问:
Find in string with Excel and VBA?
I have a spreadsheet with a few worksheets in it, one being Product Inventory and one being Material Inventory...

I am trying to figure out how I can have another worksheet to where I can look up a product code, pull the description out of Product Inventory, and extract materials needed from Material Inventory. I know how to do this in other languages, but I'm extremely limited to just Excel and I don't know how to go about it.

Say I have Product Lookup:$B$2 = "ps26k417", which I already have pulling info from Product Inventory which pulls the item description, Garden Gate Indigo/Linen Natural 26x26 KE Fiber Pillow* But now I need to figure out how to pull from Material Inventory..

From that product description, I need to pull two rows out of the Material Inventory sheet.. I need a way to extract info based on the description, in this example I need the row for 417 Garden Gate Indigo/Linen and the row for 554 Linen Natural/S Backed

Is it even worth going this in-depth in an Excel macro?

答:
Depending on what else you need to do, I would make a properly structured Access database for that. You need 3 tables: Products, Materials and BOM (Bill of materials).

BOM will have 3 fields:  ProductId, MaterialId, Quantity.

With just that, and a simple Parameter Query, you can solve your problem.

ContentLicense: CC BY-SA 2.5

Title: Find in string with Excel and VBA?


问:
Posting the name of the submit field
I have a form with one input field and submit button. I know the name of the button can be submitted but for some reason, it isn't being posted to the server.

$(document).ready(function(){

  $("form").submit(function(e) {
      e.preventDefault();
      console.log($(this).serialize());
      return false;
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<div class="a">
  <label>Name</label>
  <input name="projectName" type="text">
</div>
<div class="b">
  <input name="newProject" value="Save Project" type="submit"></div>
</form></code>```

output: projectName=abc
Expected output: projectName=abc, newProject=Save Project

Why is the "newProject" name not being sent to the server?

答:
You can add data on top:</p>

```<code>var value = $("[name='newProject']").val();
var data = $(this).serializeArray();
data.push({submit: value});
</code>```

Title: Posting the name of the submit field

Body:
I have a form with one input field and submit button. I know the name of the button can be submitted but for some reason, it isn't being posted to the server.

$(document).ready(function(){

  $("form").submit(function(e) {
      e.preventDefault();
      console.log($(this).serialize());
      return false;
  });

});

<form method="post">

  Name
  <input name="projectName" type="text">

  <input name="newProject" value="Save Project" type="submit">

</form>

output: projectName=abc
Expected output: projectName=abc, newProject=Save Project

Why is the "newProject" name not being sent to the server?

Body:
You can add data on top:

var value = $("[name='newProject']").val();
var data = $(this).serializeArray();
data.push({submit: value});


问:
SQL how to replace string which contains only new lines?
My situation is that in some cases my field contain several (multiple) new lines and nothing else.

I can't use this:

```<code>  SELECT REPLACE(REPLACE(fielddata, CHAR(13), ''), CHAR(10), '')
</code>```

because I also have a normal ones, and as I understand this will replace all new lines.

As I understand, I need somehow check if string contains only new lines, and if it does, replace them with ''.

How can I accomplish that?

答:
You can use a CASE expression like

```<code>CASE WHEN REPLACE(my_string_column, CHAR(13), '')  = ''
THEN REPLACE(REPLACE(fielddata, CHAR(13), ''), CHAR(10), '')
ELSE my_string_column END AS Computed_Column
</code>```

Body:
My situation is that in some cases my field contain several (multiple) new lines and nothing else.

I can't use this:

  SELECT REPLACE(REPLACE(fielddata, CHAR(13), ''), CHAR(10), '')

because I also have a normal ones, and as I understand this will replace all new lines.

As I understand, I need somehow check if string contains only new lines, and if it does, replace them with ''.

How can I accomplish that?

Body:
You can use a CASE expression like

CASE WHEN REPLACE(my_string_column, CHAR(13), '')  = ''
THEN REPLACE(REPLACE(fielddata, CHAR(13), ''), CHAR(10), '')
ELSE my_string_column END AS Computed_Column


问:
Rails where clause when something is stored as array
I am running rails 4.2, with a PG database.

I have an item stored in the database such as (model Item):

```<code>:something => ["1", "2", "3"]
</code>```

I would like to get the Item.where(:something.include? => "3")

Obviously this is not working - but how are you meant to do this in rails?

答:
In addition to @potashin answer, there is a shorter way to do (see documentation) if you need to get Items on one element.

```<code># Items for a single something
  Item.where("'3' = ANY (something)")
  # Or using '?'
  Item.where('? = ANY (something)', '3')

# Items for multiple something
  Item.where('something @> ARRAY[?]::varchar[]', ['3', '4'])
</code>```

Body:
I am running rails 4.2, with a PG database.

I have an item stored in the database such as (model Item):

:something => ["1", "2", "3"]

I would like to get the Item.where(:something.include? => "3")

Obviously this is not working - but how are you meant to do this in rails?

Body:
In addition to @potashin answer, there is a shorter way to do (see documentation) if you need to get Items on one element.

# Items for a single something
  Item.where("'3' = ANY (something)")
  # Or using '?'
  Item.where('? = ANY (something)', '3')

# Items for multiple something
  Item.where('something @> ARRAY[?]::varchar[]', ['3', '4'])


问:
PyQt - how to overlay a rectangle on an image
After displaying an image on a PyQt label, I want to draw a rectangle on top of the displayed image. Note that I don't mean 'draw' as in where the user 'draws' a rectangle on the image, but I mean that I just want to create a rectangle on top of the image. I have the equivalent code for matplotlib axes but I'm not sure how to do the same thing in PyQt.</p>

```<code># Create Figure/Axes Instance
figure,axes = matplotlib.pyplot.subplots()
axes.imshow(imageRGB)

# Draw Rectangle
axes.add_patch(matplotlib.patches.Rectangle((50,50),100,100,fill=False,edgecolor='red'))
</code>```

答:
```<code># convert image file into pixmap
self.pixmap_image = QtGui.QPixmap(self.filename)

# create painter instance with pixmap
self.painterInstance = QtGui.QPainter(self.pixmap_image)

# set rectangle color and thickness
self.penRectangle = QtGui.QPen(QtCore.Qt.red)
self.penRectangle.setWidth(3)

# draw rectangle on painter
self.painterInstance.setPen(self.penRectangle)
self.painterInstance.drawRect(xPos,yPos,xLen,yLen)

# set pixmap onto the label widget
self.ui.label_imageDisplay.setPixmap(self.pixmap_image)
self.ui.label_imageDisplay.show()
</code>```

Body:
After displaying an image on a PyQt label, I want to draw a rectangle on top of the displayed image. Note that I don't mean 'draw' as in where the user 'draws' a rectangle on the image, but I mean that I just want to create a rectangle on top of the image. I have the equivalent code for matplotlib axes but I'm not sure how to do the same thing in PyQt.

# Create Figure/Axes Instance
figure,axes = matplotlib.pyplot.subplots()
axes.imshow(imageRGB)

# Draw Rectangle
axes.add_patch(matplotlib.patches.Rectangle((50,50),100,100,fill=False,edgecolor='red'))

ContentLicense: CC BY-SA 4.0