问:
How to set callback function on submit button in bootstrap?
I use bootstrap modal dialog as the user register form as below:

```<code><form>
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title" id="signupModalLabel">Sign Up</h3>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="user-name-input">User Name</label>
                            <input type="text" class="form-control" id="user-name-input" placeholder="User Name" required>
                        </div>
                        <div class="form-group">
                            <label for="user-email-input">Email address</label>
                            <input type="email" class="form-control" id="user-email-input" aria-describedby="emailHelp" placeholder="Enter email" required>
                        </div>
                        <div class="form-group">
                            <label for="userPasswordInput">Password</label>
                            <input type="password" class="form-control" id="user-password-input" placeholder="Password">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" id="signup-submit-button" class="btn btn-primary">Submit</button>
                    </div>
                </div>
            </div>
        </form>
</code>```

it works fine and I want to add callback function for the submit button. I need to call a web socket request on that callback. If I do it as below:

```<code>$("#signup-submit-button").click(signup);

const signup = () => {
    // make a web socket call
}
</code>```

the callback function signup can be called but all form input validations don't work. Each input in the form has a required attribute. If I leave this blank bootstrap validation should be triggered to validate the form value.

How can I add a callback after pass validation check?

答:
Use onsubmit event inside form tag. This will allow validation rules to be checked before executing signup() function. Please note, if you want to suppress validation, then you can add novalidate attributes to form tag too.

function signup() {

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form onsubmit="signup()">
      ...
</form></code>```

Updated : Working solution

$('#signup-submit-button').on('click', function() {   $(this).parents('form:first').find('.hiddenButton').click();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title" id="signupModalLabel">Sign Up</h3>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="user-name-input">User Name</label>
                            <input type="text" class="form-control" id="user-name-input" placeholder="User Name" required>
                        </div>
                        <div class="form-group">
                            <label for="user-email-input">Email address</label>
                            <input type="email" class="form-control" id="user-email-input" aria-describedby="emailHelp" placeholder="Enter email" required>
                        </div>
                        <div class="form-group">
                            <label for="userPasswordInput">Password</label>
                            <input type="password" class="form-control" id="user-password-input" placeholder="Password">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="hiddenButton" style="display:none"></button>
                        <button type="button" id="signup-submit-button" class="btn btn-primary">Submit</button>
                    </div>
                </div>
            </div>
        </form></code>```

Body:
I use bootstrap modal dialog as the user register form as below:

<form>

Sign Up

                            User Name
                            <input type="text" class="form-control" id="user-name-input" placeholder="User Name" required>

                            Email address
                            <input type="email" class="form-control" id="user-email-input" aria-describedby="emailHelp" placeholder="Enter email" required>

                            Password
                            <input type="password" class="form-control" id="user-password-input" placeholder="Password">

                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" id="signup-submit-button" class="btn btn-primary">Submit</button>

        </form>

it works fine and I want to add callback function for the submit button. I need to call a web socket request on that callback. If I do it as below:

$("#signup-submit-button").click(signup);

const signup = () => {
    // make a web socket call
}

the callback function signup can be called but all form input validations don't work. Each input in the form has a required attribute. If I leave this blank bootstrap validation should be triggered to validate the form value.

How can I add a callback after pass validation check?

Body:
Use onsubmit event inside form tag. This will allow validation rules to be checked before executing signup() function. Please note, if you want to suppress validation, then you can add novalidate attributes to form tag too.

function signup() {

}

<form onsubmit="signup()">
      ...
</form>

Updated : Working solution

$('#signup-submit-button').on('click', function() {   $(this).parents('form:first').find('.hiddenButton').click();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title" id="signupModalLabel">Sign Up</h3>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="user-name-input">User Name</label>
                            <input type="text" class="form-control" id="user-name-input" placeholder="User Name" required>
                        </div>
                        <div class="form-group">
                            <label for="user-email-input">Email address</label>
                            <input type="email" class="form-control" id="user-email-input" aria-describedby="emailHelp" placeholder="Enter email" required>
                        </div>
                        <div class="form-group">
                            <label for="userPasswordInput">Password</label>
                            <input type="password" class="form-control" id="user-password-input" placeholder="Password">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="hiddenButton" style="display:none"></button>
                        <button type="button" id="signup-submit-button" class="btn btn-primary">Submit</button>
                    </div>
                </div>
            </div>
        </form>


来源: stackexchange

问:
Return node parameter from Neo4j graphclient query
I would like to find items from the same brand but from a different category.
And then return their id's.

In my database I currently have the following nodes: Item, Brand, Category.

And relations: IN_CATEGORY, FROM_BRAND.

The Items have properties: id, brand and category.

I have created this query, which return the correct result

```<code>MATCH (i1:Item {Id:"5"})-[r1:FROM_BRAND]->(b:Brand)<-[r2:FROM_BRAND]-(i2:Item)
WHERE i1.category <> i2.category
RETURN i2.Id
</code>```

I don't know if it is possible to avoid using the category property and instead use the IN_CATEGORY relation.

My problem is now that I would like to perform the query using the Neo4j graphclient.

By now I come this far:

```<code>public IEnumerable<string> GetIds(string itemId){
  var query = _client.Cypher
    .Match("(i1: Item)-[r:FROM_BRAND]->(b:Brand)<-[rr:FROM_BRAND]-(i2:Item)")
    .Where((Item i1) => i1.id == itemId)
    .AndWhere((Item i1, Item i2) => v1.category != i2.category)
    .Return(i2 => i2.As<Item>());

  return query.Results;
}
</code>```

Its seems to return the correct items. But I would like to return the item ids, not the whole items.

答:
I fixed it using WITH</p>

```<code>var query = _client.Cypher
    .Match("(i1: Item)-[r:FROM_BRAND]->(b:Brand)<-[rr:FROM_BRAND]-(i2:Item)")
    .Where((Item i1) => i1.id == itemId)
    .AndWhere((Item i1, Item i2) => i1.category != i2.category)
    .With("i2.id AS iId")
    .Return(iId => iId.As<string>());

    return query.Results;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to find items from the same brand but from a different category.
And then return their id's.

In my database I currently have the following nodes: Item, Brand, Category.

And relations: IN_CATEGORY, FROM_BRAND.

The Items have properties: id, brand and category.

I have created this query, which return the correct result

MATCH (i1:Item {Id:"5"})-[r1:FROM_BRAND]->(b:Brand)<-[r2:FROM_BRAND]-(i2:Item)
WHERE i1.category <> i2.category
RETURN i2.Id

I don't know if it is possible to avoid using the category property and instead use the IN_CATEGORY relation.

My problem is now that I would like to perform the query using the Neo4j graphclient.

By now I come this far:

public IEnumerable<string> GetIds(string itemId){
  var query = _client.Cypher
    .Match("(i1: Item)-[r:FROM_BRAND]->(b:Brand)<-[rr:FROM_BRAND]-(i2:Item)")
    .Where((Item i1) => i1.id == itemId)
    .AndWhere((Item i1, Item i2) => v1.category != i2.category)
    .Return(i2 => i2.As<Item>());

  return query.Results;
}

Its seems to return the correct items. But I would like to return the item ids, not the whole items.

Body:
I fixed it using WITH

var query = _client.Cypher
    .Match("(i1: Item)-[r:FROM_BRAND]->(b:Brand)<-[rr:FROM_BRAND]-(i2:Item)")
    .Where((Item i1) => i1.id == itemId)
    .AndWhere((Item i1, Item i2) => i1.category != i2.category)
    .With("i2.id AS iId")
    .Return(iId => iId.As<string>());

    return query.Results;


问:
How to get all collections and documents without their names in Cloud Firestore (web)
For example, I have database with this structure:

Solar system (collecton)

Earth (document)

Eurasia (collection)

France (document)

population: 65 000 000

area: 640 000

Germany (document)

Russia (document)

South America (collection)

Africa (collection)

Venus (document)

Mars (document)

If I use this code:

```<code>db.collection("Solar system").doc("Earth").collection("Eurasia").get().then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
                console.log(doc.id, " => ", doc);
            });
        });
</code>```

I will get a list of countries in console:

France

Germany

Russia

But what if I don't know all position in my database and I just want to get all positions in collections?

For example I don't know how many continents in my collection "Earth" and I want to print the list of all countries in all continents in console.

Another words, how can I not specify the name of collections and documents in query?

```<code>db.collection("Solar system").doc(?????).collection(?????).get().then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
                console.log(doc.id, " => ", doc);
            });
        });
</code>```

答:
You could use root level collections:

```<code> - Planets
     - Earth { id: earth }
     - Venus { id: venus }
     - Mars  { id: mars }
 - Continents
     - Europe { id: europe, planet: earth }
     - Asia   { id: asia, planet: earth }
 - Countries
     - Germany { id: germany, continent: europe, planet: earth }
     - France { id: france, continent: europe, planet: earth }
</code>```

According to your question "For example I don't know how many continents in my collection "Earth" and I want to print the list of all countries in all continents in console.", with this structure you can do this this way:

```<code>db.collection("Countries").where("planet", "==","earth")
</code>```

All countries for "Europe" continent:

```<code>db.collection("Countries").where("continent", "==", "europe")
</code>```

Body:
For example, I have database with this structure:

Solar system (collecton)

Earth (document)

Eurasia (collection)

France (document)

population: 65 000 000

area: 640 000

Germany (document)

Russia (document)

South America (collection)

Africa (collection)

Venus (document)

Mars (document)

If I use this code:

db.collection("Solar system").doc("Earth").collection("Eurasia").get().then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
                console.log(doc.id, " => ", doc);
            });
        });

I will get a list of countries in console:

France

Germany

Russia

But what if I don't know all position in my database and I just want to get all positions in collections?

For example I don't know how many continents in my collection "Earth" and I want to print the list of all countries in all continents in console.

Another words, how can I not specify the name of collections and documents in query?

db.collection("Solar system").doc(?????).collection(?????).get().then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
                console.log(doc.id, " => ", doc);
            });
        });

Body:
You could use root level collections:

 - Planets
     - Earth { id: earth }
     - Venus { id: venus }
     - Mars  { id: mars }
 - Continents
     - Europe { id: europe, planet: earth }
     - Asia   { id: asia, planet: earth }
 - Countries
     - Germany { id: germany, continent: europe, planet: earth }
     - France { id: france, continent: europe, planet: earth }

According to your question "For example I don't know how many continents in my collection "Earth" and I want to print the list of all countries in all continents in console.", with this structure you can do this this way:

db.collection("Countries").where("planet", "==","earth")

All countries for "Europe" continent:

db.collection("Countries").where("continent", "==", "europe")


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

Jon Skeet & others have suggested to use the following:

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

Reference:

How to remove duplicates from a List<T>?

Remove duplicates from a List<T> in C#

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

答:
It's not guaranteed, but it's the most obvious implementation. It would be hard to implement in a streaming manner (i.e. such that it returned results as soon as it could, having read as little as it could) without returning them in order.

You might want to read my blog post on the Edulinq implementation of Distinct().

Note that even if this were guaranteed for LINQ to Objects (which personally I think it should be) that wouldn't mean anything for other LINQ providers such as LINQ to SQL.

The level of guarantees provided within LINQ to Objects is a little inconsistent sometimes, IMO. Some optimizations are documented, others not. Heck, some of the documentation is flat out wrong.

ContentLicense: CC BY-SA 4.0

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

Jon Skeet & others have suggested to use the following:

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

Reference:

How to remove duplicates from a List<T>?

Remove duplicates from a List<T> in C#

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


问:
Prevent duplicate MDI children forms
Is there a way to prevent the opening of a certain form within an MDI container if that said form is already opened?</p>

答:
This code work for me in vb.net
``` <code></p>

<p>For Each f As Form In Application.OpenForms
            If TypeOf f Is form_name Then
                f.Activate()
                f.WindowState = FormWindowState.Normal
                f.StartPosition = FormStartPosition.WindowsDefaultLocation
                f.WindowState = FormWindowState.Maximized</p>

```<code>            Return
        End If
    Next
    form_name .MdiParent = Me
    form_name .Show()
</code>```

<p>``` </code></p>

Title: Prevent duplicate MDI children forms

Body:
This code work for me in vb.net

For Each f As Form In Application.OpenForms
            If TypeOf f Is form_name Then
                f.Activate()
                f.WindowState = FormWindowState.Normal
                f.StartPosition = FormStartPosition.WindowsDefaultLocation
                f.WindowState = FormWindowState.Maximized

            Return
        End If
    Next
    form_name .MdiParent = Me
    form_name .Show()


问:
Different Orientation for each line in Jtextpane
I want to append text in JTextPane , i make every line have different color, but when i tried to make line from left to right and right to left it's not workding

this is my code for method

```<code>private void appendToPane(JTextPane tp, String msg, Color c , String rientation)
{
        ComponentOrientation ornt = ComponentOrientation.LEFT_TO_RIGHT;

        if(orientation.equals("left"))
            ornt = ComponentOrientation.LEFT_TO_RIGHT;

        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

        AttributeSet or     =  sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Orientation , StyleConstants.ALIGN_RIGHT );
        AttributeSet fnt    = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Background , Color.YELLOW);
        AttributeSet fontSize = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.FontSize, 25);

         // aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
         // aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);

        int len = tp.getDocument().getLength();
        tp.setCaretPosition(len);
        tp.setCharacterAttributes(aset, false);
        tp.setCharacterAttributes(or , false);
        tp.setCharacterAttributes(fnt, false);
        tp.setCharacterAttributes(fontSize, false);

//      if(orientation.equals("left"))
//          tp.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
//      else
//          tp.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

//      if(orientation != null)
//          tp.setAlignmentX(Component.RIGHT_ALIGNMENT);
//      else
//          tp.setAlignmentX(orientation);

//      tp.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        tp.replaceSelection(msg);
    }
</code>```

答:
So, if your goal is to change the alignment, here is your code sample:

```<code>package test;

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Test {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame("test");

                JTextPane testPane = new JTextPane();
                testPane.setText("left\nright");

                StyledDocument doc = testPane.getStyledDocument();

                //left alignment
                SimpleAttributeSet myAttributeSet = new SimpleAttributeSet();
                StyleConstants.setAlignment(myAttributeSet, StyleConstants.ALIGN_LEFT);
                doc.setParagraphAttributes(0, 4, myAttributeSet, false);

                //right alignment
                StyleConstants.setAlignment(myAttributeSet, StyleConstants.ALIGN_RIGHT);
                doc.setParagraphAttributes(5, 9, myAttributeSet, false);

                frame.getContentPane().setLayout(new BorderLayout());
                frame.getContentPane().add(testPane,BorderLayout.CENTER);
                frame.setSize(200,200);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}
</code>```

If your goal is to change orientation of the text, check this about Bidirectional text.

If your goal is to just write text from right to left, you can just add a DocumentFilter to your document and reverse the logic of your document from there (backward will become forward, the caret will be moved before the insertion instead of after, inserted text will be mirrored, etc)

If you could show more clearly what is your expected result, we would probably be of more help to you.

Body:
I want to append text in JTextPane , i make every line have different color, but when i tried to make line from left to right and right to left it's not workding

this is my code for method

private void appendToPane(JTextPane tp, String msg, Color c , String rientation)
{
        ComponentOrientation ornt = ComponentOrientation.LEFT_TO_RIGHT;

        if(orientation.equals("left"))
            ornt = ComponentOrientation.LEFT_TO_RIGHT;

        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

        AttributeSet or     =  sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Orientation , StyleConstants.ALIGN_RIGHT );
        AttributeSet fnt    = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Background , Color.YELLOW);
        AttributeSet fontSize = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.FontSize, 25);

         // aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
         // aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);

        int len = tp.getDocument().getLength();
        tp.setCaretPosition(len);
        tp.setCharacterAttributes(aset, false);
        tp.setCharacterAttributes(or , false);
        tp.setCharacterAttributes(fnt, false);
        tp.setCharacterAttributes(fontSize, false);

//      if(orientation.equals("left"))
//          tp.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
//      else
//          tp.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

//      if(orientation != null)
//          tp.setAlignmentX(Component.RIGHT_ALIGNMENT);
//      else
//          tp.setAlignmentX(orientation);

//      tp.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        tp.replaceSelection(msg);
    }

Body:
So, if your goal is to change the alignment, here is your code sample:

package test;

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Test {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame("test");

                JTextPane testPane = new JTextPane();
                testPane.setText("left\nright");

                StyledDocument doc = testPane.getStyledDocument();

                //left alignment
                SimpleAttributeSet myAttributeSet = new SimpleAttributeSet();
                StyleConstants.setAlignment(myAttributeSet, StyleConstants.ALIGN_LEFT);
                doc.setParagraphAttributes(0, 4, myAttributeSet, false);

                //right alignment
                StyleConstants.setAlignment(myAttributeSet, StyleConstants.ALIGN_RIGHT);
                doc.setParagraphAttributes(5, 9, myAttributeSet, false);

                frame.getContentPane().setLayout(new BorderLayout());
                frame.getContentPane().add(testPane,BorderLayout.CENTER);
                frame.setSize(200,200);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

If your goal is to change orientation of the text, check this about Bidirectional text.

If your goal is to just write text from right to left, you can just add a DocumentFilter to your document and reverse the logic of your document from there (backward will become forward, the caret will be moved before the insertion instead of after, inserted text will be mirrored, etc)

If you could show more clearly what is your expected result, we would probably be of more help to you.


问:
how to track from where visitor come to my site php
I want to track the site URL from where user reached my site.

From where he came i.el, Google, GMail, Facebook, etc.

I tried $_SERVER['HTTP_REFERER'] but it does not contain anything when user click on my site link from any external site but resides the value when I visit among my site pages and this is also not trusted.

So, What I can do from here?

Is there any other way to track the external URL through PHP?

Any idea?

EDIT: Now HTTP_REFERER is able to get the url from most of sites but not able to get the url if user came through Gmail and AOL. What could be the causes?

答: Have you tried it in a variety of browsers? It's down to the browser (As far as I'm aware) to set HTTP_REFERER and sometimes privacy settings can prevent this.</p>

ContentLicense: CC BY-SA 2.5


问:
Using php class property in smarty template
Can i use php class static properties in smarty template?
For example:

```<code>class UserData
{
    const INDEX = 1;
    const STREET = 2;

    static public $_address_fields = array(
        self::INDEX,
        self::STREET
    );
}
</code>```

And in my smarty template i want do something like this:

```<code>{UserData::$_address_fields}
</code>```

Is it possible?

答:
You can pass this in from your controller

For example:
$smarty->assign('AddressFields, UserData::$_address_fields);

This should then be available for use in your template like so:
{$AddressFields}

Smarty Docs:
https://www.smarty.net/docsv2/en/api.assign.tpl

Body:
Can i use php class static properties in smarty template?
For example:

class UserData
{
    const INDEX = 1;
    const STREET = 2;

    static public $_address_fields = array(
        self::INDEX,
        self::STREET
    );
}

And in my smarty template i want do something like this:

{UserData::$_address_fields}

Is it possible?


问:
Filename match and export
I have several files in a folder. I have to match the filenames using a regex pattern. In the regex pattern I have a word which would be a variable. I want all the files matched with the pattern to be moved to a separate directory with an alternate filename replacing the string with which I had made the match.

Eg,

I have many files with filenames having the word foo in the directory like,

```<code>gadgeagfooafsa
fsafsaffooarwf
fasfsfoofsafff
</code>```

I have to list these files and copy it to another directory replacing the word foo from it. I have specified the new pattern to be "kuh", Like the above files should be copied to the new folder as

```<code>gadgeagkuhafsa
fsafsafkuharwf
fasfskuhfsafff
</code>```

Finally, can I pipe different commands together to execute these in one line? :)

I had tried this command, but it didn't work, somehow the copy is failing.

```<code>ls | grep ".*foo[} ].*" | xargs cp -t work/
</code>```

答:
find + bash solution:

```<code>find . -type f -name "*foo*" -exec bash -c 'fn=${0##*/}; cp "$0" "new_dest/${fn//foo/kuh}"' {} \;
</code>```

fn=${0##*/} - extracting file basename

${fn//foo/kuh} - substituting foo with kuh in filename

Replace/adjust new_dest with your current destination directory name.

Title: Filename match and export

Body:
I have several files in a folder. I have to match the filenames using a regex pattern. In the regex pattern I have a word which would be a variable. I want all the files matched with the pattern to be moved to a separate directory with an alternate filename replacing the string with which I had made the match.

Eg,

I have many files with filenames having the word foo in the directory like,

gadgeagfooafsa
fsafsaffooarwf
fasfsfoofsafff

I have to list these files and copy it to another directory replacing the word foo from it. I have specified the new pattern to be "kuh", Like the above files should be copied to the new folder as

gadgeagkuhafsa
fsafsafkuharwf
fasfskuhfsafff

Finally, can I pipe different commands together to execute these in one line? :)

I had tried this command, but it didn't work, somehow the copy is failing.

ls | grep ".*foo[} ].*" | xargs cp -t work/

Body:
find + bash solution:

find . -type f -name "*foo*" -exec bash -c 'fn=${0##*/}; cp "$0" "new_dest/${fn//foo/kuh}"' {} \;

fn=${0##*/} - extracting file basename

${fn//foo/kuh} - substituting foo with kuh in filename

Replace/adjust new_dest with your current destination directory name.


问:
instagram public media fetch 404 error
Getting very strange issue same Instagram API was working from last few months and now it stops working for two days and it's through 404 error, below is the code:</p>

```<code>INSTA_BASE_WEB_URL = "https://www.instagram.com"
INSTA_BASE_URL = "https://api.instagram.com"

def get_public_images username, params
      endpoint = "#{username}/media"
      http_response = HTTParty.get("#{INSTA_BASE_WEB_URL}/#{endpoint}", query: params)
      if http_response&.code == 200
        begin
          return JSON.parse(http_response.body)
        rescue
        end
      end
      return nil
    end
</code>```

答:
Did you check if there were changes in the API ?
From what I understand in https://www.instagram.com/developer/endpoints/users/#get_users_media_recent, the endpoint should be :</p>

```<code>https://api.instagram.com/v1/users/{user-id}/media/recent/?access_token=ACCESS-TOKEN
</code>```

Title: instagram public media fetch 404 error

Body:
Getting very strange issue same Instagram API was working from last few months and now it stops working for two days and it's through 404 error, below is the code:

INSTA_BASE_WEB_URL = "https://www.instagram.com"
INSTA_BASE_URL = "https://api.instagram.com"

def get_public_images username, params
      endpoint = "#{username}/media"
      http_response = HTTParty.get("#{INSTA_BASE_WEB_URL}/#{endpoint}", query: params)
      if http_response&.code == 200
        begin
          return JSON.parse(http_response.body)
        rescue
        end
      end
      return nil
    end

Body:
Did you check if there were changes in the API ?
From what I understand in https://www.instagram.com/developer/endpoints/users/#get_users_media_recent, the endpoint should be :

https://api.instagram.com/v1/users/{user-id}/media/recent/?access_token=ACCESS-TOKEN


问:
Storing and processing a lot of tiny files
There are a lot of files with size from 1Kb to 5Mb on our servers. Total size of those files is about 7Tb.  Process algorithm - read and make some decisions about this file. Files may have several formats: doc, txt, png, bmp and etc. Therefore I can't merge those files to get bigger files.
How I can effectively store and process those files? What technology fits well to this task?</p>

答:
Hadoop archieves (HAR) is usual way to address this.
More details about this are available on : https://hadoop.apache.org/docs/r2.7.0/hadoop-archives/HadoopArchives.html

You also have option to use SequenceFile, HBase as described in : https://blog.cloudera.com/blog/2009/02/the-small-files-problem/

But, looking at your usecase HAR fits the bill.


问:
Submenu in a navigation bar: li's width doesn't fit the text length
I have a navigation-bar with a submenu. The problem: the li's width in the submenu doesn't fit the text length. Why?

ul {
        margin: 0;
        padding: 0;
        list-style: none;
      }

      #nav-bar > li {
        float: left;
        position
      }

      .has-submenu {
        position: relative;
      }
      .submenu {
        position: absolute;

      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="nav-bar">
      <li>Item 1</li>
      <li class="has-submenu">Item 2
        <ul class="submenu">
          <li>Subitem 1</li>
          <li>Subitem 2</li>
        </ul>
      </li>
      <li>Item 3</li>
    </ul></code>```

答: Because the submenu is positioned absolutely so it will only take the minimum width that it needs. As ankita patel said giving it white-space: nowrap will fix it.

Body:
I have a navigation-bar with a submenu. The problem: the li's width in the submenu doesn't fit the text length. Why?

ul {
        margin: 0;
        padding: 0;
        list-style: none;
      }

      #nav-bar > li {
        float: left;
        position
      }

      .has-submenu {
        position: relative;
      }
      .submenu {
        position: absolute;

      }

Item 1

Item 2

Subitem 1

Subitem 2

Item 3


答:
The problem is that your .submenu > li elements width are computed from the parent element.

Setting the parent element width would fix that (ie .has-submenu).

Title: Submenu in a navigation bar: li's width doesn't fit the text length


问:
MySQL query to list all the employees whose name starts and ends with same character (case-sensitive)
I have one table with name "Employee" with column Id as "Name". How to get rows of employee name whose name start and end with same character (case-sensitive) in MySQL.

Example:
 - anna
 - ANITHA
 - ANNA
 - DAViD

答:
SELECT * FROM Employee WHERE
BINARY LEFT(name, 1) = RIGHT(name, 1);


问:
How can I call a variable from another script to execute a function
Hi I have a script with name 'script.js' the problem is that I have a lot of functions there, and I need execute this function at the beginning of angular.

```<code>var appMaster = {

    preLoader: function(){

    },
    smoothScroll: function() {

    }
}
</code>```

but I need to call this variable appMaster

```<code>import '../../assets/js/script.js';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    appMaster.preLoader();
    appMaster.smoothScroll();
  }
}
</code>```

The error is appMaster no undeclared variable. How can I execute the functions within that other script?

答:
```<code>You can call varibale from anthoer script in Angular application.

Step 1. Create demo.js file in assests/javascript folder.

export function test1(){
    console.log('Calling test 1 function');
}

Step 2. Create demo.d.ts file in assests/javascript folder.

export declare function test1();

Step 3. Use it in your component
//User defined file path
import { test1 } from '../assets/javascript/demo';
 @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() {
    console.log(test1());
  }
}

Note: js and .d.ts file name shoule be same
</code>```

Body:
Hi I have a script with name 'script.js' the problem is that I have a lot of functions there, and I need execute this function at the beginning of angular.

var appMaster = {

    preLoader: function(){

    },
    smoothScroll: function() {

    }
}

but I need to call this variable appMaster

import '../../assets/js/script.js';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    appMaster.preLoader();
    appMaster.smoothScroll();
  }
}

The error is appMaster no undeclared variable. How can I execute the functions within that other script?


问:
Liferay7.0 portlet build with angular and typescript
I'm wondering, is it possible to create a liferay7.0 portlet based on angular(2, angular material v1.1.1) and typescripting.

I know its possible to load (for example) Angular 1.4 lib and create a portlet with plain javascript/angular code
source: https://web.liferay.com/web/sampsa.sohlman/blog/-/blogs/trying-the-angularjs-with-liferay

What i would like to achieve is to create a portlet based on nodejs packages. and to compile it with gulp or something to a war file.

答:
Definitively you can integrate Liferay with Angular. Currently exists an official and functional example in:

https://github.com/liferay/liferay-blade-samples/tree/master/gradle/apps/npm/angular-npm-portlet

But my personal recommendation is don't merge in the same page an Angular portlet with an not Angular portlet.


问:
Creating a list with each item containing different elements in Android
I am new to Android development. I have created an Activity with the ListView like interface, but without using ListView as each item(row) in the list might have different elements. I have successfully created it by including LinearLayouts inside the ScrollView, but the XML looks messy. I have also added onClickListener to each of the inner LinearLayouts.

Is there a better way of doing this?

Thanks.

Regards,

dezull

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  android:layout_height="fill_parent"
  android:orientation="vertical"
  android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
 <ScrollView
  android:id="@+id/ScrollView01"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:layout_weight="1">
  <LinearLayout
   android:id="@+id/LinearLayout02"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical">
   <LinearLayout
    android:id="@+id/wo_status_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@color/desc_button"
    android:focusable="true"
    android:padding="3dp">
    <TextView
     android:id="@+id/wo_status"
     android:text="@string/wo_status"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <TextView
     android:id="@+id/wo_status"
     android:text="Waiting for Parts"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
   </LinearLayout>
   <LinearLayout
    android:id="@+id/wo_prob_desc_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@color/desc_button"
    android:focusable="true"
    android:padding="3dp">
    <TextView
     android:id="@+id/wo_prob_desc"
     android:text="@string/wo_status"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <TextView
     android:id="@+id/wo_prob_desc"
     android:text="New problem"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
   </LinearLayout>
  </LinearLayout>
 </ScrollView>
</LinearLayout>
</code>```

答:
I'm the lead developer for Ledgerist. What we did was create a subclass of Adapter that implemented getView as suggested above.

Inside the getView method, you'll create a ViewHolder object as I'm sure is shown in many tutorials across the web. You'll want to create an instance of each control that you may want to show inside the ViewHolder. When you get to implementing the cell, you'll want to set all the controls that you don't want to display to GONE using their setVisibility method.

Hope this is helpful,

James K., Lead Developer
www.vervv.com | support@vervv.com

Follow us on Twitter: @vervv
http://twitter.com/vervv

Body:
I am new to Android development. I have created an Activity with the ListView like interface, but without using ListView as each item(row) in the list might have different elements. I have successfully created it by including LinearLayouts inside the ScrollView, but the XML looks messy. I have also added onClickListener to each of the inner LinearLayouts.

Is there a better way of doing this?

Thanks.

Regards,

dezull

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  android:layout_height="fill_parent"
  android:orientation="vertical"
  android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
 <ScrollView
  android:id="@+id/ScrollView01"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:layout_weight="1">
  <LinearLayout
   android:id="@+id/LinearLayout02"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical">
   <LinearLayout
    android:id="@+id/wo_status_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@color/desc_button"
    android:focusable="true"
    android:padding="3dp">
    <TextView
     android:id="@+id/wo_status"
     android:text="@string/wo_status"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <TextView
     android:id="@+id/wo_status"
     android:text="Waiting for Parts"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
   </LinearLayout>
   <LinearLayout
    android:id="@+id/wo_prob_desc_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@color/desc_button"
    android:focusable="true"
    android:padding="3dp">
    <TextView
     android:id="@+id/wo_prob_desc"
     android:text="@string/wo_status"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <TextView
     android:id="@+id/wo_prob_desc"
     android:text="New problem"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
   </LinearLayout>
  </LinearLayout>
 </ScrollView>
</LinearLayout>


问:
Fatal error compiling: invalid target release: 1.8 -> [Help 1]
Similar problem like one posted on invalid target release: 1.7 but after following the blog my problem is still unresolved.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project hm_app: Fatal error compiling: invalid target release: 1.8 -> [Help 1]

I was following as tutorial when I faced this problem.

```<code>abt java & mvn

C:\mvn>echo %JAVA_HOME%
C:\mvn>echo %JRE_HOME%
C:\mvn>echo %MAVEN_HOME% yields
</code>```

outputs

```<code>C:\Program Files\Java\jdk1.7.0_51
C:\Program Files\Java\jre7
C:\apache-maven-3.0.4
</code>```

答: The problem I was facing was that I was able to make a maven build from the command prompt but not from Eclipse.What worked for me in eclipse is that I changed the run configuration to point to JRE folder inside of JDK rather than leaving it in JDK folder only as per the standard.This solution may work for you as well but try this if and only if all the java paths are correct, java and javac are showing the same version as present in the target of pom.xml.</p>

Body:
Similar problem like one posted on invalid target release: 1.7 but after following the blog my problem is still unresolved.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project hm_app: Fatal error compiling: invalid target release: 1.8 -> [Help 1]

I was following as tutorial when I faced this problem.

abt java & mvn

C:\mvn>echo %JAVA_HOME%
C:\mvn>echo %JRE_HOME%
C:\mvn>echo %MAVEN_HOME% yields

outputs

C:\Program Files\Java\jdk1.7.0_51
C:\Program Files\Java\jre7
C:\apache-maven-3.0.4


问:
Styling every 3rd and 4th item
I have an array of items that should be displayed as cards. Every 3rd and 4th item should be wider than the others (pattern: narrow - narrow - wide - wide - narrow - narrow - wide - wide... and so on). What I tried so far:

```<code>.card {
    &:nth-child(1n) {width: 33%;}
    &:nth-child(2n) {width: 33%;}
    &:nth-child(3n) {width: 66%;}
    &:nth-child(4n) {width: 66%;}
}
</code>```

Of course this only works for the first 4 items. I want to be able to use this for an infinite amount of items though.
I could figure it out neither with &:nth-child(3n) and similar stuff.

Is it possible to solve this with a css grid?

答: To select every 3rd and 4th item you can use 3n + 3 and 4n + 4 in nth-child selector.

Title: Styling every 3rd and 4th item

Body:
I have an array of items that should be displayed as cards. Every 3rd and 4th item should be wider than the others (pattern: narrow - narrow - wide - wide - narrow - narrow - wide - wide... and so on). What I tried so far:

.card {
    &:nth-child(1n) {width: 33%;}
    &:nth-child(2n) {width: 33%;}
    &:nth-child(3n) {width: 66%;}
    &:nth-child(4n) {width: 66%;}
}

Of course this only works for the first 4 items. I want to be able to use this for an infinite amount of items though.
I could figure it out neither with &:nth-child(3n) and similar stuff.

Is it possible to solve this with a css grid?


问:
How to get user's IP address in a bot with node.js?
I am writing a bot in node.js. May I know how can I insert code to console.log the IP address of message sender please? I need the IP address to perform some auto-log in.

Many Thanks!!

答:
Just want to let you know that the thing that worked for me was this:

```<code>server.post('/api/messages', [
    function(req,res,next){
        console.log(req.connection.remoteAddress);
        next();
    },
    connector.listen()
]);
</code>```

Source: https://github.com/Microsoft/BotBuilder/issues/3316

Body:
Just want to let you know that the thing that worked for me was this:

server.post('/api/messages', [
    function(req,res,next){
        console.log(req.connection.remoteAddress);
        next();
    },
    connector.listen()
]);

Source: https://github.com/Microsoft/BotBuilder/issues/3316


问:
Django: Editing as dataset like in admin site; Error
I am trying a pretty simple thing. I have a database with customers. Now I am building a site where I choose one of the customers and edit the information about it. Exactly the same like in the admin pages where you choose one of your 'views' and you can change the values.

Unfortunately I am making somewhere a mistake.

Here my code:

urls.py

```<code>from django.conf.urls import url
from django.contrib import admin

from Customer import views

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^customerDetails/(?P<pk>\d+)/$', views.customer_details, name='customer_details'),
    url(r'^customerDetails/(?P<pk>\d+)/edit/$', views.edit_customer, name='edit_customer'),
    url(r'^admin/', admin.site.urls),
]
</code>```

views.py

```<code>def home(request):
   customers = Customer.objects.all()
   return render(request, 'home.html', {'customers': customers})

def customer_details(request, pk):
   customerDetails = get_object_or_404(Customer, pk=pk)
   return render(request, 'customerDetails.html', {'customerDetails':  customerDetails})

def edit_customer(request, pk):
    user = User.objects.first()
    customerDataSet = get_object_or_404(Customer, pk=pk)
    if request.method == 'POST':
        form = EditCustomerForm(request.POST, instance=customerDataSet)
        if form.is_valid():
            form.save()
            return redirect('customer_details', pk=customerDataSet.pk)
    else:
        form = EditCustomerForm(instance=customerDataSet)

    return render(request, 'edit_customer.html', {'customerDataSet': customerDataSet, 'form': form})
</code>```

modely.py

```<code>class Customer(models.Model):
    someId = models.IntegerField()
    customerName = models.CharField(max_length=50)
#with some more fields
class customerDetails(models.Model):
    customerName = models.CharField(max_length=50)
#with some more fields
</code>```

formy.py

```<code>from django import forms
from .models import Customer

class EditCustomerForm(forms.ModelForm):

    class Meta:
        model = Customer
        fields = ['someId', 'customerName']
</code>```

edit_customer.html

```<code>{% extends 'base.html' %}

{% block title %}Edit a customer{% endblock %}

{% block breadcrumb %}
  <li class="breadcrumb-item"><a href="{% url 'home' %}">Customer</a></li>
  <li class="breadcrumb-item"><a href="{% url 'customer_details' customerDetails.pk %}">{{ customerDetails.customerName }}</a></li>
  <li class="breadcrumb-item active">Edit customer</li>
{% endblock %}

{% block content %}
<form method="post">
    {% csrf_token %}
    {{form.as_p}}
    <button type="submit" class="btn btn-success">Post</button>
  </form>

{% endblock %}
</code>```

I got the error :

```<code>Exception Type: NoReverseMatch
Exception Value: Reverse for 'customer_details' with arguments '('',)' not found. 1 pattern(s) tried: ['customerDetails/(?P<pk>\\d+)/$']
</code>```

Can you help me to find the error im my code.

Thanks in advance!

答:
I got the answer. My edit_customer.html was wrong.

The line:

```<code><li class="breadcrumb-item"><a href="{% url 'customer_details' customerDetails.pk %}">{{ customerDetails.customerName }}</a></li>
</code>```

should be instead:

```<code><li class="breadcrumb-item">{{ customerDataSet.customerName }}</li>
</code>```

Body:
I am trying a pretty simple thing. I have a database with customers. Now I am building a site where I choose one of the customers and edit the information about it. Exactly the same like in the admin pages where you choose one of your 'views' and you can change the values.

Unfortunately I am making somewhere a mistake.

Here my code:

urls.py

from django.conf.urls import url
from django.contrib import admin

from Customer import views

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^customerDetails/(?P<pk>\d+)/$', views.customer_details, name='customer_details'),
    url(r'^customerDetails/(?P<pk>\d+)/edit/$', views.edit_customer, name='edit_customer'),
    url(r'^admin/', admin.site.urls),
]

views.py

def home(request):
   customers = Customer.objects.all()
   return render(request, 'home.html', {'customers': customers})

def customer_details(request, pk):
   customerDetails = get_object_or_404(Customer, pk=pk)
   return render(request, 'customerDetails.html', {'customerDetails':  customerDetails})

def edit_customer(request, pk):
    user = User.objects.first()
    customerDataSet = get_object_or_404(Customer, pk=pk)
    if request.method == 'POST':
        form = EditCustomerForm(request.POST, instance=customerDataSet)
        if form.is_valid():
            form.save()
            return redirect('customer_details', pk=customerDataSet.pk)
    else:
        form = EditCustomerForm(instance=customerDataSet)

    return render(request, 'edit_customer.html', {'customerDataSet': customerDataSet, 'form': form})

modely.py

class Customer(models.Model):
    someId = models.IntegerField()
    customerName = models.CharField(max_length=50)
#with some more fields
class customerDetails(models.Model):
    customerName = models.CharField(max_length=50)
#with some more fields

formy.py

from django import forms
from .models import Customer

class EditCustomerForm(forms.ModelForm):

    class Meta:
        model = Customer
        fields = ['someId', 'customerName']

edit_customer.html

{% extends 'base.html' %}

{% block title %}Edit a customer{% endblock %}

{% block breadcrumb %}

Customer

{{ customerDetails.customerName }}

Edit customer

{% endblock %}

{% block content %}
<form method="post">
    {% csrf_token %}
    {{form.as_p}}
    <button type="submit" class="btn btn-success">Post</button>
  </form>

{% endblock %}

I got the error :

Exception Type: NoReverseMatch
Exception Value: Reverse for 'customer_details' with arguments '('',)' not found. 1 pattern(s) tried: ['customerDetails/(?P<pk>\\d+)/$']

Can you help me to find the error im my code.

Thanks in advance!

Body:
I got the answer. My edit_customer.html was wrong.

The line:

<li class="breadcrumb-item"><a href="{% url 'customer_details' customerDetails.pk %}">{{ customerDetails.customerName }}</a></li>

should be instead:

<li class="breadcrumb-item">{{ customerDataSet.customerName }}</li>


问:
PDF dynamically on IE
I`m trying to display a PDF dynamically. My code is working fine on Firefox, Chrome.

Only on IE it`s not working.

My HTML:

```<code><a id="link" class="pdf" href="./pdf/5/5a0ae9f13c291.pdf?id=1550811">
   <div class="container_date">
     <h1>14</h1>
     <h2>November</h2>
     <h4>2017</h4>
   </div>
</a>
</code>```

Im displaying my PDF File in:

```<code><div class="pdf_wrapper">
   <div class="pdf_container">
       <div class="pdf_frame_close">
          <img src="images/icons/to_home.png">
       </div>
        <object data=""></object>
    </div>
</div>'
</code>```

My jQuery to manipulate the PDF-Data Source is:

```<code>$(".pdf").click(function(event)
{
var link = this.href;
event.preventDefault(event);
if(!isMobile.any())
{
    link += '#toolbar=0&navpanes=0&scrollbar=0';
    $('.pdf_container object').attr('data', link);
    $('.pdf_wrapper').show();
}
else
{
    window.location.href = link;
}
});
</code>```

Is there any solution to get it work on IE?

EDIT
I Just tested my PDF-WRAPPER. When i set the default data="./pdf/5/5a0ae9f13c291.pdf?id=1550811" and do not change it via jQuery it works fine. But i need to change it via jQuery on Click...

答:
Please try below:

Tools>Internet Options>security tab, click "reset all zones to default"

Tools>ActiveX filtering (turn it off)

Tools>Manage addons>Show all addons

-> locate your installed PDF Reader addons and ensure they are enabled.

->Adobe PDF Reader 10 and earlier have an option/setting to "Display PDF in the browser"

Web documents opened with the 'file:' protocol require a mark of the web to run Active Content.

The latest IE11 update adds additional security for iframe hosted pdf documents.

MSIE browsers don't support object hosted pdf or xps content. The common design pattern is a named or Id'd iframe.

Reference:- https://social.msdn.microsoft.com/Forums/ie/en-US/298a4323-0190-4a4a-ae88-447ced39032e/how-to-display-embedded-pdf-in-internet-explorer-11-ie11?forum=iewebdevelopment

Title: PDF dynamically on IE

Body:
I`m trying to display a PDF dynamically. My code is working fine on Firefox, Chrome.

Only on IE it`s not working.

My HTML:

14

November

2017

Im displaying my PDF File in:

        <object data=""></object>

'

My jQuery to manipulate the PDF-Data Source is:

$(".pdf").click(function(event)
{
var link = this.href;
event.preventDefault(event);
if(!isMobile.any())
{
    link += '#toolbar=0&navpanes=0&scrollbar=0';
    $('.pdf_container object').attr('data', link);
    $('.pdf_wrapper').show();
}
else
{
    window.location.href = link;
}
});

Is there any solution to get it work on IE?

EDIT
I Just tested my PDF-WRAPPER. When i set the default data="./pdf/5/5a0ae9f13c291.pdf?id=1550811" and do not change it via jQuery it works fine. But i need to change it via jQuery on Click...


问:
How do you become an expert in a programming language?
Assuming you have basic to intermediate knowledge of a particular language, how can you become an expert in that language in a short amount of time?</p>

答:
I think,

Passion: to explore and learn, and then

Dedication: to learn different aspects of that programming language, finally,

Patience: to design a project and apply all that one has learned into it.

Note:The programming languages these days have grown too big to implement above strategy.

However, I would still believe that passion is the key to all learning!


问:
Section header is repeating when UITextView size is increased in UITableView Cells
I have been playing around with this problem since a day and I have tried many ways to resolve this issue but have not yet succeeded. I have a tableview with 3 custom cells and I have added section header for last two sections. Here is the screen shot.

which shows last section header is repeating when I enter text in the TextView. My TextView is editable and I have disabled the scrolling to adjust the size of the textview as per the text size.

Here is the code.

```<code>    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 3;
    }

    -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
    {
        NSArray *titleArray = @[@"",@"About You",@"Gender"];

        NSString *titleHeading = [titleArray objectAtIndex:section];

        return titleHeading;
    }

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return section == 0 ? CGFLOAT_MIN : 35;
}

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {

        NSString *identifier = [NSString stringWithFormat:@"cell%ld,%ld",indexPath.section, indexPath.row];
        id cell = [tableView dequeueReusableCellWithIdentifier:identifier];

if (indexPath.section == 1)
            {
                ProfileAboutCell *cellObj = [tableView dequeueReusableCellWithIdentifier:identifier];
                if (!cellObj)
                {
                    [_tableView registerNib:[UINib nibWithNibName:@"ProfileAboutCell" bundle:nil] forCellReuseIdentifier:identifier];
                    cellObj = [tableView dequeueReusableCellWithIdentifier:identifier];
                }
                cellObj.selectionStyle = UITableViewCellSelectionStyleNone;

                //[cellObj.txtAboutYou layoutIfNeeded];
        cellObj.txtAboutYou.delegate = self;
        cellObj.lbl = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 0.0,cellObj.txtAboutYou.frame.size.width - 10.0, 34.0)];
        cellObj.lbl.text = @"About You";
        [cellObj.lbl setBackgroundColor:[UIColor clearColor]];
        [cellObj.lbl setTextColor:[UIColor lightGrayColor]];
        [cellObj.txtAboutYou addSubview:cellObj.lbl];
    //        [cellObj.txtAboutYou setText:[kUserDefaults valueForKey:kAbout]];
        //[cellObj.txtAboutYou sizeToFit];

                cell = cellObj;
            }

        return cell;
        }
</code>```

TextView Delegate Method.

```<code>-(void)textViewDidChange:(UITextView *)textView
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    ProfileAboutCell *cell = [_tableView cellForRowAtIndexPath:indexPath];

    if(![textView hasText]) {
        cell.lbl.hidden = NO;
    }
    else{
        cell.lbl.hidden = YES;
    }
    NSInteger len = textView.text.length;
    cell.lblChar.text=[NSString stringWithFormat:@"%li",500-len];

    [_tableView beginUpdates];
    [_tableView endUpdates];
}
</code>```

I have tried this #SO solution but no help.  Any help would be much appreciated in this direction. Thanks in advance.

答:
From my understanding of the issue you can solve it by set the sections headers in "titleForHeaderInSection" the same way you set the cells in "cellForRowAtIndexPath" for each section,
this way sections that you don't set Headers for will not cause any issue.</p>

```<code>- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSArray *titleArray = @[@"",@"About You",@"Gender"];

if (indexPath.section == 1) {
        NSString *titleHeading = [titleArray objectAtIndex:1];
        return titleHeading;
}
 if (indexPath.section == 2) {
        NSString *titleHeading = [titleArray objectAtIndex:2];

        return titleHeading;
}

    }
</code>```

Body:
I have been playing around with this problem since a day and I have tried many ways to resolve this issue but have not yet succeeded. I have a tableview with 3 custom cells and I have added section header for last two sections. Here is the screen shot.

which shows last section header is repeating when I enter text in the TextView. My TextView is editable and I have disabled the scrolling to adjust the size of the textview as per the text size.

Here is the code.

    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 3;
    }

    -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
    {
        NSArray *titleArray = @[@"",@"About You",@"Gender"];

        NSString *titleHeading = [titleArray objectAtIndex:section];

        return titleHeading;
    }

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return section == 0 ? CGFLOAT_MIN : 35;
}

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {

        NSString *identifier = [NSString stringWithFormat:@"cell%ld,%ld",indexPath.section, indexPath.row];
        id cell = [tableView dequeueReusableCellWithIdentifier:identifier];

if (indexPath.section == 1)
            {
                ProfileAboutCell *cellObj = [tableView dequeueReusableCellWithIdentifier:identifier];
                if (!cellObj)
                {
                    [_tableView registerNib:[UINib nibWithNibName:@"ProfileAboutCell" bundle:nil] forCellReuseIdentifier:identifier];
                    cellObj = [tableView dequeueReusableCellWithIdentifier:identifier];
                }
                cellObj.selectionStyle = UITableViewCellSelectionStyleNone;

                //[cellObj.txtAboutYou layoutIfNeeded];
        cellObj.txtAboutYou.delegate = self;
        cellObj.lbl = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 0.0,cellObj.txtAboutYou.frame.size.width - 10.0, 34.0)];
        cellObj.lbl.text = @"About You";
        [cellObj.lbl setBackgroundColor:[UIColor clearColor]];
        [cellObj.lbl setTextColor:[UIColor lightGrayColor]];
        [cellObj.txtAboutYou addSubview:cellObj.lbl];
    //        [cellObj.txtAboutYou setText:[kUserDefaults valueForKey:kAbout]];
        //[cellObj.txtAboutYou sizeToFit];

                cell = cellObj;
            }

        return cell;
        }

TextView Delegate Method.

-(void)textViewDidChange:(UITextView *)textView
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    ProfileAboutCell *cell = [_tableView cellForRowAtIndexPath:indexPath];

    if(![textView hasText]) {
        cell.lbl.hidden = NO;
    }
    else{
        cell.lbl.hidden = YES;
    }
    NSInteger len = textView.text.length;
    cell.lblChar.text=[NSString stringWithFormat:@"%li",500-len];

    [_tableView beginUpdates];
    [_tableView endUpdates];
}

I have tried this #SO solution but no help.  Any help would be much appreciated in this direction. Thanks in advance.

Body:
From my understanding of the issue you can solve it by set the sections headers in "titleForHeaderInSection" the same way you set the cells in "cellForRowAtIndexPath" for each section,
this way sections that you don't set Headers for will not cause any issue.

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSArray *titleArray = @[@"",@"About You",@"Gender"];

if (indexPath.section == 1) {
        NSString *titleHeading = [titleArray objectAtIndex:1];
        return titleHeading;
}
 if (indexPath.section == 2) {
        NSString *titleHeading = [titleArray objectAtIndex:2];

        return titleHeading;
}

    }


问:
How to dispose unmanaged objects from static class in c#?
I want to release the unmanaged resource from the static class.

What i tried:
I have made the class as singleton instead of static.
and added a destructor. but the unmanaged resource is not geting release immediately. since destructor will not get called immediately like dispose.

and I am not implementing Idisposable since the i cannot call dispose method from the user class.

答:
Assuming you have a good reason to hold onto an object for the lifetime of the application (see comments section), you still shouldn't store it in a static variable. Instead, store it in an object that represents the lifepsan of the application; for example, in a Windows Forms application, you could store it as a member variable of the main form, and in a web application you could store it as a member of your HttpApplication (global.asax.cs).  Both a form and a web application are themselves disposable, so you can override and extend their Dispose method and dispose of your unmanaged resource there.  Both Disposes will be called implicitly when the application exits.

```<code>class MainForm : Form
{
    private readonly AutoResetEvent _global = new AutoResetEvent();

    public override void Dispose()
    {
        _global.Dispose();
        base.Dispose();
    }
}
</code>```

Body:
Assuming you have a good reason to hold onto an object for the lifetime of the application (see comments section), you still shouldn't store it in a static variable. Instead, store it in an object that represents the lifepsan of the application; for example, in a Windows Forms application, you could store it as a member variable of the main form, and in a web application you could store it as a member of your HttpApplication (global.asax.cs).  Both a form and a web application are themselves disposable, so you can override and extend their Dispose method and dispose of your unmanaged resource there.  Both Disposes will be called implicitly when the application exits.

class MainForm : Form
{
    private readonly AutoResetEvent _global = new AutoResetEvent();

    public override void Dispose()
    {
        _global.Dispose();
        base.Dispose();
    }
}


问:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"name"}
enter image description hereSource

```<code><input id="name" name="name" type="text" style="box-sizing:border-box;-moz-box-sizing:border-box;position:absolute;left:130px;top:50px;width:220px;">
</code>```

This is my code

```<code>WebElement VARName = driver.findElement(By.id("name"));
    VARName.sendKeys("Krishna-05");
</code>```

The page in this subject is a pop up page.

Error:

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  no such element: Unable to locate element:
  {"method":"id","selector":"name"}   (Session info:
  chrome=61.0.3163.100)   (Driver info: chromedriver=2.32.498550
  (9dec58e66c31bcc53a9ce3c7226f0c1c5810906a),platform=Windows NT
  10.0.10240 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 0 milliseconds

I tried finding with css,xpath,name etc and no use. All of them exhibit the same error. I'm using Selenium Webdriver with Java on Eclipse.

```<code>package open_chrome;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class Chrome_Driver {

public static void main(String[] args) throws InterruptedException{

    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://<website.com>/");

    driver.findElement(By.id("email")).sendKeys("docker@de.com");
    driver.findElement(By.id("password")).sendKeys("Test1234");
    driver.findElement(By.cssSelector("body > div:nth-child(1) > div > div >
    form > div:nth-child(5) > button")).click();
    //Adding New VAR

    driver.findElement(By.id("ext-gen224")).click();
    driver.findElement(By.id("ext-gen367")).click();
    String parentWindow = driver.getWindowHandle();
//      Set<String> handles =  driver.getWindowHandles();
    for(String childWindow:driver.getWindowHandles())
    {
        driver.switchTo().window(childWindow);
        driver.findElement(By.id("name")).sendKeys("Krishna-05");
    }
</code>```

答:
You can use any locator, seems issue with wait I guess, try explicit and Implicit wait

```<code>driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement VARName = driver.findElement(By.id("name"));
VARName.sendKeys("Krishna-05");
</code>```

Or with Explicit wait

```<code>WebDriverWait wait = new WebDriverWait(driver,20);
WebElement VARName= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("name")));
VARName.sendKeys("Krishna-05")
</code>```

Second thing check whether element is in frame or not, if it is in frame  first switch in frame and then use above code

Body:
enter image description hereSource

<input id="name" name="name" type="text" style="box-sizing:border-box;-moz-box-sizing:border-box;position:absolute;left:130px;top:50px;width:220px;">

This is my code

WebElement VARName = driver.findElement(By.id("name"));
    VARName.sendKeys("Krishna-05");

The page in this subject is a pop up page.

Error:

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  no such element: Unable to locate element:
  {"method":"id","selector":"name"}   (Session info:
  chrome=61.0.3163.100)   (Driver info: chromedriver=2.32.498550
  (9dec58e66c31bcc53a9ce3c7226f0c1c5810906a),platform=Windows NT
  10.0.10240 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 0 milliseconds

I tried finding with css,xpath,name etc and no use. All of them exhibit the same error. I'm using Selenium Webdriver with Java on Eclipse.

package open_chrome;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class Chrome_Driver {

public static void main(String[] args) throws InterruptedException{

    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://<website.com>/");

    driver.findElement(By.id("email")).sendKeys("docker@de.com");
    driver.findElement(By.id("password")).sendKeys("Test1234");
    driver.findElement(By.cssSelector("body > div:nth-child(1) > div > div >
    form > div:nth-child(5) > button")).click();
    //Adding New VAR

    driver.findElement(By.id("ext-gen224")).click();
    driver.findElement(By.id("ext-gen367")).click();
    String parentWindow = driver.getWindowHandle();
//      Set<String> handles =  driver.getWindowHandles();
    for(String childWindow:driver.getWindowHandles())
    {
        driver.switchTo().window(childWindow);
        driver.findElement(By.id("name")).sendKeys("Krishna-05");
    }

Body:
You can use any locator, seems issue with wait I guess, try explicit and Implicit wait

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement VARName = driver.findElement(By.id("name"));
VARName.sendKeys("Krishna-05");

Or with Explicit wait

WebDriverWait wait = new WebDriverWait(driver,20);
WebElement VARName= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("name")));
VARName.sendKeys("Krishna-05")

Second thing check whether element is in frame or not, if it is in frame  first switch in frame and then use above code


问:
this.xxxxx.subscribe is not a function
I'm trying to subscribe to an Observable string but I do not understand the error message:

this.templateName.subscribe is not a function

My code :

```<code>templateName: Observable<string>;

this.store.select(fromRoot.getRequestEntitiesState).subscribe(data => this.requestDetail = data)

this.templateName = this.requestDetail.request.templateName;

this.subscriptions.push(this.templateName.subscribe(templateName => {
  this.store.dispatch(new requestActions.LoadTemplateAction(templateName))
}))
</code>```

答:
```<code>this.requestDetail.request.templateName
</code>```

Should return an Observable.

Title: this.xxxxx.subscribe is not a function

Body:
I'm trying to subscribe to an Observable string but I do not understand the error message:

this.templateName.subscribe is not a function

My code :

templateName: Observable<string>;

this.store.select(fromRoot.getRequestEntitiesState).subscribe(data => this.requestDetail = data)

this.templateName = this.requestDetail.request.templateName;

this.subscriptions.push(this.templateName.subscribe(templateName => {
  this.store.dispatch(new requestActions.LoadTemplateAction(templateName))
}))

Body:
this.requestDetail.request.templateName

Should return an Observable.


问:
Display categories list in Wordpress without subcategories
I am attempting to show categories in a list, but without displaying subcatgories. My current code is:

<?php if (is_category()) {
  $this_category = get_category($cat);
  if (get_category_children($this_category->cat_ID) != "") {
    echo "
";
    wp_list_categories('orderby=id&show_count=0&title_li=
&use_desc_for_title=1&child_of='.$this_category->cat_ID);
    echo "
";
  }
}?>```

Which displays the categories nicely

but when I added a sub-category it looked like this:

Any ideas? Thanks!

答:
Use get_categories() instead.
https://developer.wordpress.org/reference/functions/get_categories/#Get_only_top_level_categories

It has "parent" parameter which you can set to 0 and get desired result.

Body:
I am attempting to show categories in a list, but without displaying subcatgories. My current code is:

<?php if (is_category()) {
  $this_category = get_category($cat);
  if (get_category_children($this_category->cat_ID) != "") {
    echo "
";
    wp_list_categories('orderby=id&show_count=0&title_li=
&use_desc_for_title=1&child_of='.$this_category->cat_ID);
    echo "
";
  }
}?>

Which displays the categories nicely

but when I added a sub-category it looked like this:

Any ideas? Thanks!


问:
Visual Studio Post Build Event MT.exe command fails with code 9009
Hi I am running following command from my post build event:

```<code>C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\mt.exe -manifest "$(ProjectDir)$(TargetName).exe.manifest" -updateresource:"$(TargetDir)$(TargetName).exe;#1"
</code>```

It is failing with Exited with code 9009... I don't understand why this happens; any suggestions?

答:
Here is a potential solution:

You can use the Post build event
  functionality of Visual Studio to do
  this typing the command above: mt.exe
  -manifest app.manifest -outputresource:myapplication.exe;#1. This probably won't work and Visual
  Studio will give you an error like
  "...exited with code 9009...".

You have to edit the csproj file using
  for example the notepad and uncomment
  the XML tags related to the Target
  Name="AfterBuild" (you can find them
  at the end of the file usually). Then,
  place the tags related to the
  PostBuildEvent within the tags related
  to the AfterBuild and then, reload the
  project and compile. It will produce a
  .exe file that needes to be execute
  with Administrator permissions.

Body:
Hi I am running following command from my post build event:

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\mt.exe -manifest "$(ProjectDir)$(TargetName).exe.manifest" -updateresource:"$(TargetDir)$(TargetName).exe;#1"

It is failing with Exited with code 9009... I don't understand why this happens; any suggestions?


问:
Angular 4 - Adding router param before url
Just wondering whether there is a way to create a angular route with parameter before of in-between a url,

```<code>{path: ':param/test/list'} or {path: 'web/:param/list'}
</code>```

and reference it in routerLink directive,

```<code>[routerLink]="['test/list', paramValue]"
</code>```

Thee parameter value is always getting appended to the end of the url.

答:
try this:

```<code>path: { ':parameter/test/list' }
[routerLink]="[paramValue + 'test/list']"
</code>```

or

```<code>path: { 'test/:parameter/list' }
[routerLink]="['test/' + paramValue + '/list']"
</code>```

Body:
Just wondering whether there is a way to create a angular route with parameter before of in-between a url,

{path: ':param/test/list'} or {path: 'web/:param/list'}

and reference it in routerLink directive,

[routerLink]="['test/list', paramValue]"

Thee parameter value is always getting appended to the end of the url.

Body:
try this:

path: { ':parameter/test/list' }
[routerLink]="[paramValue + 'test/list']"

or

path: { 'test/:parameter/list' }
[routerLink]="['test/' + paramValue + '/list']"


问:
SSRS URL Parameters Issue
I have an issue on where i cannot get the parameters to pass through via url.

Below is the url to the report i want to pass a single ID parameter (@ID).

I have tried a few ways, first time in passing via URL.

Any help grateful.

http://rpt.Server.local/Reports/Pages/Report.aspx?ItemPath=%2f%5bQuality+Sales+Report%5d%2fCP+Quailty+Sales+Details+Report+Preview&ViewMode=Detail

答:
http://rpt.Server.local/Reports/Pages/Report.aspx?ItemPath=%2f%5bQuality+Sales+Report%5d%2fCP+Quailty+Sales+Details+Report+Preview&ViewMode=Detail

instead of above link try below

Go to http://rpt.Server.local/Reportserver
find your report in above link and pass "&ID=(value) at the end of the url
or

http://rpt.Server.local/Reportserver/Pages/Report.aspx?ItemPath=%2f%5bQuality+Sales+Report%5d%2fCP+Quailty+Sales+Details+Report+Preview&ID=(value)

Title: SSRS URL Parameters Issue


问:
how to create a variable that can store object of unrelated classes
I'm using reflection to call methods of different classes which are unrelated in terms of functionality but related in terms of operation. Hence I have to pass the object of those classes to invoke method, but how do I store the object in the same variable?

```<code>Method target;
if (handlerType.equals("database")){
    target = DatabaseRequestHandler.class.getMethod(method, Args.class);
} else if (handlerType.equals("document")){
    target = DocumentRequestHandler.class.getMethod(method, Args.class);
} else if (handlerType.equals("dictionary")){
    target = DictionaryRequestHandler.class.getMethod(method, Args.class);
} else {
    throw new IllegalArgumentException("Handler not implemented for this call");
}
//Method target = RequestHandler.class.getMethod(method, Args.class);
if (target.getReturnType().equals(Void.TYPE)) {
    target.invoke(requestHandler, args);
} else {
    Object result = target.invoke(requestHandler, args);
    body = ValueSerializer.serialize(result, memory);
}
</code>```

How should I declare requestHandler variable so that I can store the object of DatabaseHandler, DocumentHandler and DictionaryHandler? All these classes are not related to each other, so there is not point of using the inheritance with them. I'm from a Python background so really not sure how to achieve this.

答:
I used the below  way to create the object.  </p>

```<code>Object requestHandler = null;
Method target;
if (handlerType.equals("
    target = DatabaseRequestHandler.class.getMethod(method, Args.class);
    requestHandler = new DatabaseRequestHandler();
} else if (handlerType.equals("document")){
    target = DocumentRequestHandler.class.getMethod(method, Args.class);
    requestHandler = new
} else if (handlerType.equals("dictionary")){
    target = DictionaryRequestHandler.class.getMethod(method, Args.class);
    requestHandler = new DictionaryRequestHandler();
} else {
    throw new IllegalArgumentException("Handler not implemented for this call");
}
if (target.getReturnType().equals(Void.TYPE)) {
    target.invoke(requestHandler, args);
} else {
    Object result = target.invoke(requestHandler, args);
    body = ValueSerializer.serialize(result, memory);
}
</code>```

Body:
I'm using reflection to call methods of different classes which are unrelated in terms of functionality but related in terms of operation. Hence I have to pass the object of those classes to invoke method, but how do I store the object in the same variable?

Method target;
if (handlerType.equals("database")){
    target = DatabaseRequestHandler.class.getMethod(method, Args.class);
} else if (handlerType.equals("document")){
    target = DocumentRequestHandler.class.getMethod(method, Args.class);
} else if (handlerType.equals("dictionary")){
    target = DictionaryRequestHandler.class.getMethod(method, Args.class);
} else {
    throw new IllegalArgumentException("Handler not implemented for this call");
}
//Method target = RequestHandler.class.getMethod(method, Args.class);
if (target.getReturnType().equals(Void.TYPE)) {
    target.invoke(requestHandler, args);
} else {
    Object result = target.invoke(requestHandler, args);
    body = ValueSerializer.serialize(result, memory);
}

How should I declare requestHandler variable so that I can store the object of DatabaseHandler, DocumentHandler and DictionaryHandler? All these classes are not related to each other, so there is not point of using the inheritance with them. I'm from a Python background so really not sure how to achieve this.

Body:
I used the below  way to create the object.

Object requestHandler = null;
Method target;
if (handlerType.equals("
    target = DatabaseRequestHandler.class.getMethod(method, Args.class);
    requestHandler = new DatabaseRequestHandler();
} else if (handlerType.equals("document")){
    target = DocumentRequestHandler.class.getMethod(method, Args.class);
    requestHandler = new
} else if (handlerType.equals("dictionary")){
    target = DictionaryRequestHandler.class.getMethod(method, Args.class);
    requestHandler = new DictionaryRequestHandler();
} else {
    throw new IllegalArgumentException("Handler not implemented for this call");
}
if (target.getReturnType().equals(Void.TYPE)) {
    target.invoke(requestHandler, args);
} else {
    Object result = target.invoke(requestHandler, args);
    body = ValueSerializer.serialize(result, memory);
}


问:
i want to include a switch case in dynamic HTML block
I want to include a switch condition in this dynamic HTML block. How can I do that?</p>

```<code>editQuestionBlockHTML=' <div class="addQuestionBlock" >'
      +'<div  class="selectQnLabel"><p class="selectQnLabel">Select a type of question</p>'
      +'<p class="questionTypes">';

       switch(questionType)
      {
      case "Radio":
      editQuestionBlockHTML += +' <select id="EditQuestionType" onchange="changeQuestionType();">'
             +' <option value="radioBtn" selected="selected">Radio Button</option>'

            +' <option value="checkBox">Check Box </option>'
            +'  <option value="pullDownMenu">Pull Down Menu</option>'
            +'  <option value="ratingScale"> Rating Scale</option>'
            +'  <option value="commentBox"> Comment Box</option>'
            +'  <option value="singleTextBox"> Single Text Box</option>'
            +' </select>';
      break;

       }

     editQuestionBlockHTML+=+'</p></div>'

      +'<div  style="float:left;width:100%;">'
      +' <p class="selectQnLabel">Enter Question</p>'
      +' <p><textarea "EditQuestionTitle-'+questionId+'" class="inputBox" rows="4" cols="65" >'+questionText+'</textarea></p>'
      +'<div style="clear:both;">'

       +'</div>'
      +'</div>'
      +'<div  style="float:left;width:100%;">'
      +' <p class="selectQnLabel">Enter Choices (Each choice on a separate line)</p>'
      +' <p><textarea id="editQuestionChoiceList-'+questionId+'" class="inputBox" rows="4" cols="65">'
      +choicelist
      +'</textarea></p>'
      +'<div style="clear:both;">'

       +'</div>'
      +'</div>'

      +'</div>'
      +'</div>';
      return editQuestionBlockHTML;
</code>```

答:
The "switch" condition is very easy in javascript:</p>

```<code>switch(n){
    case 1: // it's like: if(n == 1) ...
        /* do stuff */
    break; //really 'breaks' the switch and ignore everything else inside the switch
    case 2:
    case 3: //multiple matches ..it's like: else if(n == 2 || n == 3)
        /* do stuff */
    break;
    default: //default code if no match has been found with your cases .. it's like the last "else" in your if .. else statement
        /* do stuff */
}
</code>```

Body:
I want to include a switch condition in this dynamic HTML block. How can I do that?

editQuestionBlockHTML='
'
      +'

Select a type of question
'
      +'
';

       switch(questionType)
      {
      case "Radio":
      editQuestionBlockHTML += +' <select id="EditQuestionType" onchange="changeQuestionType();">'
             +' <option value="radioBtn" selected="selected">Radio Button</option>'

            +' <option value="checkBox">Check Box </option>'
            +'  <option value="pullDownMenu">Pull Down Menu</option>'
            +'  <option value="ratingScale"> Rating Scale</option>'
            +'  <option value="commentBox"> Comment Box</option>'
            +'  <option value="singleTextBox"> Single Text Box</option>'
            +' </select>';
      break;

       }

     editQuestionBlockHTML+=+'

'

      +'
'
      +'
Enter Question
'
      +'
<textarea "EditQuestionTitle-'+questionId+'" class="inputBox" rows="4" cols="65" >'+questionText+'</textarea>
'
      +'
'

       +'
'
      +'
'
      +'
'
      +'
Enter Choices (Each choice on a separate line)
'
      +'
<textarea id="editQuestionChoiceList-'+questionId+'" class="inputBox" rows="4" cols="65">'
      +choicelist
      +'</textarea>
'
      +'
'

       +'
'
      +'
'

      +'
'
      +'
';
      return editQuestionBlockHTML;

Body:
The "switch" condition is very easy in javascript:

switch(n){
    case 1: // it's like: if(n == 1) ...
        /* do stuff */
    break; //really 'breaks' the switch and ignore everything else inside the switch
    case 2:
    case 3: //multiple matches ..it's like: else if(n == 2 || n == 3)
        /* do stuff */
    break;
    default: //default code if no match has been found with your cases .. it's like the last "else" in your if .. else statement
        /* do stuff */
}


问:
Autofill populating wrong fields
I have a site with a checkout page that has always worked beautifully.

Recently, any customer that uses autofill to fill out his info, gets his email address dumped into the company field.
There are no changes that we did that could affect that.
What other tools can I use to get to the bottom of this?

答:
Found myself in a similar problem, and the autocomplete property is what to be used in this situations

```<code><input type="text" name="fooBar" autocomplete="organization" >
</code>```

exhaustive list of autocomplete/autofill tags for html form inputs

Title: Autofill populating wrong fields

Body:
Found myself in a similar problem, and the autocomplete property is what to be used in this situations

<input type="text" name="fooBar" autocomplete="organization" >

exhaustive list of autocomplete/autofill tags for html form inputs


问:
Join two Collections with LINQ with Contains operator
I have following two classes

```<code>Class C
{
public Guid Id{get;set;}
public string Type{get;set;}
}

Class D
{
  public List<Guid> CIds {get;set;}
  public string Type {get;set;}
}

 var D_Collection = new List<D>();
 var C_Collection = new List<C>();

 // SET The C_Collection.Type On the Basis of D_Collection
 // If C.Id exist in D.CIds then C.Type = D.Type
</code>```

I want to Set C.Type bases on the Criteria Given above in Comments

I tried following but it's not working

```<code> var temp = (from x in D_Collection
                        from y in C_Collection
                        where x.CIds.Contains(y.Id)
                        select new {
                               Id = y.Id,
                               Type = x.Type
                }).ToList();
</code>```

答:
Try this code

public IQueryable GetData(string DataType)
{

```<code> IQueryable<DatabaseObject> dbData = (
    from t in db.All<DatabaseObject>().Where(e => e.Category == TransType)
    join e in WebHelpers.LocalList
    on t.Type equals e.Type
    orderby t.DateOccurred descending
    select t
);

return dbData;
</code>```

}

Body:
I have following two classes

Class C
{
public Guid Id{get;set;}
public string Type{get;set;}
}

Class D
{
  public List<Guid> CIds {get;set;}
  public string Type {get;set;}
}

 var D_Collection = new List<D>();
 var C_Collection = new List<C>();

 // SET The C_Collection.Type On the Basis of D_Collection
 // If C.Id exist in D.CIds then C.Type = D.Type

I want to Set C.Type bases on the Criteria Given above in Comments

I tried following but it's not working

 var temp = (from x in D_Collection
                        from y in C_Collection
                        where x.CIds.Contains(y.Id)
                        select new {
                               Id = y.Id,
                               Type = x.Type
                }).ToList();

Body:
Try this code

public IQueryable GetData(string DataType)
{

 IQueryable<DatabaseObject> dbData = (
    from t in db.All<DatabaseObject>().Where(e => e.Category == TransType)
    join e in WebHelpers.LocalList
    on t.Type equals e.Type
    orderby t.DateOccurred descending
    select t
);

return dbData;

}


问:
Where is my m2 folder on Mac OS X Mavericks
I cant seem to find the local .m2 folder on Mac OS X mavericks. Ideally it should be at {user.home}/.m2 but I cant seem to find it.

Should I create it?

答:
On the top of the screen you can find the Finder. Click Go -> Go to Folder -> search ~/.m2

If it is not found, as m2 is a hidden file you need to enable visibility by typing the following command in terminal:

defaults write com.apple.finder AppleShowAllFiles YES


问:
Write sorted in ascending order numbers that were drawn more than once. [ C ]
I can't solve this one
problem

this code has Time limit exceeded, so i need to make time complexity smoller, i think

```<code>  #include <stdio.h>
  int main()
  {
    int a[100000], i, j, min, b, tmp;
    scanf("%d", &b);
    for (i = 0; i < b; i++)
    {
      scanf("%d", &a[i]);
    }

    for (i = 0; i < b; i++)
    {
      min = a[i];
      tmp = i;
      for (j = i; j < b-1; j++)
      {
        if (min > a[j])
        {
           min = a[j];
           tmp = j;
        }
      }
      a[tmp] = a[i];
      a[i] = min;
      if (i > 0)
      {
        if (a[i-2] != a[i] && a[i] == a[i-1]) printf("%d\n", a[i]);
      }
    }

    return 0;
  };
</code>```

答:
Your sorting algorithm has complexity O(n^2). For an input with size 10^5 it takes many magnitude more than O(nlogn) quick sort algorithm.

Here you can use qsort() to solve the problem.

```<code>qsort(a, b, sizeof int, cmp);
</code>```

Where cmp is

```<code>int cmp(const void *a, const void *b)
{
    return (*(int *) a - *(int *) b);
}
</code>```

The algorithm after sorting is much more simpler.

```<code>int p = a[0], ct=0;
for(size_t i = 1; i<=b-1; i++)
{
    if( a[i] == a[i-1])
       ct++;
    else{
       if( ct > 1){
       // a[i-1] should be printed.
       }
       ct = 1;
    }
}
if( ct > 1){
   //a[b-1] should also be print.
}
</code>```

The idea is something like this

As the numbers are sorted we will get a monotonic sequence.

We compare every number with one that came before. If there is duplicate they will appear next to next.

We only collect those numbers which appear multiple times.

Also there are few things you can follow

Declaring large variables inside a method sometimes is constrained by the available memory(automatic storage duration).(may have stackoverflow etc) Make it global.(something of static storage duration).

The variable names are not a bit readable.

You can get help in case of using a sorting algorithm.

Knowing the complexity of different algorithms helps. The thing is in your case the complexity is O(n^2). The sorting algorithm better than this is the popular merge sort etc. This simple idea solves the problem in your case.

You can check yourself that this code is atleast a bit more readable than your version. This helps avoid small mistakes.

```<code> int temp = a[0], count=0;
for(size_t i = 1; i<=len-1; i++)
{
    if( arr[i] == arr[i-1])
       count++;
    else{
       if( count > 1){
       // a[i-1] should be printed.
       }
       count = 1;
    }
}
if( count > 1){
   //arr[len-1] should also be print.
}
</code>```

Body:
I can't solve this one
problem

this code has Time limit exceeded, so i need to make time complexity smoller, i think

  #include <stdio.h>
  int main()
  {
    int a[100000], i, j, min, b, tmp;
    scanf("%d", &b);
    for (i = 0; i < b; i++)
    {
      scanf("%d", &a[i]);
    }

    for (i = 0; i < b; i++)
    {
      min = a[i];
      tmp = i;
      for (j = i; j  a[j])
        {
           min = a[j];
           tmp = j;
        }
      }
      a[tmp] = a[i];
      a[i] = min;
      if (i > 0)
      {
        if (a[i-2] != a[i] && a[i] == a[i-1]) printf("%d\n", a[i]);
      }
    }

    return 0;
  };

Body:
Your sorting algorithm has complexity O(n^2). For an input with size 10^5 it takes many magnitude more than O(nlogn) quick sort algorithm.

Here you can use qsort() to solve the problem.

qsort(a, b, sizeof int, cmp);

Where cmp is

int cmp(const void *a, const void *b)
{
    return (*(int *) a - *(int *) b);
}

The algorithm after sorting is much more simpler.

int p = a[0], ct=0;
for(size_t i = 1; i<=b-1; i++)
{
    if( a[i] == a[i-1])
       ct++;
    else{
       if( ct > 1){
       // a[i-1] should be printed.
       }
       ct = 1;
    }
}
if( ct > 1){
   //a[b-1] should also be print.
}

The idea is something like this

As the numbers are sorted we will get a monotonic sequence.

We compare every number with one that came before. If there is duplicate they will appear next to next.

We only collect those numbers which appear multiple times.

Also there are few things you can follow

Declaring large variables inside a method sometimes is constrained by the available memory(automatic storage duration).(may have stackoverflow etc) Make it global.(something of static storage duration).

The variable names are not a bit readable.

You can get help in case of using a sorting algorithm.

Knowing the complexity of different algorithms helps. The thing is in your case the complexity is O(n^2). The sorting algorithm better than this is the popular merge sort etc. This simple idea solves the problem in your case.

You can check yourself that this code is atleast a bit more readable than your version. This helps avoid small mistakes.

 int temp = a[0], count=0;
for(size_t i = 1; i<=len-1; i++)
{
    if( arr[i] == arr[i-1])
       count++;
    else{
       if( count > 1){
       // a[i-1] should be printed.
       }
       count = 1;
    }
}
if( count > 1){
   //arr[len-1] should also be print.
}