问:
Is complex formatting inside label of tab in Tkinter Notebook widget possible?
I've just finished adding some nice formatting to my logging console where based on the message type the prefix of the message is coloured differently:

In order to do that I used tags (tag_config()) along with Font() to make things bold:

```<code>from tkinter import font, Tk, END
from tkinter.scrolledtext import ScrolledText

def log_info(msg, widget):
  log(msg, "info", widget)

def log_error(msg, widget):
  log(msg, "error", widget)

def log_warn(msg, widget):
  log(msg, "warn", widget)

def log(msg, type, widget):
  msg_prefix = font.Font(widget, widget.cget("font"))
  msg_prefix.configure(weight="bold")
  if type == "info":
    widget.insert(END, "INFO: ", "info")
    widget.insert(END, msg + "\n")
  elif type == "error":
    widget.insert(END, "ERROR: ", "error")
    widget.insert(END, msg + "\n")
  elif type == "warn":
    widget.insert(END, "WARNING: ", "warn")
    widget.insert(END, msg + "\n")
  else:
    print("Unknown type of log message. Available types are 'info', 'error' and 'warn'")

  widget.tag_config("info", font=msg_prefix)
  widget.tag_config("error", foreground="red", font=msg_prefix)
  widget.tag_config("warn", foreground="orange", font=msg_prefix)

window = Tk()
window.geometry('970x45')
box = ScrolledText(window, width=70, height=7)
box.pack()
log_info("This is an information log message", box)
log_error("This is an error log message", box)
log_warn("This is a warning log message", box)

window.mainloop()
</code>```

However I am struggling to add a similar feature to the tab where this console is. Every time an error log message is logged in the console the tab where it is located gets updated to show the number of errors that are currently logged:

However I would like to make the (4) (from the screenshot above) coloured with red. I was unable to find font formatting for the tab label:

Reason: I've discovered that the logging console gets ignored quite often since the other tab in my widget is where the interaction happens. Since I want to keep things separated in order to prevent clustering too many things on the screen at the same time I'm trying to notify the user in an non-intrusive way that an error has occurred (other types of log messages are not that important).

答:
Short answer:

No, it's not possible from the scratch, and since appereance of ttk widgets heavily depends on theme in use and/or platform - it's hard to implement without jump to tk environment/hard to keep desired layout.

But your question is really interested, so I tried to implement this feature by myself.

Long Answer:

First of all, you need to know, that each widget has the layout structure, that represented by hierarchy of elements.

On my Win machine default theme is vista and layout for Tab is:

```<code>>>> s = ttk.Style()
>>> print(s.layout('TNotebook.Tab'))

#   formatted result, actual result is one-line string
[('Notebook.tab', {
    'children': [(
        'Notebook.padding', {
            'children': [(
                'Notebook.focus', {
                    'children': [(
                        'Notebook.label', {
                            'sticky': '',
                            'side': 'top'
                        })],
                    'sticky': 'nswe',
                    'side': 'top'
                })],
            'sticky': 'nswe',
            'side': 'top'
        })],
    'sticky': 'nswe'
})]
</code>```

As you can see - there's a Notebook.label element. And this elements handles all that options:

```<code>>>> print(s.element_options('Notebook.label'))
('-compound', '-space', '-text', '-font', '-foreground', '-underline', '-width', '-anchor', '-justify', '-wraplength', '-embossed', '-image', '-stipple', '-background')
</code>```

So that's it - you can't do partially formatting text within label, because  -font or -foreground options applies to entire string.

But what if we change this layout structure with additional label/text?
It's looks like a good idea, that we can use first text for tab title and second for counter!

```<code>s = ttk.Style()
s.configure('SOExample.TNotebook')
s.layout('SOExample.TNotebook.Tab', [('Notebook.tab', {
    'sticky': 'nswe',
    'children': [(
        'Notebook.padding', {
            'sticky': 'nswe',
            'children': [(
                'Notebook.focus', {
                    'sticky': 'nswe',
                    'children': [(
                        'Notebook.label', {
                            'sticky': '',
                            'side': 'left'
                        }), (
                        'Notebook.text', {
                            'sticky': '',
                            'side': 'right'
                        })],
                    'side': 'top'
                })],
            'side': 'top'
        })]})])
</code>```

Unfortunately and obviously, it's not gonna work, because both elements react on the same options (text, font, et cetera)

According to docs here:

The value of an element option is taken from:

an option of the same name and type in the widget containing the
  element;

a dynamic setting specified by style map and the current state;

the default setting specified by style configure; or

the element's built-in default value for the option.

However, I think it's possible to "map" second text option as text2 for Tab, but with Python on it's own, it's looks like impossible task!

Conclusion:

Long answer is attempt to implement such a feature, that leads to another question of "how to add options to custom class widget and bind them to element options". The more straitght solution there would be to use compound behaviour of a label, since you can convert any int to image/64encoded image-string, but this option is already mentioned.

Body:
I've just finished adding some nice formatting to my logging console where based on the message type the prefix of the message is coloured differently:

In order to do that I used tags (tag_config()) along with Font() to make things bold:

from tkinter import font, Tk, END
from tkinter.scrolledtext import ScrolledText

def log_info(msg, widget):
  log(msg, "info", widget)

def log_error(msg, widget):
  log(msg, "error", widget)

def log_warn(msg, widget):
  log(msg, "warn", widget)

def log(msg, type, widget):
  msg_prefix = font.Font(widget, widget.cget("font"))
  msg_prefix.configure(weight="bold")
  if type == "info":
    widget.insert(END, "INFO: ", "info")
    widget.insert(END, msg + "\n")
  elif type == "error":
    widget.insert(END, "ERROR: ", "error")
    widget.insert(END, msg + "\n")
  elif type == "warn":
    widget.insert(END, "WARNING: ", "warn")
    widget.insert(END, msg + "\n")
  else:
    print("Unknown type of log message. Available types are 'info', 'error' and 'warn'")

  widget.tag_config("info", font=msg_prefix)
  widget.tag_config("error", foreground="red", font=msg_prefix)
  widget.tag_config("warn", foreground="orange", font=msg_prefix)

window = Tk()
window.geometry('970x45')
box = ScrolledText(window, width=70, height=7)
box.pack()
log_info("This is an information log message", box)
log_error("This is an error log message", box)
log_warn("This is a warning log message", box)

window.mainloop()

However I am struggling to add a similar feature to the tab where this console is. Every time an error log message is logged in the console the tab where it is located gets updated to show the number of errors that are currently logged:

However I would like to make the (4) (from the screenshot above) coloured with red. I was unable to find font formatting for the tab label:

Reason: I've discovered that the logging console gets ignored quite often since the other tab in my widget is where the interaction happens. Since I want to keep things separated in order to prevent clustering too many things on the screen at the same time I'm trying to notify the user in an non-intrusive way that an error has occurred (other types of log messages are not that important).

Body:
Short answer:

No, it's not possible from the scratch, and since appereance of ttk widgets heavily depends on theme in use and/or platform - it's hard to implement without jump to tk environment/hard to keep desired layout.

But your question is really interested, so I tried to implement this feature by myself.

Long Answer:

First of all, you need to know, that each widget has the layout structure, that represented by hierarchy of elements.

On my Win machine default theme is vista and layout for Tab is:

>>> s = ttk.Style()
>>> print(s.layout('TNotebook.Tab'))

#   formatted result, actual result is one-line string
[('Notebook.tab', {
    'children': [(
        'Notebook.padding', {
            'children': [(
                'Notebook.focus', {
                    'children': [(
                        'Notebook.label', {
                            'sticky': '',
                            'side': 'top'
                        })],
                    'sticky': 'nswe',
                    'side': 'top'
                })],
            'sticky': 'nswe',
            'side': 'top'
        })],
    'sticky': 'nswe'
})]

As you can see - there's a Notebook.label element. And this elements handles all that options:

>>> print(s.element_options('Notebook.label'))
('-compound', '-space', '-text', '-font', '-foreground', '-underline', '-width', '-anchor', '-justify', '-wraplength', '-embossed', '-image', '-stipple', '-background')

So that's it - you can't do partially formatting text within label, because  -font or -foreground options applies to entire string.

But what if we change this layout structure with additional label/text?
It's looks like a good idea, that we can use first text for tab title and second for counter!

s = ttk.Style()
s.configure('SOExample.TNotebook')
s.layout('SOExample.TNotebook.Tab', [('Notebook.tab', {
    'sticky': 'nswe',
    'children': [(
        'Notebook.padding', {
            'sticky': 'nswe',
            'children': [(
                'Notebook.focus', {
                    'sticky': 'nswe',
                    'children': [(
                        'Notebook.label', {
                            'sticky': '',
                            'side': 'left'
                        }), (
                        'Notebook.text', {
                            'sticky': '',
                            'side': 'right'
                        })],
                    'side': 'top'
                })],
            'side': 'top'
        })]})])

Unfortunately and obviously, it's not gonna work, because both elements react on the same options (text, font, et cetera)

According to docs here:

The value of an element option is taken from:

an option of the same name and type in the widget containing the
  element;

a dynamic setting specified by style map and the current state;

the default setting specified by style configure; or

the element's built-in default value for the option.

However, I think it's possible to "map" second text option as text2 for Tab, but with Python on it's own, it's looks like impossible task!

Conclusion:

Long answer is attempt to implement such a feature, that leads to another question of "how to add options to custom class widget and bind them to element options". The more straitght solution there would be to use compound behaviour of a label, since you can convert any int to image/64encoded image-string, but this option is already mentioned.


来源: stackexchange

问:
scaling a SCNNode in runtime using the Pinch gesture
I am trying to scale and SCNNode in real time using the Pinch gesture:

This is my current code

```<code>let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(from:)))
sceneView.addGestureRecognizer(pinchGestureRecognizer)

@objc
func handlePinch(from recognizer: UIPinchGestureRecognizer){
  var pinchScale = recognizer.scale
  pinchScale = round(pinchScale * 1000) / 1000.0

  sceneView.scene.rootNode.enumerateChildNodes { (node, stop) -> Void in
    if(node.name == "Box01"){
       node.scale = SCNVector3(x: pinchScale, y: pinchScale, z: pinchScale)
    }
  }
}
</code>```

However the node doesn't scale big or small? Can someone please point my mistake?

The SCNNode is loaded and has an animation on applied like so,

```<code>sceneView.scene.rootNode.addChildNode(node)
loadAnimation(animation: .Attack, sceneName: "art.scnassets/attack", animationIdentifier: "attackID");
</code>```

答:
I used this to handle the scale:</p>

```<code>@objc
func handlePinch(from recognizer: UIPinchGestureRecognizer){
    var pinchScale = round(recognizer.scale * 1000)/1000000
    let node_arm = sceneView.scene.rootNode.childNode(withName: "army", recursively: true)
    node_arm?.runAction(.customAction(duration: 0, action: { node, progress in
        node.physicsBody = nil
        node.scale = SCNVector3(x: Float(pinchScale), y: Float(pinchScale), z: Float(pinchScale))
    }))
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to scale and SCNNode in real time using the Pinch gesture:

This is my current code

let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(from:)))
sceneView.addGestureRecognizer(pinchGestureRecognizer)

@objc
func handlePinch(from recognizer: UIPinchGestureRecognizer){
  var pinchScale = recognizer.scale
  pinchScale = round(pinchScale * 1000) / 1000.0

  sceneView.scene.rootNode.enumerateChildNodes { (node, stop) -> Void in
    if(node.name == "Box01"){
       node.scale = SCNVector3(x: pinchScale, y: pinchScale, z: pinchScale)
    }
  }
}

However the node doesn't scale big or small? Can someone please point my mistake?

The SCNNode is loaded and has an animation on applied like so,

sceneView.scene.rootNode.addChildNode(node)
loadAnimation(animation: .Attack, sceneName: "art.scnassets/attack", animationIdentifier: "attackID");

Body:
I used this to handle the scale:

@objc
func handlePinch(from recognizer: UIPinchGestureRecognizer){
    var pinchScale = round(recognizer.scale * 1000)/1000000
    let node_arm = sceneView.scene.rootNode.childNode(withName: "army", recursively: true)
    node_arm?.runAction(.customAction(duration: 0, action: { node, progress in
        node.physicsBody = nil
        node.scale = SCNVector3(x: Float(pinchScale), y: Float(pinchScale), z: Float(pinchScale))
    }))
}

ContentLicense: CC BY-SA 3.0


问:
How to display div dynamically on window
When i click on any point of screen i need to display a div on clicked point how to do this. explain me with example</p>

答:
Use clientX and clientY to get the mouse position. This is a simple example:

```<code>$(window).click(function(e)
{
    var div = $("<div style='position: absolute; width: 10px; height: 10px; background: red;'>hello</div>");
    div.css('top', e.clientY);
    div.css('left', e.clientX);

    div.appendTo("body");
});
</code>```

Demo here.

ContentLicense: CC BY-SA 2.5

Body:
Use clientX and clientY to get the mouse position. This is a simple example:

$(window).click(function(e)
{
    var div = $("<div style='position: absolute; width: 10px; height: 10px; background: red;'>hello</div>");
    div.css('top', e.clientY);
    div.css('left', e.clientX);

    div.appendTo("body");
});

Demo here.


问:
Animate / apply Transition addClass and removeClass in jQuery?
I am new to jQuery & javascript and making a simple slider by adding and removing class 'active' on next slide which is working fine but seems ugly because there is no animation. Is there any way to animate the process of adding and removing a class? Like:

```<code>$('#next').on('click', function(){
    $('div.active').removeClass('active', duration: 500ms).next().addClass('active', duration: 500ms);})
</code>```

At Jquery documentation website I have seen that there is an animate function which is used to animate things. Is it possible to use that function in my case?

Update: I have also tried to apply the CSS transition on div and div.active which is not working.

Css:

```<code>   .slider div {
        display: none;
        opacity: 0;
        -webkit-transition: opacity 1s ease-in-out;
        -moz-transition: opacity 1s ease-in-out;
        -ms-transition: opacity 1s ease-in-out;
        -o-transition: opacity 1s ease-in-out;
        transition: opacity 1s ease-in-out;
    }

    div.active {
        display: inline-block;
        opacity: 1;
        -webkit-transition: opacity 1s ease-in-out;
        -moz-transition: opacity 1s ease-in-out;
        -ms-transition: opacity 1s ease-in-out;
        -o-transition: opacity 1s ease-in-out;
        transition: opacity 1s ease-in-out;
    }
</code>```

答:
From comments of different users I came to know that css transition can not be applied on display: none elements. So instead of display none I applied height 0px; opacity: 0; which worked fine for me.

```<code>.slider img{
 height: 0px;
 opacity: 0;
 display: block;
 -webkit-transition: opacity 2s ease;
 -moz-transition: opacity 2s ease;
 -ms-transition: opacity 2s ease;
 -o-transition: opacity 2s ease;
 transition: opacity 2s ease;
}

.slider img.active{
 height: 360px;
 opacity: 1;
 -webkit-transition: opacity 2s ease;
 -moz-transition: opacity 2s ease;
 -ms-transition: opacity 2s ease;
 -o-transition: opacity 2s ease;
 transition: opacity 2s ease;
}
</code>```

Thanks to the creator of this fiddle which gave me this idea.

Body:
I am new to jQuery & javascript and making a simple slider by adding and removing class 'active' on next slide which is working fine but seems ugly because there is no animation. Is there any way to animate the process of adding and removing a class? Like:

$('#next').on('click', function(){
    $('div.active').removeClass('active', duration: 500ms).next().addClass('active', duration: 500ms);})

At Jquery documentation website I have seen that there is an animate function which is used to animate things. Is it possible to use that function in my case?

Update: I have also tried to apply the CSS transition on div and div.active which is not working.

Css:

   .slider div {
        display: none;
        opacity: 0;
        -webkit-transition: opacity 1s ease-in-out;
        -moz-transition: opacity 1s ease-in-out;
        -ms-transition: opacity 1s ease-in-out;
        -o-transition: opacity 1s ease-in-out;
        transition: opacity 1s ease-in-out;
    }

    div.active {
        display: inline-block;
        opacity: 1;
        -webkit-transition: opacity 1s ease-in-out;
        -moz-transition: opacity 1s ease-in-out;
        -ms-transition: opacity 1s ease-in-out;
        -o-transition: opacity 1s ease-in-out;
        transition: opacity 1s ease-in-out;
    }

Body:
From comments of different users I came to know that css transition can not be applied on display: none elements. So instead of display none I applied height 0px; opacity: 0; which worked fine for me.

.slider img{
 height: 0px;
 opacity: 0;
 display: block;
 -webkit-transition: opacity 2s ease;
 -moz-transition: opacity 2s ease;
 -ms-transition: opacity 2s ease;
 -o-transition: opacity 2s ease;
 transition: opacity 2s ease;
}

.slider img.active{
 height: 360px;
 opacity: 1;
 -webkit-transition: opacity 2s ease;
 -moz-transition: opacity 2s ease;
 -ms-transition: opacity 2s ease;
 -o-transition: opacity 2s ease;
 transition: opacity 2s ease;
}

Thanks to the creator of this fiddle which gave me this idea.


问:
Maths related task having trouble solving using python
I'm having trouble solving this question, using python.

When the middle digit of a three-digit number N is removed, the two-digit number thus obtained is N divided by 16. Find all such numbers n.

Can anyone answer the question and explain?

EDIT: The number N when divided by 16 has to equal that 2 digit number, but most of your answers don't work.

答:
I think what you are trying to ask is how to extract a digit from a number.
how about this for 3-digits numbers:

```<code>N = str(N) #convert to string
N = N[:1] + N[2:] #removing 2nd digit
N = int(N) #convert to int
</code>```

then you just have to loop over range(100:1000) and test if the number obtained can be divided by 16

Body:
I think what you are trying to ask is how to extract a digit from a number.
how about this for 3-digits numbers:

N = str(N) #convert to string
N = N[:1] + N[2:] #removing 2nd digit
N = int(N) #convert to int

then you just have to loop over range(100:1000) and test if the number obtained can be divided by 16


问:
How can I get the Design mode of a table without going through "Object explorer"?
I'm trying to use SQL Server Management Studio to edit database tables. But I can't seem to access the databases themselves through "Object explorer" (SQL Server Management Studio 2012 hangs).

How can I get the Design mode of a table without going through that?

答:
It looks it's not possible to open from TSQL any new tab in design mode for a table or view, the only way to do it is through the object explorer:

https://learn.microsoft.com/en-us/sql/ssms/visual-db-tools/open-the-query-and-view-designer-visual-database-tools


问:
.click() requiring 2 clicks - jquery + QuillJS
I am using quilljs to allow users to edit a certain portion of text. However I want the editor to be fired only when a user clicks the edit button. For some reason, the edit button requires 2 clicks to execute the event. Am I missing anything?</p>

```<code><button id="edit" class="button" data-edit="dormant">Edit</button>

var quill = new Quill('#editor',
             {

                theme: 'snow',
                 readOnly: true,
                            });
$(edit).click(function () {

            if (edit.data('edit') == 'dormant') {

                edit.data('edit', 'active');
                edit.text('Save');
                quill.enable();

            } else {
                edit.data('edit', 'dormant');
                edit.text('Edit');
                quill.disable();

            }

    });
</code>```

答:
You need to stop the event propagation, that way, when click, it will kill the event.

```<code>$(edit).click(function (event) {
        event.stopPropagation()
        if (edit.data('edit') == 'dormant') {

            edit.data('edit', 'active');
            edit.text('Save');
            quill.enable();

        } else {
            edit.data('edit', 'dormant');
            edit.text('Edit');
            quill.disable();

        }

});
</code>```

you can learn more on the subject here https://api.jquery.com/event.stoppropagation/

Body:
I am using quilljs to allow users to edit a certain portion of text. However I want the editor to be fired only when a user clicks the edit button. For some reason, the edit button requires 2 clicks to execute the event. Am I missing anything?

<button id="edit" class="button" data-edit="dormant">Edit</button>

var quill = new Quill('#editor',
             {

                theme: 'snow',
                 readOnly: true,
                            });
$(edit).click(function () {

            if (edit.data('edit') == 'dormant') {

                edit.data('edit', 'active');
                edit.text('Save');
                quill.enable();

            } else {
                edit.data('edit', 'dormant');
                edit.text('Edit');
                quill.disable();

            }

    });

Body:
You need to stop the event propagation, that way, when click, it will kill the event.

$(edit).click(function (event) {
        event.stopPropagation()
        if (edit.data('edit') == 'dormant') {

            edit.data('edit', 'active');
            edit.text('Save');
            quill.enable();

        } else {
            edit.data('edit', 'dormant');
            edit.text('Edit');
            quill.disable();

        }

});

you can learn more on the subject here https://api.jquery.com/event.stoppropagation/


问:
c program to find average
i am a beginner in coding ,i am trying to make a program where i input 'n' number of elements in array and find out what percentage of number are positive,negative and zeros.the output is not what i am expecting it is all 'zeros'.Where i input n=3,so the percentage should be .3,.3,.3 when i input numbers one positive,one negative and one zero.

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

int main()
{
    int n;
    float per1, per2, per3;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }

    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;

    for (int i = 0; i <= n - 1; i++)
    {
        if (arr[i] < 0)
        {
            int sum1 = sum1 + 1;
        }
        if (arr[i] > 0)
        {
            sum2 = sum2 + 1;
        }
        else
        {
            sum3 = sum3 + 1;
        }
    }

    per1 = sum1 / n;
    per2 = sum2 / n;
    per3 = sum3 / n;
    printf("%.6f\n%.6f\n%.6f\n", per1, per2, per3);

    return 0;
}
</code>```

output

```<code>3
1
-2
0
0.000000
0.000000
0.000000
</code>```

the last three numbers should be .3,.3,.3 but it is giving zeros.

答:
Do floating point arithmetic like this</p>

```<code>per1=sum1/(1.0*n);
per2=sum2/(1.0*n);
per3=sum3/(1.0*n);
</code>```

Title: c program to find average

Body:
i am a beginner in coding ,i am trying to make a program where i input 'n' number of elements in array and find out what percentage of number are positive,negative and zeros.the output is not what i am expecting it is all 'zeros'.Where i input n=3,so the percentage should be .3,.3,.3 when i input numbers one positive,one negative and one zero.

#include <math.h>
#include <stdio.h>

int main()
{
    int n;
    float per1, per2, per3;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }

    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;

    for (int i = 0; i <= n - 1; i++)
    {
        if (arr[i] < 0)
        {
            int sum1 = sum1 + 1;
        }
        if (arr[i] > 0)
        {
            sum2 = sum2 + 1;
        }
        else
        {
            sum3 = sum3 + 1;
        }
    }

    per1 = sum1 / n;
    per2 = sum2 / n;
    per3 = sum3 / n;
    printf("%.6f\n%.6f\n%.6f\n", per1, per2, per3);

    return 0;
}

output

3
1
-2
0
0.000000
0.000000
0.000000

the last three numbers should be .3,.3,.3 but it is giving zeros.

Body:
Do floating point arithmetic like this

per1=sum1/(1.0*n);
per2=sum2/(1.0*n);
per3=sum3/(1.0*n);


问:
Convert Bbcode to plain text
I am using angular application. I want to convert the bbcode into plain text. Is there any any plugin or library or any method for it. I am accepting following data.

```<code>$scope.Currentdata= "[justify][size=2]New testing.Hello World.[/size][/justify]";
</code>```

and i want to remove the bbcode and show plain text on my div.

```<code><div id="showdata" name="showdata"></div>
</code>```

答:
You can use the following plugin to parse :

https://github.com/DasRed/js-bbcode-parser

Use the following command:

bower install bbcode-parser --save

```<code>// use to create a clean parser
var parser = new BBCode({}, {})

// use default parser
var parser = BBCode.default

// configure the default parser with
BBCode.setCodes({});

console.log(BBCode.default.parse('This is a text[br]with HTML Break.'));
</code>```

Title: Convert Bbcode to plain text

Body:
I am using angular application. I want to convert the bbcode into plain text. Is there any any plugin or library or any method for it. I am accepting following data.

$scope.Currentdata= "[justify][size=2]New testing.Hello World.[/size][/justify]";

and i want to remove the bbcode and show plain text on my div.

Body:
You can use the following plugin to parse :

https://github.com/DasRed/js-bbcode-parser

Use the following command:

bower install bbcode-parser --save

// use to create a clean parser
var parser = new BBCode({}, {})

// use default parser
var parser = BBCode.default

// configure the default parser with
BBCode.setCodes({});

console.log(BBCode.default.parse('This is a text[br]with HTML Break.'));


问:
Ways to send a message from the server to the web browser at any time?
I'm in a situation where I want to be able to notify a visitor to my website of an event occurring at the server.

Think:

Website visitor is waiting for an export or report that takes a long time and is running in the background on the server, need to notify visitor when export is done.

or

Website visitor is waiting for a chat message from a sales rep, need to notify visitor when a message is sent to them.

I can think of a few ways to do this:

Keep an HTTP connection to the server
open forever

Continually polling the
HTTP server every second to check if
there are new messages

Write a Java
applet that holds a connection open
to a Java server process

None of these seem particularly graceful solutions... is there a better way to do this?

答: As far as I know you cannot open sockets (Connections through network interfaces) from java applets. That is a part of the secutiry policy.</p>


问:
Can Two controllers of two different routes can share same service?
I am trying to reuse the same service across multiple controllers on two different routes. I set name of an object in service using first controller and change the route and try to fetch the same object in service using second controller nothing gets printed.

```<code>app.js(file):

   angular.module('sampleapp', ["ngRoute"]).

   config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider
  .when('/',
   {
    templateUrl: 'src/loginform/loginform.html',
    controller: 'LoginFormController'
   })
  .when('/home',
   {
     templateUrl: 'src/home/home.html',
     controller: 'HomeController'
   })
}])

Service Code:

angular.module('sampleapp').service("CommonService", [function() {
  const Names = [
    {Name: "Mounish", age: 27},
    {Name: "Chakradhari", age: 24},
    {Name: "Venkat", age: 28}
  ];

  this.data = {
    firstName: ''
  };

  this.printNames = function() {
    return Names;
  }

  this.setName = function(value) {
    this.data.firstName = value;
  }

  this.getName = function() {
    return this.data.firstName;
  }

}])

Login form (controller 1):

angular.module('sampleapp')
.controller('LoginFormController', ["$scope", "$location", "CommonService", function($scope, $location , CommonService) {
  $scope.username = "jamili";
  $scope.submitHandler = function(event) {
    event.preventDefault();
    console.log("Clicked");
    window.location.href = '/home';
  };

  CommonService.setName("Mounish");
  CommonService.getName();
}])

Home Page (Controller 2):
angular.module('sampleapp')
.controller('HomeController', ['$scope', "CommonService", function($scope, CommonService) {
    $scope.names = CommonService.printNames();
    console.log($scope.names);
    console.log(CommonService.getName());
}])
</code>```

I am trying to reuse the same service across multiple controllers on two different routes. I set name of an object in service using first controller and change the route and try to fetch the same object in service using second controller nothing gets printed.

答:
Yes,angular services are intended to share data among multiple controllers and services.

Here, You are initializing your module multiple times. Angular module is a container for different parts of app, like controllers, services, directive etc.You should create your angular module once. If you create angular module multiple times, It will override previous module.

Here is a documentation for angular module.

You can follow this approach to register your controllers and services.

```<code>var sampleApp = angular.module('sampleApp',[])
sampleApp.service('CommonService',function(){
  //your processing logic
});

sampleApp.controller('Controller_1',function($scope,CommonService){
  //write your code here
});

sampleApp.controller('Controller_2',function($scope,CommonService){
 //write your code here
});
</code>```

I hope this would help you!!

Body:
I am trying to reuse the same service across multiple controllers on two different routes. I set name of an object in service using first controller and change the route and try to fetch the same object in service using second controller nothing gets printed.

app.js(file):

   angular.module('sampleapp', ["ngRoute"]).

   config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider
  .when('/',
   {
    templateUrl: 'src/loginform/loginform.html',
    controller: 'LoginFormController'
   })
  .when('/home',
   {
     templateUrl: 'src/home/home.html',
     controller: 'HomeController'
   })
}])

Service Code:

angular.module('sampleapp').service("CommonService", [function() {
  const Names = [
    {Name: "Mounish", age: 27},
    {Name: "Chakradhari", age: 24},
    {Name: "Venkat", age: 28}
  ];

  this.data = {
    firstName: ''
  };

  this.printNames = function() {
    return Names;
  }

  this.setName = function(value) {
    this.data.firstName = value;
  }

  this.getName = function() {
    return this.data.firstName;
  }

}])

Login form (controller 1):

angular.module('sampleapp')
.controller('LoginFormController', ["$scope", "$location", "CommonService", function($scope, $location , CommonService) {
  $scope.username = "jamili";
  $scope.submitHandler = function(event) {
    event.preventDefault();
    console.log("Clicked");
    window.location.href = '/home';
  };

  CommonService.setName("Mounish");
  CommonService.getName();
}])

Home Page (Controller 2):
angular.module('sampleapp')
.controller('HomeController', ['$scope', "CommonService", function($scope, CommonService) {
    $scope.names = CommonService.printNames();
    console.log($scope.names);
    console.log(CommonService.getName());
}])

I am trying to reuse the same service across multiple controllers on two different routes. I set name of an object in service using first controller and change the route and try to fetch the same object in service using second controller nothing gets printed.

Body:
Yes,angular services are intended to share data among multiple controllers and services.

Here, You are initializing your module multiple times. Angular module is a container for different parts of app, like controllers, services, directive etc.You should create your angular module once. If you create angular module multiple times, It will override previous module.

Here is a documentation for angular module.

You can follow this approach to register your controllers and services.

var sampleApp = angular.module('sampleApp',[])
sampleApp.service('CommonService',function(){
  //your processing logic
});

sampleApp.controller('Controller_1',function($scope,CommonService){
  //write your code here
});

sampleApp.controller('Controller_2',function($scope,CommonService){
 //write your code here
});

I hope this would help you!!


问:
Can Messenger (lightweight alternative to AIDL) be used for cross-application communication?
A quick question: the Android docs say very clearly that Messenger is an alternative for AIDL for IPC (inter process communication). They never explicitly say though if this extends to processes running in different applications, or just within one app. I strongly suspect the former, but wanted to check.

Thanks!
Jan

答:
Messenger internally uses AIDL,it can be used in multiple applications.As per android documentation a Messenger service can be used for communication between two processes but it does not restrict it in same application.Processes can be in same application or different application.

Messenger should be used if we want the requests to be processed sequentially as it enters the messages in handler's queue and they are processed one by one whereas in AIDL all requests will be handled at once and it becomes developer's responsibility to maintain thread safety.


问:
What is the best way to access redux store outside a react component?
@connect works great when I'm trying to access the store within a react component. But how should I access it in some other bit of code. For eg: let's say I want to use an authorization token for creating my axios instance that can be used globally in my app, what would be the best way to achieve that?

This is my api.js

```<code>// tooling modules
import axios from 'axios'

// configuration
const api = axios.create()
api.defaults.baseURL = 'http://localhost:5001/api/v1'
api.defaults.headers.common['Authorization'] = 'AUTH_TOKEN' // need the token here
api.defaults.headers.post['Content-Type'] = 'application/json'

export default api
</code>```

Now I want to access a data point from my store, here is what that would look like if I was trying to fetch it within a react component using @connect

```<code>// connect to store
@connect((store) => {
  return {
    auth: store.auth
  }
})
export default class App extends Component {
  componentWillMount() {
    // this is how I would get it in my react component
    console.log(this.props.auth.tokens.authorization_token)
  }
  render() {...}
}
</code>```

Any insights or workflow patterns out there?

答:
For TypeScript 2.0 it would look like this:

MyStore.ts

```<code>export namespace Store {

    export type Login = { isLoggedIn: boolean }

    export type All = {
        login: Login
    }
}

import { reducers } from '../Reducers'
import * as Redux from 'redux'

const reduxStore: Redux.Store<Store.All> = Redux.createStore(reducers)

export default reduxStore;
</code>```

MyClient.tsx

```<code>import reduxStore from "../Store";
{reduxStore.dispatch(...)}
</code>```

Body:
@connect works great when I'm trying to access the store within a react component. But how should I access it in some other bit of code. For eg: let's say I want to use an authorization token for creating my axios instance that can be used globally in my app, what would be the best way to achieve that?

This is my api.js

// tooling modules
import axios from 'axios'

// configuration
const api = axios.create()
api.defaults.baseURL = 'http://localhost:5001/api/v1'
api.defaults.headers.common['Authorization'] = 'AUTH_TOKEN' // need the token here
api.defaults.headers.post['Content-Type'] = 'application/json'

export default api

Now I want to access a data point from my store, here is what that would look like if I was trying to fetch it within a react component using @connect

// connect to store
@connect((store) => {
  return {
    auth: store.auth
  }
})
export default class App extends Component {
  componentWillMount() {
    // this is how I would get it in my react component
    console.log(this.props.auth.tokens.authorization_token)
  }
  render() {...}
}

Any insights or workflow patterns out there?

Body:
For TypeScript 2.0 it would look like this:

MyStore.ts

export namespace Store {

    export type Login = { isLoggedIn: boolean }

    export type All = {
        login: Login
    }
}

import { reducers } from '../Reducers'
import * as Redux from 'redux'

const reduxStore: Redux.Store<Store.All> = Redux.createStore(reducers)

export default reduxStore;

MyClient.tsx

import reduxStore from "../Store";
{reduxStore.dispatch(...)}


问:
Replacing DIV content based on variable sent from another HTML file
I'm trying to get this JavaScript working:

I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.

```<code><!-- ORIGINAL DIV -->
<div id="Email">

</div>

<!-- DIV replacement function -->

<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>

<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';

ReplaceContentInContainer('Email1',content);
}
</script>

<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';

ReplaceContentInContainer('Email2',content);
}
</script>
</code>```

Any ideas what I've done wrong that is causing it not to work?

答:
How about this? Hacky but works...</p>

```<code><!-- ORIGINAL DIV -->
<div id="Email"></div>

<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
var txt = document.createTextNode(content);
container.appendChild(txt);
}

window.onload = function() {
var args = document.location.search.substr(1, document.location.search.length).split('&');
var key_value = args[0].split('=');
ReplaceContentInContainer('Email', key_value[1]);
}
</script>
</code>```

Body:
I'm trying to get this JavaScript working:

I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.

Any ideas what I've done wrong that is causing it not to work?

Body:
How about this? Hacky but works...

<!-- ORIGINAL DIV -->
<div id="Email"></div>

<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
var txt = document.createTextNode(content);
container.appendChild(txt);
}

window.onload = function() {
var args = document.location.search.substr(1, document.location.search.length).split('&');
var key_value = args[0].split('=');
ReplaceContentInContainer('Email', key_value[1]);
}
</script>


问:
on windows, git show HEAD^, does not work and does not display the parent commit,
I'm currently learning git by following the book "pro git" by Scott Chacon.

In chapter 7 "git tool", the author mentioned that ^ sign is used to find out the ancestry of a commit.

e.g. to display the parent commit of the commit that is currently pointed to by the HEAD pointer

```<code>git show HEAD^
</code>```

But after I pressed enter, instead of executing the command, the command prompt asked for more

After I have pressed enter a few more times, an error is displayed

Why is this happening? I'm currently using command prompt on windows.

答:
^ is the escape character for the Windows command prompt.

Use ^^ to escape it and run a command that includes a single ^:

```<code>git show HEAD^^
</code>```

Body:
I'm currently learning git by following the book "pro git" by Scott Chacon.

In chapter 7 "git tool", the author mentioned that ^ sign is used to find out the ancestry of a commit.

e.g. to display the parent commit of the commit that is currently pointed to by the HEAD pointer

git show HEAD^

But after I pressed enter, instead of executing the command, the command prompt asked for more

After I have pressed enter a few more times, an error is displayed

Why is this happening? I'm currently using command prompt on windows.

Body:
^ is the escape character for the Windows command prompt.

Use ^^ to escape it and run a command that includes a single ^:

git show HEAD^^


问:
How can I modify this batch script's directory?
This batch script creates a text file of a list of files in its own directory, sans file extensions. However, I would like it to create a list of another directory's files instead. How could I modify it to attain those results?</p>

```<code>@echo off
cd %1
if exist filelisting.txt del filelisting.txt
for /F "delims=" %%j in ('dir /A-D /B /O:GEN') do echo %%~nj >> filelisting.txt
</code>```

答:
Nevermind, I figured it out:</p>

```<code>@echo off
cd %1
if exist filelisting.txt del filelisting.txt
for /F "delims=" %%j in ('dir "c:\Location\*" /A-D /B /O:GEN') do echo %%~nj >> filelisting.txt
</code>```

Body:
This batch script creates a text file of a list of files in its own directory, sans file extensions. However, I would like it to create a list of another directory's files instead. How could I modify it to attain those results?

@echo off
cd %1
if exist filelisting.txt del filelisting.txt
for /F "delims=" %%j in ('dir /A-D /B /O:GEN') do echo %%~nj >> filelisting.txt

Body:
Nevermind, I figured it out:

@echo off
cd %1
if exist filelisting.txt del filelisting.txt
for /F "delims=" %%j in ('dir "c:\Location\*" /A-D /B /O:GEN') do echo %%~nj >> filelisting.txt


问:
How to configure security group on AWS
Ok, I have an application on ElasticBeanstalk and have setup an EC2 server for my database.

I've been trying to limit the connections to the database to my IP and that of the applications (EB), however all configurations I have tried have not worked.

I have tried using the security group ID - where on the security group ID used by the App had a outgoing connection to the DB and the DB security group had an incoming connection from the security group ID from the App.

Unfortunately that didn't work. And I don't know how to find the CIDR for the EB environment.

Any ideas?

答:
Add the security group on ec2 server to allow the traffic from your home IP and elasticbeanstalk appliaction static IP.<br>
you can find the Elasticbeanstalk application static IP from Ec2 console Or you can use the following command using amazon cli.  </p>

```<code>aws ec2 describe-instances --instance-ids <instance-id>
</code>```

Title: How to configure security group on AWS

Body:
Add the security group on ec2 server to allow the traffic from your home IP and elasticbeanstalk appliaction static IP.

you can find the Elasticbeanstalk application static IP from Ec2 console Or you can use the following command using amazon cli.

aws ec2 describe-instances --instance-ids <instance-id>


问:
Display alert message if position of div is less than 300
I'm trying to display alert message if position of row_3 div is less than 300,
But am unable to solve.</p>

```<code>$(document).ready(function(){
  $(window).scroll(function (){
    var aa = $(".row_3").position();
    var bb = aa.top;
    if (bb <= 300) {
        alert("welcome");
    }
  });
});
</code>```

答:
```<code>$(document).scroll(function() {
if($('.row_3').offset().top<300){
    alert("alert message");
}
});
</code>```

Work for me check here https://jsfiddle.net/ankit7290/gdznsd0c/ .

Body:
I'm trying to display alert message if position of row_3 div is less than 300,
But am unable to solve.

$(document).ready(function(){
  $(window).scroll(function (){
    var aa = $(".row_3").position();
    var bb = aa.top;
    if (bb <= 300) {
        alert("welcome");
    }
  });
});

Body:
$(document).scroll(function() {
if($('.row_3').offset().top<300){
    alert("alert message");
}
});

Work for me check here https://jsfiddle.net/ankit7290/gdznsd0c/ .


问:
Get selected items of menubutton
I have 3 MenuButtons in my JavaFX-Application, each one filled with CheckMenuItems.
I want to get the Text of every selected Item of the MenuButton. How shall i proceed?

答:
Take all MenuItems, filter selected and map them to String.

```<code>MenuButton mb = new MenuButton();
mb.getItems().addAll(new CheckMenuItem("One"), new CheckMenuItem("Two"), new CheckMenuItem("Three"));
mb.getItems().stream().forEach((MenuItem menuItem) -> menuItem.setOnAction(ev -> {
    final List<String> selectedItems = mb.getItems().stream()
            .filter(item -> CheckMenuItem.class.isInstance(item) && CheckMenuItem.class.cast(item).isSelected())
            .map(MenuItem::getText)
            .collect(Collectors.toList());
    System.out.println(selectedItems);
}));
</code>```

Title: Get selected items of menubutton

Body:
Take all MenuItems, filter selected and map them to String.

MenuButton mb = new MenuButton();
mb.getItems().addAll(new CheckMenuItem("One"), new CheckMenuItem("Two"), new CheckMenuItem("Three"));
mb.getItems().stream().forEach((MenuItem menuItem) -> menuItem.setOnAction(ev -> {
    final List<String> selectedItems = mb.getItems().stream()
            .filter(item -> CheckMenuItem.class.isInstance(item) && CheckMenuItem.class.cast(item).isSelected())
            .map(MenuItem::getText)
            .collect(Collectors.toList());
    System.out.println(selectedItems);
}));


问:
Can the controls in the toolbox be used in both Winform and WPF application?
If not, how can I know which controls are used in winforms, which controls are used in WPF?</p>

答: The toolboxes already filter what controls you can use depending on whether you have created a Win Form or a WPF application project.</p>


问:
How to remove the Powered by Odoo #1 Open Source eCommerce footer from front end of Odoo 9?
I tried the Odoo8 trick it does not work .... There is no Powered by in

```<code>addons => web => views => webclient_templates.xml
</code>```

and there is no Footer Copyright in user interface views.

Where can i find this line and possible remove it..

How to remove it permanently removing it from User Interface => Views => Footer Copyright removes it temporarily.

答:
Active developer mode.(Login as admin select About on the user menu the click Activate Developer mode)

Enable technical features.

Go to Settings > Technical > User Interface > Views.

In the search box, next to "(filter icon) Active", type secondary, and hit enter to search.

Choose web.menu_secondary.Click to open it.
Now find this tag and put it comment like.

```<code><div class="oe_footer">
   Powered by
   <a href="http://www.openerp.com" target="_blank">
     <span>Odoo</span>
   </a>
</div>
</code>```

Hope this will solved your problem.

Body:
I tried the Odoo8 trick it does not work .... There is no Powered by in

addons => web => views => webclient_templates.xml

and there is no Footer Copyright in user interface views.

Where can i find this line and possible remove it..

How to remove it permanently removing it from User Interface => Views => Footer Copyright removes it temporarily.

Body:
Active developer mode.(Login as admin select About on the user menu the click Activate Developer mode)

Enable technical features.

Go to Settings > Technical > User Interface > Views.

In the search box, next to "(filter icon) Active", type secondary, and hit enter to search.

Choose web.menu_secondary.Click to open it.
Now find this tag and put it comment like.

<div class="oe_footer">
   Powered by
   <a href="http://www.openerp.com" target="_blank">
     <span>Odoo</span>
   </a>
</div>

Hope this will solved your problem.


问:
What does play fork run do?
I'm using play framework and having issues with hotswapping (or even timely starting up the sbt server)

Several sources have outlines this issue to be something to do with play's fork run, and that to solve it one should turn it to false.

But what is play fork run doing and what are the downsides to turning it off?

BTW here are some references:

solution outlining fork run as culprit

another solution, same thing

答:
Play fork run, is a function of sbt where the JVM is forked. Forking a JVM means that the JVM is run as a separate JVM running as a different process in the OS.

If a JVM is not forked it may be that certain JVM wide settings for example system properties affect the play instance.
One of the pros is that when the fork crashes for example when you are running multiple tests in multiple forks the other forks will still continue running.

In the case of play the JVM is forked such that it is not run in the same JVM process as sbt is running. See the following (from sbt documentation):

By default, the run task runs in the same JVM as sbt. Forking is required under certain circumstances, however. Or, you might want to fork Java processes when implementing new tasks.

This is usefull because if your play instance crashes for example, when system.exit is called or unterminated threads occur, sbt will keep running. Otherwise sbt would have crashed too.

references:

What does it mean to have a forked java VM?

Getting Started with SBT for Scala

Title: What does play fork run do?


问:
How to use lambda layer in keras?
I want to define lambda layer to combine features with cross product, then merge those models,just like the fig. ,What should I do?

Test model_1, get 128 dimensions form dense, use pywt get two 64 dimensions feature(cA,cD), then return cA*cD //of course I want to combine two models ,but try model_1 first.

```<code>from keras.models import Sequential,Model
from keras.layers import Input,Convolution2D,MaxPooling2D
from keras.layers.core import Dense,Dropout,Activation,Flatten,Lambda
import pywt

def myFunc(x):
    (cA, cD) = pywt.dwt(x, 'db1')
#    x=x*x
    return cA*cD

batch_size=32
nb_classes=3
nb_epoch=20
img_rows,img_cols=200,200
img_channels=1
nb_filters=32
nb_pool=2
nb_conv=3

inputs=Input(shape=(1,img_rows,img_cols))
x=Convolution2D(nb_filters,nb_conv,nb_conv,border_mode='valid',
                  input_shape=(1,img_rows,img_cols),activation='relu')(inputs)
x=Convolution2D(nb_filters,nb_conv,nb_conv,activation='relu')(x)
x=MaxPooling2D(pool_size=(nb_pool,nb_pool))(x)
x=Dropout(0.25)(x)
x=Flatten()(x)
y=Dense(128,activation='relu')(x)
cross=Lambda(myFunc,output_shape=(64,))(y)
predictions=Dense(nb_classes,activation='softmax')(cross)
model = Model(input=inputs, output=predictions)
model.compile(loss='categorical_crossentropy',optimizer='adadelta',metrics=['accuracy'])

model.fit(X_train,Y_train,batch_size=batch_size,nb_epoch=nb_epoch,
          verbose=1,validation_data=(X_test,Y_test))
</code>```

Sorry, can I ask a question about tensor?

```<code>import tensorflow as tf
W1 = tf.Variable(np.array([[1,2],[3,4]]))
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
array = W1.eval(sess)
print (array)
</code>```

That's right! However,

```<code>from keras import backend as K
import numpy as np
kvar=K.variable(np.array([[1,2],[3,4]]))
K.eval(kvar)
print(kvar)
</code>```

I got <CudaNdarrayType(float32, matrix)> and kvar.eval() I got b'CudaNdarray([[ 1.  2.]\n [ 3.  4.]])'. I use keras, so how can I get array like tensorflow using keras?

答:
I would probaly duplicate the dense layers. Instead of having 2 layers with 128 units, have 4 layers with 64 units. The result is the same, but you will be able to perform the cross products better.

```<code>from keras.models import Model

#create dense layers and store their output tensors, they use the output of models 1 and to as input
d1 = Dense(64, ....)(Model_1.output)
d2 = Dense(64, ....)(Model_1.output)
d3 = Dense(64, ....)(Model_2.output)
d4 = Dense(64, ....)(Model_2.output)

cross1 = Lambda(myFunc, output_shape=....)([d1,d4])
cross2 = Lambda(myFunc, output_shape=....)([d2,d3])

#I don't really know what kind of "merge" you want, so I used concatenate, there are Add, Multiply and others....
output = Concatenate()([cross1,cross2])
    #use the "axis" attribute of the concatenate layer to define better which axis will be doubled due to the concatenation

model = Model([Model_1.input,Model_2.input], output)
</code>```

Now, for the lambda function:

```<code>import keras.backend as K

def myFunc(x):
    return x[0] * x[1]
</code>```

Title: How to use lambda layer in keras?

Body:
I want to define lambda layer to combine features with cross product, then merge those models,just like the fig. ,What should I do?

Test model_1, get 128 dimensions form dense, use pywt get two 64 dimensions feature(cA,cD), then return cA*cD //of course I want to combine two models ,but try model_1 first.

from keras.models import Sequential,Model
from keras.layers import Input,Convolution2D,MaxPooling2D
from keras.layers.core import Dense,Dropout,Activation,Flatten,Lambda
import pywt

def myFunc(x):
    (cA, cD) = pywt.dwt(x, 'db1')
#    x=x*x
    return cA*cD

batch_size=32
nb_classes=3
nb_epoch=20
img_rows,img_cols=200,200
img_channels=1
nb_filters=32
nb_pool=2
nb_conv=3

inputs=Input(shape=(1,img_rows,img_cols))
x=Convolution2D(nb_filters,nb_conv,nb_conv,border_mode='valid',
                  input_shape=(1,img_rows,img_cols),activation='relu')(inputs)
x=Convolution2D(nb_filters,nb_conv,nb_conv,activation='relu')(x)
x=MaxPooling2D(pool_size=(nb_pool,nb_pool))(x)
x=Dropout(0.25)(x)
x=Flatten()(x)
y=Dense(128,activation='relu')(x)
cross=Lambda(myFunc,output_shape=(64,))(y)
predictions=Dense(nb_classes,activation='softmax')(cross)
model = Model(input=inputs, output=predictions)
model.compile(loss='categorical_crossentropy',optimizer='adadelta',metrics=['accuracy'])

model.fit(X_train,Y_train,batch_size=batch_size,nb_epoch=nb_epoch,
          verbose=1,validation_data=(X_test,Y_test))

Sorry, can I ask a question about tensor?

import tensorflow as tf
W1 = tf.Variable(np.array([[1,2],[3,4]]))
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
array = W1.eval(sess)
print (array)

That's right! However,

from keras import backend as K
import numpy as np
kvar=K.variable(np.array([[1,2],[3,4]]))
K.eval(kvar)
print(kvar)

I got <CudaNdarrayType(float32, matrix)> and kvar.eval() I got b'CudaNdarray([[ 1.  2.]\n [ 3.  4.]])'. I use keras, so how can I get array like tensorflow using keras?

Body:
I would probaly duplicate the dense layers. Instead of having 2 layers with 128 units, have 4 layers with 64 units. The result is the same, but you will be able to perform the cross products better.

from keras.models import Model

#create dense layers and store their output tensors, they use the output of models 1 and to as input
d1 = Dense(64, ....)(Model_1.output)
d2 = Dense(64, ....)(Model_1.output)
d3 = Dense(64, ....)(Model_2.output)
d4 = Dense(64, ....)(Model_2.output)

cross1 = Lambda(myFunc, output_shape=....)([d1,d4])
cross2 = Lambda(myFunc, output_shape=....)([d2,d3])

#I don't really know what kind of "merge" you want, so I used concatenate, there are Add, Multiply and others....
output = Concatenate()([cross1,cross2])
    #use the "axis" attribute of the concatenate layer to define better which axis will be doubled due to the concatenation

model = Model([Model_1.input,Model_2.input], output)

Now, for the lambda function:

import keras.backend as K

def myFunc(x):
    return x[0] * x[1]


问:
XPath to return default value if node not present
Say I have a pair of XML documents

```<code><Foo>
    <Bar/>
    <Baz>mystring</Baz>
</Foo>
</code>```

and

```<code><Foo>
    <Bar/>
</Foo>
</code>```

I want an XPath (Version 1.0 only) that returns "mystring" for the first document and "not-found" for the second. I tried

```<code>(string('not-found') | //Baz)[last()]
</code>```

but the left hand side of the union isn't a node-set

答:
In XPath 1.0, use:

```<code>concat(/Foo/Baz,
       substring('not-found', 1 div not(/Foo/Baz)))
</code>```

If you want to handle the posible empty Baz element, use:

```<code>concat(/Foo/Baz,
       substring('not-found', 1 div not(/Foo/Baz[node()])))
</code>```

With this input:

```<code><Foo>
    <Baz/>
</Foo>
</code>```

Result: not-found string data type.

Body:
Say I have a pair of XML documents

<Foo>
    <Bar/>
    <Baz>mystring</Baz>
</Foo>

and

<Foo>
    <Bar/>
</Foo>

I want an XPath (Version 1.0 only) that returns "mystring" for the first document and "not-found" for the second. I tried

(string('not-found') | //Baz)[last()]

but the left hand side of the union isn't a node-set

Body:
In XPath 1.0, use:

concat(/Foo/Baz,
       substring('not-found', 1 div not(/Foo/Baz)))

If you want to handle the posible empty Baz element, use:

concat(/Foo/Baz,
       substring('not-found', 1 div not(/Foo/Baz[node()])))

With this input:

<Foo>
    <Baz/>
</Foo>

Result: not-found string data type.


问:
Querying Android Groups table very slow
A single query to the Groups table takes around 5 minutes despite the table only having 15 rows and despite specifying a projection of only 3 columns.

Is there some reason this might be so slow? Does Android block access to this table while other apps are accessing it, for example? Is there a better way to get information about groups?

Here is an example of a section of code that takes upwards of 5 minutes to execute (note that here I have not included a query or projection, but it is no slower than when I do):

```<code>ContentResolver resolver = context.getContentResolver();
resolver.query(android.provider.ContactsContract.Groups.CONTENT_URI,
               null,
               null,
               null,
               null);
</code>```

答:
(Turning the comment into a proper answer)

Similar query in our production app reports timing of ~10-20ms.
Maybe you have a corrupt Groups table.

I'd suggest trying a different device, using a different contacts account preferably.

Title: Querying Android Groups table very slow

Body:
A single query to the Groups table takes around 5 minutes despite the table only having 15 rows and despite specifying a projection of only 3 columns.

Is there some reason this might be so slow? Does Android block access to this table while other apps are accessing it, for example? Is there a better way to get information about groups?

Here is an example of a section of code that takes upwards of 5 minutes to execute (note that here I have not included a query or projection, but it is no slower than when I do):

ContentResolver resolver = context.getContentResolver();
resolver.query(android.provider.ContactsContract.Groups.CONTENT_URI,
               null,
               null,
               null,
               null);


问:
Scrapy unable to follow internal links while crawling website
I am trying to follow all internal links while tracking all internal and external links to a website. I have just started working with Scrapy and I am unable to figure out how I could crawl while following all internal links in the website.

It just fetches the links on depth one but doesn't follow them.

```<code>class BRS(CrawlSpider):
    name = "brs"
    rules = (Rule(SgmlLinkExtractor(allow=()), callback='parse_obj', follow=True),)
    def __init__(self):
        global start_urls
        #settings.overrides['DEPTH_LIMIT'] = 10
        path = os.path.dirname(os.path.abspath(__file__))
        with open(os.path.join(path,"urls.txt"), "rt") as f:
            self.start_urls = filter(None,[url.strip() for url in f.readlines()])
        start_urls = self.start_urls

    def parse(self, response):
        brsitem = BrsItem()
        brsitem['url'] = response.url
        internal = LinkExtractor(allow_domains=[response.url])
        external = LinkExtractor(deny_domains=[response.url])
        links = internal.extract_links(response)
        internal = []
        fd = open('output.txt','a+')
        for link in links:
            internal.append(link.url)

        links = external.extract_links(response)
        external = []
        for link in links:
            external.append(link.url)
        for link in internal:
            fd.write(link+"\tinternal\n")

        for link in external:
            fd.write(link+"\texternal\n")

        return brsitem
</code>```

My urls.txt contains as of now:
  http://www.stackoverflow.com

Any help is appreciated.

答:
Got it working using a reference of this link and also got my ip blocked on stackoverflow when I had forgotten to set the DEPTH_LIMIT parameter. Somethings are learnt the hard way.</p>

```<code>import scrapy
from scrapy.contrib.linkextractors.sgml import  SgmlLinkExtractor
from scrapy.contrib.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor
import urllib2,requests
from scrapy.conf import settings
from requests.auth import HTTPBasicAuth
import urllib2,requests,os,sys
from urlparse import urlparse
from brs.items import BrsItem

class BRS(CrawlSpider):
    name = "brs"

    def __init__(self):
        global start_urls,rules
        settings.overrides['DEPTH_LIMIT'] = 10
        path = os.path.dirname(os.path.abspath(__file__))
        with open(os.path.join(path,"urls.txt"), "r+") as f:
            self.start_urls = filter(None,[url.strip() for url in f.readlines()])

        start_urls = self.start_urls
        self.rules = (Rule(SgmlLinkExtractor(allow=()), callback=self.parse_items, follow=True),)
        rules = self.rules
        self._rules = rules

    def extract_domain(self,url):
        return urlparse(url).netloc

    def parse_items(self, response):

        internal = LinkExtractor(allow_domains=[self.extract_domain(response.url)])
        external = LinkExtractor(deny_domains=[self.extract_domain(response.url)])
        links = internal.extract_links(response)
        internal = []
        fd = open('output.txt','a+')
        for link in links:
            internal.append(link.url)

        for link in internal:
            fd.write(link+"\tinternal\n")

        links = external.extract_links(response)
        external = []
        for link in links:
            external.append(link.url)
        for link in external:
            fd.write(link+"\texternal\n")
        for link in internal:
            yield scrapy.Request(link.strip(), callback=self.parse_attr)

    def parse_attr(self, response):
        brsitem = BrsItem()
        brsitem['url'] = response.url.strip()
        return brsitem
</code>```

Body:
I am trying to follow all internal links while tracking all internal and external links to a website. I have just started working with Scrapy and I am unable to figure out how I could crawl while following all internal links in the website.

It just fetches the links on depth one but doesn't follow them.

class BRS(CrawlSpider):
    name = "brs"
    rules = (Rule(SgmlLinkExtractor(allow=()), callback='parse_obj', follow=True),)
    def __init__(self):
        global start_urls
        #settings.overrides['DEPTH_LIMIT'] = 10
        path = os.path.dirname(os.path.abspath(__file__))
        with open(os.path.join(path,"urls.txt"), "rt") as f:
            self.start_urls = filter(None,[url.strip() for url in f.readlines()])
        start_urls = self.start_urls

    def parse(self, response):
        brsitem = BrsItem()
        brsitem['url'] = response.url
        internal = LinkExtractor(allow_domains=[response.url])
        external = LinkExtractor(deny_domains=[response.url])
        links = internal.extract_links(response)
        internal = []
        fd = open('output.txt','a+')
        for link in links:
            internal.append(link.url)

        links = external.extract_links(response)
        external = []
        for link in links:
            external.append(link.url)
        for link in internal:
            fd.write(link+"\tinternal\n")

        for link in external:
            fd.write(link+"\texternal\n")

        return brsitem

My urls.txt contains as of now:
  http://www.stackoverflow.com

Any help is appreciated.

Body:
Got it working using a reference of this link and also got my ip blocked on stackoverflow when I had forgotten to set the DEPTH_LIMIT parameter. Somethings are learnt the hard way.

import scrapy
from scrapy.contrib.linkextractors.sgml import  SgmlLinkExtractor
from scrapy.contrib.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor
import urllib2,requests
from scrapy.conf import settings
from requests.auth import HTTPBasicAuth
import urllib2,requests,os,sys
from urlparse import urlparse
from brs.items import BrsItem

class BRS(CrawlSpider):
    name = "brs"

    def __init__(self):
        global start_urls,rules
        settings.overrides['DEPTH_LIMIT'] = 10
        path = os.path.dirname(os.path.abspath(__file__))
        with open(os.path.join(path,"urls.txt"), "r+") as f:
            self.start_urls = filter(None,[url.strip() for url in f.readlines()])

        start_urls = self.start_urls
        self.rules = (Rule(SgmlLinkExtractor(allow=()), callback=self.parse_items, follow=True),)
        rules = self.rules
        self._rules = rules

    def extract_domain(self,url):
        return urlparse(url).netloc

    def parse_items(self, response):

        internal = LinkExtractor(allow_domains=[self.extract_domain(response.url)])
        external = LinkExtractor(deny_domains=[self.extract_domain(response.url)])
        links = internal.extract_links(response)
        internal = []
        fd = open('output.txt','a+')
        for link in links:
            internal.append(link.url)

        for link in internal:
            fd.write(link+"\tinternal\n")

        links = external.extract_links(response)
        external = []
        for link in links:
            external.append(link.url)
        for link in external:
            fd.write(link+"\texternal\n")
        for link in internal:
            yield scrapy.Request(link.strip(), callback=self.parse_attr)

    def parse_attr(self, response):
        brsitem = BrsItem()
        brsitem['url'] = response.url.strip()
        return brsitem


问:
Dynamic reference to the above cell
In my Excel worksheet, every 25 rows or so (this number is subject to change), a cell in column C contains a progressive number, identifying a set. Right now, there is a simple formula, e.g. in Cell 34:

```<code>= C9 + 1
</code>```

When The number of rows above C34 changes, the formula updates automatically. No issue with that.

I am now experimenting with a macro that inserts a set in between two existing sets; therefore another number that should fit in the progression, and the following numbers should adapt.

I thought that formulas should change, to find the first number above the current cell and add +1.

Trying a solution from this link, I came up with the following formula:

```<code>=LOOKUP("z";$C$9:OFFSET(INDIRECT(ADDRESS(ROW();COLUMN()));-1;0))+1
</code>```

It seems however that it only searches for text, giving a #N/Awhen there is no text and a #VALUE! when there is text; if I do not add the +1, it works fine.

I also tried

```<code>=LOOKUP(2;1/(C$9:C9<>"");C:C)
</code>```

As explained in the link but all I get is 0

How do I modify these formulas to give me the expected result?

答:
Assuming than the number of the first set is in A1,
enter this formula

```<code>=INDEX(A:A,MATCH(1E+100,OFFSET(A$1,,,ROW()-1)))+1
</code>```

in the counting cells (A5,A10, A16 in the example):

Then you can insert rows for a new inserted set, for example:

When ypu copy the same formula into C10,
 the set numbers update accordingly:

And you can fill the text elements of the set:

Title: Dynamic reference to the above cell

Body:
In my Excel worksheet, every 25 rows or so (this number is subject to change), a cell in column C contains a progressive number, identifying a set. Right now, there is a simple formula, e.g. in Cell 34:

= C9 + 1

When The number of rows above C34 changes, the formula updates automatically. No issue with that.

I am now experimenting with a macro that inserts a set in between two existing sets; therefore another number that should fit in the progression, and the following numbers should adapt.

I thought that formulas should change, to find the first number above the current cell and add +1.

Trying a solution from this link, I came up with the following formula:

=LOOKUP("z";$C$9:OFFSET(INDIRECT(ADDRESS(ROW();COLUMN()));-1;0))+1

It seems however that it only searches for text, giving a #N/Awhen there is no text and a #VALUE! when there is text; if I do not add the +1, it works fine.

I also tried

=LOOKUP(2;1/(C$9:C9<>"");C:C)

As explained in the link but all I get is 0

How do I modify these formulas to give me the expected result?

Body:
Assuming than the number of the first set is in A1,
enter this formula

=INDEX(A:A,MATCH(1E+100,OFFSET(A$1,,,ROW()-1)))+1

in the counting cells (A5,A10, A16 in the example):

Then you can insert rows for a new inserted set, for example:

When ypu copy the same formula into C10,
 the set numbers update accordingly:

And you can fill the text elements of the set:


问:
Append to site <title> in Django template using block.super
I have 3 Django templates:

base.html

```<code><title>{% block title %} SITE NAME {% endblock %}</title>
</code>```

default.html

```<code>{% extends "base.html" %}
{% block title %} {{ block.super }} - SECTION NAME {% endblock %}
</code>```

main.html

```<code>{% extends "default.html" %}
{% block title %} {{ block.super }} {% endblock %}
</code>```

I'd like to get SITE NAME in template main.html i.e. the content of the parent of the parent block. Something like

```<code>{{ block.super.super }}
</code>```

Is this possible?

答:
Note, Django 1.2.3 seems to already do what you want. Assuming SITE_NAME is exposed via a context_preprocessor like lzerscience illustrates, block.super should expose it through all the layers of inheritance.

main.html

```<code>{% extends "default.html" %}
{% block title %} {{ block.super }} - MAIN{% endblock %}
</code>```

That displays the title "SITE NAME - SECTION NAME - MAIN" for me.

Body:
I have 3 Django templates:

base.html

<title>{% block title %} SITE NAME {% endblock %}</title>

default.html

{% extends "base.html" %}
{% block title %} {{ block.super }} - SECTION NAME {% endblock %}

main.html

{% extends "default.html" %}
{% block title %} {{ block.super }} {% endblock %}

I'd like to get SITE NAME in template main.html i.e. the content of the parent of the parent block. Something like

{{ block.super.super }}

Is this possible?

Body:
Note, Django 1.2.3 seems to already do what you want. Assuming SITE_NAME is exposed via a context_preprocessor like lzerscience illustrates, block.super should expose it through all the layers of inheritance.

main.html

{% extends "default.html" %}
{% block title %} {{ block.super }} - MAIN{% endblock %}

That displays the title "SITE NAME - SECTION NAME - MAIN" for me.


问:
Limit Pagination Numbers
I've got a pagination up and running which works fine. However I would like it to only display 5 page numbers at for example 1.2.3.4.5 then when I click next it goes 6.7.8.9.10 and so on.

I've created it using JavaScript and the code is below.

I have tried multiple pieces of code from various places but i'm positive i'm missing something as nothing seems to work.

```<code>$( document ).ready(function() {

    pageSize = 2;
    pagesCount = $(".content").length;
    var currentPage = 1;

    /////////// PREPARE NAV ///////////////
    var nav = '';
    var totalPages = Math.ceil(pagesCount / pageSize);
    for (var s=0; s<totalPages; s++){
        nav += '<li class="numeros"><a href="#">'+(s+1)+'</a></li>';
    }
    $(".pag_prev").after(nav);
    $(".numeros").first().addClass("active");
    //////////////////////////////////////

    showPage = function() {
        $(".content").hide().each(function(n) {
            if (n >= pageSize * (currentPage - 1) && n < pageSize * currentPage)
                $(this).show();
        });
    }
    showPage();

    $(".pagination li.numeros").click(function() {
        $(".pagination li").removeClass("active");
        $(this).addClass("active");
        currentPage = parseInt($(this).text());
        showPage();
    });

    $(".pagination li.pag_prev").click(function() {
        if($(this).next().is('.active')) return;
        $('.numeros.active').removeClass('active').prev().addClass('active');
        currentPage = currentPage > 1 ? (currentPage-1) : 1;
        showPage();
    });

    $(".pagination li.pag_next").click(function() {
        if($(this).prev().is('.active')) return;
        $('.numeros.active').removeClass('active').next().addClass('active');
        currentPage = currentPage < totalPages ? (currentPage+1) : totalPages;
        showPage();
    });
});
</code>```

答:
The first part of your question is easy

However I would like it to only display 5 page numbers

for (var s=0; s<Math.min(totalPages,5); s++) {
  nav += '
'+ (s + 1) + '
';
}
```
<p>This limits the number of page numbers displayed to <code>totalPages</code> or <code>5</code> whichever is smaller.
For the second part of your question - seeing as you found a lugin which does exactly what you want there's not much point trying to replicate the behaviour. You're better off just using it directly. The appropriate code would be along the lines of:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>pageSize = 2;
pagesCount = $(".content").length;
var totalPages = Math.ceil(pagesCount / pageSize)

$('.pagination').twbsPagination({
  totalPages: totalPages,
  visiblePages: 5,
  onPageClick: function(event, page) {
    var startIndex = (pageSize * (page - 1))
    var endIndex = startIndex + pageSize
    $('.content').hide().filter(function() {
      var idx = $(this).index();
      return idx >= startIndex && idx < endIndex;
    }).show()
  }
});</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />

NEWS 1

Page 1 contents...

NEWS 2

Page 2 contents...

NEWS 3

Page 3 contents...

NEWS 4

Page 4 contents...

NEWS 5

Page 5 contents...

NEWS 6

Page 6 contents...

NEWS 7

Page 7 contents...

NEWS 8

Page 8 contents...

NEWS 9

Page 9 contents...

NEWS 10

Page 10 contents...

NEWS 11

Page 11 contents...

```

Title: Limit Pagination Numbers

Body:
I've got a pagination up and running which works fine. However I would like it to only display 5 page numbers at for example 1.2.3.4.5 then when I click next it goes 6.7.8.9.10 and so on.

I've created it using JavaScript and the code is below.

I have tried multiple pieces of code from various places but i'm positive i'm missing something as nothing seems to work.

$( document ).ready(function() {

    pageSize = 2;
    pagesCount = $(".content").length;
    var currentPage = 1;

    /////////// PREPARE NAV ///////////////
    var nav = '';
    var totalPages = Math.ceil(pagesCount / pageSize);
    for (var s=0; s<totalPages; s++){
        nav += '
'+(s+1)+'
';
    }
    $(".pag_prev").after(nav);
    $(".numeros").first().addClass("active");
    //////////////////////////////////////

    showPage = function() {
        $(".content").hide().each(function(n) {
            if (n >= pageSize * (currentPage - 1) && n < pageSize * currentPage)
                $(this).show();
        });
    }
    showPage();

    $(".pagination li.numeros").click(function() {
        $(".pagination li").removeClass("active");
        $(this).addClass("active");
        currentPage = parseInt($(this).text());
        showPage();
    });

    $(".pagination li.pag_prev").click(function() {
        if($(this).next().is('.active')) return;
        $('.numeros.active').removeClass('active').prev().addClass('active');
        currentPage = currentPage > 1 ? (currentPage-1) : 1;
        showPage();
    });

    $(".pagination li.pag_next").click(function() {
        if($(this).prev().is('.active')) return;
        $('.numeros.active').removeClass('active').next().addClass('active');
        currentPage = currentPage < totalPages ? (currentPage+1) : totalPages;
        showPage();
    });
});

Body:
The first part of your question is easy

However I would like it to only display 5 page numbers

for (var s=0; s<Math.min(totalPages,5); s++) {
  nav += '<li class="numeros"><a href="#">'+ (s + 1) + '</a></li>';
}

This limits the number of page numbers displayed to totalPages or 5 whichever is smaller.
For the second part of your question - seeing as you found a lugin which does exactly what you want there's not much point trying to replicate the behaviour. You're better off just using it directly. The appropriate code would be along the lines of:

pageSize = 2;
pagesCount = $(".content").length;
var totalPages = Math.ceil(pagesCount / pageSize)

$('.pagination').twbsPagination({
  totalPages: totalPages,
  visiblePages: 5,
  onPageClick: function(event, page) {
    var startIndex = (pageSize * (page - 1))
    var endIndex = startIndex + pageSize
    $('.content').hide().filter(function() {
      var idx = $(this).index();
      return idx >= startIndex && idx < endIndex;
    }).show()
  }
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twbs-pagination/1.4.1/jquery.twbsPagination.js"></script>

<div class="contents text-center">
  <div class="content">
    <h1>NEWS 1</h1>
    <h3>Page 1 contents...</h3>
  </div>
  <div class="content">
    <h1>NEWS 2</h1>
    <h3>Page 2 contents...</h3>
  </div>
  <div class="content">
    <h1>NEWS 3</h1>
    <h3>Page 3 contents...</h3>
  </div>
  <div class="content">
    <h1>NEWS 4</h1>
    <h3>Page 4 contents...</h3>
  </div>
  <div class="content">
    <h1>NEWS 5</h1>
    <h3>Page 5 contents...</h3>
  </div>
  <div class="content">
    <h1>NEWS 6</h1>
    <h3>Page 6 contents...</h3>
  </div>
  <div class="content">
    <h1>NEWS 7</h1>
    <h3>Page 7 contents...</h3>
  </div>
  <div class="content">
    <h1>NEWS 8</h1>
    <h3>Page 8 contents...</h3>
  </div>
  <div class="content">
    <h1>NEWS 9</h1>
    <h3>Page 9 contents...</h3>
  </div>
  <div class="content">
    <h1>NEWS 10</h1>
    <h3>Page 10 contents...</h3>
  </div>
  <div class="content">
    <h1>NEWS 11</h1>
    <h3>Page 11 contents...</h3>
  </div>
</div>

<nav class="text-center">
  <ul class="pagination">
  </ul>
</nav>


问:
Preg Match All into single variables
im really stuck in my code.

I have a text thats looks like this

[[QVQ]]Money [[QVQ]]New Zealand | WATER [ 2nd Test ] [[QVQ]]Who? (Personality
      Test) [[QVQ]] New Car

And I need the text behind the [[QVQ]]. I read about preg match.

```<code>preg_match_all('/\[[QVQ\]](.*?)\[[QVQ\]]/s', $input, $matches);
</code>```

But how do I use preg_match in this case to get the matches into single Variables?

Like $match1 , $match2 ,$match3 [...]

答:
Because chris isn't using look arounds with his preg_match_all() pattern, not all substrings are captured.

This will capture all of the substrings (without any unwanted leading/trailing white space characters) using preg_match_all(): /(?<=\]{2}) ?\K.+?(?=$| \[{2})/ Pattern Demo

```<code>var_export(preg_match_all('/(?<=\]{2}) ?\K.+?(?=$| \[{2})/', $input, $out) ? $out[0] : []);
</code>```

chris' preg_split() method does not contend with leading and trailing spaces.  This is a corrected/refined method (this is my recommended regex method):

```<code>var_export(preg_split('/ ?\[{2}QVQ\]{2} ?/', $input, 0, PREG_SPLIT_NO_EMPTY));
</code>```

This is a non-regex method:

```<code>var_export(array_values(array_filter(array_map('trim', explode('[[QVQ]]', $input)), 'strlen')));
</code>```

Breakdown of non-regex method:

```<code>array_values(                          // reindex the array
    array_filter(                      // unset any empty elements
        array_map('trim',              // remove leading/trailing spaces from each element
            explode('[[QVQ]]', $input) // split on known delimiter
        ),
        'strlen'
     )
 )
</code>```

Title: Preg Match All into single variables

Body:
im really stuck in my code.

I have a text thats looks like this

[[QVQ]]Money [[QVQ]]New Zealand | WATER [ 2nd Test ] [[QVQ]]Who? (Personality
      Test) [[QVQ]] New Car

And I need the text behind the [[QVQ]]. I read about preg match.

preg_match_all('/\[[QVQ\]](.*?)\[[QVQ\]]/s', $input, $matches);

But how do I use preg_match in this case to get the matches into single Variables?

Like $match1 , $match2 ,$match3 [...]

Body:
Because chris isn't using look arounds with his preg_match_all() pattern, not all substrings are captured.

This will capture all of the substrings (without any unwanted leading/trailing white space characters) using preg_match_all(): /(?<=\]{2}) ?\K.+?(?=$| \[{2})/ Pattern Demo

var_export(preg_match_all('/(?<=\]{2}) ?\K.+?(?=$| \[{2})/', $input, $out) ? $out[0] : []);

chris' preg_split() method does not contend with leading and trailing spaces.  This is a corrected/refined method (this is my recommended regex method):

var_export(preg_split('/ ?\[{2}QVQ\]{2} ?/', $input, 0, PREG_SPLIT_NO_EMPTY));

This is a non-regex method:

var_export(array_values(array_filter(array_map('trim', explode('[[QVQ]]', $input)), 'strlen')));

Breakdown of non-regex method:

array_values(                          // reindex the array
    array_filter(                      // unset any empty elements
        array_map('trim',              // remove leading/trailing spaces from each element
            explode('[[QVQ]]', $input) // split on known delimiter
        ),
        'strlen'
     )
 )


问:
How to utilize parallel nodes through Shell Script?
I am trying to utilize parallel nodes to run numerical simulations. I have Nodes #0 though 12 and I wish to utilize them each individually to run a separate part of the simulation. Essentially, I need to evaluate f(x) for x=1 through 4 on one node, then f(x) for x=5 through 9 on the next node, and then f(x) for x = 10 through 14 one the next one, and then so on from there. Initially, I tried using a loop like:

```<code>n=0
while [ $n -le 12 ]
do
   ssh compute-0-$n
   #evaluate the f(x) for the x values that I want
   exit
   n=$(($n+1))
done
</code>```

But this did not work because whenever I used the ssh compute-0-$n command to jump to a node the connection to the original shell script seemed to cease, when I would exit the node, the shell script seemed to continue along its merry way... I suppose there is a better way to accomplish this, but I am relatively new to this, can anyone help?

答:
GNU Parallel is made for exactly this kind of tasks.

```<code>evaluate_f() {
  x="$1"
  # do some crazy computation
}
seq 48 | env_parallel --env evaluate_f -Snode{1..12} evaluate_f {}
</code>```

If the machines are not really called node1 .. node12, then is becomes a bit longer:

```<code>seq 48 | env_parallel --env evaluate_f -Snode1,nodeb,nodeIII,node0100,node0x5,node6,nodeg,nodeVIII,node01001,node0xa,node11,nodel evaluate_f {}
</code>```

If you have the nodes in a file:

```<code>seq 48 | env_parallel --env evaluate_f --slf my_nodefile evaluate_f {}
</code>```

What this does is to copy the function evaluate_f to the remote servers and run it there with one argument from seq 48. By default it will run one job per cpu-core in the servers. This makes sense if your computation is not multithreaded and does not have a lot of disk I/O. This can be changed with --jobs.

env_parallel was introduced in version 20160322, so make sure your version is newer than that.

GNU Parallel is a general parallelizer and makes is easy to run jobs in parallel on the same machine or on multiple machines you have ssh access to.

If you have 32 different jobs you want to run on 4 CPUs, a straight forward way to parallelize is to run 8 jobs on each CPU:

GNU Parallel instead spawns a new process when one finishes - keeping the CPUs active and thus saving time:

Installation

You should install GNU Parallel with your package manager, but if GNU Parallel is not packaged for your distribution, you can do a personal installation, which does not require root access. It can be done in 10 seconds by doing this:

```<code>(wget -O - pi.dk/3 || curl pi.dk/3/ || fetch -o - http://pi.dk/3) | bash
</code>```

For other installation options see http://git.savannah.gnu.org/cgit/parallel.git/tree/README

Learn more

See more examples: http://www.gnu.org/software/parallel/man.html

Watch the intro videos: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

Walk through the tutorial: http://www.gnu.org/software/parallel/parallel_tutorial.html

Sign up for the email list to get support: https://lists.gnu.org/mailman/listinfo/parallel

Body:
I am trying to utilize parallel nodes to run numerical simulations. I have Nodes #0 though 12 and I wish to utilize them each individually to run a separate part of the simulation. Essentially, I need to evaluate f(x) for x=1 through 4 on one node, then f(x) for x=5 through 9 on the next node, and then f(x) for x = 10 through 14 one the next one, and then so on from there. Initially, I tried using a loop like:

n=0
while [ $n -le 12 ]
do
   ssh compute-0-$n
   #evaluate the f(x) for the x values that I want
   exit
   n=$(($n+1))
done

But this did not work because whenever I used the ssh compute-0-$n command to jump to a node the connection to the original shell script seemed to cease, when I would exit the node, the shell script seemed to continue along its merry way... I suppose there is a better way to accomplish this, but I am relatively new to this, can anyone help?

Body:
GNU Parallel is made for exactly this kind of tasks.

evaluate_f() {
  x="$1"
  # do some crazy computation
}
seq 48 | env_parallel --env evaluate_f -Snode{1..12} evaluate_f {}

If the machines are not really called node1 .. node12, then is becomes a bit longer:

seq 48 | env_parallel --env evaluate_f -Snode1,nodeb,nodeIII,node0100,node0x5,node6,nodeg,nodeVIII,node01001,node0xa,node11,nodel evaluate_f {}

If you have the nodes in a file:

seq 48 | env_parallel --env evaluate_f --slf my_nodefile evaluate_f {}

What this does is to copy the function evaluate_f to the remote servers and run it there with one argument from seq 48. By default it will run one job per cpu-core in the servers. This makes sense if your computation is not multithreaded and does not have a lot of disk I/O. This can be changed with --jobs.

env_parallel was introduced in version 20160322, so make sure your version is newer than that.

GNU Parallel is a general parallelizer and makes is easy to run jobs in parallel on the same machine or on multiple machines you have ssh access to.

If you have 32 different jobs you want to run on 4 CPUs, a straight forward way to parallelize is to run 8 jobs on each CPU:

GNU Parallel instead spawns a new process when one finishes - keeping the CPUs active and thus saving time:

Installation

You should install GNU Parallel with your package manager, but if GNU Parallel is not packaged for your distribution, you can do a personal installation, which does not require root access. It can be done in 10 seconds by doing this:

(wget -O - pi.dk/3 || curl pi.dk/3/ || fetch -o - http://pi.dk/3) | bash

For other installation options see http://git.savannah.gnu.org/cgit/parallel.git/tree/README

Learn more

See more examples: http://www.gnu.org/software/parallel/man.html

Watch the intro videos: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

Walk through the tutorial: http://www.gnu.org/software/parallel/parallel_tutorial.html

Sign up for the email list to get support: https://lists.gnu.org/mailman/listinfo/parallel


问:
Search/Filter/Select/Manipulate data from a website using Python
I'm working on a project that basically requires me to go to a website, pick a search mode (name, year, number, etc), search a name, select amongst the results those with a specific type (filtering in other words), pick the option to save those results as opposed to emailing them, pick a format to save them then download them by clicking the save button.

My question is, is there a way to do those steps using a Python program? I am only aware of extracting data and downloading pages/images, but I was wondering if there was a way to write a script that would manipulate the data, and do what a person would manually do, only for a large number of iterations.

I've thought of looking into the URL structures, and finding a way to generate for each iteration the accurate URL, but even if that works, I'm still stuck because of the "Save" button, as I can't find a link that would automatically download the data that I want, and using a function of the urllib2 library would download the page but not the actual file that I want.

Any idea on how to approach this? Any reference/tutorial would be extremely helpful, thanks!

EDIT: When I inspect the save button here is what I get:
Search Button

答:
You should take a look at the Library of Congress docs for developers. If they have an API, you'll be able to learn about how you can do search and filter through their API. This will make everything much easier than manipulating a browser through something like Selenium. If there's an API, then you could easily scale your solution up or down.

If there's no API, then you have

Use Selenium with a browser(I prefer Firefox)

Try to get as much info generated, filtered, etc. without actually having to push any buttons on that page by learning how their search engine works with GET and POST requests. For example, if you're looking for books within a range, then manually conduct this search and look at how the URL changes. If you're lucky, you'll see that your search criteria is in the URL. Using this info you can actually conduct a search by visiting that URL which means your program won't have to fill out a form and push buttons, drop-downs, etc.

If you have to use the browser through Selenium(for example, if you want to save the whole page with html, css, js files then you have to press ctrl+s then click "save" button), then you need to find libraries that allow you to manipulate the keyboard within Python. There are such libraries for Ubuntu. These libraries will allow you to press any keys on the keyboard and even do key combinations.

An example of what's possible:

I wrote a script that logs me in to a website, then navigates me to some page, downloads specific links on that page, visits every link, saves every page, avoids saving duplicate pages, and avoids getting caught(i.e. it doesn't behave like a bot by for example visiting 100 pages per minute).

The whole thing took 3-4 hours to code and it actually worked in a virtual Ubuntu machine I had running on my Mac which means while it was doing all that work I could do use my machine. If you don't use a virtual machine, then you'll either have to leave the script running and not interfere with it or make a much more robust program that IMO is not worth coding since you can just use a virtual machine.


问:
How to display div dynamically on window
When i click on any point of screen i need to display a div on clicked point how to do this. explain me with example</p>

答:
Example: http://jsfiddle.net/patrick_dw/erG9Q/

```<code>$(document).click(function(e) {
    $( "<div class='mydiv'></div>" ).offset({top:e.pageY,left:e.pageX} )
                                    .appendTo(document.body);
});
</code>```

css

```<code>div.mydiv {
    width: 50px;
    height: 50px;
    position: absolute;
    background: orange;
}
</code>```

Assign a .click() handler to the document

In the handler, create a new element $( "

" )

Set its page .offset() to the point of the click .offset({top:e.pageY,left:e.pageX} )

.appendTo()  the page .appendTo(document.body)

Body:
Example: http://jsfiddle.net/patrick_dw/erG9Q/

$(document).click(function(e) {
    $( "<div class='mydiv'></div>" ).offset({top:e.pageY,left:e.pageX} )
                                    .appendTo(document.body);
});

css

div.mydiv {
    width: 50px;
    height: 50px;
    position: absolute;
    background: orange;
}

Assign a .click() handler to the document

In the handler, create a new element $( "<div class='mydiv'></div>" )

Set its page .offset() to the point of the click .offset({top:e.pageY,left:e.pageX} )

.appendTo()  the page .appendTo(document.body)