问:
/signalr/hubs 404 (Not Found) in DNN 7.3.4
I am developing a website using DNN 7.3.4. I am signalr in this.
I have executed this script for AUM_DoNotRewriteRegEx.

```<code>IF NOT EXISTS (SELECT * FROM dnn_hostsettings WHERE SettingName = 'AUM_DoNotRewriteRegEx' )

      insert into dnn_hostsettings
        (SettingName
        , SettingValue
        , SettingIsSecure
        , CreatedByUserId
        , CreatedOnDate
        , LastModifiedByUserId
        , LastModifiedOnDate
        )
        values(
        'AUM_DoNotRewriteRegEx'
        ,'/DesktopModules/|/Providers|/LinkClick\.aspx|/SignalR'
        , 0
        , -1
        , GETDATE()
        , -1
        , GETDATE()
        )

    GO

    IF EXISTS (SELECT * FROM dnn_hostsettings WHERE SettingName = 'AUM_DoNotRewriteRegEx' and SettingValue not like '%/signalr%' )

    update dnn_hostsettings
        set settingValue = (select settingValue + '|/signalr' from dnn_hostsettings where settingname = 'AUM_DoNotRewriteRegEx')
    where settingname = 'AUM_DoNotRewriteRegEx'

    GO
</code>```

And in my page

```<code><script type="text/javascript" src='<%=ResolveClientUrl("~/signalr/hubs") %>'></script>

var objHub = $.connection.myHub;
$.connection.hub.start().done(function () {
    //....
})
</code>```

But it's not working every time it's showing this.

答:
I think you are missing the OwinStartup class that starts the signalR hub in your application.  Look at this project on my github called DnnLogAnalyzer.  I have a class called Startup.cs that hooks into the OwinStartup and starts the signalR hub for the application.

```<code>using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(DotNetNuclear.Modules.LogAnalyzer.Components.Startup))]

namespace DotNetNuclear.Modules.LogAnalyzer.Components
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ...
            app.MapSignalR();
        }
    }
}
</code>```

If you are a DNNHero.com subscriber, you can also check out my step-by-step tutorial for tips on getting SignalR working in your DNN application.

Body:
I am developing a website using DNN 7.3.4. I am signalr in this.
I have executed this script for AUM_DoNotRewriteRegEx.

IF NOT EXISTS (SELECT * FROM dnn_hostsettings WHERE SettingName = 'AUM_DoNotRewriteRegEx' )

      insert into dnn_hostsettings
        (SettingName
        , SettingValue
        , SettingIsSecure
        , CreatedByUserId
        , CreatedOnDate
        , LastModifiedByUserId
        , LastModifiedOnDate
        )
        values(
        'AUM_DoNotRewriteRegEx'
        ,'/DesktopModules/|/Providers|/LinkClick\.aspx|/SignalR'
        , 0
        , -1
        , GETDATE()
        , -1
        , GETDATE()
        )

    GO

    IF EXISTS (SELECT * FROM dnn_hostsettings WHERE SettingName = 'AUM_DoNotRewriteRegEx' and SettingValue not like '%/signalr%' )

    update dnn_hostsettings
        set settingValue = (select settingValue + '|/signalr' from dnn_hostsettings where settingname = 'AUM_DoNotRewriteRegEx')
    where settingname = 'AUM_DoNotRewriteRegEx'

    GO

And in my page

var objHub = $.connection.myHub;
$.connection.hub.start().done(function () {
    //....
})

But it's not working every time it's showing this.

Body:
I think you are missing the OwinStartup class that starts the signalR hub in your application.  Look at this project on my github called DnnLogAnalyzer.  I have a class called Startup.cs that hooks into the OwinStartup and starts the signalR hub for the application.

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(DotNetNuclear.Modules.LogAnalyzer.Components.Startup))]

namespace DotNetNuclear.Modules.LogAnalyzer.Components
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ...
            app.MapSignalR();
        }
    }
}

If you are a DNNHero.com subscriber, you can also check out my step-by-step tutorial for tips on getting SignalR working in your DNN application.


来源: stackexchange

问:
How to go over angular collection
I have the following structure in Component:

```<code>const Data = {
"java : [{text: "question", answer: "yes"},
    {text: "some question", answer: "yes"}],
"python":[{text: "some question", answer: "yes"},
        {text: "some question", answer: "no"}],
}
}
</code>```

And now I want to go over this collection and output questions with answers in the list. I am doing that like this:

```<code> <p *ngFor="let line of currentComponent" class="center">
    {{line.text}}
    {{line.answer}}
 </p>
</code>```

But this code doesn't show anything. If I try to display currentComponent it displays

[object Object],[object Object]

currentComponent is deffined:

```<code>export class ThisComponent implements OnInit {

  @Input() title:string;

  currentComponent:ThisComponent;

  line:string;

  ngOnInit() {
    this.currentComponent = this.thisServise.getCourse(this.title);
  }

}
</code>```

What is wrong?

答:
I don't know exactly what you're trying to do. This won't work. It sounds like you want a separate class/interface to define your data. It should simplify your solution.

```<code>// in something like 'data.model.ts'
export interface Data {
  name: string; //eg: 'java'
  text: string; //eg: 'question?'
  answer: string; //eg: 'yes'
}
</code>```

And then you would want your service to return Data objects.

```<code>// in your service class
data: Data[] = [
  {name: 'java', text: 'foo', answer: 'no'},
  {name: 'python', text: 'bar', answer: 'yes'}
];

// ...
// you could use filtering here since data is an array of objects
getDataForLanguage(language: string) {
  return this.data.filter(course -> {
    return course.name == language;
  })
}
</code>```

It would be something like that. I didn't go and compile the code to check, but that would be the approach I took rather than trying to manipulate a complex Object like what you are trying to do.

ContentLicense: CC BY-SA 3.0

Title: How to go over angular collection

Body:
I have the following structure in Component:

const Data = {
"java : [{text: "question", answer: "yes"},
    {text: "some question", answer: "yes"}],
"python":[{text: "some question", answer: "yes"},
        {text: "some question", answer: "no"}],
}
}

And now I want to go over this collection and output questions with answers in the list. I am doing that like this:

    {{line.text}}
    {{line.answer}}

But this code doesn't show anything. If I try to display currentComponent it displays

[object Object],[object Object]

currentComponent is deffined:

export class ThisComponent implements OnInit {

  @Input() title:string;

  currentComponent:ThisComponent;

  line:string;

  ngOnInit() {
    this.currentComponent = this.thisServise.getCourse(this.title);
  }

}

What is wrong?

Body:
I don't know exactly what you're trying to do. This won't work. It sounds like you want a separate class/interface to define your data. It should simplify your solution.

// in something like 'data.model.ts'
export interface Data {
  name: string; //eg: 'java'
  text: string; //eg: 'question?'
  answer: string; //eg: 'yes'
}

And then you would want your service to return Data objects.

// in your service class
data: Data[] = [
  {name: 'java', text: 'foo', answer: 'no'},
  {name: 'python', text: 'bar', answer: 'yes'}
];

// ...
// you could use filtering here since data is an array of objects
getDataForLanguage(language: string) {
  return this.data.filter(course -> {
    return course.name == language;
  })
}

It would be something like that. I didn't go and compile the code to check, but that would be the approach I took rather than trying to manipulate a complex Object like what you are trying to do.


问:
Show only results in query with more then 2 hits
didnt find a solution yet... ;-)

suppose this is the result of a query:

```<code>ID, SUBS, DATE .
19967,142, 2017-06-15 .
20214,147, 2017-05-09 .
20214,137, 2017-06-07 .
20303,147, 2017-05-31 .
</code>```

and i want only the records with an ID who are more then 1 time in result, but i do want the 2 or more records, so not GROUP BY.

How to manipulate the query?

答:
create a table where it shows the number of occurrence of a record called sumRecords, and left join sumRecords with constraints as WHERE occurrence > 1

I am referring your table as temp Here is the code:

```<code>SELECT temp.* FROM
temp LEFT JOIN
(SELECT ID, COUNT(*) occurance
FROM temp
GROUP BY ID) sumRecords ON temp.ID = sumRecords.ID
WHERE sumRecords.occurance > 1
</code>```

result:

```<code>ID      subs     dat
20214   147     2017-05-09
20214   137     2017-06-07
</code>```

Body:
didnt find a solution yet... ;-)

suppose this is the result of a query:

ID, SUBS, DATE .
19967,142, 2017-06-15 .
20214,147, 2017-05-09 .
20214,137, 2017-06-07 .
20303,147, 2017-05-31 .

and i want only the records with an ID who are more then 1 time in result, but i do want the 2 or more records, so not GROUP BY.

How to manipulate the query?

Body:
create a table where it shows the number of occurrence of a record called sumRecords, and left join sumRecords with constraints as WHERE occurrence > 1

I am referring your table as temp Here is the code:

SELECT temp.* FROM
temp LEFT JOIN
(SELECT ID, COUNT(*) occurance
FROM temp
GROUP BY ID) sumRecords ON temp.ID = sumRecords.ID
WHERE sumRecords.occurance > 1

result:

ID      subs     dat
20214   147     2017-05-09
20214   137     2017-06-07


问:
Practical non-image based CAPTCHA approaches?
It looks like we'll be adding CAPTCHA support to Stack Overflow. This is necessary to prevent bots, spammers, and other malicious scripted activity. We only want human beings to post or edit things here!

We'll be using a JavaScript (jQuery) CAPTCHA as a first line of defense:

http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs

The advantage of this approach is that, for most people, the CAPTCHA won't ever be visible!

However, for people with JavaScript disabled, we still need a fallback and this is where it gets tricky.

I have written a traditional CAPTCHA control for ASP.NET which we can re-use.

However, I'd prefer to go with something textual to avoid the overhead of creating all these images on the server with each request.

I've seen things like..

ASCII text captcha: \/\/(_)\/\/

math puzzles: what is 7 minus 3 times 2?

trivia questions: what tastes better, a toad or a popsicle?

Maybe I'm just tilting at windmills here, but I'd like to have a less resource intensive, non-image based  compatible CAPTCHA if possible.

Ideas?

答:
1) Human solvers

All mentioned here solutions are circumvented by human solvers approach.  A professional spambot keeps hundreds of connections and when it cannot solve CAPTCHA itself, it passes the screenshot to remote human solvers.

I frequently read that human solvers of CAPTCHAs break the laws. Well, this is written by those who do not know how this (spamming) industry works.

Human solvers do not directly interact with sites which CAPTCHAs they solve. They even do not know from which sites CAPTCHAs were taken and sent them. I am aware about dozens (if not hundreds) companies or/and websites offering human solvers services but not a single one for direct interaction with boards being broken.

The latter do not infringe any law, so CAPTCHA solving  is completely legal (and officialy registered) business companies. They do not have criminal intentions and might, for example, have been used for remote testing, investigations, concept proofing, prototypong, etc.

2) Context-based Spam

AI (Artificial Intelligent) bots determine contexts and maintain context sensitive dialogues at different times from different IP addresses (of different countries). Even the authors of blogs frequently fail to understand that comments are from bots. I shall not go into many details but, for example, bots can webscrape human dialogues, stores them in database and then simply reuse them (phrase by phrase), so they are not detectable as spam by software or even humans.

The most voted answer telling:

*"The theory being that:

A spam bot will not support JavaScript and will submit what it sees

If the bot does support JavaScript it will submit the form instantly

The commenter has at least read some of the page before posting"*

as well honeypot  answer and most answers in this thread are just plain wrong.

I daresay they are victim-doomed approaches

Most spambots work through local and remote javascript-aware (patched and managed) browsers from different IPs (of different countries) and they are quite clever to circumvent honey traps and honey pots.

The different problem is that even blog owners cannot frequently detect that comments are from bot since they are really from human dialogs and comments harvested from other web boards (forums, blog comments, etc)

3) Conceptually New Approach

Sorry, I removed this part as precipitated one

LastEditorDisplayName: Jeff Atwood


问:
How to extract concrete url with Regex from a block of text written in html in PHP?
I have the following block of text:

```<code><div class="view view-views-fichas view-id-views_fichas view-display-id-block_4 view-dom-id-a77b24219bd9d1b93008f7ac4fac8979">

  <div class="view-content">

<!-- THEME DEBUG -->
<!-- CALL: theme('views_view_unformatted') -->
<!-- BEGIN OUTPUT from 'profiles/tema/modules/contrib/views/theme/views-view-unformatted.tpl.php' -->
  <div>

<!-- THEME DEBUG -->
<!-- CALL: theme('views_view_fields') -->
<!-- BEGIN OUTPUT from 'profiles/tema/modules/contrib/views/theme/views-view-fields.tpl.php' -->

      /textname%C3%B3n-name-test/13-theme/020-alecl%C3%B3n-more-text-in-theme/03-more-and-more-text
<!-- END OUTPUT from 'profiles/tema/modules/contrib/views/theme/views-view-fields.tpl.php' -->

</div>

<!-- END OUTPUT from 'profiles/tema/modules/contrib/views/theme/views-view-unformatted.tpl.php' -->

</div>
</code>```

The text that I need to extract is the one that says:
/textname%C3%B3n-name-test/13-theme/020-alecl%C3%B3n-more-text-in-theme/03-more-and-more-text

I have the following example:
Link to regex php

Thanks..

答:
Just use

```<code>/textname\S+
</code>```

with e.g. ~ as delimiters, see your modified demo on regex101.com.

Body:
I have the following block of text:

      /textname%C3%B3n-name-test/13-theme/020-alecl%C3%B3n-more-text-in-theme/03-more-and-more-text

The text that I need to extract is the one that says:
/textname%C3%B3n-name-test/13-theme/020-alecl%C3%B3n-more-text-in-theme/03-more-and-more-text

I have the following example:
Link to regex php

Thanks..

Body:
Just use

/textname\S+

with e.g. ~ as delimiters, see your modified demo on regex101.com.


问:
What's the role of EX stage for branching in Pipelined MIPS w Forwarding?
Consider the following Pipelined Processor structure:

Notice that the condition test for branching (the = circuit), as well as the target address calculation for the next instruction in case of branch taken are executed in the ID phase - as a way to save on stalls/flushes (as opposed to doing all that in the EX phase and forwarding the results in the MEM phase of the given branch instruction).

Since all the work gets done in Instruction Decode stage, why bother waiting for the given branching instruction to reach the EX stage? Does the EX stage ALU unit have a role in this, somehow?

Thank you in advance.

答:
When the beq presents a control hazard, the pipelined processor does not know in advance what instruction to fetch next,because the branch decision has not been made by the time the next instruction is fetched.

Because the decision is made in the MEM-stage we need to stall the pipeline for three cycles at every branch which of course effect the system performance.

another way is to predict whether the branch will be taken and begin to executing instructions based on the prediction.Once the branch decision is made and is available, the processor can throw out(flushes) the instructions if the prediction was wrong (this called branch misprediction penalty)  which also effect the performance.

To reduce the branch misprediction penalty one could make the branch decision made earlier.
Making the decision simply requires comparing two registers. using a dedicated equality comparator is faster than performing a subtraction and zero detection. If the comparator is fast enough, it could be moved back into the Decode stage, so that the operands are read from the register file and compared to determine the next PC by the end of the Decode stage.

Unfortunately the early branch decision hardware introduce a new RAW data hazard.


问:
Java GUI Calculator
My JTextArea does not display and no errors or problems shows up. It's a Java GUI Calculator.

Main class code:

```<code>    import javax.swing.JFrame;

    public class calulator_main{

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            calulator_ui frame = new calulator_ui();
            frame.frame.setVisible(true);
        }

    }
</code>```

Calculator code:

```<code>import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class calulator_ui extends calulator_main {

    JFrame frame = new JFrame("cal");

    JPanel panel = new JPanel(new FlowLayout());
    JPanel screen = new JPanel(new BorderLayout());
    JTextArea text = new JTextArea(1,20);
    JButton button1 = new JButton("1");
    JButton button2 = new JButton("2");
    JButton button3 = new JButton("3");
    JButton button4 = new JButton("4");
    JButton button5 = new JButton("5");
    JButton button6 = new JButton("6");
    JButton button7 = new JButton("7");

    JButton button8 = new JButton("8");
    JButton button9 = new JButton("9");
    JButton button0 = new JButton("0");

    JButton add = new JButton("+");
    JButton subtract = new JButton("-");
    JButton mutliple = new JButton("*");
    JButton divide = new JButton("/");
    JButton equals = new JButton("=");

    JButton clear = new JButton("C");

    JLabel label = new JLabel();

    double numberone,numbertwo,result;

    int addc=0, subc=0,mutlic=0,divc=0;

    public calulator_ui() {
        ui();
        placeComponets();
        createListeners();

    }

    public void placeComponets(){

        screen.add(text, BorderLayout.NORTH);
        panel.add(button0);
        panel.add(button1);
        panel.add(button2);
        panel.add(button3);
        panel.add(button4);
        panel.add(button5);
        panel.add(button6);
        panel.add(button7);
        panel.add(button8);
        panel.add(button9);
        panel.add(add);
        panel.add(mutliple);
        panel.add(subtract);
        panel.add(divide);
        panel.add(clear);
        panel.add(equals);
        panel.add(label);
    }

    public void ui(){

        frame.setVisible(true);
        frame.setSize(250,200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);

    }

    public void createListeners(){

        this.button0.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button1.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button2.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button3.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button4.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button5.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button6.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button7.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button8.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button9.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.add.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.subtract.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.mutliple.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.divide.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.equals.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });

    }

    void onCutClicked(ActionEvent ae){

        Object source = ae.getSource();

        if(source==button0)
        {
            text.append("0");

        }

        if(source==button1)
        {
            text.append("1");

        }

        if(source==button2)
        {
            text.append("2");

        }

        if(source==button3)
        {
            text.append("3");

        }

        if(source==button4)
        {
            text.append("4");

        }

        if(source==button5)
        {
            text.append("5");

        }

        if(source==button6)
        {
            text.append("6");

        }

        if(source==button7)
        {
            text.append("7");

        }

        if(source==button8)
        {
            text.append("8");

        }

        if(source==button9)
        {
            text.append("9");

        }

        if (source==add)
        {
            numberone=number_reader();
            text.setText("");
            addc=1;
            subc=0;
            mutlic=0;
            divc=0;
        }

        if (source==subtract)
        {
            numberone=number_reader();
            text.setText("");
            addc=0;
            subc=1;
            mutlic=0;
            divc=0;
        }

        if (source==mutliple)
        {
            numberone=number_reader();
            text.setText("");
            addc=0;
            subc=0;
            mutlic=1;
            divc=0;
        }

        if (source==divide)
        {
            numberone=number_reader();
            text.setText("");
            addc=0;
            subc=0;
            mutlic=0;
            divc=1;
        }

        if (source==equals)
        {
            numbertwo=number_reader();
            if (addc>0)
            {
                result=numberone+numbertwo;
                text.setText(Double.toString(result));
            }

            if (subc>0)
            {
                result=numberone-numbertwo;
                text.setText(Double.toString(result));
            }

            if (divc>0)
            {
                result=numberone/numbertwo;
                text.setText(Double.toString(result));
            }

            if (mutlic>0)
            {
                result=numberone*numbertwo;
                text.setText(Double.toString(result));
            }

        }
    }

    public double number_reader()

    {

        double returnnumber;
        String numberstring;
        numberstring=text.getText();
        returnnumber=Double.valueOf(numberstring);

        return returnnumber;

    }

}
</code>```

Any suggestions on improvements to the code?

答:
Try to look at your code, you have tried to pass Panel with arguments.
Use one layout, add the components that will be managed by that particular layout then another manager followed by its components.
 Declaring as you have done will make JVM to use only BorderLayout.</p>

```<code>JPanel panel = new JPanel(new FlowLayout());
JPanel screen = new JPanel(new BorderLayout());
</code>```

Title: Java GUI Calculator

Body:
My JTextArea does not display and no errors or problems shows up. It's a Java GUI Calculator.

Main class code:

    import javax.swing.JFrame;

    public class calulator_main{

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            calulator_ui frame = new calulator_ui();
            frame.frame.setVisible(true);
        }

    }

Calculator code:

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class calulator_ui extends calulator_main {

    JFrame frame = new JFrame("cal");

    JPanel panel = new JPanel(new FlowLayout());
    JPanel screen = new JPanel(new BorderLayout());
    JTextArea text = new JTextArea(1,20);
    JButton button1 = new JButton("1");
    JButton button2 = new JButton("2");
    JButton button3 = new JButton("3");
    JButton button4 = new JButton("4");
    JButton button5 = new JButton("5");
    JButton button6 = new JButton("6");
    JButton button7 = new JButton("7");

    JButton button8 = new JButton("8");
    JButton button9 = new JButton("9");
    JButton button0 = new JButton("0");

    JButton add = new JButton("+");
    JButton subtract = new JButton("-");
    JButton mutliple = new JButton("*");
    JButton divide = new JButton("/");
    JButton equals = new JButton("=");

    JButton clear = new JButton("C");

    JLabel label = new JLabel();

    double numberone,numbertwo,result;

    int addc=0, subc=0,mutlic=0,divc=0;

    public calulator_ui() {
        ui();
        placeComponets();
        createListeners();

    }

    public void placeComponets(){

        screen.add(text, BorderLayout.NORTH);
        panel.add(button0);
        panel.add(button1);
        panel.add(button2);
        panel.add(button3);
        panel.add(button4);
        panel.add(button5);
        panel.add(button6);
        panel.add(button7);
        panel.add(button8);
        panel.add(button9);
        panel.add(add);
        panel.add(mutliple);
        panel.add(subtract);
        panel.add(divide);
        panel.add(clear);
        panel.add(equals);
        panel.add(label);
    }

    public void ui(){

        frame.setVisible(true);
        frame.setSize(250,200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);

    }

    public void createListeners(){

        this.button0.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button1.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button2.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button3.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button4.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button5.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button6.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button7.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button8.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.button9.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.add.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.subtract.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.mutliple.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.divide.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });
        this.equals.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        onCutClicked(ae);
                    }
                });

    }

    void onCutClicked(ActionEvent ae){

        Object source = ae.getSource();

        if(source==button0)
        {
            text.append("0");

        }

        if(source==button1)
        {
            text.append("1");

        }

        if(source==button2)
        {
            text.append("2");

        }

        if(source==button3)
        {
            text.append("3");

        }

        if(source==button4)
        {
            text.append("4");

        }

        if(source==button5)
        {
            text.append("5");

        }

        if(source==button6)
        {
            text.append("6");

        }

        if(source==button7)
        {
            text.append("7");

        }

        if(source==button8)
        {
            text.append("8");

        }

        if(source==button9)
        {
            text.append("9");

        }

        if (source==add)
        {
            numberone=number_reader();
            text.setText("");
            addc=1;
            subc=0;
            mutlic=0;
            divc=0;
        }

        if (source==subtract)
        {
            numberone=number_reader();
            text.setText("");
            addc=0;
            subc=1;
            mutlic=0;
            divc=0;
        }

        if (source==mutliple)
        {
            numberone=number_reader();
            text.setText("");
            addc=0;
            subc=0;
            mutlic=1;
            divc=0;
        }

        if (source==divide)
        {
            numberone=number_reader();
            text.setText("");
            addc=0;
            subc=0;
            mutlic=0;
            divc=1;
        }

        if (source==equals)
        {
            numbertwo=number_reader();
            if (addc>0)
            {
                result=numberone+numbertwo;
                text.setText(Double.toString(result));
            }

            if (subc>0)
            {
                result=numberone-numbertwo;
                text.setText(Double.toString(result));
            }

            if (divc>0)
            {
                result=numberone/numbertwo;
                text.setText(Double.toString(result));
            }

            if (mutlic>0)
            {
                result=numberone*numbertwo;
                text.setText(Double.toString(result));
            }

        }
    }

    public double number_reader()

    {

        double returnnumber;
        String numberstring;
        numberstring=text.getText();
        returnnumber=Double.valueOf(numberstring);

        return returnnumber;

    }

}

Any suggestions on improvements to the code?

Body:
Try to look at your code, you have tried to pass Panel with arguments.
Use one layout, add the components that will be managed by that particular layout then another manager followed by its components.
 Declaring as you have done will make JVM to use only BorderLayout.

JPanel panel = new JPanel(new FlowLayout());
JPanel screen = new JPanel(new BorderLayout());


问:
remove repeated items from an xml array in jquery
I am trying to eliminate repeated elements in an xml output. The loop works, but I need to skip over the repeated ID and PO values from all but the first loop.

Right now, the output looks like:

2 123456

1234567890: AA100

2 123456

0987654321: BB100

3 123456

11223345: CC00

3 123456

554433221: DD100

I am trying to make it look like:

2 123456

1234567890: AA100

0987654321: BB100

3 123456

11223345: CC00

554433221: DD100

This is my code - and you can see an example here:
https://codepen.io/BIGREDBOOTS/pen/VWQNBw

```<code>jQuery(function ($) {
   $("#dvContent").append("<p class='mainblock'></p>");
  var customerInfo = [];

  $.get("https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.xml", function(xml) {
    $('manifest', xml).each(function() {
      var id = $(this).find('id').text();
      var po = $(this).find('po').text();
      var loc = {
        "UPC": $(this).find("upc").first().text(),
        "Contents": {
          "Item": $.map($(this).find("item").toArray(), function(manifest) {
            return {
              "ID": id,
              "PO": po,
              "UPC": $(manifest).find("upc").text(),
              "SKU": $(manifest).find("sku").text()
            };
          })
        }
      };
      customerInfo.push(loc);

      $("<div></div>").html($.map($(loc.Contents.Item).toArray(), function(manifest) {
        return '<div class="title">' + manifest.ID + ' ' + manifest.PO + '</div>' +
          '<span class="title">' + manifest.UPC + ": " + manifest.SKU + '</span> <br/>' ;
      }).join("")).append("<br>").appendTo("#dvContent p");
    });
  });
});
</code>```

答:
Please consider using of Object instead of Array:

jQuery(function($) {
  var customerInfo = {};

  $.get("https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.xml", function(xml) {

    $('manifest', xml).each(function(n, m) {
      var id = $(m).find('id').text(),
        po = $(m).find('po').text();
      if (!customerInfo[id + ' ' + po]) customerInfo[id + ' ' + po] = [];

      $(m).find('item').each(function(n, i) {
        customerInfo[id + ' ' + po]
          .push({
            "UPC": $(i).find("upc").text(),
            "SKU": $(i).find("sku").text()
          })
      });
    });

    $("

").html(
      Object.keys(customerInfo).map(function(k) {
        return '
' + k + '
' +
          customerInfo[k].map(function(i) {
            return '' + i.UPC + ": " + i.SKU + '
'
          }).join('')
      }).join('
')
    ).appendTo("#dvContent");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dvContent"></div></code>```

Also it's not valid to append
 to
 so I've omitted it.

Body:
I am trying to eliminate repeated elements in an xml output. The loop works, but I need to skip over the repeated ID and PO values from all but the first loop.

Right now, the output looks like:

2 123456

1234567890: AA100

2 123456

0987654321: BB100

3 123456

11223345: CC00

3 123456

554433221: DD100

I am trying to make it look like:

2 123456

1234567890: AA100

0987654321: BB100

3 123456

11223345: CC00

554433221: DD100

This is my code - and you can see an example here:
https://codepen.io/BIGREDBOOTS/pen/VWQNBw

jQuery(function ($) {
   $("#dvContent").append("

");
  var customerInfo = [];

  $.get("https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.xml", function(xml) {
    $('manifest', xml).each(function() {
      var id = $(this).find('id').text();
      var po = $(this).find('po').text();
      var loc = {
        "UPC": $(this).find("upc").first().text(),
        "Contents": {
          "Item": $.map($(this).find("item").toArray(), function(manifest) {
            return {
              "ID": id,
              "PO": po,
              "UPC": $(manifest).find("upc").text(),
              "SKU": $(manifest).find("sku").text()
            };
          })
        }
      };
      customerInfo.push(loc);

      $("

").html($.map($(loc.Contents.Item).toArray(), function(manifest) {
        return '
' + manifest.ID + ' ' + manifest.PO + '
' +
          '' + manifest.UPC + ": " + manifest.SKU + '
' ;
      }).join("")).append("
").appendTo("#dvContent p");
    });
  });
});

Body:
Please consider using of Object instead of Array:

jQuery(function($) {
  var customerInfo = {};

  $.get("https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.xml", function(xml) {

    $('manifest', xml).each(function(n, m) {
      var id = $(m).find('id').text(),
        po = $(m).find('po').text();
      if (!customerInfo[id + ' ' + po]) customerInfo[id + ' ' + po] = [];

      $(m).find('item').each(function(n, i) {
        customerInfo[id + ' ' + po]
          .push({
            "UPC": $(i).find("upc").text(),
            "SKU": $(i).find("sku").text()
          })
      });
    });

    $("<div></div>").html(
      Object.keys(customerInfo).map(function(k) {
        return '<div class="title">' + k + '</div>' +
          customerInfo[k].map(function(i) {
            return '<span class="title">' + i.UPC + ": " + i.SKU + '</span><br>'
          }).join('')
      }).join('<br>')
    ).appendTo("#dvContent");
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dvContent"></div>

Also it's not valid to append <div> to <p> so I've omitted it.


问:
array() function returns an object
I have a problem with discord.js

I'm trying to get all the players that have a role with let gplayers = games_array[0].role.members, but since it returns an object that's like {"123" => GuildMember {}, "456" => GuildMember {} ...} and I need only the "123" and "456" objects I tried to use let gplayers = games_array[0].role.members.array() and then using gplayers[i]m but it didn't work.

I tried to check what was going wrong and I found out that gplayers was an object, even if I used the array() function.

console.log('Members: ', JSON.stringify(games_array[0].role.members, null, 4)) logs Members: {}

What can I do to store my objects in an array?

答:
I finally found the solution: I used this method

```<code>collection.forEach(function(guildMember) {
  //guildMember is now a User object, and I can do everything using properties
  console.log(guildMember.user.username);
})
</code>```

Solution thread: Loop through Snowflake array

ContentLicense: CC BY-SA 4.0

Title: array() function returns an object

Body:
I finally found the solution: I used this method

collection.forEach(function(guildMember) {
  //guildMember is now a User object, and I can do everything using properties
  console.log(guildMember.user.username);
})

Solution thread: Loop through Snowflake array


问:
FirebaseRecyclerAdapter and multiply item types on android
I want to add 2 types:-

with image

without image

in my recyclerview. I know that I need to override method from FirebaseRecyclerAdapter but I don't know how.
Help me please with this.

```<code>@Override
public int getItemViewType(int position) {
    return mModelLayout;
}

abstract protected void populateViewHolder(VH viewHolder, T model, int position);
</code>```

So I want to get from T-model type of item via int (1 - with image, 2 - without) and change mModelLayout basing on this info. Can I just add if else statement there ?

答:
This answer builds on hatboysam's answer. It took me ages to figure out how everything fits together so I thought I'd describe the solution thoroughly here:

```<code>    mRecyclerViewAdapter = new FirebaseRecyclerAdapter<DataObjectModel, ViewHolder>(
            DataObjectModel.class, R.layout.defaultitem_layout, ViewHolder.class, mDatabaseRef) {

        @Override
        public void populateViewHolder(ViewHolder viewholder, final DataObjectModel dataobject, int position) {

            if (getItemViewType(position) == R.layout.my_image_item){
                viewholder.setName(dataobject.getName());
            }
            else if (getItemViewType(position) == R.layout.my_no_image_item{
                viewholder.setText(dataobject.getText());
        }

        @Override
        public int getItemViewType(int position) {
            DataObjectModel dataobject = getItem(position);
            if (dataobject.getType() != null && dataobject.getType().equals("image")) {
                // Layout for an item with an image
                return  R.layout.my_image_item);
            } else if (dataobject.getType() != null && dataobject.getType().equals("noimage")) {
                // Layout for an item without an image
                return  R.layout.my_no_image_item;
            }
        }
    };
</code>```

//getName() and setText() are methods you have to write in the  "public static class ChatHolder extends RecyclerView.ViewHolder" class

// Here's the ViewHolder Class for good measure

```<code>    public static class ViewHolder extends RecyclerView.ViewHolder {
        View mView;

        public ViewHolder (View itemView) {
            super(itemView);
            mView = itemView;
        }

        public void setName(String name) {
            TextView field = (TextView) mView.findViewById(R.id.name_text);
            field.setText(name);
        }

        public void setText(String text) {
            TextView field = (TextView) mView.findViewById(R.id.message_text);
            field.setText(text);
        }
}
</code>```

Body:
I want to add 2 types:-

with image

without image

in my recyclerview. I know that I need to override method from FirebaseRecyclerAdapter but I don't know how.
Help me please with this.

@Override
public int getItemViewType(int position) {
    return mModelLayout;
}

abstract protected void populateViewHolder(VH viewHolder, T model, int position);

So I want to get from T-model type of item via int (1 - with image, 2 - without) and change mModelLayout basing on this info. Can I just add if else statement there ?

Body:
This answer builds on hatboysam's answer. It took me ages to figure out how everything fits together so I thought I'd describe the solution thoroughly here:

    mRecyclerViewAdapter = new FirebaseRecyclerAdapter<DataObjectModel, ViewHolder>(
            DataObjectModel.class, R.layout.defaultitem_layout, ViewHolder.class, mDatabaseRef) {

        @Override
        public void populateViewHolder(ViewHolder viewholder, final DataObjectModel dataobject, int position) {

            if (getItemViewType(position) == R.layout.my_image_item){
                viewholder.setName(dataobject.getName());
            }
            else if (getItemViewType(position) == R.layout.my_no_image_item{
                viewholder.setText(dataobject.getText());
        }

        @Override
        public int getItemViewType(int position) {
            DataObjectModel dataobject = getItem(position);
            if (dataobject.getType() != null && dataobject.getType().equals("image")) {
                // Layout for an item with an image
                return  R.layout.my_image_item);
            } else if (dataobject.getType() != null && dataobject.getType().equals("noimage")) {
                // Layout for an item without an image
                return  R.layout.my_no_image_item;
            }
        }
    };

//getName() and setText() are methods you have to write in the  "public static class ChatHolder extends RecyclerView.ViewHolder" class

// Here's the ViewHolder Class for good measure

    public static class ViewHolder extends RecyclerView.ViewHolder {
        View mView;

        public ViewHolder (View itemView) {
            super(itemView);
            mView = itemView;
        }

        public void setName(String name) {
            TextView field = (TextView) mView.findViewById(R.id.name_text);
            field.setText(name);
        }

        public void setText(String text) {
            TextView field = (TextView) mView.findViewById(R.id.message_text);
            field.setText(text);
        }
}


问:
Rails Devise-JWT, how to configure devise.rb to add a dispatch_requests
I'm using devise-jwt

The readme has the following:

dispatch_requests: "additional requests where JWT tokens should be dispatched"

Example:

```<code>jwt.dispatch_requests = [
                          ['POST', %r{^/dispatch_path_1$}],
                          ['GET', %r{^/dispatch_path_2$}],
                        ]
</code>```

Based on the doc, I updated my devise.rb with the following:

```<code>  config.jwt do |jwt|
    jwt.secret = ENV['DEVISE_JWT_SECRET_KEY']
    jwt.expiration_time = 30.days
    jwt.dispatch_requests = [
                              ['GET', %r{^/users/confirmation.*$}]
                            ]
  end
</code>```

With the goal of getting devise-jwt to dispatch the JWT token when a user confirms their email address via email by clicking the following link:

```<code>http://localhost:4400/users/confirmation?confirmation_token=16J2zDtDhjyF3vCQv2ba
</code>```

For some reason, the above URL is not getting the JWT token dispatched in the header... Given I'm horrible at regex, I'm hoping for some help... Did I do something wrong to add the additional dispatch request in my devise config?

Thank you!

答:
If the token is in the link you click on then the token won't be in the header, it will be sent as a param called 'confirmation_token'. which you would access as:
params[:confirmation_token] from within the controller.

p.s. JSON web tokens are awesome, I like using them to manage state in an application so no need for session storage :D, of course this does present a slight issue when you need to access data within token on the front end.

Body:
I'm using devise-jwt

The readme has the following:

dispatch_requests: "additional requests where JWT tokens should be dispatched"

Example:

jwt.dispatch_requests = [
                          ['POST', %r{^/dispatch_path_1$}],
                          ['GET', %r{^/dispatch_path_2$}],
                        ]

Based on the doc, I updated my devise.rb with the following:

  config.jwt do |jwt|
    jwt.secret = ENV['DEVISE_JWT_SECRET_KEY']
    jwt.expiration_time = 30.days
    jwt.dispatch_requests = [
                              ['GET', %r{^/users/confirmation.*$}]
                            ]
  end

With the goal of getting devise-jwt to dispatch the JWT token when a user confirms their email address via email by clicking the following link:

http://localhost:4400/users/confirmation?confirmation_token=16J2zDtDhjyF3vCQv2ba

For some reason, the above URL is not getting the JWT token dispatched in the header... Given I'm horrible at regex, I'm hoping for some help... Did I do something wrong to add the additional dispatch request in my devise config?

Thank you!


问:
How to avoid page breaks (print / PDF) on text within large HTML table?
I have the following single HTML file (style / scripts included): FQ.html

I have the following issue:

I have iterated on solution attempts, the latest attempt for which has some of the following CSS...

```<code>@media print{
  @page {
    size:1080px 1080px;
    margin: 0px;
  }
  .page-break-before  { page-break-before: always; display:block; width:200%;}
  .page-break  { display:block; page-break-after: always; width:200%; }
}
</code>```

...and Javascript.

```<code>//set viewport height in print mode.
var height = 780;  //screen.height;
//pick up the total table.
var table = $('#identification_section > table')[0];
//initialize the sum variable with height of title (h2 tag)
var sum = 24;
//loop all table rows including child tables
for (var i = 0, row; row = table.rows[i]; i++) {
  //tr is the parent table row which may contain child table.
  var tr = row;
  if (tr.offsetHeight > height) {  //if row's hight is bigger than viewport height, it contains child table.
    var child_table = tr.cells[0].children[0];
    if (child_table.className=="group-table") {  //pick up child table.
      var child_sum = 0;
      for (var j=0, subrow; subrow = child_table.rows[j]; j++) {
        var subtr = subrow;  //pick up child table's row
        child_sum += subtr.offsetHeight; // sum up the row's height.
        if (child_table.rows[j+1]!=null) //check if next row is existing, not end row.
          if (child_sum + child_table.rows[j+1].offsetHeight > height) {  // if (sum of table rows so far + next row's height) > viewport height
            //var temp = subtr.cells[0]; // pick up the first cell of row
            child_table.rows[j+1].classList.add('page-break-before'); // set the page-break-before to next row.
            subtr.classList.add('page-break'); // set the page-break to current row
            child_sum = 0; // set the sum 0 for next page calculation.
          }
      }
    }
  }

  sum += tr.offsetHeight; // sum up the height of parent rows.
  //tr.cells[0].setAttribute('style', 'height:'+tr.offsetHeight+'px');
  if (table.rows[i+1]!=null) // check if there is next row.
    if (sum + table.rows[i+1].offsetHeight>height) {  // if sum + next row'height is bigger than viewport row
      //var temp = tr.cells[0];
      table.rows[i+1].classList.add('page-break-before'); //set the page-break-before class to next row
      tr.classList.add('page-break'); // set the page-break class to current row
      sum = 0; //set the sum 0 for next page calculation.
    }
}
</code>```

However, I am still at a loss. Rather than trying to avoid breaking on text, I felt it would be easier to avoid breaking on a . Even trying that, though, there are 2 or more issues with my attempted solution. One is that the breaks are overly excessive, and the second is that somehow some of the 's no longer seem to have width set at 50%.

Would be great to prevent breaks on text or 's, preferably text.

答:
You have to apply page-break-before and page-break-after rules to all of the elements inside the document.

For instance, for the tables, you may use table tr and similar selectors.

Body:
I have the following single HTML file (style / scripts included): FQ.html

I have the following issue:

I have iterated on solution attempts, the latest attempt for which has some of the following CSS...

@media print{
  @page {
    size:1080px 1080px;
    margin: 0px;
  }
  .page-break-before  { page-break-before: always; display:block; width:200%;}
  .page-break  { display:block; page-break-after: always; width:200%; }
}

...and Javascript.

//set viewport height in print mode.
var height = 780;  //screen.height;
//pick up the total table.
var table = $('#identification_section > table')[0];
//initialize the sum variable with height of title (h2 tag)
var sum = 24;
//loop all table rows including child tables
for (var i = 0, row; row = table.rows[i]; i++) {
  //tr is the parent table row which may contain child table.
  var tr = row;
  if (tr.offsetHeight > height) {  //if row's hight is bigger than viewport height, it contains child table.
    var child_table = tr.cells[0].children[0];
    if (child_table.className=="group-table") {  //pick up child table.
      var child_sum = 0;
      for (var j=0, subrow; subrow = child_table.rows[j]; j++) {
        var subtr = subrow;  //pick up child table's row
        child_sum += subtr.offsetHeight; // sum up the row's height.
        if (child_table.rows[j+1]!=null) //check if next row is existing, not end row.
          if (child_sum + child_table.rows[j+1].offsetHeight > height) {  // if (sum of table rows so far + next row's height) > viewport height
            //var temp = subtr.cells[0]; // pick up the first cell of row
            child_table.rows[j+1].classList.add('page-break-before'); // set the page-break-before to next row.
            subtr.classList.add('page-break'); // set the page-break to current row
            child_sum = 0; // set the sum 0 for next page calculation.
          }
      }
    }
  }

  sum += tr.offsetHeight; // sum up the height of parent rows.
  //tr.cells[0].setAttribute('style', 'height:'+tr.offsetHeight+'px');
  if (table.rows[i+1]!=null) // check if there is next row.
    if (sum + table.rows[i+1].offsetHeight>height) {  // if sum + next row'height is bigger than viewport row
      //var temp = tr.cells[0];
      table.rows[i+1].classList.add('page-break-before'); //set the page-break-before class to next row
      tr.classList.add('page-break'); // set the page-break class to current row
      sum = 0; //set the sum 0 for next page calculation.
    }
}

However, I am still at a loss. Rather than trying to avoid breaking on text, I felt it would be easier to avoid breaking on a . Even trying that, though, there are 2 or more issues with my attempted solution. One is that the breaks are overly excessive, and the second is that somehow some of the 's no longer seem to have width set at 50%.

Would be great to prevent breaks on text or 's, preferably text.


问:
Examine and replace characters at end of line or before whitespace
I currently have two arrays set up, and I am trying to examine the last two letters in a word and replace it with other characters if there is a match with the first array. I currently have it working to do this to the end of the line, but I cannot figure out how to do this for words that are not at the end of a line.

The following is an example of what my arrays might look like. These are populated from a database query. The characters could be any Unicode character, so not necessarily in the range from A-Z or a-z.

```<code>$array1 = ['mp', 'tm', 'de', 'HK'];
$array2 = ['MAP', 'TM', "DECIMAL", '字'];
</code>```

My current code looks like this:

```<code>$mystring = "samplemp";
$last = substr($mystring, -2);
$newlast = str_replace($array1, $array2, $last);
if ($last != $newlast){
    $mystring = substr($mystr, 0, 2).$newlast;
}
</code>```

What I have working:

So, the code I currently have looks at the last two characters in the string. If the last two characters are "mp" for example it replaces them with "MAP". So if my string looks like:

```<code>samplemp
</code>```

it gets changed correctly to

```<code>sampleMAP
</code>```

up to this point everything is working correctly.

The problem

The issue I am having is dealing with the words that are not at the end of a string. For example:

```<code>samplemp okay de     hellotm
blatm theHK end
</code>```

should be replaced with

```<code>sampleMAP okay DECIMAL     helloTM
blaTM the字 end
</code>```

I want to be able to account for all white space including spaces, tabs, and carriage returns. However, the whitespace must remain intact and not changed. Spaces must stay as spaces, tabs as tabs, and carriage returns as carriage returns.

So far, I've been able to figure out that I likely need to use a regular expression using the \s escape character to account for whitespace. However, I cannot comprehend how to use this with the str_replace functions which are acting on the arrays. Is there a way to do this? If not, what else should I do to get this to work?

答:
To go a little simpler than some of the other answers already here:</p>

```<code>$mystring = <<<EOD
samplemp okay MADE  de     hellotm
blatm theHK end
EOD;
$array1 = ['mp', 'tm', 'de', 'HK'];
$array2 = ['MAP', 'TM', "DECIMAL", '字'];
foreach($array1 as $key=>$v){
    $mystring = preg_replace("/".preg_quote($v)."\b/u", $array2[$key], $mystring);
}
</code>```

Body:
I currently have two arrays set up, and I am trying to examine the last two letters in a word and replace it with other characters if there is a match with the first array. I currently have it working to do this to the end of the line, but I cannot figure out how to do this for words that are not at the end of a line.

The following is an example of what my arrays might look like. These are populated from a database query. The characters could be any Unicode character, so not necessarily in the range from A-Z or a-z.

$array1 = ['mp', 'tm', 'de', 'HK'];
$array2 = ['MAP', 'TM', "DECIMAL", '字'];

My current code looks like this:

$mystring = "samplemp";
$last = substr($mystring, -2);
$newlast = str_replace($array1, $array2, $last);
if ($last != $newlast){
    $mystring = substr($mystr, 0, 2).$newlast;
}

What I have working:

So, the code I currently have looks at the last two characters in the string. If the last two characters are "mp" for example it replaces them with "MAP". So if my string looks like:

samplemp

it gets changed correctly to

sampleMAP

up to this point everything is working correctly.

The problem

The issue I am having is dealing with the words that are not at the end of a string. For example:

samplemp okay de     hellotm
blatm theHK end

should be replaced with

sampleMAP okay DECIMAL     helloTM
blaTM the字 end

I want to be able to account for all white space including spaces, tabs, and carriage returns. However, the whitespace must remain intact and not changed. Spaces must stay as spaces, tabs as tabs, and carriage returns as carriage returns.

So far, I've been able to figure out that I likely need to use a regular expression using the \s escape character to account for whitespace. However, I cannot comprehend how to use this with the str_replace functions which are acting on the arrays. Is there a way to do this? If not, what else should I do to get this to work?

Body:
To go a little simpler than some of the other answers already here:

$mystring = <<<EOD
samplemp okay MADE  de     hellotm
blatm theHK end
EOD;
$array1 = ['mp', 'tm', 'de', 'HK'];
$array2 = ['MAP', 'TM', "DECIMAL", '字'];
foreach($array1 as $key=>$v){
    $mystring = preg_replace("/".preg_quote($v)."\b/u", $array2[$key], $mystring);
}


问:
How can you connect through a SOCKS proxy with python httplib / http.client?
Normally, when using httplib (python 2.x) or http.client (python 3.x), you set up a connection and make a request like so:

```<code>from http.client import HTTPConnection
from urllib.parse import urlparse, urlencode

url = urlparse("http://final.destination.example.com:8888/")
conn = HTTPConnection(url.netloc)
request_path = "%s?%s" % (url.path, url.query)
conn.request("POST", request_path, post_data)
</code>```

(note that this example code has python 3.x imports)

I am in a situation where I would like to use http.client for performance reasons, but I'd also like to use a SOCKS proxy for remote access into a cluster.

Is there any way to use a SOCKS proxy with httplib/http.client?

答:
I am answering my own question here so that hopefully the next person in this situation can find the solution.

First install PySocks with:

```<code>pip install PySocks
</code>```

Then you need to manually set up your SOCKS proxy after making instantiating your HTTPConnection and informing it that it's going to be using a proxy:

```<code>from http.client import HTTPConnection
from urllib.parse import urlparse, urlencode

import socks

url = urlparse("http://final.destination.example.com:8888/")

conn = HTTPConnection('127.0.0.1', 9000) # use socks proxy address
conn.set_tunnel(url.netloc, url.port) # remote host and port that you actually want to talk to
conn.sock = socks.socksocket() # manually set socket
conn.sock.set_proxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9000) # use socks proxy address
conn.sock.connect((url.netloc, url.port)) # remote host and port that you actually want to talk to

request_path = "%s?%s" % (url.path, url.query)
conn.request("POST", request_path, post_data)
</code>```

Body:
Normally, when using httplib (python 2.x) or http.client (python 3.x), you set up a connection and make a request like so:

from http.client import HTTPConnection
from urllib.parse import urlparse, urlencode

url = urlparse("http://final.destination.example.com:8888/")
conn = HTTPConnection(url.netloc)
request_path = "%s?%s" % (url.path, url.query)
conn.request("POST", request_path, post_data)

(note that this example code has python 3.x imports)

I am in a situation where I would like to use http.client for performance reasons, but I'd also like to use a SOCKS proxy for remote access into a cluster.

Is there any way to use a SOCKS proxy with httplib/http.client?

Body:
I am answering my own question here so that hopefully the next person in this situation can find the solution.

First install PySocks with:

pip install PySocks

Then you need to manually set up your SOCKS proxy after making instantiating your HTTPConnection and informing it that it's going to be using a proxy:

from http.client import HTTPConnection
from urllib.parse import urlparse, urlencode

import socks

url = urlparse("http://final.destination.example.com:8888/")

conn = HTTPConnection('127.0.0.1', 9000) # use socks proxy address
conn.set_tunnel(url.netloc, url.port) # remote host and port that you actually want to talk to
conn.sock = socks.socksocket() # manually set socket
conn.sock.set_proxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9000) # use socks proxy address
conn.sock.connect((url.netloc, url.port)) # remote host and port that you actually want to talk to

request_path = "%s?%s" % (url.path, url.query)
conn.request("POST", request_path, post_data)


问:
PHP can't determine whether user is logged in or not
I'm creating a system that the header will show 'login' if the user is not logged in, and if they are, it'll display logout. I've simplified it for now, just showing if the user is logged in or not. With "Login!" meaning they need to login, and "Welcome!" if they are logged in. I used the PHP Code Checker website (https://phpcodechecker.com/) and it couldn't find any errors. I also searched stackoverflow, and everyone else's seems to work.

```<code>  <?php
  ob_start();
  session_start();
  require_once 'dbconnect.php';
  if( !isset($_SESSION['user']) ) {
  echo "Login!";
  } else {
  echo "Welcome!";
  }
  ?>
</code>```

is the code that checks if the user is logged in or not.

My login page works for EVERYTHING else, for my homepage is shows that the user is logged in, but here is the code anyway. (This is only the PHP code, there is HTML for the submit button, ect.)

```<code>  <?php
  ob_start();
  session_start();
  require_once 'dbconnect.php';

  // it will never let you open index(login) page if session is set
  if ( isset($_SESSION['user'])!="" ) {
  header("Location: index.php");
  exit;
  }

  $error = false;

  if( isset($_POST['btn-login']) ) {

  // prevent sql injections/ clear user invalid inputs
  $email = trim($_POST['email']);
  $email = strip_tags($email);
  $email = htmlspecialchars($email);

  $name = trim($_POST['name']);
  $name = strip_tags($name);
  $name = htmlspecialchars($name);

  $pass = trim($_POST['pass']);
  $pass = strip_tags($pass);
  $pass = htmlspecialchars($pass);
  // prevent sql injections / clear user invalid inputs

  if(empty($name)){
  $error = true;
  $nameError = "Please enter your username.";
  }

  if(empty($pass)){
  $error = true;
  $passError = "Please enter your password.";
  }

  // if there's no error, continue to login
  if (!$error) {

  $password = hash('sha256', $pass); // password hashing using SHA256

  $res=mysql_query("SELECT userId, userEmail, userPass FROM users WHERE
  userName='$name'");
  $row=mysql_fetch_array($res);
  $count = mysql_num_rows($res); // if email/pass correct it returns must be
  1 row

  if( $count == 1 && $row['userPass']==$password ) {
  $_SESSION['user'] = $row['userId'];
  header("Location: dashboard.php");
  } else {
  $errMSG = "Incorrect Credentials, Try again...";
  }

  }

  }
  ?>
</code>```

It connects to the database fine, and i'm certain there is no problems with the database, since it works on my other pages.

I've spent a long-while trying to figure this out, and can't.

Thanks!

答:
In your code

```<code>if ( isset($_SESSION['user'])!="" ) {
</code>```

you are comparing true|false != ""

change it to if (isset($_SESSION['user'])) {

or
if (isset($_SESSION['user']) && ($_SESSION['user']!="")) {

Body:
I'm creating a system that the header will show 'login' if the user is not logged in, and if they are, it'll display logout. I've simplified it for now, just showing if the user is logged in or not. With "Login!" meaning they need to login, and "Welcome!" if they are logged in. I used the PHP Code Checker website (https://phpcodechecker.com/) and it couldn't find any errors. I also searched stackoverflow, and everyone else's seems to work.

  <?php
  ob_start();
  session_start();
  require_once 'dbconnect.php';
  if( !isset($_SESSION['user']) ) {
  echo "Login!";
  } else {
  echo "Welcome!";
  }
  ?>

is the code that checks if the user is logged in or not.

My login page works for EVERYTHING else, for my homepage is shows that the user is logged in, but here is the code anyway. (This is only the PHP code, there is HTML for the submit button, ect.)

  <?php
  ob_start();
  session_start();
  require_once 'dbconnect.php';

  // it will never let you open index(login) page if session is set
  if ( isset($_SESSION['user'])!="" ) {
  header("Location: index.php");
  exit;
  }

  $error = false;

  if( isset($_POST['btn-login']) ) {

  // prevent sql injections/ clear user invalid inputs
  $email = trim($_POST['email']);
  $email = strip_tags($email);
  $email = htmlspecialchars($email);

  $name = trim($_POST['name']);
  $name = strip_tags($name);
  $name = htmlspecialchars($name);

  $pass = trim($_POST['pass']);
  $pass = strip_tags($pass);
  $pass = htmlspecialchars($pass);
  // prevent sql injections / clear user invalid inputs

  if(empty($name)){
  $error = true;
  $nameError = "Please enter your username.";
  }

  if(empty($pass)){
  $error = true;
  $passError = "Please enter your password.";
  }

  // if there's no error, continue to login
  if (!$error) {

  $password = hash('sha256', $pass); // password hashing using SHA256

  $res=mysql_query("SELECT userId, userEmail, userPass FROM users WHERE
  userName='$name'");
  $row=mysql_fetch_array($res);
  $count = mysql_num_rows($res); // if email/pass correct it returns must be
  1 row

  if( $count == 1 && $row['userPass']==$password ) {
  $_SESSION['user'] = $row['userId'];
  header("Location: dashboard.php");
  } else {
  $errMSG = "Incorrect Credentials, Try again...";
  }

  }

  }
  ?>

It connects to the database fine, and i'm certain there is no problems with the database, since it works on my other pages.

I've spent a long-while trying to figure this out, and can't.

Thanks!

Body:
In your code

if ( isset($_SESSION['user'])!="" ) {

you are comparing true|false != ""

change it to if (isset($_SESSION['user'])) {

or
if (isset($_SESSION['user']) && ($_SESSION['user']!="")) {


问:
"Uncaught TypeError: csv.replace is not a function" when using csv jquery plugin, how do I fix this?
In the following code:

```<code>  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "file://csvFileName.csv", true);
  console.log(rawFile);
  var input = $.csv.toObjects(rawFile);
  console.log(input);
</code>```

I'm trying to convert a .csv file into a readable file, and then I'm trying to run a .toObjects command on it to produce a csv file that's easier to work with, but I keep running into an "Uncaught TypeError: csv.replace is not a function" error on the fourth line. I'm using the most upvoted answer to this question as a basis.

I've read through the documentation but I can't seem to find a particular answer to this error, does anyone know of a fix?

edit: this isn't my entire code, I have a script link to the jquery plugin in my html header. This is just the section where the error is. link looks like:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
</code>```

答:
XMLHttpRequest is not a file, you should do a request either with XMLHttpRequest's open function, or see bellow, after that you should get the file out the response data.
you can use instead:</p>

```<code>fetch("file://csvFileName.csv").then(function(resp) {
    return resp.blob();
}).then(function(blob) {
    var file = new File([blob], "name");
    var input = $.csv.toObjects(rawFile);
    console.log(input);
});
</code>```

Body:
In the following code:

  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "file://csvFileName.csv", true);
  console.log(rawFile);
  var input = $.csv.toObjects(rawFile);
  console.log(input);

I'm trying to convert a .csv file into a readable file, and then I'm trying to run a .toObjects command on it to produce a csv file that's easier to work with, but I keep running into an "Uncaught TypeError: csv.replace is not a function" error on the fourth line. I'm using the most upvoted answer to this question as a basis.

I've read through the documentation but I can't seem to find a particular answer to this error, does anyone know of a fix?

edit: this isn't my entire code, I have a script link to the jquery plugin in my html header. This is just the section where the error is. link looks like:

Body:
XMLHttpRequest is not a file, you should do a request either with XMLHttpRequest's open function, or see bellow, after that you should get the file out the response data.
you can use instead:

fetch("file://csvFileName.csv").then(function(resp) {
    return resp.blob();
}).then(function(blob) {
    var file = new File([blob], "name");
    var input = $.csv.toObjects(rawFile);
    console.log(input);
});


问:
Find a text in a range and copy the next Activecell.offset(1,1)16 cells to destination
I have a range I13 to I6076. I am starting at first I13 cell and finding a match in Range("D12:D103333"). If it finds a match in Col D then it should offset Activecell.offset(1,1) from Col D cell and copy the next 16 cells(vertical copy) to corresponding I13 row(horizontal paste). and then move on to I14 and so on. I have created a do while loop to find the cells in the range Range("D12:D103333"), but how do I offset and copy the next 16 cells. and then go to next cell in col I.
Any help would be greatly appreciated. Many Thanks. Code is below.

```<code>Sub Kantar()

    Dim Category As String
    i As Integer

    Range("I13").Select
    Do While Not IsEmpty(ActiveCell)
        Category = ActiveCell.Value
        Range("D12:D103333").Find(What:=Category, MatchCase:=True).Select

        ActiveCell.Offset(1, 0).Select
    Loop

End Sub
</code>```

答:
Try doing something like this:

1) Once the cell is found, activecell.offset(1,1)

2) From there, use your activecell.address and activecell.address + 16 as a range to do range.copy

3) Offset the active cell to where you want to paste.

4) Paste Special with transpose to transpose it horizontally (use macro recorder to show you how if you are unsure)

5) Offset back to original cell (coordinates based on where you end up)

6) Offset down 1 cell and continue the loop. (Which you already have coded)

I'd give actual code but I'm not at a PC. Hopefully these steps still help if someone else doesn't give you the code :)

Body:
I have a range I13 to I6076. I am starting at first I13 cell and finding a match in Range("D12:D103333"). If it finds a match in Col D then it should offset Activecell.offset(1,1) from Col D cell and copy the next 16 cells(vertical copy) to corresponding I13 row(horizontal paste). and then move on to I14 and so on. I have created a do while loop to find the cells in the range Range("D12:D103333"), but how do I offset and copy the next 16 cells. and then go to next cell in col I.
Any help would be greatly appreciated. Many Thanks. Code is below.

Sub Kantar()

    Dim Category As String
    i As Integer

    Range("I13").Select
    Do While Not IsEmpty(ActiveCell)
        Category = ActiveCell.Value
        Range("D12:D103333").Find(What:=Category, MatchCase:=True).Select

        ActiveCell.Offset(1, 0).Select
    Loop

End Sub


问:
g++ error: ‘stricmp’ was not declared in this scope (but OK for 'strcmp')
I am trying to compile the following very very simple piece of source code:

```<code>#include <cstring>
// #include <string.h>
// using namespace std;

class Helper {
public:
    int cStringsAreEqual(const char *s1, const char *s2) {
        return stricmp(s1, s2);
    }
};
</code>```

... but I am getting the following error message:

```<code>   g++ error: ‘stricmp’ was not declared in this scope
</code>```

However when I use strcmp() instead of stricmp() then everything is fine!

What can be wrong here? Shouldn't stricmp() be allowed when strcmp() is allowed?

Sureley, this all could be written in a much better way without using strcmp/stricmp.

But that's not the point here.

I am porting a piece of software - which makes much use of calls to stricmp(). And if somehow possible I would like to avoid all of the efforts needed to change every call to stricmp.

Any help on this would be very much appreciated!

BTW: I am using Ubuntu karmic OS (v9.10) with g++ v4.4.1.

BTW: as you can see I also made some trials with '#include string.h' or with 'namespace std' but nothing helped.

答:
Pretty easy to make your own if need be...</p>

```<code>int my_stricmp (const char *s1, const char *s2)
{
    while (*s1 != 0 && *s2 != 0)
    {
        if (*s1 != *s2 && ::toupper (*s1) != ::toupper(*s2))
        {
            return -1;
        }
        s1++;
        s2++;
    }
    return (*s1 == 0 && *s2 == 0) ? 0 : -1;
}
</code>```

OwnerDisplayName: anon

ContentLicense: CC BY-SA 2.5

Body:
I am trying to compile the following very very simple piece of source code:

#include <cstring>
// #include <string.h>
// using namespace std;

class Helper {
public:
    int cStringsAreEqual(const char *s1, const char *s2) {
        return stricmp(s1, s2);
    }
};

... but I am getting the following error message:

   g++ error: ‘stricmp’ was not declared in this scope

However when I use strcmp() instead of stricmp() then everything is fine!

What can be wrong here? Shouldn't stricmp() be allowed when strcmp() is allowed?

Sureley, this all could be written in a much better way without using strcmp/stricmp.

But that's not the point here.

I am porting a piece of software - which makes much use of calls to stricmp(). And if somehow possible I would like to avoid all of the efforts needed to change every call to stricmp.

Any help on this would be very much appreciated!

BTW: I am using Ubuntu karmic OS (v9.10) with g++ v4.4.1.

BTW: as you can see I also made some trials with '#include string.h' or with 'namespace std' but nothing helped.

Body:
Pretty easy to make your own if need be...

int my_stricmp (const char *s1, const char *s2)
{
    while (*s1 != 0 && *s2 != 0)
    {
        if (*s1 != *s2 && ::toupper (*s1) != ::toupper(*s2))
        {
            return -1;
        }
        s1++;
        s2++;
    }
    return (*s1 == 0 && *s2 == 0) ? 0 : -1;
}


问:
check for a property in array of objects and return a string based on the value
I have an array of objects  like this ,

```<code>   let employee =  [
            {
                NodeType: "intern",
                NodeName: "Node1"
            }, {
                NodeType: "intern",
                NodeName: "Node2"
            }, {
                NodeType: "full-time",
                NodeName: "Node1"
            }, {
                NodeType: "contract",
                NodeName: "Node1"
            }
 ]
</code>```

I need to be able to look through the array and see if all employees are full time then return "full time"  or if the employee list is only "interns" return interns  or if its mixed , return "mixed"

I tried

```<code>         var interntype = employee.find((obj) => {
                return obj.type == "intern"
            });
         var fulltimetype = employee.find((obj) => {
                return obj.type == "full-time"
            });
         var contracttype = employee.find((obj) => {
                return obj.type == "contract"
            });

    if( internType) {
      return "intern";
    } else if (fulltimeType) {
          return "fullTime"
     } else return "mixed";
</code>```

but is there a way where i dont do this multiple times and instead do it once

答:
Insert all NodeType values into a set, and check the size. If it's more than 1, return mixed, if not return the single item:

const employees = [{"NodeType":"intern","NodeName":"Node1"},{"NodeType":"intern","NodeName":"Node2"},{"NodeType":"full-time","NodeName":"Node1"},{"NodeType":"contract","NodeName":"Node1"}];

const getEmployeesType = (employees) => {
  const types = new Set(employees.map(({ NodeType }) => NodeType));
  return types.size > 1 ? 'mixed' : [...types][0];
};

console.log('mixed: ', getEmployeesType(employees));

console.log('internes: ', getEmployeesType(employees.slice(0, 2)));```

Body:
I have an array of objects  like this ,

   let employee =  [
            {
                NodeType: "intern",
                NodeName: "Node1"
            }, {
                NodeType: "intern",
                NodeName: "Node2"
            }, {
                NodeType: "full-time",
                NodeName: "Node1"
            }, {
                NodeType: "contract",
                NodeName: "Node1"
            }
 ]

I need to be able to look through the array and see if all employees are full time then return "full time"  or if the employee list is only "interns" return interns  or if its mixed , return "mixed"

I tried

         var interntype = employee.find((obj) => {
                return obj.type == "intern"
            });
         var fulltimetype = employee.find((obj) => {
                return obj.type == "full-time"
            });
         var contracttype = employee.find((obj) => {
                return obj.type == "contract"
            });

    if( internType) {
      return "intern";
    } else if (fulltimeType) {
          return "fullTime"
     } else return "mixed";

but is there a way where i dont do this multiple times and instead do it once


问:
Avoiding script in Tumblr oembed API
I need to work on oembed API of Tumblr. I completed Tumblr API but I need information how to disable script in Tumblr oembed api like in Twitter or Facebook. I tried to do as in Twitter API by adding omit_script=false

```<code>$tbdata = file_get_contents(
    'https://www.tumblr.com/oembed/1.0?url=https://breakup.tumblr.com/post/160221963841&omit_script=true'
);
</code>```

Oembed is working but omit_script has no effect. Please let me know if the is any ways to work. The Tumblr api documentation does not describe anything about oembed except providing oembed endpoint.

答:
oEmbed spec does not contain any option like omit_script to skip the script content in response. Only way to avoid it is to omit it from response.

I don't think even face book or twitter oEmbed api's have that support.

Title: Avoiding script in Tumblr oembed API

Body:
I need to work on oembed API of Tumblr. I completed Tumblr API but I need information how to disable script in Tumblr oembed api like in Twitter or Facebook. I tried to do as in Twitter API by adding omit_script=false

$tbdata = file_get_contents(
    'https://www.tumblr.com/oembed/1.0?url=https://breakup.tumblr.com/post/160221963841&omit_script=true'
);

Oembed is working but omit_script has no effect. Please let me know if the is any ways to work. The Tumblr api documentation does not describe anything about oembed except providing oembed endpoint.


问:
OAuth2 authorization for project and custom project-specific user role
I'm new to OAuth2 and trying to figure out what is the best practice for the following scenario:

I'm implementing 'ToDo' web service (CRUD for 'tasks')

I'm using OAuth2 and Google as auth provider to get user details (email, name)

Now I need to implement project-specific roles for users ('admin', 'user')

Speaking in terms of OAuth2 - Google doesn't 'own' my service, so it cannot help me with storing/providing 'ToDo'-specific roles, is it correct?

What is the common/best approach to implement it, do I need to create my own authorization service where I'll need to store relations like userinfo -> project-specific role?

答:
Well, it depends what, exactly, you're looking to do.

If you have users, and those users have specific roles that you have assigned to them already, then you're just using Google's OAuth service as an identity service. You don't need to implement your own authorization service, but you will need to keep track (typically in your own database) a relationship between the userid and the roles for that users.

If the goal is to create a service where the user can delegate specific permissions they have to a third-party service, then you will certainly need to implement your own OAuth server. This will allow the user to limit the scopes that are necessary for the third-party service to do its job.


问:
Copy file(s) from one project to another using post build event...VS2010
I have a solution with 3 projects in it. I need to copy a view from one project to another. I'm able to copy the created DLL via post build events like so:

So i want to copy the file in project one '/Views/ModuleHome/Index.cshtml' to a folder in project 2.
How do I copy file(s) to my desired project via post-build event? Thanks

答:
I use it like this.

```<code>xcopy "$(TargetDir)$(TargetName).dll" "$(SolutionDir)Lib\TIRM\x86\" /F /Y
xcopy "$(TargetDir)$(TargetName).lib" "$(SolutionDir)Lib\TIRM\x86\" /F /Y

/F : Copy source is File
/Y : Overwrite and don't ask me
</code>```

Note the use of this.
$(TargetDir)  has already '\'
"D:\MyProject\bin\" = $(TargetDir)

You can find macro in Command editor

Body:
I use it like this.

xcopy "$(TargetDir)$(TargetName).dll" "$(SolutionDir)Lib\TIRM\x86\" /F /Y
xcopy "$(TargetDir)$(TargetName).lib" "$(SolutionDir)Lib\TIRM\x86\" /F /Y

/F : Copy source is File
/Y : Overwrite and don't ask me

Note the use of this.
$(TargetDir)  has already '\'
"D:\MyProject\bin\" = $(TargetDir)

You can find macro in Command editor


问:
I keep getting a 404 error when I try to add a background image to a div in jQuery
I am trying to create a div as I press enter in my search bar. That part works for me and if I keep pressing enter a new div is created. However, I cannot give the created div a background image. My console keeps giving me a 404 error. Here is my code:

```<code>function appendToDom(poster) {
    var aPoster = $('<div>');
    aPoster.css({
        display: 'inline block',
        float: 'left',
        margin: '10px',
        marginLeft: '37px',
        marginTop: '20px',
        width: '200px',
        height: '300px',
        fontSize: '36px',
        color: 'black'
        //backgroundImage: '../services/images/1425663956-outline.png'
    })
    $(aPoster).css("background-image", "url(~/desktop/MyMovies/public/js/images/1425663956-outline.png)");
    $(main).append(aPoster);
</code>```

I tried to put my images file in a bunch of places and I changed the path a bunch of times. My ultimate goal is to add the image provided by the api I'm using as the background image of each div and have the image I am currently trying to use as the default for when the api has no image for a given data point.

I am working in node if that helps.

答:
Can you try like this:</p>

```<code>$(aPoster).attr("style","background-image: url(~/desktop/MyMovies/public/js/images/1425663956-outline.png)");
</code>```

Body:
I am trying to create a div as I press enter in my search bar. That part works for me and if I keep pressing enter a new div is created. However, I cannot give the created div a background image. My console keeps giving me a 404 error. Here is my code:

function appendToDom(poster) {
    var aPoster = $('
');
    aPoster.css({
        display: 'inline block',
        float: 'left',
        margin: '10px',
        marginLeft: '37px',
        marginTop: '20px',
        width: '200px',
        height: '300px',
        fontSize: '36px',
        color: 'black'
        //backgroundImage: '../services/images/1425663956-outline.png'
    })
    $(aPoster).css("background-image", "url(~/desktop/MyMovies/public/js/images/1425663956-outline.png)");
    $(main).append(aPoster);

I tried to put my images file in a bunch of places and I changed the path a bunch of times. My ultimate goal is to add the image provided by the api I'm using as the background image of each div and have the image I am currently trying to use as the default for when the api has no image for a given data point.

I am working in node if that helps.

Body:
Can you try like this:

$(aPoster).attr("style","background-image: url(~/desktop/MyMovies/public/js/images/1425663956-outline.png)");


问:
How to change Pandas plot annotation to whole number?
I've been using the line of code from this post in order to annotate total values on top of my columns in a bar plot, but I can't seem to figure out how to get the result in a whole number with no decimal places?

```<code>ax = df.plot.bar(title="Scores")
for p in ax.patches:
    ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')
</code>```

Any ideas?

答:
Just convert the number to an int:

```<code>ax = df.plot.bar(title="Scores")
for p in ax.patches:
    ax.annotate(str(int(p.get_height())), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')
</code>```

Demo:

Body:
I've been using the line of code from this post in order to annotate total values on top of my columns in a bar plot, but I can't seem to figure out how to get the result in a whole number with no decimal places?

ax = df.plot.bar(title="Scores")
for p in ax.patches:
    ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')

Any ideas?

Body:
Just convert the number to an int:

ax = df.plot.bar(title="Scores")
for p in ax.patches:
    ax.annotate(str(int(p.get_height())), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')

Demo:


问:
Last_value with IGNORE NULLS in SQL Server
I have a time series that with null values.  I want to be replace each null value with the most recent non-non value.  From what I've researched, Oracle SQL can easily accomplish this using Last_value with IGNORE NULLS.  Is there a similar way to accomplish this using SQL Server 2016?  Otherwise I'm just going to code it using C#, but felt using SQL would be faster, cleaner, and easier.

```<code>Sec SCORE
1   Null
2   Null
3   5
4   Null
5   8
6   7
7   Null
</code>```

Should be replaced with:

```<code>Sec SCORE
1   Null
2   Null
3   5
4   5
5   8
6   7
7   7
</code>```

答:
You can do this with two cumulative operations:

```<code>select t.*,
       coalesce(score, max(score) over (partition by maxid)) as newscore
from (select t.*,
             max(case when score is not null then id end) over (order by id) as maxid
      from t
     ) t;
</code>```

The innermost subquery gets the most recent id where there is a value.  The outermost one "spreads" that value to the subsequent rows.

If you actually want to update the table, you can incorporate this easily into an update.  But, Oracle cannot do that (easily), so I'm guessing this is not necessary....

Body:
I have a time series that with null values.  I want to be replace each null value with the most recent non-non value.  From what I've researched, Oracle SQL can easily accomplish this using Last_value with IGNORE NULLS.  Is there a similar way to accomplish this using SQL Server 2016?  Otherwise I'm just going to code it using C#, but felt using SQL would be faster, cleaner, and easier.

Sec SCORE
1   Null
2   Null
3   5
4   Null
5   8
6   7
7   Null

Should be replaced with:

Sec SCORE
1   Null
2   Null
3   5
4   5
5   8
6   7
7   7

Body:
You can do this with two cumulative operations:

select t.*,
       coalesce(score, max(score) over (partition by maxid)) as newscore
from (select t.*,
             max(case when score is not null then id end) over (order by id) as maxid
      from t
     ) t;

The innermost subquery gets the most recent id where there is a value.  The outermost one "spreads" that value to the subsequent rows.

If you actually want to update the table, you can incorporate this easily into an update.  But, Oracle cannot do that (easily), so I'm guessing this is not necessary....


问:
Changing the x-label in HTML Canvas charts
Hi I am using HTML Canvas charts. In one of the charts can I change the label of x-axis?

The source code for the chart is :

```<code><!DOCTYPE HTML>
<html>

<head>

</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>

<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
    document.addEventListener("DOMContentLoaded",function () {
        var chart = new CanvasJS.Chart("chartContainer",
            {
                animationEnabled: true,
                theme: "theme2",
                title:{
                    text: "Multi Series Spline Chart - Hide / Unhide via Legend"
                },
                axisY:[{
                    lineColor: "#4F81BC",
                    tickColor: "#4F81BC",
                    labelFontColor: "#4F81BC",
                    titleFontColor: "#4F81BC",
                    lineThickness: 2,
                },
                    {
                        lineColor: "#C0504E",
                        tickColor: "#C0504E",
                        labelFontColor: "#C0504E",
                        titleFontColor: "#C0504E",
                        lineThickness: 2,

                    }],
                data: [
                    {
                        type: "spline", //change type to bar, line, area, pie, etc
                        showInLegend: true,
                        dataPoints: [
                            { x: 10, y: 51 },
                            { x: 20, y: 45},
                            { x: 30, y: 50 },
                            { x: 40, y: 62 },
                            { x: 50, y: 95 },
                            { x: 60, y: 66 },
                            { x: 70, y: 24 },
                            { x: 80, y: 32 },
                            { x: 90, y: 16}
                        ]
                    },
                    {
                        type: "spline",
                        axisYIndex: 1,
                        showInLegend: true,
                        dataPoints: [
                            { x: 10, y: 201 },
                            { x: 20, y: 404},
                            { x: 30, y: 305 },
                            { x: 40, y: 405 },
                            { x: 50, y: 905 },
                            { x: 60, y: 508 },
                            { x: 70, y: 108 },
                            { x: 80, y: 300 },
                            { x: 90, y: 101}
                        ]
                    }
                ],
                legend: {
                    cursor: "pointer",
                    itemclick: function (e) {
                        if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
                            e.dataSeries.visible = false;
                        } else {
                            e.dataSeries.visible = true;
                        }
                        chart.render();
                    }
                }
            });

        chart.render();
    });
</script>
</body>

</html>
</code>```

Now here we can see that x-values is 10,20,30... My question is can we change them to other format like 10am or 10pm?

答:
You can add a suffix (or a prefix) to the x-axis with chart.options.axisX

```<code>chart.options.axisX = { suffix: "AM" };
</code>```

Or you can add both like this:

```<code>chart.options.axisX = { prefix: "/", suffix: "AM" };
</code>```

Body:
Hi I am using HTML Canvas charts. In one of the charts can I change the label of x-axis?

The source code for the chart is :

<!DOCTYPE HTML>

Now here we can see that x-values is 10,20,30... My question is can we change them to other format like 10am or 10pm?

Body:
You can add a suffix (or a prefix) to the x-axis with chart.options.axisX

chart.options.axisX = { suffix: "AM" };

Or you can add both like this:

chart.options.axisX = { prefix: "/", suffix: "AM" };


问:
R - how to get median and mean with string field?
I have a table (Class) like this:

```<code>County    Age.Group
Albany      0-5
Albany      10-15
Albany      10-15
new York    5-10
new York    5-10
new York    0-5
LI          0-5
LI          0-5
LI          0-5
</code>```

I need to get mean and median by County so I know I need to calculate the how many times Albany, New York, and LI appeared in the list and then use the mean and median function. I'm not sure how to do this as I get an error message when I use mean or median as that field is not an integer. Please help.....

答:
I would assume that @snoram's interpretation of your desired output is correct- if so, here is a dplyr alternative:

```<code>df2 <- df %>%
    group_by(County) %>%
    summarise(
        mean.age = mean(as.numeric(unlist(strsplit(Age.Group, "-")))),
        median.age = median(as.numeric(unlist(strsplit(Age.Group, "-"))))
    )

> data.frame(df2)
    County mean.age median.age
1   Albany 9.166667       10.0
2       LI 2.500000        2.5
3 new York 5.833333        5.0
</code>```

Data:

```<code>df <- structure(list(County = c("Albany", "Albany", "Albany", "new York",
                                "new York", "new York", "LI", "LI", "LI"), Age.Group = c("0-5",
                                                                                "10-15", "10-15", "5-10", "5-10", "0-5", "0-5", "0-5", "0-5")), .Names = c("County",
                                                                                "Age.Group"), row.names = c(NA, -9L), class = "data.frame")
</code>```

Body:
I have a table (Class) like this:

County    Age.Group
Albany      0-5
Albany      10-15
Albany      10-15
new York    5-10
new York    5-10
new York    0-5
LI          0-5
LI          0-5
LI          0-5

I need to get mean and median by County so I know I need to calculate the how many times Albany, New York, and LI appeared in the list and then use the mean and median function. I'm not sure how to do this as I get an error message when I use mean or median as that field is not an integer. Please help.....

Body:
I would assume that @snoram's interpretation of your desired output is correct- if so, here is a dplyr alternative:

df2 <- df %>%
    group_by(County) %>%
    summarise(
        mean.age = mean(as.numeric(unlist(strsplit(Age.Group, "-")))),
        median.age = median(as.numeric(unlist(strsplit(Age.Group, "-"))))
    )

> data.frame(df2)
    County mean.age median.age
1   Albany 9.166667       10.0
2       LI 2.500000        2.5
3 new York 5.833333        5.0

Data:

df <- structure(list(County = c("Albany", "Albany", "Albany", "new York",
                                "new York", "new York", "LI", "LI", "LI"), Age.Group = c("0-5",
                                                                                "10-15", "10-15", "5-10", "5-10", "0-5", "0-5", "0-5", "0-5")), .Names = c("County",
                                                                                "Age.Group"), row.names = c(NA, -9L), class = "data.frame")