问:
getting null pointer exception when running the simulator of the restaurant app in eclipse
I'm getting the following error when trying to run the restaurant app in eclipse:

java.lang.NullPointerException
    at com.myrestaurant.app.ui.MainMenuForm.lambda$0(MainMenuForm.java:73)
    at com.codename1.ui.util.EventDispatcher.fireSelectionSync(EventDispatcher.java:321)
    at com.codename1.ui.util.EventDispatcher.fireSelectionEvent(EventDispatcher.java:402)
    at com.codename1.ui.list.DefaultListModel.setSelectedIndex(DefaultListModel.java:181)
    at com.codename1.ui.List.initComponentImpl(List.java:329)
    at com.codename1.ui.Container.initComponentImpl(Container.java:979)
    at com.codename1.ui.Container.insertComponentAtImpl(Container.java:715)
    at com.codename1.ui.Container.insertComponentAt(Container.java:687)
    at com.codename1.ui.Container.addComponent(Container.java:641)
    at com.codename1.ui.Form.addComponent(Form.java:1207)
    at com.codename1.ui.Container.add(Container.java:281)
    at com.myrestaurant.app.ui.BaseForm.init(BaseForm.java:102)
    at com.myrestaurant.app.ui.BaseForm.(BaseForm.java:34)
    at com.myrestaurant.app.ui.MainMenuForm.(MainMenuForm.java:43)
    at com.myrestaurant.app.ui.BaseForm.showMainMenuForm(BaseForm.java:156)
    at com.myrestaurant.app.MyRestaurant.start(MyRestaurant.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.codename1.impl.javase.Executor$1$1.run(Executor.java:123)
    at com.codename1.ui.Display.processSerialCalls(Display.java:1154)
    at com.codename1.ui.Display.mainEDTLoop(Display.java:971)
    at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
    at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

Any help please?

The method is the following:

```<code>@Override
protected List<String> createCategoryList() {
    if(Restaurant.getInstance().
                menu.get().
                categories.size() == 0) {
        categoryModel = new DefaultListModel<>("Loading...");
    } else {
        categoryModel = new DefaultListModel<>(
                Restaurant.getInstance().
                    menu.get().
                    categories.asList());
    }
    List<String> l = new List<String>(categoryModel) {
        @Override
        protected boolean shouldRenderSelection() {
            return true;
        }
    };
    ((DefaultListCellRenderer<String>)l.getRenderer()).setAlwaysRenderSelection(true);
    l.setIgnoreFocusComponentWhenUnfocused(false);
    l.setOrientation(List.HORIZONTAL);
    l.setFixedSelection(List.FIXED_CENTER);
    l.addSelectionListener((i, ii) -> {
        if(currentCategory != l.getSelectedItem()) {
            currentCategory = l.getSelectedItem();
            for(Component c : dishesContainer) {
                Dish d = (Dish)c.getClientProperty("dish");
                ***boolean hidden = d.category.get().equals(currentCategory);***
                c.setHidden(hidden);
                c.setVisible(!hidden);
            }
            dishesContainer.animateLayout(150);
        }
    });
    return l;
}
</code>```

答:
This was fixed in later iterations of the app as the course progresses. This is the current code for this block:

```<code>for(Component c : dishesContainer) {
    Dish d = (Dish)c.getClientProperty("dish");
    if(d != null) {
        String cat = d.category.get();
        if(cat != null) {
            boolean hidden = cat.equals(currentCategory);
            c.setHidden(hidden);
            c.setVisible(!hidden);
        }
    }
}
</code>```

At this time I haven't finished uploading everything but I'm working on that.

Body:
I'm getting the following error when trying to run the restaurant app in eclipse:

java.lang.NullPointerException
    at com.myrestaurant.app.ui.MainMenuForm.lambda$0(MainMenuForm.java:73)
    at com.codename1.ui.util.EventDispatcher.fireSelectionSync(EventDispatcher.java:321)
    at com.codename1.ui.util.EventDispatcher.fireSelectionEvent(EventDispatcher.java:402)
    at com.codename1.ui.list.DefaultListModel.setSelectedIndex(DefaultListModel.java:181)
    at com.codename1.ui.List.initComponentImpl(List.java:329)
    at com.codename1.ui.Container.initComponentImpl(Container.java:979)
    at com.codename1.ui.Container.insertComponentAtImpl(Container.java:715)
    at com.codename1.ui.Container.insertComponentAt(Container.java:687)
    at com.codename1.ui.Container.addComponent(Container.java:641)
    at com.codename1.ui.Form.addComponent(Form.java:1207)
    at com.codename1.ui.Container.add(Container.java:281)
    at com.myrestaurant.app.ui.BaseForm.init(BaseForm.java:102)
    at com.myrestaurant.app.ui.BaseForm.(BaseForm.java:34)
    at com.myrestaurant.app.ui.MainMenuForm.(MainMenuForm.java:43)
    at com.myrestaurant.app.ui.BaseForm.showMainMenuForm(BaseForm.java:156)
    at com.myrestaurant.app.MyRestaurant.start(MyRestaurant.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.codename1.impl.javase.Executor$1$1.run(Executor.java:123)
    at com.codename1.ui.Display.processSerialCalls(Display.java:1154)
    at com.codename1.ui.Display.mainEDTLoop(Display.java:971)
    at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
    at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

Any help please?

The method is the following:

@Override
protected List<String> createCategoryList() {
    if(Restaurant.getInstance().
                menu.get().
                categories.size() == 0) {
        categoryModel = new DefaultListModel<>("Loading...");
    } else {
        categoryModel = new DefaultListModel<>(
                Restaurant.getInstance().
                    menu.get().
                    categories.asList());
    }
    List<String> l = new List<String>(categoryModel) {
        @Override
        protected boolean shouldRenderSelection() {
            return true;
        }
    };
    ((DefaultListCellRenderer<String>)l.getRenderer()).setAlwaysRenderSelection(true);
    l.setIgnoreFocusComponentWhenUnfocused(false);
    l.setOrientation(List.HORIZONTAL);
    l.setFixedSelection(List.FIXED_CENTER);
    l.addSelectionListener((i, ii) -> {
        if(currentCategory != l.getSelectedItem()) {
            currentCategory = l.getSelectedItem();
            for(Component c : dishesContainer) {
                Dish d = (Dish)c.getClientProperty("dish");
                ***boolean hidden = d.category.get().equals(currentCategory);***
                c.setHidden(hidden);
                c.setVisible(!hidden);
            }
            dishesContainer.animateLayout(150);
        }
    });
    return l;
}

Body:
This was fixed in later iterations of the app as the course progresses. This is the current code for this block:

for(Component c : dishesContainer) {
    Dish d = (Dish)c.getClientProperty("dish");
    if(d != null) {
        String cat = d.category.get();
        if(cat != null) {
            boolean hidden = cat.equals(currentCategory);
            c.setHidden(hidden);
            c.setVisible(!hidden);
        }
    }
}

At this time I haven't finished uploading everything but I'm working on that.


来源: stackexchange

问:
Embed PDF file in the html from /var/www/pdf/ directory
I want to embed pdf file in my website from /var/www/pdf/ directory. I have hosted my webpage at /var/www/html/portal/index.php. I tried following ways

1) using embed

2) using iframe

```<code><iframe src="../../pdf/ebook.pdf" width="900" height="750" frameborder="0" allowfullscreen></iframe>
</code>```

3) using object

```<code><object data="../../pdf/ebook.pdf#scrollbar=0&toolbar=0&navpanes=0" width="900" height="750" type="application/pdf">
    <p>PDF cannot be displayed</p>
</object>
</code>```

None of them working, but if I place the pdf file /var/www/html/pdf/ folder it is working fine.

For my requirement, I cannot keep the file in the web directory because public can access the PDF file directly using URL without login in to my web portal. And Also google also can index my PDF file from public search

Please help me to embed pdf

Thanks in advance

答:
You can do it by .htaccess

First : prevent direct access to open pdf  file

Refer this questions and answers

Second: prevent Search engine indexing

Refere this

Hope it will work. I try to give this information in comment but it is not displaying properly there.

ContentLicense: CC BY-SA 3.0

Body:
I want to embed pdf file in my website from /var/www/pdf/ directory. I have hosted my webpage at /var/www/html/portal/index.php. I tried following ways

1) using embed

2) using iframe

3) using object

<object data="../../pdf/ebook.pdf#scrollbar=0&toolbar=0&navpanes=0" width="900" height="750" type="application/pdf">

PDF cannot be displayed

</object>

None of them working, but if I place the pdf file /var/www/html/pdf/ folder it is working fine.

For my requirement, I cannot keep the file in the web directory because public can access the PDF file directly using URL without login in to my web portal. And Also google also can index my PDF file from public search

Please help me to embed pdf

Thanks in advance


问:
Regex pattern match with PHP
I have the following data in a file, which is repeated multiple times:

Date:21
  Month:03
  Year:2017
  Amount:50
  Category:Grocery
  Account:bank
  Note:expensive

Now, I want to extract the value after "Amount:", i.e. "50".

I'm using the following code in PHP:

```<code>$result = preg_split("/Amount/", $contents);
$truncated = substr($printresult, 1, 2);
print_r($truncated);
</code>```

The result I'm getting is this:

```<code>    Da50
</code>```

Could you please help me figure out what exactly I'm doing wrong in this code?

Thank you.

[Edit: $contents contains all the string data]

This is the entire code: http://paste.ideaslabs.com/show/hwj7IiPUcd
Content of data.txt is this: http://paste.ideaslabs.com/show/5TxWH8MUX

答:
Use this pattern: /Amount:\K\d+/
It will accurately extract the full desired numeric value that follows each Amount: without using the much less efficient "lookarounds".

My web filter software does not let me visit your pastelabs links, so I cannot see your actual input.  (This is one of many reasons why you should post your input samples directly into your question.)  You state that you have several lines which you must extract from, so this is the sample input that I have tested with:

```<code>Date:21 Month:03 Year:2017 Amount:50 Category:Grocery Account:bank Note:expensive
Date:1 Month:04 Year:2017 Amount:150 Category:Grocery Account:bank Note:expensive
Date:14 Month:04 Year:2017 Amount:5 Category:Grocery Account:bank Note:expensive
Date:28 Month:04 Year:2017 Amount:5935 Category:Grocery Account:bank Note:expensive
</code>```

My pattern captures the desired results in just 48 steps.  (Pattern Demo)
The pattern uses \K which means "KEEP the character starting from this point", so there is no need for a capture group, nor a "lookbehind".
If your actual input data has optional spaces between Amount: and the number value, then just add ? (space then question mark) to the pattern after the :.

When used with preg_match_all(), the output array is as small as preg_match_all() can make: an array containing 1 subarray with 4 elements.  I cut directly to the subarray in my code to follow:

Code: (Demo)

```<code>$in='Date:21 Month:03 Year:2017 Amount:50 Category:Grocery Account:bank Note:expensive
Date:1 Month:04 Year:2017 Amount:150 Category:Grocery Account:bank Note:expensive
Date:14 Month:04 Year:2017 Amount:5 Category:Grocery Account:bank Note:expensive
Date:28 Month:04 Year:2017 Amount:5935 Category:Grocery Account:bank Note:expensive';

var_export(preg_match_all('/Amount:\K\d+/',$in,$out)?$out[0]:[]);
</code>```

Output:

```<code>array (
  0 => '50',
  1 => '150',
  2 => '5',
  3 => '5935',
)
</code>```

As far as the other answers on this page, they all process my test data in over 600 steps (more than 12x slower / less efficient than my pattern).  At the time of this post, one of them is completely wrong, and some use sloppy regex syntax and shouldn't be learned from.

Title: Regex pattern match with PHP

Body:
I have the following data in a file, which is repeated multiple times:

Date:21
  Month:03
  Year:2017
  Amount:50
  Category:Grocery
  Account:bank
  Note:expensive

Now, I want to extract the value after "Amount:", i.e. "50".

I'm using the following code in PHP:

$result = preg_split("/Amount/", $contents);
$truncated = substr($printresult, 1, 2);
print_r($truncated);

The result I'm getting is this:

    Da50

Could you please help me figure out what exactly I'm doing wrong in this code?

Thank you.

[Edit: $contents contains all the string data]

This is the entire code: http://paste.ideaslabs.com/show/hwj7IiPUcd
Content of data.txt is this: http://paste.ideaslabs.com/show/5TxWH8MUX

Body:
Use this pattern: /Amount:\K\d+/
It will accurately extract the full desired numeric value that follows each Amount: without using the much less efficient "lookarounds".

My web filter software does not let me visit your pastelabs links, so I cannot see your actual input.  (This is one of many reasons why you should post your input samples directly into your question.)  You state that you have several lines which you must extract from, so this is the sample input that I have tested with:

Date:21 Month:03 Year:2017 Amount:50 Category:Grocery Account:bank Note:expensive
Date:1 Month:04 Year:2017 Amount:150 Category:Grocery Account:bank Note:expensive
Date:14 Month:04 Year:2017 Amount:5 Category:Grocery Account:bank Note:expensive
Date:28 Month:04 Year:2017 Amount:5935 Category:Grocery Account:bank Note:expensive

My pattern captures the desired results in just 48 steps.  (Pattern Demo)
The pattern uses \K which means "KEEP the character starting from this point", so there is no need for a capture group, nor a "lookbehind".
If your actual input data has optional spaces between Amount: and the number value, then just add ? (space then question mark) to the pattern after the :.

When used with preg_match_all(), the output array is as small as preg_match_all() can make: an array containing 1 subarray with 4 elements.  I cut directly to the subarray in my code to follow:

Code: (Demo)

$in='Date:21 Month:03 Year:2017 Amount:50 Category:Grocery Account:bank Note:expensive
Date:1 Month:04 Year:2017 Amount:150 Category:Grocery Account:bank Note:expensive
Date:14 Month:04 Year:2017 Amount:5 Category:Grocery Account:bank Note:expensive
Date:28 Month:04 Year:2017 Amount:5935 Category:Grocery Account:bank Note:expensive';

var_export(preg_match_all('/Amount:\K\d+/',$in,$out)?$out[0]:[]);

Output:

array (
  0 => '50',
  1 => '150',
  2 => '5',
  3 => '5935',
)

As far as the other answers on this page, they all process my test data in over 600 steps (more than 12x slower / less efficient than my pattern).  At the time of this post, one of them is completely wrong, and some use sloppy regex syntax and shouldn't be learned from.


问:
R - End a loop on a fixed number of rows
I have a loop that begins when a certain condition exits. It begins when the value is below  -.1.0 The loop exits when the condition is over 1.0

```<code>    #Loop for long entry and exit signal
    entry <- -1.0     #Input value for entry
    exit <- 1.o       #Input value for exit

mydf$sig_long[[1]] = ifelse(mydf$roll.z.score.n3[[1]] < (entry), 1, 0)

    for (i in 2:nrow(mydf)){
      mydf$sig_long[i] = ifelse(mydf$roll.z.score.n3[i] < (entry), 1,
                              ifelse(mydf$roll.z.score.n3[i] > (exit), 0,
                              mydf$sig_long[i-1]))
    }
</code>```

I wanted to learn how to use the same loop but instead of exit on values > 1.0 Exit after a set number of lines. If for example I set nline variable to 5. It would loop and print 1, for a total of 5 lines after the initial entry. An example data frame below:

```<code>    roll.z.score.n3
1   0
2   0
3   0.651651537
4   -1.153593891
5   -0.926552368
6   -0.369016769
7   0.65405595
8   -1.139305279
9   0.358231351
10  1.135314685
11  0.944997472
12  -0.293105191
13  -1.146659778
14  -0.66246734
15  -1.131901741
16  -0.600480649
17  -1.152333435
18  1.1025176
19  -0.144684006
20  -0.678000883
21  -1.146875039
22  -1.132235788
23  0.115583229
24  0.645489447
25  1.148754398
26  0.988193418
27  -0.818892395
</code>```

After the script has run I would use zoo to +1 line the sig_long column.

```<code>  new.df$sig_long <- Lag(new.df$sig_long,1)
</code>```

Code Testing

Ok so i see the issue. As we are specifying the first part of the loop to enter and exit between -1.0 and 1.0 this prints 1's between those two criteria in the new.df$sig_long column. The issue arises if I set the nlines to 5. The entry/exit might exit the trade in 3 lines in the sig_long column. If that is the case, rollsum has no 1's to count in that column, even if i want to hold for 5 lines, if theres only 3 1's from entry... its not going to be able to compute the 5 line hold time. Perhaps we can use the first part of the loop like this in order to print a 1 at the entry condition:

```<code>new.df$sig_long <- ifelse(new.df$roll.z.score.n3 < -1.0 , 1, 0) #Set 1 at entry criteria
</code>```

That sets the 1 at each < -1.0 value. Next would be how to count +5 lines from that point forward. Counting until...1,2,3,4,5, else 0... 0, until next +1.... count until 1,2,3,4,5, else 0, 0 until next +1....

I can see the logic... if newdf$sig_long == 1, count until nlines 5, else 0, repeat...

Then the 2nd part of the loop would work I think for the new_sig_long column

Body:
I have a loop that begins when a certain condition exits. It begins when the value is below  -.1.0 The loop exits when the condition is over 1.0

    #Loop for long entry and exit signal
    entry <- -1.0     #Input value for entry
    exit <- 1.o       #Input value for exit

mydf$sig_long[[1]] = ifelse(mydf$roll.z.score.n3[[1]] < (entry), 1, 0)

    for (i in 2:nrow(mydf)){
      mydf$sig_long[i] = ifelse(mydf$roll.z.score.n3[i] < (entry), 1,
                              ifelse(mydf$roll.z.score.n3[i] > (exit), 0,
                              mydf$sig_long[i-1]))
    }

I wanted to learn how to use the same loop but instead of exit on values > 1.0 Exit after a set number of lines. If for example I set nline variable to 5. It would loop and print 1, for a total of 5 lines after the initial entry. An example data frame below:

    roll.z.score.n3
1   0
2   0
3   0.651651537
4   -1.153593891
5   -0.926552368
6   -0.369016769
7   0.65405595
8   -1.139305279
9   0.358231351
10  1.135314685
11  0.944997472
12  -0.293105191
13  -1.146659778
14  -0.66246734
15  -1.131901741
16  -0.600480649
17  -1.152333435
18  1.1025176
19  -0.144684006
20  -0.678000883
21  -1.146875039
22  -1.132235788
23  0.115583229
24  0.645489447
25  1.148754398
26  0.988193418
27  -0.818892395

After the script has run I would use zoo to +1 line the sig_long column.

  new.df$sig_long <- Lag(new.df$sig_long,1)

Code Testing

Ok so i see the issue. As we are specifying the first part of the loop to enter and exit between -1.0 and 1.0 this prints 1's between those two criteria in the new.df$sig_long column. The issue arises if I set the nlines to 5. The entry/exit might exit the trade in 3 lines in the sig_long column. If that is the case, rollsum has no 1's to count in that column, even if i want to hold for 5 lines, if theres only 3 1's from entry... its not going to be able to compute the 5 line hold time. Perhaps we can use the first part of the loop like this in order to print a 1 at the entry condition:

new.df$sig_long <- ifelse(new.df$roll.z.score.n3 < -1.0 , 1, 0) #Set 1 at entry criteria

That sets the 1 at each < -1.0 value. Next would be how to count +5 lines from that point forward. Counting until...1,2,3,4,5, else 0... 0, until next +1.... count until 1,2,3,4,5, else 0, 0 until next +1....

I can see the logic... if newdf$sig_long == 1, count until nlines 5, else 0, repeat...

Then the 2nd part of the loop would work I think for the new_sig_long column

Body:
Made many changes. This should now work:

zz = '
    roll.z.score.n3 sig_long
1           NA          0
2           NA          0
3   -1.135974424        0
4   0.193311168         1
5   0.714285714         1
6   -1.148753543        1
7   -0.942160394        1
8   -0.695763683        1
9   1.140646864         1
10  0.985196899         0
11  -0.768766574        0
12  -1.011293858        0
13  -0.516703612        1
14  -1.120897077        1
15  1.091089451         1
16  0.968364052         0
17  0.872871561         0
18  1.099524999         0
19  0.918397948         0
'

df <- read.table(text = zz, header = TRUE)
df = na.omit(df)

df$sig_long[[1]] = ifelse(df$roll.z.score.n3[[1]] < (-1), 1, 0)

for (i in 2:nrow(df)){
  df$sig_long[i] = ifelse(df$roll.z.score.n3[i] < (-1), 1,
                          ifelse(df$roll.z.score.n3[i] > 1, 0,
                                 df$sig_long[i-1]))
}

df$sig_long <- Lag(df$sig_long, 1)
colnames(df[, 2]) = "sig_long"

df = na.omit(df)
nlines = 5

df$rollsum = rollsumr(df$sig_long, k = nlines, fill = 0)
colnames(df[, 3]) = "rollsum"
df$new_sig_long[[1]] = ifelse(df$roll.z.score.n3[[1]] < (-1), 1, 0)

for (i in 2:nrow(df)){
  df$new_sig_long[i] = ifelse(df$roll.z.score.n3[i] < (-1) & df$rollsum[i] < 5, 1,
                              ifelse(df$roll.z.score.n3[i] > 1 | df$rollsum[i] >= 5, 0,
                                     df$sig_long[i-1]))
}

df

Output:

    > df
       roll.z.score.n3 sig_long rollsum new_sig_long
  #  4        0.1933112        1       0            0
  #  5        0.7142857        1       0            1
  #  6       -1.1487535        1       0            1
  #  7       -0.9421604        1       0            1
  #  8       -0.6957637        1       5            0
  #  9        1.1406469        1       5            0
  #  10       0.9851969        0       4            1
  #  11      -0.7687666        0       3            0
  #  12      -1.0112939        0       2            1
  #  13      -0.5167036        1       2            0
  #  14      -1.1208971        1       2            1
  #  15       1.0910895        1       3            0
  #  16       0.9683641        0       3            1
  #  17       0.8728716        0       3            0
  #  18       1.0995250        0       2            0
  #  19       0.9183979        0       1            0

Then you can take the lag of the new_sig_long if you wish.


问:
Not Able to Connect Prod OIM
I have a code that actually able to connect to Lab OIM but same code i am not able to connect to Prod OIM. Below is the code i am using. Did i miss anything? I have all those Jars also in my Project build path. Help and any suggestion will be appreciated. Below are the code and error i am getting after debugging the class.

```<code> public class ConnectionTest {
         UserManager userManager;

          public ConnectionTest() {
                  super();
                }
   public static void main(String[] arg) throws IOException, Exception {

    ConnectionTest oim=new ConnectionTest();
    oim.OIMConnection();
}
 public void OIMConnection(){
    Hashtable<Object, Object> env = new Hashtable<Object, Object>();
    env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL, "weblogic.jndi.WLInitialContextFactory");
    env.put(OIMClient.JAVA_NAMING_PROVIDER_URL, "t3://hostname:port");
    System.setProperty("java.security.auth.login.config", "C:\\Documents\\authwl.conf");
    System.setProperty("OIM.AppServerType", "wls");
    System.setProperty("APPSERVER_TYPE", "wls");
    oracle.iam.platform.OIMClient oimClient = new oracle.iam.platform.OIMClient(env);

    try {
        oimClient.login("username", "password".toCharArray());
        logger.info("Successfully Connected with OIM!\n");
    } catch (LoginException e) {
        CharArrayWriter cw = new CharArrayWriter();
        PrintWriter w = new PrintWriter(cw);
        e.printStackTrace(w);
        logger.error("Login Exception: "+ cw.toString());
    }
    userManager = oimClient.getService(UserManager.class);
}}
</code>```

Error I am getting is here.....

Login Exception: javax.security.auth.login.LoginException: weblogic.socket.UnrecoverableConnectException: [Login failed for an unknown reason:  P] at weblogic.security.auth.login.UsernamePasswordLoginModule.login(UsernamePasswordLoginModule.java:194)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at javax.security.auth.login.LoginContext.invoke(LoginContext.java:762)
    at javax.security.auth.login.LoginContext.access$000(LoginContext.java:203)
    at javax.security.auth.login.LoginContext$4.run(LoginContext.java:690)
    at javax.security.auth.login.LoginContext$4.run(LoginContext.java:688)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:687)
    at javax.security.auth.login.LoginContext.login(LoginContext.java:595)
    at Thor.API.Security.LoginHandler.weblogicLoginHandler.login(weblogicLoginHandler.java:61)
    at oracle.iam.platform.OIMClient.login(OIMClient.java:212)
    at oracle.iam.platform.OIMClient.login(OIMClient.java:196)
    at org.com.dis.exa.ConnectionTest.OIMConnection(ConnectionTest.java:73)
    at org.com.dis.exa.ConnectionTest.main(ConnectionTest.java:53)

答:
Check username and password.

Get wlfullclient.jar from Prod(not Lab).

Check C:\Documents\authwl.conf. It is Prod's file?

refer my sample:

```<code>public static final String OIM_HOSTNAME = "oim.hpt.lab";
public static final String OIM_PORT = "14000";
public static final String OIM_PROVIDER_URL = "t3://"+ OIM_HOSTNAME + ":" + OIM_PORT;
public static final String OIM_USERNAME = "tungpt";
public static final String OIM_PASSWORD = "Hpt123456";
public static final String OIM_CLIENT_HOME = "F:/designconsole11gr3/config";
public static final String AUTHWL_PATH = OIM_CLIENT_HOME + "/authwl.conf";

public static void main(String[] args) {
    // TODO Auto-generated method stub
    OIMClient oimClient = null;
    try {
        //Set system properties required for OIMClient
        System.setProperty("java.security.auth.login.config", AUTHWL_PATH);
        System.setProperty("APPSERVER_TYPE", "wls");

        // Create an instance of OIMClient with OIM environment information
        Hashtable env = new Hashtable();
        env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL, "weblogic.jndi.WLInitialContextFactory");
        env.put(OIMClient.JAVA_NAMING_PROVIDER_URL, OIM_PROVIDER_URL);
        oimClient = new OIMClient(env);

        // Login to OIM with the approriate credentials
        System.out.println("Login by: "+ OIM_USERNAME);
        oimClient.login(OIM_USERNAME, OIM_PASSWORD.toCharArray());
        System.out.println("Login Done!");
    }catch(Exception e){
        e.printStackTrace();
    }
}
</code>```

Title: Not Able to Connect Prod OIM

Body:
I have a code that actually able to connect to Lab OIM but same code i am not able to connect to Prod OIM. Below is the code i am using. Did i miss anything? I have all those Jars also in my Project build path. Help and any suggestion will be appreciated. Below are the code and error i am getting after debugging the class.

 public class ConnectionTest {
         UserManager userManager;

          public ConnectionTest() {
                  super();
                }
   public static void main(String[] arg) throws IOException, Exception {

    ConnectionTest oim=new ConnectionTest();
    oim.OIMConnection();
}
 public void OIMConnection(){
    Hashtable<Object, Object> env = new Hashtable<Object, Object>();
    env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL, "weblogic.jndi.WLInitialContextFactory");
    env.put(OIMClient.JAVA_NAMING_PROVIDER_URL, "t3://hostname:port");
    System.setProperty("java.security.auth.login.config", "C:\\Documents\\authwl.conf");
    System.setProperty("OIM.AppServerType", "wls");
    System.setProperty("APPSERVER_TYPE", "wls");
    oracle.iam.platform.OIMClient oimClient = new oracle.iam.platform.OIMClient(env);

    try {
        oimClient.login("username", "password".toCharArray());
        logger.info("Successfully Connected with OIM!\n");
    } catch (LoginException e) {
        CharArrayWriter cw = new CharArrayWriter();
        PrintWriter w = new PrintWriter(cw);
        e.printStackTrace(w);
        logger.error("Login Exception: "+ cw.toString());
    }
    userManager = oimClient.getService(UserManager.class);
}}

Error I am getting is here.....

Login Exception: javax.security.auth.login.LoginException: weblogic.socket.UnrecoverableConnectException: [Login failed for an unknown reason:  P] at weblogic.security.auth.login.UsernamePasswordLoginModule.login(UsernamePasswordLoginModule.java:194)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at javax.security.auth.login.LoginContext.invoke(LoginContext.java:762)
    at javax.security.auth.login.LoginContext.access$000(LoginContext.java:203)
    at javax.security.auth.login.LoginContext$4.run(LoginContext.java:690)
    at javax.security.auth.login.LoginContext$4.run(LoginContext.java:688)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:687)
    at javax.security.auth.login.LoginContext.login(LoginContext.java:595)
    at Thor.API.Security.LoginHandler.weblogicLoginHandler.login(weblogicLoginHandler.java:61)
    at oracle.iam.platform.OIMClient.login(OIMClient.java:212)
    at oracle.iam.platform.OIMClient.login(OIMClient.java:196)
    at org.com.dis.exa.ConnectionTest.OIMConnection(ConnectionTest.java:73)
    at org.com.dis.exa.ConnectionTest.main(ConnectionTest.java:53)

Body:
Check username and password.

Get wlfullclient.jar from Prod(not Lab).

Check C:\Documents\authwl.conf. It is Prod's file?

refer my sample:

public static final String OIM_HOSTNAME = "oim.hpt.lab";
public static final String OIM_PORT = "14000";
public static final String OIM_PROVIDER_URL = "t3://"+ OIM_HOSTNAME + ":" + OIM_PORT;
public static final String OIM_USERNAME = "tungpt";
public static final String OIM_PASSWORD = "Hpt123456";
public static final String OIM_CLIENT_HOME = "F:/designconsole11gr3/config";
public static final String AUTHWL_PATH = OIM_CLIENT_HOME + "/authwl.conf";

public static void main(String[] args) {
    // TODO Auto-generated method stub
    OIMClient oimClient = null;
    try {
        //Set system properties required for OIMClient
        System.setProperty("java.security.auth.login.config", AUTHWL_PATH);
        System.setProperty("APPSERVER_TYPE", "wls");

        // Create an instance of OIMClient with OIM environment information
        Hashtable env = new Hashtable();
        env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL, "weblogic.jndi.WLInitialContextFactory");
        env.put(OIMClient.JAVA_NAMING_PROVIDER_URL, OIM_PROVIDER_URL);
        oimClient = new OIMClient(env);

        // Login to OIM with the approriate credentials
        System.out.println("Login by: "+ OIM_USERNAME);
        oimClient.login(OIM_USERNAME, OIM_PASSWORD.toCharArray());
        System.out.println("Login Done!");
    }catch(Exception e){
        e.printStackTrace();
    }
}


问:
JQuery append method multiple parent elements append same element
As the API document declared:

If an element selected this way is inserted into a single location
  elsewhere in the DOM, it will be moved into the target (not cloned).
  Important: If there is more than one target element, however, cloned
  copies of the inserted element will be created for each target except
  for the last one.

```<code>var div = $("<div></div>").addClass("divCells"),
    tdName = $("<td></td>").addClass("tdName"),
    tdAge = $("<td></td>").addClass("tdAge"),
    tdGender = $("<td></td>").addClass("tdGender"),
    tds = [tdName, tdAge, tdGender],
    tr = $("<tr></tr>"),
    tbody = $("#peopleList tbody");
    tds.append(div);
    tr.append(tdName).append(tdAge).append(tdTimetdGenderstamp);
    tbody.append(tr);
</code>```

As above code represents, I try to include the 3 tds in to an Array, so that I could append div into all of them, but it is not working.

答:
You're trying to use jQuery .append on a vanilla JavaScript Array.  .append only works on jQuery/DOM elements, not JavaScript types such as Arrays.

Your tds array contains jQuery/DOM elements, but the Array itself isn't 'appendable' in the manner you're attempting.

Using an Array, you'll have to iterate through your array, and manually append the div to each element in it.  Furthermore, since you will be appending to 3 separate elements individually (i.e. 1 per iteration, not all 3 at the same time) you'll have to manually .clone the div yourself, otherwise you'll just be appending the one div to the 1st item in the Array, and then moving the same div to the 2nd, and again to the 3rd. So...

```<code>// tds.append(div); // Change this to...
for (var i=0; i< tds.length; i++) {
   tds[i].append(div.clone())
}
</code>```

OR...

You could forget about using the Array altogether, and have jQuery clone and append the div for you (as your original question implied).  Here's how...

```<code>// Remove the following lines...
// tds = [tdName, tdAge, tdGender],
// tds.append(div);

// Then, after you add the td's to your row here...
tr.append(tdName).append(tdAge).append(tdGender);

// ...have jQuery find all the td's and clone+append your div to them in one hit:
tr.find('td').append(div)
</code>```

Body:
As the API document declared:

If an element selected this way is inserted into a single location
  elsewhere in the DOM, it will be moved into the target (not cloned).
  Important: If there is more than one target element, however, cloned
  copies of the inserted element will be created for each target except
  for the last one.

var div = $("

").addClass("divCells"),
    tdName = $("	").addClass("tdName"),
    tdAge = $("	").addClass("tdAge"),
    tdGender = $("	").addClass("tdGender"),
    tds = [tdName, tdAge, tdGender],
    tr = $("

"),
    tbody = $("#peopleList tbody");
    tds.append(div);
    tr.append(tdName).append(tdAge).append(tdTimetdGenderstamp);
    tbody.append(tr);

As above code represents, I try to include the 3 tds in to an Array, so that I could append div into all of them, but it is not working.

Body:
You're trying to use jQuery .append on a vanilla JavaScript Array.  .append only works on jQuery/DOM elements, not JavaScript types such as Arrays.

Your tds array contains jQuery/DOM elements, but the Array itself isn't 'appendable' in the manner you're attempting.

Using an Array, you'll have to iterate through your array, and manually append the div to each element in it.  Furthermore, since you will be appending to 3 separate elements individually (i.e. 1 per iteration, not all 3 at the same time) you'll have to manually .clone the div yourself, otherwise you'll just be appending the one div to the 1st item in the Array, and then moving the same div to the 2nd, and again to the 3rd. So...

// tds.append(div); // Change this to...
for (var i=0; i< tds.length; i++) {
   tds[i].append(div.clone())
}

OR...

You could forget about using the Array altogether, and have jQuery clone and append the div for you (as your original question implied).  Here's how...

// Remove the following lines...
// tds = [tdName, tdAge, tdGender],
// tds.append(div);

// Then, after you add the td's to your row here...
tr.append(tdName).append(tdAge).append(tdGender);

// ...have jQuery find all the td's and clone+append your div to them in one hit:
tr.find('td').append(div)


问:
PHP files and folder structure showing, need to hide it
I have the following folder structure:

```<code>+users
   -adduser.php
   -viewuser.php
</code>```

When a visitor navigates to example.com/users it's showing the folder structure. I need to restrict visitors ability to see the file listing, either by hiding it or removing it. How can I do that in php?

答:
You can add the following to your Apache virtual host file:

```<code><Directory "path_to_folder">
    Options -Indexes
</Directory>
</code>```

The above rule will disallow directory listing. It was suggested in this post: Using .htaccess, prevent users from accessing resource directories, and yet allow the sourcecode access resources

Body:
I have the following folder structure:

+users
   -adduser.php
   -viewuser.php

When a visitor navigates to example.com/users it's showing the folder structure. I need to restrict visitors ability to see the file listing, either by hiding it or removing it. How can I do that in php?

Body:
You can add the following to your Apache virtual host file:

<Directory "path_to_folder">
    Options -Indexes
</Directory>

The above rule will disallow directory listing. It was suggested in this post: Using .htaccess, prevent users from accessing resource directories, and yet allow the sourcecode access resources


问:
Sending data with Segue with Swift
I have two view controllers and two views.
In my first view, I set the variable 'currentUser' to false.
I need to be able to set 'currentUser' to true in the second view controller.

When trying to reference 'currentUser' from the second view it's not picking it up as 'currentUser' is defined in the first view controller.

How do I carry across variables with segue?

答:
The function that should be defined as override is:</p>

```<code>open func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "Segue Name Defined In Storyboard") {
        //set the property of the designated view controller with the value you need
    }
}
</code>```

Title: Sending data with Segue with Swift

Body:
The function that should be defined as override is:

open func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "Segue Name Defined In Storyboard") {
        //set the property of the designated view controller with the value you need
    }
}


问:
What is the best way to deal with CSS style conflicts in React application which has dashboard and landing?
I'm not really into styling, I'm a programmer, so maybe I'm doing something wrong but I can't figure out how to deal with this problem:
I have a SPA on reactjs which has admin dashboard and a landing page. Depending on whether user is logged in or not, different module is rendered on the same domain and url.
The index.html page is very simple:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title></title>

</head>
<body>

<div id="app">
</div>
</body>
</html>
</code>```

There's a session check in index.js, and if user is logged in Dashboard is rendered to the app div instead of Landing.
I didn't create dashboard style myself, I took a bootstrap template from the Internet with it's custom styles of course. I also have styles.scss file with the following contents:

```<code>@import "./custom";
@import "./font-awesome";
@import "./app/admin";
@import "./app/daterangepicker";
@import "./app/nprogress";
@import "./app/skin";
@import "./bootstrap";
</code>```

This file is imported to index.js.
The problem is that dashboard's custom styles conflict with my landing page's (which is also built with bootstrap) css styles.

So my first idea was to create 2 scss files with imports, one for dashboard and one for landing. But is there any way to attach different css files depending on what part of the application must be rendered and to be able to do it in a conditional statement without reloading the whole page in the browser?
Or maybe there are some better ideas to get around this problem?

答:
This is generally a hard problem to solve nicely after-the-fact. These css specificity and shadowing problems have not had nice solutions, in my experience, but you have some options.

You can give some top-level component for these two views an additional className based on the page and then scope your scss bundle, or the specific custom styles you need to take precedence, under that class. For example, say that app.scss has all the styles:

```<code>#app {
    // shared styles

    &.landing-page {
        // landing-page specific styles
        .bootstrap-component {
            color: blue;
        }
    }

    &.dashboard {
        // dashboard-specific styles
        .bootstrap-component {
            color: red;
        }
    }
}
</code>```

A cause of this problem is simply that you have two different custom styles for similar components that use the same classes. As best you can, try to be consistent in the UI for a component so that the same component uses the same styles, with minor modifications applied through new classes. If that's not possible, maybe there is a different way to approach styling these components:

The changes to Bootstrap styles shared between the two pages can be made as custom styles to that class but differences in the components' styles should be brought out instead, as modifiers to that component. Using the BEM class naming convention really helped me to do this better: brief | more helpful

For example, if Bootstrap had a header component and both your dashboard and landing page wanted it to be green rather than blue, include that in your changes to bootstrap's styles. If the header, however, is smaller on the dashboard page and bigger on the landing page, those changes can be applied by new classes altogether.

If the server knows the authentication status beforehand (via some token - which it likely does), you can serve different html pages or different versions of the css. This kind of combines server-side rendering with some smart css minification. I don't think that's what you're looking for, but is possible depending on the scope of your project. I think that the point mentioned about about trying to isolate the shared and unqiue styles to a component is a better route, though.

Body:
I'm not really into styling, I'm a programmer, so maybe I'm doing something wrong but I can't figure out how to deal with this problem:
I have a SPA on reactjs which has admin dashboard and a landing page. Depending on whether user is logged in or not, different module is rendered on the same domain and url.
The index.html page is very simple:

<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title></title>

There's a session check in index.js, and if user is logged in Dashboard is rendered to the app div instead of Landing.
I didn't create dashboard style myself, I took a bootstrap template from the Internet with it's custom styles of course. I also have styles.scss file with the following contents:

@import "./custom";
@import "./font-awesome";
@import "./app/admin";
@import "./app/daterangepicker";
@import "./app/nprogress";
@import "./app/skin";
@import "./bootstrap";

This file is imported to index.js.
The problem is that dashboard's custom styles conflict with my landing page's (which is also built with bootstrap) css styles.

So my first idea was to create 2 scss files with imports, one for dashboard and one for landing. But is there any way to attach different css files depending on what part of the application must be rendered and to be able to do it in a conditional statement without reloading the whole page in the browser?
Or maybe there are some better ideas to get around this problem?

Body:
This is generally a hard problem to solve nicely after-the-fact. These css specificity and shadowing problems have not had nice solutions, in my experience, but you have some options.

You can give some top-level component for these two views an additional className based on the page and then scope your scss bundle, or the specific custom styles you need to take precedence, under that class. For example, say that app.scss has all the styles:

#app {
    // shared styles

    &.landing-page {
        // landing-page specific styles
        .bootstrap-component {
            color: blue;
        }
    }

    &.dashboard {
        // dashboard-specific styles
        .bootstrap-component {
            color: red;
        }
    }
}

A cause of this problem is simply that you have two different custom styles for similar components that use the same classes. As best you can, try to be consistent in the UI for a component so that the same component uses the same styles, with minor modifications applied through new classes. If that's not possible, maybe there is a different way to approach styling these components:

The changes to Bootstrap styles shared between the two pages can be made as custom styles to that class but differences in the components' styles should be brought out instead, as modifiers to that component. Using the BEM class naming convention really helped me to do this better: brief | more helpful

For example, if Bootstrap had a header component and both your dashboard and landing page wanted it to be green rather than blue, include that in your changes to bootstrap's styles. If the header, however, is smaller on the dashboard page and bigger on the landing page, those changes can be applied by new classes altogether.

If the server knows the authentication status beforehand (via some token - which it likely does), you can serve different html pages or different versions of the css. This kind of combines server-side rendering with some smart css minification. I don't think that's what you're looking for, but is possible depending on the scope of your project. I think that the point mentioned about about trying to isolate the shared and unqiue styles to a component is a better route, though.


问:
join performance temp table in sql
In my database for somereasons not all table have foreign key
then for have  a better performance I used a select into (with data filtered) in a temp table , I did this for the tables I'll use for to have a better performance but now....

In the final result when I need do join between those table (temp table can't have foreign key, isn't it?) do not have foreign key I got "Merge Join" (I understand they are caused because my temp table does not have foreign key)

(If you dont see the pic I reupload it at here)
https://ibb.co/f0XRHv

答:
How about using something like suggested in the following answer?

No foreign key restraints on a temporary table? SQL Server 2008

Title: join performance temp table in sql


问:
why is my time/date picker formatting adding minutes?
I have both a time picker and a date picker in my template. The values store to my database together as one numeric string, so I have to do a few steps to parse them from one another in the right formats when I interpolate them to my template in the required places on a different page. First I call a formatting function to separate the values and then I run it through an angular-moment pipe to convert the military time to standard 12 hour time.

I noticed that consistently when I pick a time, say 7:00 or 12:00 on the time picker, it will interpolate to my template as 7:08 or 12:08. Why is it adding minutes?

THIS IS HOW I SAVE THE DATE AND TIME TO THE DATABASE

```<code>constructor(//controllers n stuff) {

//empty event object

      this.event = {
        hostName : "",
        hostId: "",
        hostPhoto : "",
        coverCharge: 0,
        drinkMin: false,
        reimburse: false,
        venue : "",
        guests : 0,
        date : "",
        time : "",
        city : "",
        eventTime : "",
        createdTime: "",
        volunteers : 0

      }
}//close constructor

addEvent(){

    let authData = OnymosAccess.getAuth(); //GET DATABASE AUTH
            this.event.hostName = authData.userName;
            this.event.hostId = authData.userId;
            this.event.hostPhoto = authData.userPhoto();
          **this.event.eventTime = new Date(this.event.date + " " + this.event.time).getTime();**
            this.event.createdTime = Date.now();

            let that = this;

                OnymosUtil.addData( //SEND TO DATABASE

        '/events/' + this.event.city + '/' + this.event.createdTime,
                        this.event,

        function optionalSuccessCallback (statusMessage) {
                            console.log(statusMessage);

                            that.saveStatus = "successfully saved";
                         },

            function optionalFailureCallback (error) {

                            that.saveStatus = "failed saving" + error;
                        });
}//end addEvent
</code>```

HTML TEMPLATE

```<code><ion-row>
                <ion-col>
                    <ion-icon name="calendar"></ion-icon>
                    <BR>
                    **{{getFormattedTime(event.eventTime, 'MM-dd-yyyy')}}**
                </ion-col>
                <ion-col>
                    <ion-icon name="clock"></ion-icon>
                    <BR>
                    **{{ getFormattedTime(event.eventTime,'HH:MM' ) | amParse:'HH:mm' | amDateFormat:'hh:mm A' }}**

                </ion-col>
</code>```

THE GET FORMATTED TIME FUNCTION I RUN THE TIME THROUGH BEFORE I USE MOMENT.

```<code>getFormattedTime (time, format) {
        var t = new Date(time);
        var tf = function (i) { return (i < 10 ? '0' : '') + i };
        return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
            switch (a) {
                case 'yyyy':
                    return tf(t.getFullYear());

                case 'MM':
                    return tf(t.getMonth() + 1);

                case 'mm':
                    return tf(t.getMinutes());

                case 'dd':
                    return tf(t.getDate());

                case 'HH':
                    return tf(t.getHours());

                case 'ss':
                    return tf(t.getSeconds());

            }
        })
    } // end of getFormattedTime
</code>```

答:
```<code><ion-col>
     <ion-icon name="calendar"></ion-icon>
     <BR>
     **{{getFormattedTime(event.eventTime, 'MM-dd-yyyy')}}**
</ion-col>
<ion-col>
     <ion-icon name="clock"></ion-icon>
     <BR>
     **{{ getFormattedTime(event.eventTime,'HH:mm' ) | amParse:'HH:mm' | amDateFormat:'hh:mm A' }}**
</ion-col>
</code>```

You have to use getFormattedTime(event.eventTime,'HH:mm' ). In your code you are using getFormattedTime(event.eventTime,'HH:MM' ) MM will return month

MM- Months,
mm -Minutes

Body:
I have both a time picker and a date picker in my template. The values store to my database together as one numeric string, so I have to do a few steps to parse them from one another in the right formats when I interpolate them to my template in the required places on a different page. First I call a formatting function to separate the values and then I run it through an angular-moment pipe to convert the military time to standard 12 hour time.

I noticed that consistently when I pick a time, say 7:00 or 12:00 on the time picker, it will interpolate to my template as 7:08 or 12:08. Why is it adding minutes?

THIS IS HOW I SAVE THE DATE AND TIME TO THE DATABASE

constructor(//controllers n stuff) {

//empty event object

      this.event = {
        hostName : "",
        hostId: "",
        hostPhoto : "",
        coverCharge: 0,
        drinkMin: false,
        reimburse: false,
        venue : "",
        guests : 0,
        date : "",
        time : "",
        city : "",
        eventTime : "",
        createdTime: "",
        volunteers : 0

      }
}//close constructor

addEvent(){

    let authData = OnymosAccess.getAuth(); //GET DATABASE AUTH
            this.event.hostName = authData.userName;
            this.event.hostId = authData.userId;
            this.event.hostPhoto = authData.userPhoto();
          **this.event.eventTime = new Date(this.event.date + " " + this.event.time).getTime();**
            this.event.createdTime = Date.now();

            let that = this;

                OnymosUtil.addData( //SEND TO DATABASE

        '/events/' + this.event.city + '/' + this.event.createdTime,
                        this.event,

        function optionalSuccessCallback (statusMessage) {
                            console.log(statusMessage);

                            that.saveStatus = "successfully saved";
                         },

            function optionalFailureCallback (error) {

                            that.saveStatus = "failed saving" + error;
                        });
}//end addEvent

HTML TEMPLATE

<ion-row>
                <ion-col>
                    <ion-icon name="calendar"></ion-icon>

                    **{{getFormattedTime(event.eventTime, 'MM-dd-yyyy')}}**
                </ion-col>
                <ion-col>
                    <ion-icon name="clock"></ion-icon>

                    **{{ getFormattedTime(event.eventTime,'HH:MM' ) | amParse:'HH:mm' | amDateFormat:'hh:mm A' }}**

                </ion-col>

THE GET FORMATTED TIME FUNCTION I RUN THE TIME THROUGH BEFORE I USE MOMENT.

getFormattedTime (time, format) {
        var t = new Date(time);
        var tf = function (i) { return (i < 10 ? '0' : '') + i };
        return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
            switch (a) {
                case 'yyyy':
                    return tf(t.getFullYear());

                case 'MM':
                    return tf(t.getMonth() + 1);

                case 'mm':
                    return tf(t.getMinutes());

                case 'dd':
                    return tf(t.getDate());

                case 'HH':
                    return tf(t.getHours());

                case 'ss':
                    return tf(t.getSeconds());

            }
        })
    } // end of getFormattedTime

Body:
<ion-col>
     <ion-icon name="calendar"></ion-icon>
     <BR>
     **{{getFormattedTime(event.eventTime, 'MM-dd-yyyy')}}**
</ion-col>
<ion-col>
     <ion-icon name="clock"></ion-icon>
     <BR>
     **{{ getFormattedTime(event.eventTime,'HH:mm' ) | amParse:'HH:mm' | amDateFormat:'hh:mm A' }}**
</ion-col>

You have to use getFormattedTime(event.eventTime,'HH:mm' ). In your code you are using getFormattedTime(event.eventTime,'HH:MM' ) MM will return month

MM- Months,
mm -Minutes


问:
Majority element in an array.It
```<code>#include <stdio.h>

void main()
{
    int maj, count, n = 6;
    int arr[] = {1, 2, 2, 2, 2, 3, 4};

    for (int i = 0; i < n; i++) {
        maj = arr[i];
        count = 0;
        for (int j = 9; j < n; j++) {
            if (arr[j] == maj) count++;
        }
        if (count > n / 2) {
            break; /* I think some problem is here ,if majority element not found then it takes last element as the majority element */
        }
    }
    printf("%d", maj);
}
</code>```

It is giving correct output if majority ellement is there but incorrect output if no majority element is there for example if array is {1,2,3,4} it is giving output as 4. please help!!

答:
```<code>#include <stdio.h>
int main() {
    int maj, count, n = 7; //n is size of arr
    int arr[] = {1, 2, 2, 2, 2, 3, 4};
    int isFound = 0; //0 -> false, 1 -> true

    for (int i = 0; i < n; i++) {
        maj = arr[i];
        count = 1;  //first elements is itself
        isFound = 0;  //by default we assume that no major elements is found

        for (int j = i+1; j < n; j++) { //iterate from next elements onwards to right in array
            if (arr[j] == maj) count++;
        }
        if (count > n / 2) {
            isFound = 1;
            break; //major elements found; no need to iterator further; just break the loop now
        }
    }
    if(isFound)   printf("%d ", maj);
    else printf("no major element");
    return 0;
}
</code>```

Title: Majority element in an array.It

Body:
#include <stdio.h>

void main()
{
    int maj, count, n = 6;
    int arr[] = {1, 2, 2, 2, 2, 3, 4};

    for (int i = 0; i < n; i++) {
        maj = arr[i];
        count = 0;
        for (int j = 9; j < n; j++) {
            if (arr[j] == maj) count++;
        }
        if (count > n / 2) {
            break; /* I think some problem is here ,if majority element not found then it takes last element as the majority element */
        }
    }
    printf("%d", maj);
}

It is giving correct output if majority ellement is there but incorrect output if no majority element is there for example if array is {1,2,3,4} it is giving output as 4. please help!!


问:
Why do we need an Object Relational Mapper?
I bought a book on Hibernate.  I wanted to learn on what Hibernate is and what is Object Relational Mapping in general.

Harnessing Hibernate has good topics on Hibernate and I do think that I am able to write simple mapping classes now. My problem is, I think I am way ahead on the Hibernate but I really don't know why we need one.

The book explains Hibernate clearly but I think I am at lost because it does not discuss why we need Hibernate and an ORM.

答:
I too would suggest starting at wikipedia.

From there, follow the links at the bottom.

To provide a short answer: An ORM is used to abstract from the data storage, usually a database. This can serve multiple purposes, among those:

Application programmers can add and
maintain functionality of the
software without in-depth knowledge
of the database (you can write your
code in Java, not in SQL).

It takes away the pitfalls of having
to assemble your SQL statements as
strings and therefore eliminates a
huge source of errors.

Database optimization is independent
from business logic. This ensures
better maintainability.  The
optimization can either be done by
the ORM ( via configuration files) or
directly in the database (by manually
adding index tables and/or query
caches). Both will not take place in
the actual program code.

Data providers can more easily be
exchanged, because the ORM usually
offers drivers for multiple
databases, so that the same
functional logic will work with
different products and vendors.

ContentLicense: CC BY-SA 2.5


问:
Why is a javascript object literal in memory so much bigger than its text file size in JSON form?
I have a huge JSON (let's call it {...}) which is about 80 MB. All keys/values are strings or objects. I expect that if I load it into javascript by saying var myJson = {...}, the amount of memory it takes up should be not too much bigger than 80 MB. However, using node.js's process.memoryUsage(), I see that as soon as I load this object my memory used increases by about 600 MB. Why does this happen, and what are some workarounds? </p>

<p>Edit: I have changed it from var myJSon = {...} to const myJson = require('./database.json'), with the contents of the json in a .json file rather than a .js file. Strangely, this seemed to reduce the amount of memory used by 50%, so still about 4x as large as the .json file. </p>

答:
There is a gap between JSON text file size and JSON object memory size.

"the amount of memory it takes up should be not too much bigger than 80 MB" -- That's not true, especially when the object is very big.

According to ECMAScript Language Specification, each string character will occupy 16 bits, and each number value will occupy 64 bits. This means there is a huge gap between JSON text file size and JSON object memory size.

Take the following simple object for example: {name:'John',age:16}. Saving this object as a text file only need 20 ascii characters, which means 20 Bytes. However, store this JSON object in memory needs at least 30 bytes ("name".length + "John".length + "age".length = 11, with each character occupy 2 Bytes, it is 22 Bytes; plus the 8 Bytes used for 16, in all, it needs 30 Bytes.).

The internal object structure ("John" is mapping to "name", and 16 is mapping to "age") also occupy memory. Even without this consideration, the gap between 20 Bytes and 30 Bytes is already big for such a simple object.

The gap would be very big if the JSON object is huge (like the one in question), or if the JSON object structure is very complex.

Of course, JavaScript engine will do some optimization work and reduce the usage of memory. But as ECMAScript specification already stated the bits usage of string and number etc., the gap would alway exist, and such gap is not trivial.

p.s. There is a npm module called object-sizeof, which can be used to estimate object memory allocation.

Body:
I have a huge JSON (let's call it {...}) which is about 80 MB. All keys/values are strings or objects. I expect that if I load it into javascript by saying var myJson = {...}, the amount of memory it takes up should be not too much bigger than 80 MB. However, using node.js's process.memoryUsage(), I see that as soon as I load this object my memory used increases by about 600 MB. Why does this happen, and what are some workarounds?

Edit: I have changed it from var myJSon = {...} to const myJson = require('./database.json'), with the contents of the json in a .json file rather than a .js file. Strangely, this seemed to reduce the amount of memory used by 50%, so still about 4x as large as the .json file.


问:
choicemodelr: Error in Ops.data.frame: '==' only defined for equally-sized data frames
I am analyzing data from a conjoint (test data) to get prepared for real data.

The data file has the form as required (UnitID Set Alt X_1 ... X_natts y) were y is discrete. In each choice set I have 3 alternatives (alt: 1-3) as well as a no choice option (alt: 4). The independent variables are effect coded (1, 0, -1). As far as I can see, that data are in the required format.

However, I can’t estimate the coefficients. If I run the model without demographic variables I get the following error:

Error in Ops.data.frame(data[, 1], ID[i]) :

‘==’ only defined for equally-sized data frames

Using the demographic variables I get the following:

Error: number of rows in demos does not equal number of units

I do not find an error explanation in the internet so far and does not know how to solve this issue. I guess, it is a simple mistake in the data file that I do not see. I already tried to use a different coding but I get the same errors. Here is the code I use:

```<code>> xcoding=c(0,0,0,0,0,0,0,0,0,0,0,0,0,0)
> mcmc = list(R = 20000, use = 10000)
> options = list(none=FALSE, save=TRUE, keep=1)
> out = choicemodelr(data=robottest_bayes, xcoding, mcmc = mcmc, options = options)
> #with demographic variables
> out = choicemodelr(data=robottest_bayes, demos=robottest_bayes_demo, xcoding, mcmc = mcmc, options = options)
</code>```

The data files are the following:

```<code>    > show(robottest_bayes)
# A tibble: 8,464 × 18
   respid  ques   alt apperance_burly apperance_intelligent apperance_pink features_car features_laundry features_compute
    <int> <int> <int>           <int>                 <int>          <int>        <int>            <int>            <int>
1       1     1     1               1                     0              0            1                0                0
2       1     1     2               0                     1              0            0                1                0
3       1     1     3               0                     0              1            0                0                1
4       1     1     4               0                     0              0            0                0                0
5       1     2     1               0                     1              0            0                0                0
6       1     2     2               0                     0              1            0                0                0
7       1     2     3               1                     0              0            0                0                0
8       1     2     4               0                     0              0            0                0                0
9       1     3     1               0                     0              1            0                0                0
10      1     3     2               1                     0              0            0                0                0
# ... with 8,454 more rows, and 9 more variables: features_dog <int>, features_vaccuum <int>, features_splines <int>,
#   brand_botpro <int>, brand_gizmobot <int>, price_10 <int>, price_11 <int>, nochoice <int>, choice <int>

> show(robottest_bayes_demo)
# A tibble: 529 × 3
   respid   sex   age
    <int> <int> <int>
1       1     0    42
2       2     0    55
3       3     0    37
4       4     0    35
5       5     1    41
6       6     1    35
7       7     0    56
8       8     0    27
9       9     1    36
10     10     1    42
# ... with 519 more rows
</code>```

答:
You may try to exclude the rows of no choice option from the data file, and amend the script as:

```<code>options = list(none=TRUE, save=TRUE, keep=1)
</code>```

As you have 3 alternatives, for the choice set which the respondent chose the "no choice option", the choice number will be "number of alternatives +1", that is, 4. The ChoiceModelR will recognise that the "no choice option" is selected.

According to p. 5 of the vignette of ChoiceModelR,

none: set to TRUE to estimate a none parameter, and the data does not include a row for “none” (i.e., no choice) (default is FALSE).

Try whether it works.

ContentLicense: CC BY-SA 4.0

Body:
I am analyzing data from a conjoint (test data) to get prepared for real data.

The data file has the form as required (UnitID Set Alt X_1 ... X_natts y) were y is discrete. In each choice set I have 3 alternatives (alt: 1-3) as well as a no choice option (alt: 4). The independent variables are effect coded (1, 0, -1). As far as I can see, that data are in the required format.

However, I can’t estimate the coefficients. If I run the model without demographic variables I get the following error:

Error in Ops.data.frame(data[, 1], ID[i]) :

‘==’ only defined for equally-sized data frames

Using the demographic variables I get the following:

Error: number of rows in demos does not equal number of units

I do not find an error explanation in the internet so far and does not know how to solve this issue. I guess, it is a simple mistake in the data file that I do not see. I already tried to use a different coding but I get the same errors. Here is the code I use:

> xcoding=c(0,0,0,0,0,0,0,0,0,0,0,0,0,0)
> mcmc = list(R = 20000, use = 10000)
> options = list(none=FALSE, save=TRUE, keep=1)
> out = choicemodelr(data=robottest_bayes, xcoding, mcmc = mcmc, options = options)
> #with demographic variables
> out = choicemodelr(data=robottest_bayes, demos=robottest_bayes_demo, xcoding, mcmc = mcmc, options = options)

The data files are the following:

    > show(robottest_bayes)
# A tibble: 8,464 × 18
   respid  ques   alt apperance_burly apperance_intelligent apperance_pink features_car features_laundry features_compute
    <int> <int> <int>           <int>                 <int>          <int>        <int>            <int>            <int>
1       1     1     1               1                     0              0            1                0                0
2       1     1     2               0                     1              0            0                1                0
3       1     1     3               0                     0              1            0                0                1
4       1     1     4               0                     0              0            0                0                0
5       1     2     1               0                     1              0            0                0                0
6       1     2     2               0                     0              1            0                0                0
7       1     2     3               1                     0              0            0                0                0
8       1     2     4               0                     0              0            0                0                0
9       1     3     1               0                     0              1            0                0                0
10      1     3     2               1                     0              0            0                0                0
# ... with 8,454 more rows, and 9 more variables: features_dog <int>, features_vaccuum <int>, features_splines <int>,
#   brand_botpro <int>, brand_gizmobot <int>, price_10 <int>, price_11 <int>, nochoice <int>, choice <int>

> show(robottest_bayes_demo)
# A tibble: 529 × 3
   respid   sex   age
    <int> <int> <int>
1       1     0    42
2       2     0    55
3       3     0    37
4       4     0    35
5       5     1    41
6       6     1    35
7       7     0    56
8       8     0    27
9       9     1    36
10     10     1    42
# ... with 519 more rows

Body:
You may try to exclude the rows of no choice option from the data file, and amend the script as:

options = list(none=TRUE, save=TRUE, keep=1)

As you have 3 alternatives, for the choice set which the respondent chose the "no choice option", the choice number will be "number of alternatives +1", that is, 4. The ChoiceModelR will recognise that the "no choice option" is selected.

According to p. 5 of the vignette of ChoiceModelR,

none: set to TRUE to estimate a none parameter, and the data does not include a row for “none” (i.e., no choice) (default is FALSE).

Try whether it works.


问:
OracleDataAdapter, Fill method hangs, how do I handle connection terminations/drop offs/cut outs?
I have a C# program that connects to a remote server to query data. The data is quite big so the query takes about 2 mins to finish. During this 2 min window, the internet went down. This resulted in the job being unable to finish with the program stuck in the getting data routine.

It established connection but during the select query it was cut off. Setting the command timeout to 30 seconds did not work. I need the query to fail when encountering this error because the program can handle failure but it cannot handle being stuck. Thanks!

UPDATE: included code

```<code>OracleConnection connection = new OracleConnection(connectionstring);
OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(new OracleCommand(query, connection));
oracleDataAdapter.SelectCommand.CommandTimeout = 30;

  DataSet dataSet = new DataSet();
  try
  {
    oracleDataAdapter.Fill(dataSet, table); //Hangs on this line when connection is lost
    return dataSet;
  }
  catch
  {
    throw;
  }
  finally
  {
    dataSet.Dispose();
    oracleDataAdapter.Dispose();
  }
</code>```

UPDATE AGAIN:

What I need to do is handle this situation because I don't want a dangling process.

Simplest would be once the connection is lost is that the program will throw an error. That is what I don't know how to do. I assumed that the commandtimeout will fix it but it did not.

答:
There are a few duplicates reporting this problem, eg: System being hang when the connection is lost while adapter is filling the datatables

I found a good thread on MSDN where the OP answers:

I have solved this problem a while back, sorry i forgot to come and let you all know. I worked out that the code stopped executing at that line because (for some reason) there was already an open connection to the database.

Since DA.Fill would open a connection itself if there wasnt one previously opened, it was having a hissy fit and bombing out.

I solved this by putting Connection.Close(); before and after any connection to the database is needed.

Based on this we can see you are not explicitly opening a Connection to the Database. Suggest you do a:

connection.Open();

Also follow Steve Py's answer with the using to confirm you are closing the connection and disposing unmanaged resources.

Body:
I have a C# program that connects to a remote server to query data. The data is quite big so the query takes about 2 mins to finish. During this 2 min window, the internet went down. This resulted in the job being unable to finish with the program stuck in the getting data routine.

It established connection but during the select query it was cut off. Setting the command timeout to 30 seconds did not work. I need the query to fail when encountering this error because the program can handle failure but it cannot handle being stuck. Thanks!

UPDATE: included code

OracleConnection connection = new OracleConnection(connectionstring);
OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(new OracleCommand(query, connection));
oracleDataAdapter.SelectCommand.CommandTimeout = 30;

  DataSet dataSet = new DataSet();
  try
  {
    oracleDataAdapter.Fill(dataSet, table); //Hangs on this line when connection is lost
    return dataSet;
  }
  catch
  {
    throw;
  }
  finally
  {
    dataSet.Dispose();
    oracleDataAdapter.Dispose();
  }

UPDATE AGAIN:

What I need to do is handle this situation because I don't want a dangling process.

Simplest would be once the connection is lost is that the program will throw an error. That is what I don't know how to do. I assumed that the commandtimeout will fix it but it did not.


问:
Java does not recognize ListView variable
I trying to create a ListView in AndroidStudio with value "nome". I created a list and a adapter for this, but my application not recognize variable "services".

This is my activity code

```<code>public class MainActivity extends AppCompatActivity {
    private String service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = (ListView) findViewById(R.id.list_item1);

        ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, services); <-- in this line
        listView.setAdapter(servicesAdapter);

    }

    private List<Services> gerarServices(){
        List<Services> services  = new ArrayList<Services>();
        services.add(criarServices("Home"));
        services.add(criarServices("Delivery"));

        return services;
    }

    private Services criarServices(String nome){
        Services service = new Services(nome);
        return service;
    }
}
</code>```

Any suggestion? Thank's in advance!

答:
In your code, I dont see any mehod for declaring and initializing services.

But gerarServices() return a list of Services. So I guess you have to do above action(s) before using any variables or instances of class, etc.

Like so,

```<code>ListView listView = (ListView) findViewById(R.id.list_item1);

// Add this line of code
List<Services> services = gerarServices();

ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, services);
</code>```

Hope this help.

Body:
I trying to create a ListView in AndroidStudio with value "nome". I created a list and a adapter for this, but my application not recognize variable "services".

This is my activity code

public class MainActivity extends AppCompatActivity {
    private String service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = (ListView) findViewById(R.id.list_item1);

        ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, services); <-- in this line
        listView.setAdapter(servicesAdapter);

    }

    private List<Services> gerarServices(){
        List<Services> services  = new ArrayList<Services>();
        services.add(criarServices("Home"));
        services.add(criarServices("Delivery"));

        return services;
    }

    private Services criarServices(String nome){
        Services service = new Services(nome);
        return service;
    }
}

Any suggestion? Thank's in advance!

Body:
In your code, I dont see any mehod for declaring and initializing services.

But gerarServices() return a list of Services. So I guess you have to do above action(s) before using any variables or instances of class, etc.

Like so,

ListView listView = (ListView) findViewById(R.id.list_item1);

// Add this line of code
List<Services> services = gerarServices();

ArrayAdapter<Services> servicesAdapter = new ArrayAdapter<Services>(this, android.R.layout.simple_list_item_1, services);

Hope this help.


问:
Python TypeError must be str not int
I am having trouble with the following piece of code:

```<code>    if verb == "stoke":

        if items["furnace"] >= 1:
            print("going to stoke the furnace")

            if items["coal"] >= 1:
                print("successful!")
                temperature += 250
                print("the furnace is now " + (temperature) + "degrees!")
                           ^this line is where the issue is occuring
            else:
                print("you can't")

        else:
            print("you have nothing to stoke")
</code>```

The resulting error comes up as the following:

```<code>    Traceback(most recent call last):
       File "C:\Users\User\Documents\Python\smelting game 0.3.1 build
       incomplete.py"
     , line 227, in <module>
         print("the furnace is now " + (temperature) + "degrees!")
    TypeError: must be str, not int
</code>```

I am unsure what the problem is as i have changed the name from temp to temperature and added the brackets around temperature but still the error occurs.

答:
print("the furnace is now " + str(temperature) + "degrees!")

cast it to str

Title: Python TypeError must be str not int

Body:
I am having trouble with the following piece of code:

    if verb == "stoke":

        if items["furnace"] >= 1:
            print("going to stoke the furnace")

            if items["coal"] >= 1:
                print("successful!")
                temperature += 250
                print("the furnace is now " + (temperature) + "degrees!")
                           ^this line is where the issue is occuring
            else:
                print("you can't")

        else:
            print("you have nothing to stoke")

The resulting error comes up as the following:

    Traceback(most recent call last):
       File "C:\Users\User\Documents\Python\smelting game 0.3.1 build
       incomplete.py"
     , line 227, in <module>
         print("the furnace is now " + (temperature) + "degrees!")
    TypeError: must be str, not int

I am unsure what the problem is as i have changed the name from temp to temperature and added the brackets around temperature but still the error occurs.


问:
redirected Autocomplete Jquery
I have a script with autocomplete that I wanted if the user typed a word that does not have in the script it was redirected to a specific url example warning.html but I am not able to do that, if you can help me from now thank you.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery UI Autocomplete Testt</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>

<input id="autocomplete" />

```

答:
You are using jqueryui 1.8. I am using 1.9 in the example below. Because, 1.9 has the response function, which can check the length.</p>

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery UI Autocomplete Testt</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
    $(document).ready(function() {
        var data = [
            {label: 'Google', value: 'http://google.com'},
            {label: 'Yahoo', value: 'http://yahoo.com'},
            {label: 'BMW', value: 'http://bmw.com'},
            {label: 'Bing', value: 'http://bing.com'}
        ];

        $("input#autocomplete").autocomplete({
            source: data,
            focus: function (event, ui) {
                $(event.target).val(ui.item.label);
                return false;
            },
            select: function (event, ui) {
                $(event.target).val(ui.item.label);
                window.location = ui.item.value;
                return false;
            },
            response: function(event, ui) {
            if (ui.content.length === 0) {
                console.log('action here');
            }
        }
        });
    });
  </script>
</head>
<body>
<input id="autocomplete" />
</body>
</html>
</code>```

Title: redirected Autocomplete Jquery

Body:
You are using jqueryui 1.8. I am using 1.9 in the example below. Because, 1.9 has the response function, which can check the length.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery UI Autocomplete Testt</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
    $(document).ready(function() {
        var data = [
            {label: 'Google', value: 'http://google.com'},
            {label: 'Yahoo', value: 'http://yahoo.com'},
            {label: 'BMW', value: 'http://bmw.com'},
            {label: 'Bing', value: 'http://bing.com'}
        ];

        $("input#autocomplete").autocomplete({
            source: data,
            focus: function (event, ui) {
                $(event.target).val(ui.item.label);
                return false;
            },
            select: function (event, ui) {
                $(event.target).val(ui.item.label);
                window.location = ui.item.value;
                return false;
            },
            response: function(event, ui) {
            if (ui.content.length === 0) {
                console.log('action here');
            }
        }
        });
    });
  </script>
</head>
<body>
<input id="autocomplete" />
</body>
</html>


问:
How to have two password fields controlled by one checkbox?
```<code><form>
<fieldset>
Password: <span id="capsalert">CAPS LOCK = on</span><br>
<input type="password" id="pwd">
<script type="text/javascript">
  document.write(
    '<input type="checkbox" name="masking" onclick="unmask(this.checked)"> ' +
    'Show the password as I type'
  );
</script>
<br>
Password2:<br>
<input type="password" id="pwd2">
</fieldset>
</form>
<script type="text/javascript">
function chkCaps(e) {
ev = (e ? e : window.event);
kc = (ev.which ? ev.which : (ev.keyCode ? ev.keyCode : false));
sk = (ev.shiftKey ? ev.shiftKey : (ev.modifiers ? !!(ev.modifiers & 4) : false));
if(
  (kc >= 97 && kc <= 122 && sk) ||
  (kc >= 65 && kc <= 90 && !sk)
) {
  document.getElementById('capsalert').style.display = 'inline';
}
else {
  document.getElementById('capsalert').style.display = 'none';
}//end if
}//end function
function unmask(truefalse) {
oldElem = document.getElementById('pwd');
elem = document.createElement('input');
elem.setAttribute('type', (truefalse == true ? 'text' : 'password'));
elem.setAttribute('value', document.getElementById('pwd').value);
elem.id = 'pwd';
oldElem.parentNode.replaceChild(elem,oldElem);

document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
}//end function
document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
</script>
</code>```

I'm using the above code in a slightly more complex form.

I have two separate "password" fields on the form.  With the current code I can have the first password field show the characters as they are typed when the checkbox is ticked.

Also, the code notifies the user if they are typing with CAPS Lock enabled.

I would like to have both password fields exhibiting the same behavior rather than the first field only.  Unfortunately, I do not know how to make that happen.

Thanks for the help.

EDIT:

A simple solution might be easier to find with the following code.  I'm willing to use either one.

```<code><script>
function changeType()
{
    document.myform.pass.type=(document.myform.option.value=(document.myform.option.value==1)?'-1':'1')=='1'?'password':'text';
}
</script>

<body>
<form name="myform">
   <input type="password" name="pass" />
   <input type="password" name="pass2" />
   <input type="checkbox" name="option" value='1' onchange="changeType()" />
</form>
</body>
</code>```

答:
Why don't you just change the type attribute of the password inputs in your unmask() function? That way it will be easier for you to manage more than 1 field. After checking whether you have to turn the input into a text one or a password one, do this:

```<code>// Suppose 'new_type' is either 'text' or 'password'
// and that 'pwd' and 'pwd2' are the id attributes for
// both of your password fields
document.getElementById('pwd').type = new_type;
document.getElementById('pwd2').type = new_type;
</code>```

Body:
<form>
<fieldset>
Password: CAPS LOCK = on

<input type="password" id="pwd">

Password2:

<input type="password" id="pwd2">
</fieldset>
</form>

I'm using the above code in a slightly more complex form.

I have two separate "password" fields on the form.  With the current code I can have the first password field show the characters as they are typed when the checkbox is ticked.

Also, the code notifies the user if they are typing with CAPS Lock enabled.

I would like to have both password fields exhibiting the same behavior rather than the first field only.  Unfortunately, I do not know how to make that happen.

Thanks for the help.

EDIT:

A simple solution might be easier to find with the following code.  I'm willing to use either one.

<form name="myform">
   <input type="password" name="pass" />
   <input type="password" name="pass2" />
   <input type="checkbox" name="option" value='1' onchange="changeType()" />
</form>

Body:
Why don't you just change the type attribute of the password inputs in your unmask() function? That way it will be easier for you to manage more than 1 field. After checking whether you have to turn the input into a text one or a password one, do this:

// Suppose 'new_type' is either 'text' or 'password'
// and that 'pwd' and 'pwd2' are the id attributes for
// both of your password fields
document.getElementById('pwd').type = new_type;
document.getElementById('pwd2').type = new_type;


问:
Mupdf: how to reset the resolution of pdf view page PROPERLY when the CDialogEx(MFC) OnSize?
my pdf file is rendering in a CDialogEx(it's MFC Class),and what i want is to reset the resolution when the Dialog resized.....

I find a solution via the mupdf offical downloads site:first set the desired resolution with pdfapp_setresolution(...), then call pdfapp_reloadpage(...). This reaches my goal but not perfect, with this method the displaying dialog gets a conspicuous redrawing (first the background color, then recovered back normal)...

anybody have a better optimization? thanks

答:
1st. resize the pdfapp_t object according to the view_window size via API pdfapp_onresize()

2nd. adjust the resolution of pdfapp_t object//#attentison# here the resolution needs some transformation on the basis of yr actual requirement, referencing the API pdfapp_autozoom() in pdfapp.c source file.

3rd. show page via pdfapp_showpage()

thats all :) maybe helpful to sb.

PS:lesson is that referencing the official document or example in details first :)


问:
Should I use strings or constant integers to map properties? Does it make a difference?
Example of strings mapping properties:

```<code>var OPACITY = {
 "visible" : 10,
 "hidden : 0.1
}
</code>```

How Ill be using it:

```<code>window.opacity = OPACITY["visible"]
</code>```

Example of using constant integers instead:

```<code>const VISIBLE = 0
const HIDDEN = 1
var OPACITY = [10, 0.1];
</code>```

How Ill be using it:

```<code>window.opacity = OPACITY[VISIBLE]
</code>```

So I have two questions, which is more standard practice and does it make a difference in performance or reliability?

答:
If you use constant integers, you'll never have to worry about having to make sure you cast your value to an integer to make it work.

As for performance? If your app is so loaded down it would impact performance, you have much, much bigger problems.

Body:
Example of strings mapping properties:

var OPACITY = {
 "visible" : 10,
 "hidden : 0.1
}

How Ill be using it:

window.opacity = OPACITY["visible"]

Example of using constant integers instead:

const VISIBLE = 0
const HIDDEN = 1
var OPACITY = [10, 0.1];

How Ill be using it:

window.opacity = OPACITY[VISIBLE]

So I have two questions, which is more standard practice and does it make a difference in performance or reliability?


问:
Increment character in string
I have the following code:

```<code>string str="A";
</code>```

I want to get the next alphabetical character programmatically (so B, C, D, E etc.)

Can anyone suggest a way of doing this?

答:
I am looking for the same thing, and I am using string so I need to cast it.

You can do this if your variable is string:

```<code>string foo = "b";
char result = Convert.ToChar(foo[0] + 1); //Will result to 'c'
</code>```

Title: Increment character in string

Body:
I have the following code:

string str="A";

I want to get the next alphabetical character programmatically (so B, C, D, E etc.)

Can anyone suggest a way of doing this?

Body:
I am looking for the same thing, and I am using string so I need to cast it.

You can do this if your variable is string:

string foo = "b";
char result = Convert.ToChar(foo[0] + 1); //Will result to 'c'


问:
How to make cmake from brew install the default cmake - Mac OS
On the terminal, I've

```<code>$ cmake --version
cmake version 3.4.1

CMake suite maintained and supported by Kitware (kitware.com/cmake).

$ which cmake
/usr/local/bin/cmake
</code>```

But when I upgraded the cmake using brew:

```<code>$ brew upgrade cmake
Error: cmake 3.8.2 already installed
$ brew edit cmake
</code>```

How to make cmake from brew install the default cmake ?

My formula file from brew edit cmake:

```<code>class Cmake < Formula
  desc "Cross-platform make"
  homepage "https://www.cmake.org/"
  url "https://cmake.org/files/v3.8/cmake-3.8.2.tar.gz"
  sha256 "da3072794eb4c09f2d782fcee043847b99bb4cf8d4573978d9b2024214d6e92d"
  head "https://cmake.org/cmake.git"

  bottle do
    cellar :any_skip_relocation
    sha256 "2bbeaf0866446737719aca74468290101b0c502065a02ad6e286f69fc0e69c77" => :sierra
    sha256 "74ecc634b8cc6facc828cc434ec16383681736c3c2fc42dd144f78e88bd34842" => :el_capitan
    sha256 "9b53dec241998124c67645be81c8e85db097404115e466cf409caf43add783ae" => :yosemite
  end

  devel do
    url "https://cmake.org/files/v3.9/cmake-3.9.0-rc5.tar.gz"
    sha256 "3ef250f93f1887d99c567542e987938bf1cb49af06275e0081b547765e03e6ac"
  end

  option "without-docs", "Don't build man pages"
  option "with-completion", "Install Bash completion (Has potential problems with system bash)"

  depends_on "sphinx-doc" => :build if build.with? "docs"

  # The `with-qt` GUI option was removed due to circular dependencies if
  # CMake is built with Qt support and Qt is built with MySQL support as MySQL uses CMake.
  # For the GUI application please instead use `brew cask install cmake`.

  def install
    args = %W[
      --prefix=#{prefix}
      --no-system-libs
      --parallel=#{ENV.make_jobs}
      --datadir=/share/cmake
      --docdir=/share/doc/cmake
      --mandir=/share/man
      --system-zlib
      --system-bzip2
      --system-curl
    ]

    if build.with? "docs"
      # There is an existing issue around macOS & Python locale setting
      # See https://bugs.python.org/issue18378#msg215215 for explanation
      ENV["LC_ALL"] = "en_US.UTF-8"
      args << "--sphinx-man" << "--sphinx-build=#{Formula["sphinx-doc"].opt_bin}/sphinx-build"
    end

    system "./bootstrap", *args
    system "make"
    system "make", "install"

    if build.with? "completion"
      cd "Auxiliary/bash-completion/" do
        bash_completion.install "ctest", "cmake", "cpack"
      end
    end

    elisp.install "Auxiliary/cmake-mode.el"
  end

  test do
    (testpath/"CMakeLists.txt").write("find_package(Ruby)")
    system bin/"cmake", "."
  end
end
</code>```

答:
Using brew link would work but before you have to purge the /usr/local/bin/cmake and /usr/local/bin/ccmake:

```<code>sudo rm /usr/local/bin/cmake
sudo rm /usr/local/bin/ccmake
brew link cmake
</code>```

Or let brew automatically purge them:

```<code>brew link --overwrite cmake
</code>```

Body:
On the terminal, I've

$ cmake --version
cmake version 3.4.1

CMake suite maintained and supported by Kitware (kitware.com/cmake).

$ which cmake
/usr/local/bin/cmake

But when I upgraded the cmake using brew:

$ brew upgrade cmake
Error: cmake 3.8.2 already installed
$ brew edit cmake

How to make cmake from brew install the default cmake ?

My formula file from brew edit cmake:

class Cmake < Formula
  desc "Cross-platform make"
  homepage "https://www.cmake.org/"
  url "https://cmake.org/files/v3.8/cmake-3.8.2.tar.gz"
  sha256 "da3072794eb4c09f2d782fcee043847b99bb4cf8d4573978d9b2024214d6e92d"
  head "https://cmake.org/cmake.git"

  bottle do
    cellar :any_skip_relocation
    sha256 "2bbeaf0866446737719aca74468290101b0c502065a02ad6e286f69fc0e69c77" => :sierra
    sha256 "74ecc634b8cc6facc828cc434ec16383681736c3c2fc42dd144f78e88bd34842" => :el_capitan
    sha256 "9b53dec241998124c67645be81c8e85db097404115e466cf409caf43add783ae" => :yosemite
  end

  devel do
    url "https://cmake.org/files/v3.9/cmake-3.9.0-rc5.tar.gz"
    sha256 "3ef250f93f1887d99c567542e987938bf1cb49af06275e0081b547765e03e6ac"
  end

  option "without-docs", "Don't build man pages"
  option "with-completion", "Install Bash completion (Has potential problems with system bash)"

  depends_on "sphinx-doc" => :build if build.with? "docs"

  # The `with-qt` GUI option was removed due to circular dependencies if
  # CMake is built with Qt support and Qt is built with MySQL support as MySQL uses CMake.
  # For the GUI application please instead use `brew cask install cmake`.

  def install
    args = %W[
      --prefix=#{prefix}
      --no-system-libs
      --parallel=#{ENV.make_jobs}
      --datadir=/share/cmake
      --docdir=/share/doc/cmake
      --mandir=/share/man
      --system-zlib
      --system-bzip2
      --system-curl
    ]

    if build.with? "docs"
      # There is an existing issue around macOS & Python locale setting
      # See https://bugs.python.org/issue18378#msg215215 for explanation
      ENV["LC_ALL"] = "en_US.UTF-8"
      args << "--sphinx-man" << "--sphinx-build=#{Formula["sphinx-doc"].opt_bin}/sphinx-build"
    end

    system "./bootstrap", *args
    system "make"
    system "make", "install"

    if build.with? "completion"
      cd "Auxiliary/bash-completion/" do
        bash_completion.install "ctest", "cmake", "cpack"
      end
    end

    elisp.install "Auxiliary/cmake-mode.el"
  end

  test do
    (testpath/"CMakeLists.txt").write("find_package(Ruby)")
    system bin/"cmake", "."
  end
end

Body:
Using brew link would work but before you have to purge the /usr/local/bin/cmake and /usr/local/bin/ccmake:

sudo rm /usr/local/bin/cmake
sudo rm /usr/local/bin/ccmake
brew link cmake

Or let brew automatically purge them:

brew link --overwrite cmake