问:
typesafe select onChange event using reactjs and typescript
I have figured out how to tie up an event handler on a SELECT element using an ugly cast of the event to any.

Is it possible to retrieve the value in a type-safe manner without casting to any?

```<code>import React = require('react');

interface ITestState {
    selectedValue: string;
}

export class Test extends React.Component<{}, ITestState> {

    constructor() {
        super();
        this.state = { selectedValue: "A" };
    }

    change(event: React.FormEvent) {
        console.log("Test.change");
        console.log(event.target); // in chrome => <select class="form-control" id="searchType" data-reactid=".0.0.0.0.3.1">...</select>

        // Use cast to any works but is not type safe
        var unsafeSearchTypeValue = ((event.target) as any).value;

        console.log(unsafeSearchTypeValue); // in chrome => B

        this.setState({
            selectedValue: unsafeSearchTypeValue
        });
    }

    render() {
        return (
            <div>
                <label htmlFor="searchType">Safe</label>
                <select className="form-control" id="searchType" onChange={ e => this.change(e) } value={ this.state.selectedValue }>
                    <option value="A">A</option>
                    <option value="B">B</option>
                </select>
                <h1>{this.state.selectedValue}</h1>
            </div>
        );
    }
}
</code>```

答:
I tried using React.FormEvent<HTMLSelectElement> but it led to an error in the editor, even though there is no EventTarget visible in the code:

The property 'value' does not exist on value of type 'EventTarget'

Then I changed React.FormEvent to React.ChangeEvent and it helped:

```<code>private changeName(event: React.ChangeEvent<HTMLSelectElement>) {
    event.preventDefault();
    this.props.actions.changeName(event.target.value);
}
</code>```

Body:
I have figured out how to tie up an event handler on a SELECT element using an ugly cast of the event to any.

Is it possible to retrieve the value in a type-safe manner without casting to any?

import React = require('react');

interface ITestState {
    selectedValue: string;
}

export class Test extends React.Component<{}, ITestState> {

    constructor() {
        super();
        this.state = { selectedValue: "A" };
    }

    change(event: React.FormEvent) {
        console.log("Test.change");
        console.log(event.target); // in chrome => <select class="form-control" id="searchType" data-reactid=".0.0.0.0.3.1">...</select>

        // Use cast to any works but is not type safe
        var unsafeSearchTypeValue = ((event.target) as any).value;

        console.log(unsafeSearchTypeValue); // in chrome => B

        this.setState({
            selectedValue: unsafeSearchTypeValue
        });
    }

    render() {
        return (

                Safe
                <select className="form-control" id="searchType" onChange={ e => this.change(e) } value={ this.state.selectedValue }>
                    <option value="A">A</option>
                    <option value="B">B</option>
                </select>

{this.state.selectedValue}

        );
    }
}

Body:
I tried using React.FormEvent<HTMLSelectElement> but it led to an error in the editor, even though there is no EventTarget visible in the code:

The property 'value' does not exist on value of type 'EventTarget'

Then I changed React.FormEvent to React.ChangeEvent and it helped:

private changeName(event: React.ChangeEvent<HTMLSelectElement>) {
    event.preventDefault();
    this.props.actions.changeName(event.target.value);
}


来源: stackexchange

问:
Polymer dom-repeat inside Iron-data-table
So, I have a data something like this:

```<code>data: {
  0: {
    id: 1
    name: Config1
    devices: {
      data: {
        0: {
          id: 1
          ip_address: 192.168.11.1
        },
        1: {
          id: 2
          ip_address: 192.168.11.2
        },
        ..
    },
  },
  1: {
    id: 2
    name: Config2
    devices: {
      data: {
        0: {
          id: 1
          ip_address: 192.168.11.3
        },
        1: {
          id: 2
          ip_address: 192.168.11.4
        },
        2: {
          id: 3
          ip_address: 192.168.11.5
        },
        ..
    },
  },
  ..
}
</code>```

lets say I want to display it in <iron-data-table>, and I'm expecting like this:

```<code>Config Name | IP Address
Config1 | 192.168.11.1 - 192.168.11.2
Config2 | 192.168.11.3 - 192.168.11.4 - 192.168.11.5
</code>```

and, this is current code:

```<code><iron-ajax url="data" last-response="{{response}}" auto></iron-ajax>

<iron-data-table items="[[response.data]]">
  <data-table-column name="Config Name">
    <template>[[item.name]]</template>
  <data-table-column>

  <data-table-column name="IP Address">
    <template is="dom-repeat items="[[item.devices.data]]" as="dev">
      [[dev.ip_address]]
    </template>
  <data-table-column>

</iron-data-table>
</code>```

The problem is, the IP Address aren't displayed.
I need to use something like <dom-repeat> because the number of device each config are different, like id=1 have 2 device, id=2 have 3.

Is there any other way for this problem?

Thanks for your attention and your help.

答:
As you already have noticed dom-repeat won´t work here. Your only solution is to write a function which then returns the ip´s as String.

```<code><data-table-column name="IP Address">
   <template>[[_getIpAddresses(item)]]</template>
<data-table-column>
</code>```

Little advice iron-data-table is dead no one maintains this repo better use vaadin-grid

ContentLicense: CC BY-SA 3.0

Body:
So, I have a data something like this:

data: {
  0: {
    id: 1
    name: Config1
    devices: {
      data: {
        0: {
          id: 1
          ip_address: 192.168.11.1
        },
        1: {
          id: 2
          ip_address: 192.168.11.2
        },
        ..
    },
  },
  1: {
    id: 2
    name: Config2
    devices: {
      data: {
        0: {
          id: 1
          ip_address: 192.168.11.3
        },
        1: {
          id: 2
          ip_address: 192.168.11.4
        },
        2: {
          id: 3
          ip_address: 192.168.11.5
        },
        ..
    },
  },
  ..
}

lets say I want to display it in <iron-data-table>, and I'm expecting like this:

Config Name | IP Address
Config1 | 192.168.11.1 - 192.168.11.2
Config2 | 192.168.11.3 - 192.168.11.4 - 192.168.11.5

and, this is current code:

<iron-ajax url="data" last-response="{{response}}" auto></iron-ajax>

<iron-data-table items="[[response.data]]">
  <data-table-column name="Config Name">
    <template>[[item.name]]</template>
  <data-table-column>

  <data-table-column name="IP Address">
    <template is="dom-repeat items="[[item.devices.data]]" as="dev">
      [[dev.ip_address]]
    </template>
  <data-table-column>

</iron-data-table>

The problem is, the IP Address aren't displayed.
I need to use something like <dom-repeat> because the number of device each config are different, like id=1 have 2 device, id=2 have 3.

Is there any other way for this problem?

Thanks for your attention and your help.

Body:
As you already have noticed dom-repeat won´t work here. Your only solution is to write a function which then returns the ip´s as String.

<data-table-column name="IP Address">
   <template>[[_getIpAddresses(item)]]</template>
<data-table-column>

Little advice iron-data-table is dead no one maintains this repo better use vaadin-grid


问:
JavaFX with Swing
I am trying to connect two classes. One is main swing class and other is javafx web view in a swing frame. This is run perfectly but do not show the exact output. My URL is coming from my swing frame class.</p>

```<code>public Instruction() {
    System.out.println("new url number is=="+newurl);
    System.out.println("token number is=="+first.tokennum);
    System.out.println("final link is="+FirstToken.finallink);
    frame1.add(panel);
    frame1.setSize(500,500);
    frame1.setVisible(true);
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            //To change body of generated methods, choose Tools | Templates.
            initfx(panel);
        }
    });
}

public void initfx(JFXPanel panel){
    Scene scene = createscene();
    panel.setScene(scene);
    geturl(FirstToken.finallink);
}
public Scene createscene(){
    Group root = new Group();
    Scene scene=new Scene(root);
    Text text = new Text();
    text.setX(50);
    text.setY(100);
    root.getChildren().add(text);
    return (scene);

}
public void geturl(String url){
    WebView web=new WebView();
    System.out.println("url is="+url);
    web.getEngine().load(url);

}
</code>```

答:
You are not adding the WebView that you create to the scene graph.  To fix it, have your geturl routine return your WebView and add that WebView to the group which forms the root of your scene.

If you don't understand, read the Oracle tutorial on integrating a JavaFX WebView into Swing and review the accompanied source.

Example code:

```<code>public WebView geturl(String url){
    WebView webView = new WebView();
    webView.getEngine().load(url);
    return webView;
}

public void initfx(JFXPanel panel){
    WebView webView = geturl(FirstToken.finallink);
    Scene scene = createscene(webView);
    panel.setScene(scene);
}

public Scene createscene(WebView webView){
    Pane root = new Pane();
    Scene scene = new Scene(root);
    root.getChildren().add(webView);

    return scene;
}
</code>```

Title: JavaFX with Swing

Body:
I am trying to connect two classes. One is main swing class and other is javafx web view in a swing frame. This is run perfectly but do not show the exact output. My URL is coming from my swing frame class.

public Instruction() {
    System.out.println("new url number is=="+newurl);
    System.out.println("token number is=="+first.tokennum);
    System.out.println("final link is="+FirstToken.finallink);
    frame1.add(panel);
    frame1.setSize(500,500);
    frame1.setVisible(true);
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            //To change body of generated methods, choose Tools | Templates.
            initfx(panel);
        }
    });
}

public void initfx(JFXPanel panel){
    Scene scene = createscene();
    panel.setScene(scene);
    geturl(FirstToken.finallink);
}
public Scene createscene(){
    Group root = new Group();
    Scene scene=new Scene(root);
    Text text = new Text();
    text.setX(50);
    text.setY(100);
    root.getChildren().add(text);
    return (scene);

}
public void geturl(String url){
    WebView web=new WebView();
    System.out.println("url is="+url);
    web.getEngine().load(url);

}

Body:
You are not adding the WebView that you create to the scene graph.  To fix it, have your geturl routine return your WebView and add that WebView to the group which forms the root of your scene.

If you don't understand, read the Oracle tutorial on integrating a JavaFX WebView into Swing and review the accompanied source.

Example code:

public WebView geturl(String url){
    WebView webView = new WebView();
    webView.getEngine().load(url);
    return webView;
}

public void initfx(JFXPanel panel){
    WebView webView = geturl(FirstToken.finallink);
    Scene scene = createscene(webView);
    panel.setScene(scene);
}

public Scene createscene(WebView webView){
    Pane root = new Pane();
    Scene scene = new Scene(root);
    root.getChildren().add(webView);

    return scene;
}


问:
reducing list based on fuzzy values in python
I have a list that contains groups of nearly identical numeric values. i.e. (1004.523, 1004.575, 1004.475, 791.385, 791.298, 791.301, 791.305, 791.299)

What I am trying to do is read through the list and find all the 1004.5 +- values aggregate them and find the average value. then continue on and find all the 791.0 +- values and do the same to them.

I do not know how many individual values there will be in each "group" nor do I know how many groups there will be.

The result I am looking for is another list which would contain the average values of each of the groups. So in the example my result would be (1004.524, 791.3176)

The code I'm currently using is very Kludgey and it seems there should be a much better way to do it.

As you can see I have to repeat code twice once in the else and once at the end of the if since the last set of numbers does not trigger the else. Plus at the completion of the if I need to add the last value.

If I use the len(tones) rather that len(tones)-i I get an out of range error.

Any thoughts or suggestions would be appreciated. Thanks for your help.

Ed

```<code>    toneLen = len(tones) -1
    for i in range(0, toneLen):
        if abs(tones[i]-tones[i+1]) <= 2.0:
            tmpTones.append(tones[i])
        else:
            freq = mean(tmpTones)
            newTones.append(freq)
            tmpTones = []
    tmpTones.append(tones[i+1])
    freq = mean(tmpTones)
    newTones.append(freq)
    tones = newTones
</code>```

UPDATE:
First I wanted to thank everyone who submitted suggestions. The response was very quick and helpful. I should have probably included some more info which I am doing below. Thanks so much for your help.

Second , a quick explanation of what I am trying to do. Our local Fire Department is looking for a way to track dispatches for departments close to them. For the most part they use two tone sequential paging i.e. 1000Hz followed by 500Hz.

So I am using numpy fft to find the tone frequency. Since the accuracy of the tone appears to be about +- 2 Hz, I compare the calculated frequency to a list of known paging tones and pick the closest match. After all the tones have been matched to the paging tones I look for matches to departments of interest.

One thing I did not know when I started this that in any given dispatch the same tone can be repeated several times, so the order of the tones is important. An example:
707.3, 339.6, 707.3, 569.1, 447.2, 569.1 would be a typical dispatch. I then look to see if any of the tone pairs are ones I'm interested in if so I display a message

Thanks again for all your help.

Ed

答:
If you know what numbers may appear in the sequence, you can use this (exacttones is expected values list):

```<code>tones = (1004.523, 1004.575, 1004.475, 791.385, 791.298, 791.301, 791.305, 791.299)
exacttones = (1004.5, 791.3)
limit = 0.2
[sum(x)/len(x) for x in [[y for y in tones if abs((y-e))<=limit] for e in exacttones]]
# [1004.5243333333333, 791.31759999999997]
</code>```

To analyze the sequence without knowing the exacttones, something like this will work:

```<code>def calc(d, value):
    for k in d:
        if abs(k-value) <= limit:
            d[k].append(value)
            return d
    d[value] = [value]
    return d
[sum(x)/len(x) for x in reduce(calc, values, {}).values()]
# [1004.5243333333333, 791.31759999999997]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a list that contains groups of nearly identical numeric values. i.e. (1004.523, 1004.575, 1004.475, 791.385, 791.298, 791.301, 791.305, 791.299)

What I am trying to do is read through the list and find all the 1004.5 +- values aggregate them and find the average value. then continue on and find all the 791.0 +- values and do the same to them.

I do not know how many individual values there will be in each "group" nor do I know how many groups there will be.

The result I am looking for is another list which would contain the average values of each of the groups. So in the example my result would be (1004.524, 791.3176)

The code I'm currently using is very Kludgey and it seems there should be a much better way to do it.

As you can see I have to repeat code twice once in the else and once at the end of the if since the last set of numbers does not trigger the else. Plus at the completion of the if I need to add the last value.

If I use the len(tones) rather that len(tones)-i I get an out of range error.

Any thoughts or suggestions would be appreciated. Thanks for your help.

Ed

    toneLen = len(tones) -1
    for i in range(0, toneLen):
        if abs(tones[i]-tones[i+1]) <= 2.0:
            tmpTones.append(tones[i])
        else:
            freq = mean(tmpTones)
            newTones.append(freq)
            tmpTones = []
    tmpTones.append(tones[i+1])
    freq = mean(tmpTones)
    newTones.append(freq)
    tones = newTones

UPDATE:
First I wanted to thank everyone who submitted suggestions. The response was very quick and helpful. I should have probably included some more info which I am doing below. Thanks so much for your help.

Second , a quick explanation of what I am trying to do. Our local Fire Department is looking for a way to track dispatches for departments close to them. For the most part they use two tone sequential paging i.e. 1000Hz followed by 500Hz.

So I am using numpy fft to find the tone frequency. Since the accuracy of the tone appears to be about +- 2 Hz, I compare the calculated frequency to a list of known paging tones and pick the closest match. After all the tones have been matched to the paging tones I look for matches to departments of interest.

One thing I did not know when I started this that in any given dispatch the same tone can be repeated several times, so the order of the tones is important. An example:
707.3, 339.6, 707.3, 569.1, 447.2, 569.1 would be a typical dispatch. I then look to see if any of the tone pairs are ones I'm interested in if so I display a message

Thanks again for all your help.

Ed

Body:
If you know what numbers may appear in the sequence, you can use this (exacttones is expected values list):

tones = (1004.523, 1004.575, 1004.475, 791.385, 791.298, 791.301, 791.305, 791.299)
exacttones = (1004.5, 791.3)
limit = 0.2
[sum(x)/len(x) for x in [[y for y in tones if abs((y-e))<=limit] for e in exacttones]]
# [1004.5243333333333, 791.31759999999997]

To analyze the sequence without knowing the exacttones, something like this will work:

def calc(d, value):
    for k in d:
        if abs(k-value) <= limit:
            d[k].append(value)
            return d
    d[value] = [value]
    return d
[sum(x)/len(x) for x in reduce(calc, values, {}).values()]
# [1004.5243333333333, 791.31759999999997]


问:
Appcelerator Emulator not loading
I have installed Appcelerator and the required SDK but the emulator still doesn't load on the screen.

It comes up with this error:

[ERROR] Application Installer abnormal process termination. Process exit value was 1

[ERROR] :  Emulator exited with error: 1

[ERROR] :  PANIC: ANDROID_SDK_HOME is defined but could not find titanium_1_WVGA800.ini file in $ANDROID_SDK_HOME.android\avd

[ERROR] :  (Note: avd is searched in the order of $ANDROID_AVD_HOME,$ANDROID_SDK_HOME.android\avd and $HOME.android\avd)

Appreciate any help.

Thank You

答:
What helped me to solve the problem was:

Delete all with Android Studio created Emulators.

Delete all with Genymotion created Emulators.

Then create one new Genymotion Emulator. Try it again.

Title: Appcelerator Emulator not loading


问:
Windows Task Scheduler - Run only during window of time
I have a task already set up in the Windows Scheduler (on Win Server 2008).  It works great but it can put a burden on the system during peak hours (when the box is being used for other things).  I currently run the job every 15 minutes.  Can Task Sch. be setup to run every 15 minutes but only during a certain window of time.  So I could set it up to run every 15 min, but only from 5pm to 5am -- and not run at all from 5am to 5pm?</p>

答: You have to set on the the Start field: 5:00:00 AM and on 'for duration of' you have to write '12 hours' or '12:00:00'</p>


问:
Unexpected Behavior from .Net Charts
I am trying to create .Net Chart (Windows.Forms) and export it to a .jpeg file.

Below is the code for it

```<code>public void ExportRouteGraphToJpeg(string nameOfChart, int xMax, int yMax, int xMin, int yMin )
{
    var chartForExport = new Chart();
    chartForExport.Series.Clear();

    var xVsYSeries = new Series
    {
        Name = "XvsY",
        Color = Color.Blue,
        IsVisibleInLegend = false,
        IsXValueIndexed = true,
        ChartType = SeriesChartType.Point,
        MarkerSize = 6,
        MarkerColor   = Color.Blue
    };

    for (var i = 0; i < xValue.Length; i++)
    {
        xVsYSeries.Points.AddXY(xValue[i], yValue[i]);
    }

    chartForExport.Series.Add(xVsYSeries);

    // Chart Area Definition
    var chartArea = new ChartArea
    {
        Name = "SupportPoints",
        AxisX =
        {
            Title = "X Co-ordinate [cm]",
            ArrowStyle = AxisArrowStyle.Triangle,
            Maximum = xMax + 100,
            Minimum = xMin - 100
        },
        AxisY =
        {
            Title = "Y Co-ordinate [cm]",
            ArrowStyle = AxisArrowStyle.Triangle,
            Maximum = yMax + 100,
            Minimum = yMin - 100
        }
    };

    chartForExport.ChartAreas.Add(chartArea);
    chartForExport.Location = new Point(0, 50);
    chartForExport.TabIndex = 0;

    chartForExport.Name = "ChartRoute";

    chartForExport.SaveImage(nameOfChart + ".jpeg", ChartImageFormat.Jpeg);
}
</code>```

The output I get is shown below (for 5 points of xValue = 1000, 2000, 3000, 4000 and same for yValue)

When I remove Maximum = yMax + 100, Minimum = yMin - 100 for AxisX and AxisY, I get desired output. please see below

Any suggestion why is this happening?

答: Remove IsXValueIndexed = true from your series definition.

Title: Unexpected Behavior from .Net Charts

Body:
I am trying to create .Net Chart (Windows.Forms) and export it to a .jpeg file.

Below is the code for it

public void ExportRouteGraphToJpeg(string nameOfChart, int xMax, int yMax, int xMin, int yMin )
{
    var chartForExport = new Chart();
    chartForExport.Series.Clear();

    var xVsYSeries = new Series
    {
        Name = "XvsY",
        Color = Color.Blue,
        IsVisibleInLegend = false,
        IsXValueIndexed = true,
        ChartType = SeriesChartType.Point,
        MarkerSize = 6,
        MarkerColor   = Color.Blue
    };

    for (var i = 0; i < xValue.Length; i++)
    {
        xVsYSeries.Points.AddXY(xValue[i], yValue[i]);
    }

    chartForExport.Series.Add(xVsYSeries);

    // Chart Area Definition
    var chartArea = new ChartArea
    {
        Name = "SupportPoints",
        AxisX =
        {
            Title = "X Co-ordinate [cm]",
            ArrowStyle = AxisArrowStyle.Triangle,
            Maximum = xMax + 100,
            Minimum = xMin - 100
        },
        AxisY =
        {
            Title = "Y Co-ordinate [cm]",
            ArrowStyle = AxisArrowStyle.Triangle,
            Maximum = yMax + 100,
            Minimum = yMin - 100
        }
    };

    chartForExport.ChartAreas.Add(chartArea);
    chartForExport.Location = new Point(0, 50);
    chartForExport.TabIndex = 0;

    chartForExport.Name = "ChartRoute";

    chartForExport.SaveImage(nameOfChart + ".jpeg", ChartImageFormat.Jpeg);
}

The output I get is shown below (for 5 points of xValue = 1000, 2000, 3000, 4000 and same for yValue)

When I remove Maximum = yMax + 100, Minimum = yMin - 100 for AxisX and AxisY, I get desired output. please see below

Any suggestion why is this happening?


问:
javascript object error
This is my situation:

```<code>

var r = {"id":"test","files":[],"code":""};

var Page = Class.create({

 initialize: function(json) {
  this.id = json.id;
  this.json = json;

 },
        start: function() {
  this.json.files.each(function(x) {
   var cssResource = this.pageResource(x, 'css');
   this.attachCssResource(cssResource);

  }.bind(this));
        },

//etc....

});

var P = new Page(r);
P.start();

</code>```

Hi have this.json.files.each is not a function.. why?

I use prototype 1.7 library.

if i use this

```<code>
var P = new Page({"id":"test","files":[],"code":""});
</code>```

i have NO error??....

答:
Perhaps you can forcibly cast it to an array with:

```<code>$A(this.json.files).each(...
</code>```

Sometimes I find it easier to work with a hash instead of an array -- $H instead of $A.

Title: javascript object error

Body:
This is my situation:

var r = {"id":"test","files":[],"code":""};

var Page = Class.create({

 initialize: function(json) {
  this.id = json.id;
  this.json = json;

 },
        start: function() {
  this.json.files.each(function(x) {
   var cssResource = this.pageResource(x, 'css');
   this.attachCssResource(cssResource);

  }.bind(this));
        },

//etc....

});

var P = new Page(r);
P.start();

Hi have this.json.files.each is not a function.. why?

I use prototype 1.7 library.

if i use this

var P = new Page({"id":"test","files":[],"code":""});

i have NO error??....

Body:
Perhaps you can forcibly cast it to an array with:

$A(this.json.files).each(...

Sometimes I find it easier to work with a hash instead of an array -- $H instead of $A.


问:
How to force java to draw swing label?
I am creating a progressBar using JLabel. Problem is when I add this label to my frame and execute some other tasks, my JFrame freezes. Is there any method like invoke and wait for swing to complete its drawing?</p>

```<code>private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {
   JLabel loadingBar = new JLabel("test");
   myFrame.add(loadingBar);
   doSomeOtherTasks();
}
</code>```

答:
Try this

```<code>int delay = 1000; //milliseconds
  ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
          //...Perform a task...
      }
  };
  new Timer(delay, taskPerformer).start();
</code>```

Title: How to force java to draw swing label?

Body:
I am creating a progressBar using JLabel. Problem is when I add this label to my frame and execute some other tasks, my JFrame freezes. Is there any method like invoke and wait for swing to complete its drawing?

private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {
   JLabel loadingBar = new JLabel("test");
   myFrame.add(loadingBar);
   doSomeOtherTasks();
}

Body:
Try this

int delay = 1000; //milliseconds
  ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
          //...Perform a task...
      }
  };
  new Timer(delay, taskPerformer).start();


问:
Where is my Electron App located
I have an electron app, that also operates on files in the same directory. These are not files the user selects, or files bundled inside the electron application, but I do need to reference them

for example:

/Users/test/Documents/myapp.app

/Users/test/Documents/example.zip

I need to know where that application is located, e.g.:

/Users/test/Documents

But instead when test.app is ran I get:

/Users/test/Documents/myapp.app/Contents/Resources/app/

Resulting in errors when it tries to access /Users/test/Documents/myapp.app/Contents/Resources/app/test.zip, or if I use a relative path, /test.zip.

How would I reliably access example.zip in this scenario? Note that I cannot bundle it with my app, it's being placed there by somebody else, so moving it is not an option, and it's a file I'm expecting to be there.

答:
I think either app.getPath('exe') or process.execPath is what you are looking for. They both give you the path of the currently used executable.

Edit: Look at the docs for app.getPath() to get the paths of all the different folder (e.g. home, appdata, documents, etc.)

Title: Where is my Electron App located


问:
Open auto complete on click on button
I am using ofer's autocomplete in Angular2 app

https://github.com/oferh/ng2-completer

I want a behavior where the auto complete does not open automatically upon typing but I need to press a button and only then should the autocomplete make a server request and show the dropdown I tried to implement CompleterData:

```<code>import { Http, Response } from "@angular/http";
import { Subject } from "rxjs/Subject";
import { HttpClient } from './shared';
import { CompleterData, CompleterItem } from 'ng2-completer';

export class AddressData extends Subject<CompleterItem[]> implements CompleterData {
    private url: string;

    constructor(private http: HttpClient, public erpIDParent: number, url: string) {
        super();
        this.url = url;
    }

    public setErpIDParent(erpIDParent: number) {
        this.erpIDParent = erpIDParent;
    }

    public search(term: string): void {
        console.log('searching');
        if (this.erpIDParent > 0) {
            this.http.get(`${this.url}${term}&erpIDParent=${this.erpIDParent}`)
                .map((res: Response) => {
                    // Convert the result to CompleterItem[]
                    let data = res.json();
                    let matches: CompleterItem[] = data.map((address: any) => {
                        return {
                            originalObject: address,
                            title: address.Name
                        }
                    });
                    console.log(matches);
                    this.next(matches);
                })
                .subscribe();
        }
    }

    public cancel() {
        // Handle cancel
    }
}
</code>```

and kept the minSearchLength to 1000

```<code><ng2-completer placeholder="{{ 'NewOrder.typeToSearch' | translate }}" formControlName="address" [(ngModel)]="address" [datasource]="addressDataService" (selected)="addressSelected($event)" [minSearchLength]="1000"></ng2-completer>
</code>```

so it wouldn't send the server request then on my button click I have this code:

```<code>searchAddresses() {
        this.addressDataService.search(this.address);
    }
</code>```

so it would start the search manually but it doesn't seem to work the way I want to. The dropdown shows and hides instantly. Is there any way to fix this?

答:
There is a way although it's a workaround and not sure that the end result will be good enough.

You'll need a custom CompleterDatacomponent that will handle the search and this will provide you a way to control when to perform the search:

```<code>export class CustomData extends Subject<CompleterItem[]> implements CompleterData {

    public doSearch = false;

    constructor(private http: Http) {
        super();
    }
    public search(term: string): void {
      if (this.doSearch) {
         this.http.get("http://example.com?term=" + term)
            .map((res: Response) => {
                // Convert the result to CompleterItem[]
                let data = res.json();
                let matches: CompleterItem[] = data.map((item: any) => this.convertToItem(item));
                this.next(matches);
            })
            .subscribe();
      } else {
        // if we don't do the search return empty results
        this.next([]);
      }
    }
}
</code>```

Since search is called we need to prevent the display of searching and no results text so we set textSearching and textNoResults to false

```<code><ng2-completer #completer [(ngModel)]="searchStr" [datasource]="datasource" [minSearchLength]="0" [textNoResults]="false" [textSearching]="false"></ng2-completer>
</code>```

now when you want to do the search you can set doSearch on the data provider and it will start working.

the last part is to set the focus back to the completer and do the search again when it's activated:

in your component:

```<code> @ViewChild("completer") private completer: CompleterCmp;

   protected startSearch() {
       this.datasource.doSearch = true;
       this.completer.focus();
       this.datasource.search(this.searchStr);
   }
</code>```

here is a plunker example

Title: Open auto complete on click on button

Body:
I am using ofer's autocomplete in Angular2 app

https://github.com/oferh/ng2-completer

I want a behavior where the auto complete does not open automatically upon typing but I need to press a button and only then should the autocomplete make a server request and show the dropdown I tried to implement CompleterData:

import { Http, Response } from "@angular/http";
import { Subject } from "rxjs/Subject";
import { HttpClient } from './shared';
import { CompleterData, CompleterItem } from 'ng2-completer';

export class AddressData extends Subject<CompleterItem[]> implements CompleterData {
    private url: string;

    constructor(private http: HttpClient, public erpIDParent: number, url: string) {
        super();
        this.url = url;
    }

    public setErpIDParent(erpIDParent: number) {
        this.erpIDParent = erpIDParent;
    }

    public search(term: string): void {
        console.log('searching');
        if (this.erpIDParent > 0) {
            this.http.get(`${this.url}${term}&erpIDParent=${this.erpIDParent}`)
                .map((res: Response) => {
                    // Convert the result to CompleterItem[]
                    let data = res.json();
                    let matches: CompleterItem[] = data.map((address: any) => {
                        return {
                            originalObject: address,
                            title: address.Name
                        }
                    });
                    console.log(matches);
                    this.next(matches);
                })
                .subscribe();
        }
    }

    public cancel() {
        // Handle cancel
    }
}

and kept the minSearchLength to 1000

<ng2-completer placeholder="{{ 'NewOrder.typeToSearch' | translate }}" formControlName="address" [(ngModel)]="address" [datasource]="addressDataService" (selected)="addressSelected($event)" [minSearchLength]="1000"></ng2-completer>

so it wouldn't send the server request then on my button click I have this code:

searchAddresses() {
        this.addressDataService.search(this.address);
    }

so it would start the search manually but it doesn't seem to work the way I want to. The dropdown shows and hides instantly. Is there any way to fix this?

Body:
There is a way although it's a workaround and not sure that the end result will be good enough.

You'll need a custom CompleterDatacomponent that will handle the search and this will provide you a way to control when to perform the search:

export class CustomData extends Subject<CompleterItem[]> implements CompleterData {

    public doSearch = false;

    constructor(private http: Http) {
        super();
    }
    public search(term: string): void {
      if (this.doSearch) {
         this.http.get("http://example.com?term=" + term)
            .map((res: Response) => {
                // Convert the result to CompleterItem[]
                let data = res.json();
                let matches: CompleterItem[] = data.map((item: any) => this.convertToItem(item));
                this.next(matches);
            })
            .subscribe();
      } else {
        // if we don't do the search return empty results
        this.next([]);
      }
    }
}

Since search is called we need to prevent the display of searching and no results text so we set textSearching and textNoResults to false

<ng2-completer #completer [(ngModel)]="searchStr" [datasource]="datasource" [minSearchLength]="0" [textNoResults]="false" [textSearching]="false"></ng2-completer>

now when you want to do the search you can set doSearch on the data provider and it will start working.

the last part is to set the focus back to the completer and do the search again when it's activated:

in your component:

 @ViewChild("completer") private completer: CompleterCmp;

   protected startSearch() {
       this.datasource.doSearch = true;
       this.completer.focus();
       this.datasource.search(this.searchStr);
   }

here is a plunker example


问:
How do I change Atom ctrl-tab to not show pane?
In Sublime when cycling through tabs using ctrl-tab it opens and shows the file as I cycle through them. In Atom it shows a pane / list of the recently viewed files. I want to turn this off and just have it cycle through the files and display them as I press ctrl-tab like Sublime. How do I do this?

答:
Go to File > Keymap...

Enter in the following code:

```<code>'body':
  'ctrl-tab': 'unset!'
  'ctrl-tab ^ctrl': 'unset!'
</code>```

This should disable the pane feature completely.

If you want to cycle through the tabs, you press CTRL+PAGEDOWN for left to right; and CTRL+PAGEUP from right to left.

If you want to change the keybind entirely, as in you want to use CTRL+TAB to cycle through the tabs, you can insert this snippet into the Keymap:

```<code>'body':
  'ctrl-tab': 'pane:show-next-item'
</code>```

Body:
Go to File > Keymap...

Enter in the following code:

'body':
  'ctrl-tab': 'unset!'
  'ctrl-tab ^ctrl': 'unset!'

This should disable the pane feature completely.

If you want to cycle through the tabs, you press CTRL+PAGEDOWN for left to right; and CTRL+PAGEUP from right to left.

If you want to change the keybind entirely, as in you want to use CTRL+TAB to cycle through the tabs, you can insert this snippet into the Keymap:

'body':
  'ctrl-tab': 'pane:show-next-item'


问:
How to upload certain committed files in PhpStorm
I am a php developer and already use phpstorm automatic uploading feature after committing a function, but sometimes it failed to upload to the ftp server due to some reasons.

In that situation(finished committing but not uploading), how can I re-upload those modified files (may 20~30 files, maybe more), really takes time to upload one by one. Besides, I just can't use "Sync with Deployed" function, because the project contains above ten thousand files and scattered in different folders. maybe someone can help me save time ....thanks in advance ^^

BTW, can I upload certain commitment file list committed before.

sorry, I am poor at typing git command @@

答:
You can open "Changed Files" scope in a Project view for example:

Then right click root folder > Upload to ... or Synchronize with ...


问:
SQL/PLSQL merge multilist value
I have two table name table1 and table2.

from first table I'm getting number,id and value.ID column is multilist so values in that column are separated by comma, eg: 3799952,3799953. For each ID there is some value in table2. eg for 3799952 value is Assembly and for 3799953 value is Indiviual. I have to get these values with comma separation. in multilist as of now I have only two value so I used sequence upto 2, tomorrow I will be getting multiple value . can anyone help me procedures or userdefined function.

```<code>select id,item_number,max(decode(seq,1,entry_id))||','||max(decode(seq,2,entry_id)) entry_id,
  max(decode(seq,1,entryvalue))||','||max(decode(seq,2,entryvalue)) entryvalue
  from (

  select a.id,a.item_number,a.entry_id,list.entryvalue,row_number() over (partition by item_number order by entry_id) seq
  from  (SELECT i.id,i.item_number,
 trim(regexp_substr(i.product_lines, '[^,]+', 1, lines.column_value)) entry_id
  FROM item i,
     TABLE (CAST (MULTISET
     (SELECT LEVEL FROM dual CONNECT BY LEVEL <= regexp_count(i.product_lines, ','))AS sys.odciNumberList)) lines   ORDER BY i.id)a , listentry list where a.entry_id=list.entryid and a.entry_id is not null)
  group by id,item_number;
</code>```

This is my query and output for this is given below,

```<code>**ID    ITEM_NUMBER ENTRY_ID             ENTRYVALUE**
6024065 P00008           3799953,            Individual,
6024607 U00024          3799952,3799953       Assembly,Individual
6024886 U00154      3799952,3799953       Assembly,Individual
6015685 INK_PEN         3799952,              Assembly,
6036877 P0000020    3799952,3799953       Assembly,Individual
</code>```

As of now I have only two entryvalue so used max(decode(seq,1,entry_id))||','||max(decode(seq,2,entry_id)) entry_id could any one tell me how to modify this for multiple values.

Thanks in advance

答:
Use the function listagg() twice:

```<code>select id, item_number,
       listagg(entry_id, ',') within group (order by seq) entry_id,
       listagg(entryvalue, ',') within group (order by seq) entryvalue
  from your_inner_query
  group by id, item_number
</code>```

test data:

```<code>create table item (id number(8), item_number varchar2(10), product_lines varchar2(20));
insert into item values (6024065, 'P00008',   '3799953,');
insert into item values (6024607, 'U00024',   '3799952,3799953,');
insert into item values (6024886, 'U00154',   '3799952,3799953,');
insert into item values (6015685, 'INK_PEN',  '3799952,');
insert into item values (6036877, 'P0000020', '3799952,3799953,');

create table listentry(entryid number(8), entryvalue varchar2(10));
insert into listentry values (3799952, 'Assembly');
insert into listentry values (3799953, 'Individual');
</code>```

full query:

```<code>with t as (
    select a.id, a.item_number, a.entry_id, list.entryvalue,
                row_number() over (partition by item_number order by entry_id) seq
      from (select i.id,i.item_number,
                   trim(regexp_substr(i.product_lines, '[^,]+', 1, lines.column_value)) entry_id
              from item i,
                   table (cast (multiset ( select level
                                             from dual
                                             connect by level <= regexp_count(i.product_lines, ','))
                            as sys.odcinumberlist)) lines
              order by i.id) a
           join listentry list on a.entry_id = list.entryid and a.entry_id is not null )
select id, item_number,
       listagg(entry_id, ',') within group (order by seq) entry_id,
       listagg(entryvalue, ',') within group (order by seq) entryvalue
  from t
  group by id, item_number
  order by id;
</code>```

output:

```<code>       ID ITEM_NUMBER ENTRY_ID           ENTRYVALUE
--------- ----------- ------------------ ----------------------
  6015685 INK_PEN     3799952            Assembly
  6024065 P00008      3799953            Individual
  6024607 U00024      3799952,3799953    Assembly,Individual
  6024886 U00154      3799952,3799953    Assembly,Individual
  6036877 P0000020    3799952,3799953    Assembly,Individual
</code>```

Edit: explanation

Subquery a divides data in table item into individual rows. Hierarchical query connect by generates as many rows as needed for each id counting commas , in product_lines.
Function regexp_substr cuts off needed entry_id into separate rows.

```<code>ID       ITEM_NUMBER   ENTRY_ID
-------  ------------  --------
6015685  INK_PEN        3799952
6024065  P00008         3799953
6024607  U00024         3799952
6024607  U00024         3799953
6024886  U00154         3799953
6024886  U00154         3799952
6036877  P0000020       3799952
6036877  P0000020       3799953
</code>```

Such table is next joined with your lookup table listentry. Each row is numbered with row_number(). So we have this:

```<code>ID       ITEM_NUMBER   ENTRY_ID  ENTRYVALUE   SEQ
-------  ------------  --------  -----------  ---
6015685  INK_PEN        3799952  Assembly       1
6036877  P0000020       3799952  Assembly       1
6036877  P0000020       3799953  Individual     2
6024065  P00008         3799953  Individual     1
6024607  U00024         3799952  Assembly       1
6024607  U00024         3799953  Individual     2
6024886  U00154         3799952  Assembly       1
6024886  U00154         3799953  Individual     2
</code>```

Now we can use listagg() which groups data for the same id. They are sorted by SEQ.

Note that I didn't change your original inner query, only added last select with listagg() instead of decode's You tried.

Title: SQL/PLSQL merge multilist value

Body:
I have two table name table1 and table2.

from first table I'm getting number,id and value.ID column is multilist so values in that column are separated by comma, eg: 3799952,3799953. For each ID there is some value in table2. eg for 3799952 value is Assembly and for 3799953 value is Indiviual. I have to get these values with comma separation. in multilist as of now I have only two value so I used sequence upto 2, tomorrow I will be getting multiple value . can anyone help me procedures or userdefined function.

select id,item_number,max(decode(seq,1,entry_id))||','||max(decode(seq,2,entry_id)) entry_id,
  max(decode(seq,1,entryvalue))||','||max(decode(seq,2,entryvalue)) entryvalue
  from (

  select a.id,a.item_number,a.entry_id,list.entryvalue,row_number() over (partition by item_number order by entry_id) seq
  from  (SELECT i.id,i.item_number,
 trim(regexp_substr(i.product_lines, '[^,]+', 1, lines.column_value)) entry_id
  FROM item i,
     TABLE (CAST (MULTISET
     (SELECT LEVEL FROM dual CONNECT BY LEVEL <= regexp_count(i.product_lines, ','))AS sys.odciNumberList)) lines   ORDER BY i.id)a , listentry list where a.entry_id=list.entryid and a.entry_id is not null)
  group by id,item_number;

This is my query and output for this is given below,

**ID    ITEM_NUMBER ENTRY_ID             ENTRYVALUE**
6024065 P00008           3799953,            Individual,
6024607 U00024          3799952,3799953       Assembly,Individual
6024886 U00154      3799952,3799953       Assembly,Individual
6015685 INK_PEN         3799952,              Assembly,
6036877 P0000020    3799952,3799953       Assembly,Individual

As of now I have only two entryvalue so used max(decode(seq,1,entry_id))||','||max(decode(seq,2,entry_id)) entry_id could any one tell me how to modify this for multiple values.

Thanks in advance

Body:
Use the function listagg() twice:

select id, item_number,
       listagg(entry_id, ',') within group (order by seq) entry_id,
       listagg(entryvalue, ',') within group (order by seq) entryvalue
  from your_inner_query
  group by id, item_number

test data:

create table item (id number(8), item_number varchar2(10), product_lines varchar2(20));
insert into item values (6024065, 'P00008',   '3799953,');
insert into item values (6024607, 'U00024',   '3799952,3799953,');
insert into item values (6024886, 'U00154',   '3799952,3799953,');
insert into item values (6015685, 'INK_PEN',  '3799952,');
insert into item values (6036877, 'P0000020', '3799952,3799953,');

create table listentry(entryid number(8), entryvalue varchar2(10));
insert into listentry values (3799952, 'Assembly');
insert into listentry values (3799953, 'Individual');

full query:

with t as (
    select a.id, a.item_number, a.entry_id, list.entryvalue,
                row_number() over (partition by item_number order by entry_id) seq
      from (select i.id,i.item_number,
                   trim(regexp_substr(i.product_lines, '[^,]+', 1, lines.column_value)) entry_id
              from item i,
                   table (cast (multiset ( select level
                                             from dual
                                             connect by level <= regexp_count(i.product_lines, ','))
                            as sys.odcinumberlist)) lines
              order by i.id) a
           join listentry list on a.entry_id = list.entryid and a.entry_id is not null )
select id, item_number,
       listagg(entry_id, ',') within group (order by seq) entry_id,
       listagg(entryvalue, ',') within group (order by seq) entryvalue
  from t
  group by id, item_number
  order by id;

output:

       ID ITEM_NUMBER ENTRY_ID           ENTRYVALUE
--------- ----------- ------------------ ----------------------
  6015685 INK_PEN     3799952            Assembly
  6024065 P00008      3799953            Individual
  6024607 U00024      3799952,3799953    Assembly,Individual
  6024886 U00154      3799952,3799953    Assembly,Individual
  6036877 P0000020    3799952,3799953    Assembly,Individual

Edit: explanation

Subquery a divides data in table item into individual rows. Hierarchical query connect by generates as many rows as needed for each id counting commas , in product_lines.
Function regexp_substr cuts off needed entry_id into separate rows.

ID       ITEM_NUMBER   ENTRY_ID
-------  ------------  --------
6015685  INK_PEN        3799952
6024065  P00008         3799953
6024607  U00024         3799952
6024607  U00024         3799953
6024886  U00154         3799953
6024886  U00154         3799952
6036877  P0000020       3799952
6036877  P0000020       3799953

Such table is next joined with your lookup table listentry. Each row is numbered with row_number(). So we have this:

ID       ITEM_NUMBER   ENTRY_ID  ENTRYVALUE   SEQ
-------  ------------  --------  -----------  ---
6015685  INK_PEN        3799952  Assembly       1
6036877  P0000020       3799952  Assembly       1
6036877  P0000020       3799953  Individual     2
6024065  P00008         3799953  Individual     1
6024607  U00024         3799952  Assembly       1
6024607  U00024         3799953  Individual     2
6024886  U00154         3799952  Assembly       1
6024886  U00154         3799953  Individual     2

Now we can use listagg() which groups data for the same id. They are sorted by SEQ.

Note that I didn't change your original inner query, only added last select with listagg() instead of decode's You tried.


问:
Nesting two ng-repeats
I'm trying to show some data in a table with two ng-repeats. But the second ng-repeat doesn't seem to work. This is what I'm trying:

```<code><tbody>
    <tr class="admin-detail-rows" ng-repeat="lesson in lessons | orderBy:sortType:sortReverse">
       <div ng-repeat="group in lesson.groups">
           <td>{{ working_days[lesson.day - 1] }}</td>
           <td>{{ lesson.start_time }} - {{ lesson.end_time }}</td>
           <td>{{ group.available_seats ? group.max_seats - group.available_seats : 0 }} / {{ group.max_seats }}</td>
           <td>{{ lesson.room }}</td>
           <td>{{ lesson.teacher }}</td>
           <td>{{ group.group_name }}</td>
           <td>{{ lesson.groupDetails  }}</td>
           <td ng-click="removeLesson(lesson)" class="delete-button">✖</td>
      </div>
   </tr>
</tbody>
</code>```

But it never does the second repeat more than once, and it doesn't know a lot of the properties.

A lesson that I'm iterating through in the first ng-repeat could look like this:

```<code> {
    "id":140,
    "course_id":156,
    "start_time":"08:45",
    "end_time":"10:30",
    "day":2,
    "type":1,
    "course_description":"The Business Dimension of Europe (lecture; group P:3+Q:3+R:3)",
    "room":"OVk.41 left",
    "teacher":"Test teacher","created_at":"2017-04-11 13:43:29",
    "course": {
    "id":156,
    "code":"Test code",
    "name":"The Business Dimension of Europe",
    "credits":3,
    "category_id":20,
    "entry_requirements":null,
    "assessment_materials":null,
    "study_materials":null,
    "outline":null,
    "description":null,
    "created_at":"2017-04-11 13:41:45"
},
    "groups":[{
    "id":181,"timetable_id":140,
    "course_id":156,
    "group_name":"P",
    "group_details":null,
    "max_seats":3,
    "available_seats":-4,
    "created_at":"2017-04-11 13:43:29"
    }, {
    "id":182,
    "timetable_id":140,
    "course_id":156,
    "group_name":"Q",
    "group_details":null,"max_seats":3,
    "available_seats":null,
    "created_at":"2017-04-11 13:43:29"
    },{"id":183,
    "timetable_id":140,
    "course_id":156,
    "group_name":"R",
    "group_details":null,
    "max_seats":3,"available_seats":null,
    "created_at":"2017-04-11 13:43:29"}
    ]}
</code>```

Assigning the lesson to the scope:

```<code>$scope.$watch(function () {
  return lessonsService.getLessons();
}, function (lessons) {
  $scope.lessons = lessons;
});
</code>```

What am I doing wrong?

答:
Hey there is some issue with json structure and ng-repeat statement.

 angular.module('myApp',[]).controller('myCtrl', function($scope){

   $scope.lessons  =[{
 "id": 140,
 "course_id": 156,
 "start_time": "08:45",
 "end_time": "10:30",
 "day": 2,
 "type": 1,
 "course_description": "The Business Dimension of Europe (lecture; group P:3+Q:3+R:3)",
 "room": "OVk.41 left",
 "teacher": "Kerkhof van de B.K.W.",
 "created_at": "2017-04-11 13:43:29",
 "course": {
  "id": 156,
  "code": "ES-ISBMDIMEUR-16",
  "name": "The Business Dimension of Europe",
  "credits": 3,
  "category_id": 20,
  "entry_requirements": null,
  "assessment_materials": null,
  "study_materials": null,
  "outline": null,
  "description": null,
  "created_at": "2017-04-11 13:41:45"
 },
 "groups": [{
  "id": 181,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "P",
  "group_details": null,
  "max_seats": 3,
  "available_seats": -4,
  "created_at": "2017-04-11 13:43:29"
 }, {
  "id": 182,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "Q",
  "group_details": null,
  "max_seats": 3,
  "available_seats": null,
  "created_at": "2017-04-11 13:43:29"
 }, {
  "id": 183,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "R",
  "group_details": null,
  "max_seats": 3,
  "available_seats": null,
  "created_at": "2017-04-11 13:43:29"
 }]
}];

 });

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<table>
    <tr  ng-repeat="lesson in lessons ">
       <div ng-repeat="group in lesson.groups">
           <td>{{ working_days[lesson.day - 1] }}     </td>
           <td>{{ lesson.start_time }} - {{ lesson.end_time }}   </td>
           <td>{{ group.available_seats  }} / {{ group.max_seats }}  </td>
           <td>{{ lesson.room }}   </td>
           <td>{{ lesson.teacher }}   </td>
           <td>{{ group.group_name }}   </td>
           <td>{{ lesson.groupDetails  }}   </td>
           <td ng-click="removeLesson(lesson)" class="delete-button">✖</td>
      </div>
   </tr>
</table>
</div></code>```

here is the json structure:

[{
 "id": 140,
 "course_id": 156,
 "start_time": "08:45",
 "end_time": "10:30",
 "day": 2,
 "type": 1,
 "course_description": "The Business Dimension of Europe (lecture; group P:3+Q:3+R:3)",
 "room": "OVk.41 left",
 "teacher": "Kerkhof van de B.K.W.",
 "created_at": "2017-04-11 13:43:29",
 "course": {
  "id": 156,
  "code": "ES-ISBMDIMEUR-16",
  "name": "The Business Dimension of Europe",
  "credits": 3,
  "category_id": 20,
  "entry_requirements": null,
  "assessment_materials": null,
  "study_materials": null,
  "outline": null,
  "description": null,
  "created_at": "2017-04-11 13:41:45"
 },
 "groups": [{
  "id": 181,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "P",
  "group_details": null,
  "max_seats": 3,
  "available_seats": -4,
  "created_at": "2017-04-11 13:43:29"
 }, {
  "id": 182,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "Q",
  "group_details": null,
  "max_seats": 3,
  "available_seats": null,
  "created_at": "2017-04-11 13:43:29"
 }, {
  "id": 183,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "R",
  "group_details": null,
  "max_seats": 3,
  "available_seats": null,
  "created_at": "2017-04-11 13:43:29"
 }]
}]```

Hope it will work for you thanks

Title: Nesting two ng-repeats

Body:
I'm trying to show some data in a table with two ng-repeats. But the second ng-repeat doesn't seem to work. This is what I'm trying:

           {{ working_days[lesson.day - 1] }}
           {{ lesson.start_time }} - {{ lesson.end_time }}
           {{ group.available_seats ? group.max_seats - group.available_seats : 0 }} / {{ group.max_seats }}
           {{ lesson.room }}
           {{ lesson.teacher }}
           {{ group.group_name }}
           {{ lesson.groupDetails  }}
           ✖

But it never does the second repeat more than once, and it doesn't know a lot of the properties.

A lesson that I'm iterating through in the first ng-repeat could look like this:

 {
    "id":140,
    "course_id":156,
    "start_time":"08:45",
    "end_time":"10:30",
    "day":2,
    "type":1,
    "course_description":"The Business Dimension of Europe (lecture; group P:3+Q:3+R:3)",
    "room":"OVk.41 left",
    "teacher":"Test teacher","created_at":"2017-04-11 13:43:29",
    "course": {
    "id":156,
    "code":"Test code",
    "name":"The Business Dimension of Europe",
    "credits":3,
    "category_id":20,
    "entry_requirements":null,
    "assessment_materials":null,
    "study_materials":null,
    "outline":null,
    "description":null,
    "created_at":"2017-04-11 13:41:45"
},
    "groups":[{
    "id":181,"timetable_id":140,
    "course_id":156,
    "group_name":"P",
    "group_details":null,
    "max_seats":3,
    "available_seats":-4,
    "created_at":"2017-04-11 13:43:29"
    }, {
    "id":182,
    "timetable_id":140,
    "course_id":156,
    "group_name":"Q",
    "group_details":null,"max_seats":3,
    "available_seats":null,
    "created_at":"2017-04-11 13:43:29"
    },{"id":183,
    "timetable_id":140,
    "course_id":156,
    "group_name":"R",
    "group_details":null,
    "max_seats":3,"available_seats":null,
    "created_at":"2017-04-11 13:43:29"}
    ]}

Assigning the lesson to the scope:

$scope.$watch(function () {
  return lessonsService.getLessons();
}, function (lessons) {
  $scope.lessons = lessons;
});

What am I doing wrong?

Body:
Hey there is some issue with json structure and ng-repeat statement.

 angular.module('myApp',[]).controller('myCtrl', function($scope){

   $scope.lessons  =[{
 "id": 140,
 "course_id": 156,
 "start_time": "08:45",
 "end_time": "10:30",
 "day": 2,
 "type": 1,
 "course_description": "The Business Dimension of Europe (lecture; group P:3+Q:3+R:3)",
 "room": "OVk.41 left",
 "teacher": "Kerkhof van de B.K.W.",
 "created_at": "2017-04-11 13:43:29",
 "course": {
  "id": 156,
  "code": "ES-ISBMDIMEUR-16",
  "name": "The Business Dimension of Europe",
  "credits": 3,
  "category_id": 20,
  "entry_requirements": null,
  "assessment_materials": null,
  "study_materials": null,
  "outline": null,
  "description": null,
  "created_at": "2017-04-11 13:41:45"
 },
 "groups": [{
  "id": 181,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "P",
  "group_details": null,
  "max_seats": 3,
  "available_seats": -4,
  "created_at": "2017-04-11 13:43:29"
 }, {
  "id": 182,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "Q",
  "group_details": null,
  "max_seats": 3,
  "available_seats": null,
  "created_at": "2017-04-11 13:43:29"
 }, {
  "id": 183,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "R",
  "group_details": null,
  "max_seats": 3,
  "available_seats": null,
  "created_at": "2017-04-11 13:43:29"
 }]
}];

 });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<table>
    <tr  ng-repeat="lesson in lessons ">
       <div ng-repeat="group in lesson.groups">
           <td>{{ working_days[lesson.day - 1] }} &nbsp;&nbsp;&nbsp;&nbsp;</td>
           <td>{{ lesson.start_time }} - {{ lesson.end_time }}&nbsp;&nbsp;&nbsp;</td>
           <td>{{ group.available_seats  }} / {{ group.max_seats }}&nbsp;&nbsp;</td>
           <td>{{ lesson.room }}&nbsp;&nbsp;&nbsp;</td>
           <td>{{ lesson.teacher }}&nbsp;&nbsp;&nbsp;</td>
           <td>{{ group.group_name }}&nbsp;&nbsp;&nbsp;</td>
           <td>{{ lesson.groupDetails  }}&nbsp;&nbsp;&nbsp;</td>
           <td ng-click="removeLesson(lesson)" class="delete-button">✖</td>
      </div>
   </tr>
</table>
</div>

here is the json structure:

[{
 "id": 140,
 "course_id": 156,
 "start_time": "08:45",
 "end_time": "10:30",
 "day": 2,
 "type": 1,
 "course_description": "The Business Dimension of Europe (lecture; group P:3+Q:3+R:3)",
 "room": "OVk.41 left",
 "teacher": "Kerkhof van de B.K.W.",
 "created_at": "2017-04-11 13:43:29",
 "course": {
  "id": 156,
  "code": "ES-ISBMDIMEUR-16",
  "name": "The Business Dimension of Europe",
  "credits": 3,
  "category_id": 20,
  "entry_requirements": null,
  "assessment_materials": null,
  "study_materials": null,
  "outline": null,
  "description": null,
  "created_at": "2017-04-11 13:41:45"
 },
 "groups": [{
  "id": 181,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "P",
  "group_details": null,
  "max_seats": 3,
  "available_seats": -4,
  "created_at": "2017-04-11 13:43:29"
 }, {
  "id": 182,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "Q",
  "group_details": null,
  "max_seats": 3,
  "available_seats": null,
  "created_at": "2017-04-11 13:43:29"
 }, {
  "id": 183,
  "timetable_id": 140,
  "course_id": 156,
  "group_name": "R",
  "group_details": null,
  "max_seats": 3,
  "available_seats": null,
  "created_at": "2017-04-11 13:43:29"
 }]
}]

Hope it will work for you thanks


问:
type of high order functions
if I specify the (I think) correct type for a high order function the OCaml compiler rejects the second usage of that function.

The code

```<code>let foo ():string  =
    let f: ('a -> string) -> 'a -> string = fun g v -> g v
    in let h = string_of_int
    in let i = string_of_float
    in let x = f h 23
    in let y = f i 23.0
    in x ^ y
</code>```

leads to the following error message

```File "test.ml", line 6, characters 14-15:
Error: This expression has type float -> string
       but an expression was expected of type int -> string```

So the first usage of f seems to fix the type of its first parameter to int -> string. I could understand that. But what I don't get is that omitting the type restriction on f fixes the problem.

```<code>let foo ():string  =
    let f g v = g v
    in let h = string_of_int
    in let i = string_of_float
    in let x = f h 23
    in let y = f i 23.0
    in x ^ y</code>```

And moving f to global scope fixes the problem, too:

```<code>let f: ('a -> string) -> 'a -> string = fun g v -> g v

let foo ():string  =
  let h = string_of_int
  in let i = string_of_float
  in let x = f h 23
  in let y = f i 23.0
  in x ^ y</code>```

Why is it that the first example does not compile while the later ones do?

答:
This is a real head-scratcher and I wouldn't be surprised if it's a compiler bug.  That said, you can do what you want by explicitly naming the type:

```<code>let f (type t) (g: t->string) (v: t) = g v in
</code>```

From the manual: http://caml.inria.fr/pub/docs/manual-ocaml/manual021.html#htoc108

Edit:

This also works:

```<code>let f g v:string = g v in
</code>```

which has the type signature you are looking for: ('a -> string) -> 'a -> string

Strange that it doesn't work when you annotate the type of the arguments.

EDIT:

Polymorphic type annotations have a special syntax:

```<code>let f: 'a. ('a -> string)-> 'a -> string = fun g v -> g v in
</code>```

And the type is required to be polymorphic: http://caml.inria.fr/pub/docs/manual-ocaml/manual021.html#toc79

Title: type of high order functions

Body:
if I specify the (I think) correct type for a high order function the OCaml compiler rejects the second usage of that function.

The code

let foo ():string  =
    let f: ('a -> string) -> 'a -> string = fun g v -> g v
    in let h = string_of_int
    in let i = string_of_float
    in let x = f h 23
    in let y = f i 23.0
    in x ^ y

leads to the following error message

File "test.ml", line 6, characters 14-15:
Error: This expression has type float -> string
       but an expression was expected of type int -> string

So the first usage of f seems to fix the type of its first parameter to int -> string. I could understand that. But what I don't get is that omitting the type restriction on f fixes the problem.

let foo ():string  =
    let f g v = g v
    in let h = string_of_int
    in let i = string_of_float
    in let x = f h 23
    in let y = f i 23.0
    in x ^ y

And moving f to global scope fixes the problem, too:

let f: ('a -> string) -> 'a -> string = fun g v -> g v

let foo ():string  =
  let h = string_of_int
  in let i = string_of_float
  in let x = f h 23
  in let y = f i 23.0
  in x ^ y

Why is it that the first example does not compile while the later ones do?

Body:
This is a real head-scratcher and I wouldn't be surprised if it's a compiler bug.  That said, you can do what you want by explicitly naming the type:

let f (type t) (g: t->string) (v: t) = g v in

From the manual: http://caml.inria.fr/pub/docs/manual-ocaml/manual021.html#htoc108

Edit:

This also works:

let f g v:string = g v in

which has the type signature you are looking for: ('a -> string) -> 'a -> string

Strange that it doesn't work when you annotate the type of the arguments.

EDIT:

Polymorphic type annotations have a special syntax:

let f: 'a. ('a -> string)-> 'a -> string = fun g v -> g v in

And the type is required to be polymorphic: http://caml.inria.fr/pub/docs/manual-ocaml/manual021.html#toc79


问:
How to optimize an hybrid Mobile App for slow internet connections
I have an ionic mobile application that has been developed, but it throws a lot of connection error when used on phones with poor internet connection.

Is there a way I can optimize my application to function well on devices with poor internet connection. i.e (GPRS or EDGE connection)

答:
Use the Network plugin:

https://ionicframework.com/docs/native/network/

You can check the network change event:

```<code>// watch network for a disconnect
let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
   console.log('network was disconnected :-(');
});
</code>```

And the connection type:

```<code>function checkConnection() {
var networkState = navigator.connection.type;

var states = {};
states[Connection.UNKNOWN]  = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI]     = 'WiFi connection';
states[Connection.CELL_2G]  = 'Cell 2G connection';
states[Connection.CELL_3G]  = 'Cell 3G connection';
states[Connection.CELL_4G]  = 'Cell 4G connection';
states[Connection.CELL]     = 'Cell generic connection';
states[Connection.NONE]     = 'No network connection';

alert('Connection type: ' + states[networkState]);
}
</code>```

Maybe you should manage your requests depending on if user has connection and user connection type.

Body:
Use the Network plugin:

https://ionicframework.com/docs/native/network/

You can check the network change event:

// watch network for a disconnect
let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
   console.log('network was disconnected :-(');
});

And the connection type:

function checkConnection() {
var networkState = navigator.connection.type;

var states = {};
states[Connection.UNKNOWN]  = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI]     = 'WiFi connection';
states[Connection.CELL_2G]  = 'Cell 2G connection';
states[Connection.CELL_3G]  = 'Cell 3G connection';
states[Connection.CELL_4G]  = 'Cell 4G connection';
states[Connection.CELL]     = 'Cell generic connection';
states[Connection.NONE]     = 'No network connection';

alert('Connection type: ' + states[networkState]);
}

Maybe you should manage your requests depending on if user has connection and user connection type.


问:
Alternative to triggers in SQL Server
To eliminate the potential problems with triggers, what are some of the alternatives one may use to get the same functionality of reacting to an event fired on a INSERT action?

I have a database that needs to have some additional values added on insert. The INSERT is controlled by compiled code and cannot be changed.

EXAMPLE: The program inserts a string and from this string I need to supply an integer to a new field that points to a look-up table.

If there is an alternative to a trigger then please let me know some pros and cons to any alternative. The main reason for this is that Triggers are not allowed in our DB standards.

SQL Server 2008 Enterprise

答: I think we can implement trigger with hibernate event system nowdays despite of the performance impact.I didn't do that before.but I think it works</p>

Title: Alternative to triggers in SQL Server


问:
Using admin-on-rest with public routes
I´d like make a site with public routes ('/') and admin routes (/admin).
How can I do it with rest-admin!?
Thanks </p>

答:
You can simply use Router for distinguishing public routes from admin ones, e.g.:

```<code>    <Router>
        <div>
            <Route exact path="/" component={Index}/>
            <Route path='/admin' component={YourAdmin}/>
        </div>
    </Router>
</code>```

Here Index component is you public component (e.g. homepage). And YourAdmin component includes admin-on-rest, e.g.:

```<code>class YourAdmin extends Component {
    render() {
        return (
            <Admin ...>
                <Resource .../>
                <Resource .../>
                <Resource .../>
            </Admin>
        )
    }
}
</code>```

And your admin-page can be secured with built-in admin-on-rest functionality.

Title: Using admin-on-rest with public routes

Body:
You can simply use Router for distinguishing public routes from admin ones, e.g.:

    <Router>
        <div>
            <Route exact path="/" component={Index}/>
            <Route path='/admin' component={YourAdmin}/>
        </div>
    </Router>

Here Index component is you public component (e.g. homepage). And YourAdmin component includes admin-on-rest, e.g.:

class YourAdmin extends Component {
    render() {
        return (
            <Admin ...>
                <Resource .../>
                <Resource .../>
                <Resource .../>
            </Admin>
        )
    }
}

And your admin-page can be secured with built-in admin-on-rest functionality.


问:
rails redirect from child create to child show
I am sure there is a solution for this but I am not seeing it. I want to redirect to the show page for my child after creation.

I have just created a child record for my parent record in my child controller like so:

```<code>def create
   @article = Article.find(params[:article_id])
   @comment = article.comments.create(comment_params)
   redirect_to "/articles/#{@article.id}/comments/#{@comment.id}"
end

...
private

def comment_params
    params.require(:comment).permit(:commenter, :body)
</code>```

I would like to do something like redirect_to @comment

Is there a way to do this? Once I did the above I also got an error with this prebaked code from the scaffold creation:

```<code><%= link_to 'Edit', edit_comment_path(@comment) %>
</code>```

I feel like there is something wrong with my routes maybe or I am not referencing the path for my child correctly.

routes.rb:

```<code>resources :articles do
  resources :comments
end
</code>```

How do I redirect to the "show" of my child correctly in the create method of my controller

Why would my edit path be broken in my child show view?

thanks

答:
Try below code:

controller

```<code>def create
   @article = Article.find(params[:article_id])
   @comment = article.comments.create(comment_params)
   redirect_to article_comment_path(@article,@comment)
end
</code>```

view

```<code><%= link_to 'Edit', edit_article_comment_path(@article, @comment) %>
</code>```

routes

```<code>resources :articles do
  resources :comments
end
</code>```

Body:
I am sure there is a solution for this but I am not seeing it. I want to redirect to the show page for my child after creation.

I have just created a child record for my parent record in my child controller like so:

def create
   @article = Article.find(params[:article_id])
   @comment = article.comments.create(comment_params)
   redirect_to "/articles/#{@article.id}/comments/#{@comment.id}"
end

...
private

def comment_params
    params.require(:comment).permit(:commenter, :body)

I would like to do something like redirect_to @comment

Is there a way to do this? Once I did the above I also got an error with this prebaked code from the scaffold creation:

<%= link_to 'Edit', edit_comment_path(@comment) %>

I feel like there is something wrong with my routes maybe or I am not referencing the path for my child correctly.

routes.rb:

resources :articles do
  resources :comments
end

How do I redirect to the "show" of my child correctly in the create method of my controller

Why would my edit path be broken in my child show view?

thanks

Body:
Try below code:

controller

def create
   @article = Article.find(params[:article_id])
   @comment = article.comments.create(comment_params)
   redirect_to article_comment_path(@article,@comment)
end

view

<%= link_to 'Edit', edit_article_comment_path(@article, @comment) %>

routes

resources :articles do
  resources :comments
end


问:
understanding View.setTranslationY() [ /X() ]
as the title says i want to understand what that method exactly is doing.

firstable i have double checked that the coordinate system of android works like that:
coordinate system

secondary - please take a minute to check my android studio screen, and the method quick doc. why is that value of my view (after clicking it) is 106?
android screen

答:
the coordinate system is correct.

getY() will return the value of the top of your View + the Y translation. so, if getY() is returning 106 and you set translation y to 10, the top of your view should be at 96. try calling also getTop() and check what is that value

the translation is an offset that is applied to the position of the View. if the layout place your View at x;y and you call setTranslationY(10), your View will appear at x;y+10. it's a way to control the positioning of the View after the layout

bonus tip, instead of logging everything, use the debugger

in case you still have doubts about the difference between the position and translation, you could try this, create an empty activity and set this layout

```<code><?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.example.lelloman.dummy.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="asd asd"
        android:layout_above="@+id/button"
        android:layout_centerHorizontal="true"/>
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="asd"/>

</RelativeLayout>
</code>```

then, you will see that the TextView is right above the Button, because this is how the RelativeLayout will position the Views given these layout parameters. now, try to call

```<code>findViewById(R.id.button).setTranslationY(100);
</code>```

you will notice that the button will be moved down by 100px, but the TextView will still be at the old position, because the translation is applied after the layout. it is something specific to that View that is not taken into account for the positioning of the View within its parent

you could also set the translation in the xml with

```<code><Button
    android:translationY="100px"
    ...
</code>```

Body:
the coordinate system is correct.

getY() will return the value of the top of your View + the Y translation. so, if getY() is returning 106 and you set translation y to 10, the top of your view should be at 96. try calling also getTop() and check what is that value

the translation is an offset that is applied to the position of the View. if the layout place your View at x;y and you call setTranslationY(10), your View will appear at x;y+10. it's a way to control the positioning of the View after the layout

bonus tip, instead of logging everything, use the debugger

in case you still have doubts about the difference between the position and translation, you could try this, create an empty activity and set this layout

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.example.lelloman.dummy.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="asd asd"
        android:layout_above="@+id/button"
        android:layout_centerHorizontal="true"/>
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="asd"/>

</RelativeLayout>

then, you will see that the TextView is right above the Button, because this is how the RelativeLayout will position the Views given these layout parameters. now, try to call

findViewById(R.id.button).setTranslationY(100);

you will notice that the button will be moved down by 100px, but the TextView will still be at the old position, because the translation is applied after the layout. it is something specific to that View that is not taken into account for the positioning of the View within its parent

you could also set the translation in the xml with

<Button
    android:translationY="100px"
    ...


问:
how to remove a file from git to never exist at all
so i pushed a ouath key file into my git branch from my local copy. how do i overwrite commits in git to remove the oauth key file?

i tried doing

git rm cache /storage/oauth.key and did a git add, git commit, git push to my branch but the file is still there.

i also tried doing

git revert commitID  but got an error

error: commit 5ac87ad863059396jkljkljlkjce4c64 is a merge but no -m option was given.
fatal: revert failed

please advice.

答:
try

git rm --cached storage/oauth.key

then add your deleted oauth key file on stage, commit and push.

This must delete the key file from your remote repository.


问:
win32api TextOut()
When I write code for Windows several functions give me error message

"undefined reference to ...",

for example TextOut(...) function generate

"undefined reference to 'TextOut@20' ".

Example:

```<code>case WM_KEYDOWN ://cand apas o tasta
       {
          char szName[31];
          HDC  hDC;

          InvalidateRect( hWnd, NULL, TRUE );
          UpdateWindow( hWnd );

          hDC = GetDC( hWnd );
          GetKeyNameText( lParam, szName, 30 );
          TextOut( hDC, 10, 10, szName, lstrlen( szName ) );
          ReleaseDC( hWnd, hDC );
       }
       break;
</code>```

I use GNU GCC codeblocks - mingw Compiler

Please,somebody tell me why I receive this error message?
Thank You.

答:
The symbol TextOut@20 isn't exported from any library. The symbols are called TextOutA and TextOutW (with appropriate decoration). You are using header files that aren't compatible with the Windows API, and they fail to map TextOut to either TextOutA or TextOutW. Consider using the official SDK.

As an aside: The call to TextOut takes a const TCHAR*, not a const char*. If you wish to use a char array (you shouldn't), call TextOutA. It is recommended to use wchar_t arrays instead, and call TextOutW, though.

Title: win32api TextOut()

Body:
When I write code for Windows several functions give me error message

"undefined reference to ...",

for example TextOut(...) function generate

"undefined reference to 'TextOut@20' ".

Example:

case WM_KEYDOWN ://cand apas o tasta
       {
          char szName[31];
          HDC  hDC;

          InvalidateRect( hWnd, NULL, TRUE );
          UpdateWindow( hWnd );

          hDC = GetDC( hWnd );
          GetKeyNameText( lParam, szName, 30 );
          TextOut( hDC, 10, 10, szName, lstrlen( szName ) );
          ReleaseDC( hWnd, hDC );
       }
       break;

I use GNU GCC codeblocks - mingw Compiler

Please,somebody tell me why I receive this error message?
Thank You.


问:
Using spinner in android fragment view and button click
I am a newbie programmer in android.I am trying to develop a simple paternity blood test.The logic is like this.I have three spinners and blood group A,B,AB and O will be listed into the spinner.The user have to chose blood type from A,B,AB or O for child,mother and father and then click submit button.The button will do some matching and produce a string result.I have tried several methods whichI found on internet. But still unable to use button click function.
Here is my code.Plz correct my mistake .Thanks.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:text="TextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn_paternity"
            android:layout_centerHorizontal="true"
            android:gravity="center_horizontal"
            android:layout_marginTop="52dp"
            android:id="@+id/paternity_ans" />

        <TextView
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:id="@+id/textView6"
            android:text="Father"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:layout_width="100dp"
            android:layout_above="@+id/childblds"
            android:layout_centerHorizontal="true" />

        <TextView
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_marginTop="53dp"
            android:id="@+id/textView5"
            android:text="Child "
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"

            android:layout_width="100dp"
            android:layout_marginRight="15dp"
            android:layout_marginEnd="15dp"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@+id/btn_paternity"
            android:layout_toStartOf="@+id/btn_paternity" />

        <Spinner
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:spinnerMode="dialog"
            android:id="@+id/dadblds"
            android:dropDownWidth="match_parent"
            android:layout_toLeftOf="@+id/textView4"
            android:layout_toStartOf="@+id/textView4"
            android:layout_alignBottom="@+id/childblds"
            android:layout_alignTop="@+id/childblds" />

        <Spinner
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/childblds"
            android:spinnerMode="dialog"

            android:dropDownWidth="match_parent"
            android:layout_marginTop="13dp"

            android:layout_below="@+id/textView5"
            android:layout_alignLeft="@+id/textView5"
            android:layout_alignStart="@+id/textView5" />

        <Spinner
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/momblds"
            android:spinnerMode="dialog"
            android:entries="@array/paternitybldtype"
            android:dropDownWidth="match_parent"
            android:layout_alignTop="@+id/dadblds"
            android:layout_alignLeft="@+id/textView4"
            android:layout_alignStart="@+id/textView4" />

        <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn_paternity"
            android:layout_below="@+id/dadblds"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="35dp" />

        <TextView
            android:layout_height="wrap_content"
            android:id="@+id/textView4"
            android:gravity="center_horizontal"

            android:text="Mother"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:layout_width="100dp"
            android:layout_marginLeft="9dp"
            android:layout_marginStart="9dp"
            android:layout_above="@+id/childblds"
            android:layout_toRightOf="@+id/textView6"
            android:layout_toEndOf="@+id/textView6" />
    </RelativeLayout>
</LinearLayout>
</code>```

Fragments code:

```<code>public class Paternitytest extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.paternitytestlo, container, false);
        final Button setItem = (Button) view.findViewById(R.id.btn_paternity);
        final TextView txt1 = (TextView) view.findViewById(R.id.paternity_ans);

        setItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Some if else statement will be applied here by using String c, f and m
            }
        });

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Spinner childspinner = (Spinner) view.findViewById(R.id.childblds);
        Spinner dadspinner = (Spinner) view.findViewById(R.id.dadblds);
        Spinner momspinner = (Spinner) view.findViewById(R.id.momblds);

        // Spinner Drop down elements
        String[] categories = {"A", "B", "O", "AB",};

        // Creating adapter for spinner
        ArrayAdapter adapter = new ArrayAdapter(
                getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, categories);

        // Drop down layout style - list view with radio button
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        childspinner.setAdapter(adapter);
        dadspinner.setAdapter(adapter);
        momspinner.setAdapter(adapter);

        // Spinner click listener
        childspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                String c = parent.getItemAtPosition(position).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        dadspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {

                String f = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        momspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                String m = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}
</code>```

答:
Try onClickListener for your button:</p>

```<code>btn_paternity.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            String mom = momblds.getSelectedItem().toString();

        }
    });
</code>```

Body:
I am a newbie programmer in android.I am trying to develop a simple paternity blood test.The logic is like this.I have three spinners and blood group A,B,AB and O will be listed into the spinner.The user have to chose blood type from A,B,AB or O for child,mother and father and then click submit button.The button will do some matching and produce a string result.I have tried several methods whichI found on internet. But still unable to use button click function.
Here is my code.Plz correct my mistake .Thanks.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:text="TextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn_paternity"
            android:layout_centerHorizontal="true"
            android:gravity="center_horizontal"
            android:layout_marginTop="52dp"
            android:id="@+id/paternity_ans" />

        <TextView
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:id="@+id/textView6"
            android:text="Father"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:layout_width="100dp"
            android:layout_above="@+id/childblds"
            android:layout_centerHorizontal="true" />

        <TextView
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_marginTop="53dp"
            android:id="@+id/textView5"
            android:text="Child "
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"

            android:layout_width="100dp"
            android:layout_marginRight="15dp"
            android:layout_marginEnd="15dp"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@+id/btn_paternity"
            android:layout_toStartOf="@+id/btn_paternity" />

        <Spinner
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:spinnerMode="dialog"
            android:id="@+id/dadblds"
            android:dropDownWidth="match_parent"
            android:layout_toLeftOf="@+id/textView4"
            android:layout_toStartOf="@+id/textView4"
            android:layout_alignBottom="@+id/childblds"
            android:layout_alignTop="@+id/childblds" />

        <Spinner
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/childblds"
            android:spinnerMode="dialog"

            android:dropDownWidth="match_parent"
            android:layout_marginTop="13dp"

            android:layout_below="@+id/textView5"
            android:layout_alignLeft="@+id/textView5"
            android:layout_alignStart="@+id/textView5" />

        <Spinner
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/momblds"
            android:spinnerMode="dialog"
            android:entries="@array/paternitybldtype"
            android:dropDownWidth="match_parent"
            android:layout_alignTop="@+id/dadblds"
            android:layout_alignLeft="@+id/textView4"
            android:layout_alignStart="@+id/textView4" />

        <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn_paternity"
            android:layout_below="@+id/dadblds"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="35dp" />

        <TextView
            android:layout_height="wrap_content"
            android:id="@+id/textView4"
            android:gravity="center_horizontal"

            android:text="Mother"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:layout_width="100dp"
            android:layout_marginLeft="9dp"
            android:layout_marginStart="9dp"
            android:layout_above="@+id/childblds"
            android:layout_toRightOf="@+id/textView6"
            android:layout_toEndOf="@+id/textView6" />
    </RelativeLayout>
</LinearLayout>

Fragments code:

public class Paternitytest extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.paternitytestlo, container, false);
        final Button setItem = (Button) view.findViewById(R.id.btn_paternity);
        final TextView txt1 = (TextView) view.findViewById(R.id.paternity_ans);

        setItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Some if else statement will be applied here by using String c, f and m
            }
        });

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Spinner childspinner = (Spinner) view.findViewById(R.id.childblds);
        Spinner dadspinner = (Spinner) view.findViewById(R.id.dadblds);
        Spinner momspinner = (Spinner) view.findViewById(R.id.momblds);

        // Spinner Drop down elements
        String[] categories = {"A", "B", "O", "AB",};

        // Creating adapter for spinner
        ArrayAdapter adapter = new ArrayAdapter(
                getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, categories);

        // Drop down layout style - list view with radio button
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        childspinner.setAdapter(adapter);
        dadspinner.setAdapter(adapter);
        momspinner.setAdapter(adapter);

        // Spinner click listener
        childspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                String c = parent.getItemAtPosition(position).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        dadspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {

                String f = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        momspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                String m = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}

Body:
Try onClickListener for your button:

btn_paternity.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            String mom = momblds.getSelectedItem().toString();

        }
    });


问:
How to create a custom checkbox in css

I want to create a checkbox like this. with a white tick and transparent background. Can someone help me on how to do it
I tried
 input[type="checkbox"]{
background-color:rgba(255,255,255,0.1);
color:white;
}

But doesnt work as in this
codepen

答:
On Chrome, you'll need to overwrite the default browser settings like this.

```<code>input[type="checkbox"]{
    -webkit-appearance: none;
}
</code>```

Here's a similar JS fiddle I made that might help you out.

https://jsfiddle.net/pappy/3eLduj2c/

Title: How to create a custom checkbox in css

Body:
On Chrome, you'll need to overwrite the default browser settings like this.

input[type="checkbox"]{
    -webkit-appearance: none;
}

Here's a similar JS fiddle I made that might help you out.

https://jsfiddle.net/pappy/3eLduj2c/


问:
FetchXML - Today - minus 30 days
I am attempting to create a FetchXML script that retrieves records with a date of today minus 30 days.

Below is the SQL that works.  Could somebody help me with the FetchXML, please?

```<code>SELECT *
FROM [students]
WHERE start_date = CONVERT(DATE,DATEADD(DAY,-30,GETDATE()))
</code>```

Thanks in advance,

Richard

答:
FetchXml does not have option for this problem.

It can be achieved using combination of Last X Days and OlderThan X Days.

```<code><fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
  <entity name="students">
    <attribute name="name" />
      <filter type="and">
        <condition attribute="start_date" value="30" operator="last-x-days"/>
        <condition attribute="start_date" value="29" operator="olderthan-x-days"/>
      </filter>
  </entity>
</fetch>
</code>```

Title: FetchXML - Today - minus 30 days

Body:
I am attempting to create a FetchXML script that retrieves records with a date of today minus 30 days.

Below is the SQL that works.  Could somebody help me with the FetchXML, please?

SELECT *
FROM [students]
WHERE start_date = CONVERT(DATE,DATEADD(DAY,-30,GETDATE()))

Thanks in advance,

Richard

Body:
FetchXml does not have option for this problem.

It can be achieved using combination of Last X Days and OlderThan X Days.

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
  <entity name="students">
    <attribute name="name" />
      <filter type="and">
        <condition attribute="start_date" value="30" operator="last-x-days"/>
        <condition attribute="start_date" value="29" operator="olderthan-x-days"/>
      </filter>
  </entity>
</fetch>