问:
nVarchar and SqlParameter
I'm developing an application which must support several languages. To solve the special characters problem I'm using NVarhcar for my text fields. So my SQL query for a text field is

```<code>insert into tbl_text(text)values(N'Chci tančit v oblasti')
</code>```

My problem is to put it in SqlCommand, wich is "insert into tbl_text(text)values(N@text)". It saves "N@text" in the DB table, sure.

Do you guys know someway to do it? I'm using C# and SQL 2008.

Sorry if it was hard to understand my question. My English is poor =/

答:
Don't put "N" before the parameter name, it is only used when using string constant to indicate it is a unicode string. So your query should be: </p>

```<code>insert into tbl_text(text) values (@text)
</code>```

Title: nVarchar and SqlParameter

Body:
I'm developing an application which must support several languages. To solve the special characters problem I'm using NVarhcar for my text fields. So my SQL query for a text field is

insert into tbl_text(text)values(N'Chci tančit v oblasti')

My problem is to put it in SqlCommand, wich is "insert into tbl_text(text)values(N@text)". It saves "N@text" in the DB table, sure.

Do you guys know someway to do it? I'm using C# and SQL 2008.

Sorry if it was hard to understand my question. My English is poor =/

Body:
Don't put "N" before the parameter name, it is only used when using string constant to indicate it is a unicode string. So your query should be:

insert into tbl_text(text) values (@text)


来源: stackexchange

问:
Issue with bean from another JAR
I'm exporting a JAR that contains a class:

```<code>public class SerializerHelper {
    public String toJson(final Object src) {...}
}
</code>```

And the trialApplicationContext.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="serializerHelper" class="com.trial.SerializerHelper"/>

</beans>
</code>```

Then, I'm importing that JAR on another project, and on its applicationContext.xml I'm importing the trial context as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- Replace all @Autowired by its instances -->
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

    <import resource="classpath*:trialApplicationContext"/>

    <bean id="booksSerializer" class="com.trial.BooksSerializerImpl" />
    ...

</beans>
</code>```

And then, I'm using that bean on my class as:

```<code>public interface BooksSerializer {
    String getBooks();
}

public class BooksSerializerImpl implements BooksSerializer {

    @Autowired
    private SerializerHelper serializerHelper;

    ...

}
</code>```

However, the code is failing with the following error:

java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'booksSerializer' defined in URL [...applicationContext.xml]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.trial.BooksSerializerImpl] for autowiring metadata: could not find class that it depends on
  java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'booksSerializer' defined in URL [jar:file:/....jar!/applicationContext.xml]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.trial.BooksSerializerImpl] for autowiring metadata: could not find class that it depends on
      at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:921)
      at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:900)
      at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:684)
      at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2044)
      at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1690)
      at com.sun.enterprise.web.WebApplication.start(WebApplication.java:107)
      at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
  java.lang.Exception: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'booksSerializer' defined in URL [jar:file:/....jar!/applicationContext]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.trial.BooksSerializerImpl] for autowiring metadata: could not find class that it depends on
      at com.sun.enterprise.web.WebApplication.start(WebApplication.java:136)
      at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
  java.lang.Exception: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productSerializer' defined in URL [jar:file:/....jar!/applicationContext.xml]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.trial.BooksSerializerImpl] for autowiring metadata: could not find class that it depends on
      at com.sun.enterprise.web.WebApplication.start(WebApplication.java:136)
      at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
    Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'booksSerializer' defined in URL [jar:file:/....jar!/applicationContext.xml]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.trial.BooksSerializerImpl] for autowiring metadata: could not find class that it depends on]]

This error is happening when I'm trying to run my project on a jersey server.

What am I doing wrong? Thanks a lot.

答:
Please Use context component scan for scanning your package, so that your declare spring bean can be discoverable by spring container.
Declare it in applicationContext.xml

```<code><context:component-scan base-package="com.jartrial.*, com.trial.*" />
</code>```

ContentLicense: CC BY-SA 3.0

Title: Issue with bean from another JAR

Body:
I'm exporting a JAR that contains a class:

public class SerializerHelper {
    public String toJson(final Object src) {...}
}

And the trialApplicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="serializerHelper" class="com.trial.SerializerHelper"/>

</beans>

Then, I'm importing that JAR on another project, and on its applicationContext.xml I'm importing the trial context as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

    <import resource="classpath*:trialApplicationContext"/>

    <bean id="booksSerializer" class="com.trial.BooksSerializerImpl" />
    ...

</beans>

And then, I'm using that bean on my class as:

public interface BooksSerializer {
    String getBooks();
}

public class BooksSerializerImpl implements BooksSerializer {

    @Autowired
    private SerializerHelper serializerHelper;

    ...

}

However, the code is failing with the following error:

java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'booksSerializer' defined in URL [...applicationContext.xml]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.trial.BooksSerializerImpl] for autowiring metadata: could not find class that it depends on
  java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'booksSerializer' defined in URL [jar:file:/....jar!/applicationContext.xml]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.trial.BooksSerializerImpl] for autowiring metadata: could not find class that it depends on
      at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:921)
      at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:900)
      at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:684)
      at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2044)
      at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1690)
      at com.sun.enterprise.web.WebApplication.start(WebApplication.java:107)
      at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
  java.lang.Exception: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'booksSerializer' defined in URL [jar:file:/....jar!/applicationContext]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.trial.BooksSerializerImpl] for autowiring metadata: could not find class that it depends on
      at com.sun.enterprise.web.WebApplication.start(WebApplication.java:136)
      at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
  java.lang.Exception: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productSerializer' defined in URL [jar:file:/....jar!/applicationContext.xml]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.trial.BooksSerializerImpl] for autowiring metadata: could not find class that it depends on
      at com.sun.enterprise.web.WebApplication.start(WebApplication.java:136)
      at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
    Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'booksSerializer' defined in URL [jar:file:/....jar!/applicationContext.xml]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.trial.BooksSerializerImpl] for autowiring metadata: could not find class that it depends on]]

This error is happening when I'm trying to run my project on a jersey server.

What am I doing wrong? Thanks a lot.

Body:
Please Use context component scan for scanning your package, so that your declare spring bean can be discoverable by spring container.
Declare it in applicationContext.xml

<context:component-scan base-package="com.jartrial.*, com.trial.*" />


问:
Android Studio 3.0 migration AAPT2 error
After migrating my existing project to Android Studio 3.0, it is not compiling. Below are the log details:

```<code>Error:java.util.concurrent.ExecutionException:
    java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for
details
Error:Execution failed for task ':app:processDebugResources'.
Failed to execute aapt
Information:BUILD FAILED in 27s
Information:11 errors
Information:0 warnings
</code>```

答:
Go to your gradle.properties write the below code and Sync your project

```<code>android.enableAapt2=false
</code>```

Body:
After migrating my existing project to Android Studio 3.0, it is not compiling. Below are the log details:

Error:java.util.concurrent.ExecutionException:
    java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for
details
Error:Execution failed for task ':app:processDebugResources'.
Failed to execute aapt
Information:BUILD FAILED in 27s
Information:11 errors
Information:0 warnings

Body:
Go to your gradle.properties write the below code and Sync your project

android.enableAapt2=false


问:
how to make content occupy whole page regardless of the screen size?
I am designing a web page for the mobile first time. I have given 100% width and height so that content will render at the full page regardless of mobile screen size. but still, as you can see from the screenshot, there is empty space below and on the right side. Also even one of my checkbox content is even crossing the width of the page. I have tried putting that content in a span tag and defining a class and putting something like max-width: 20 px or something but it is not having any effect whatsoever. below my code snippet of HTML and css

/* style.css */
/* You can add global styles to this file, and also import other style files */
@import "~@angular/material/prebuilt-themes/indigo-pink.css";

body {
 margin: 0;
height: 100%;
width: 100%;
}

/* this page css */

mat-card{
width: 100%;
}

img{
padding: 2%;
text-align: center;
width:5%;
height: 5%;
}

.logo {
  margin: 10%;
 text-align: center;

}

.confirm-text {
max-width: 30px;
   display: block;
}

.example-container {
  display: flex;
  flex-direction: column;
}

.example-container>* {
  width: 100%;
}

.example-right-align {
  text-align: right;
}

input.example-right-align::-webkit-outer-spin-button,
input.example-right-align::-webkit-inner-spin-button {
  display: none;
}

.example-radio-group {
  display: inline-flex;
  flex-direction: column;
}
.checkbox {
display: block;
flex-direction: column;
padding-left:4%;
}

strong {
padding-left: 4%;
}
p {
  padding-left: 4%;
}

.example-radio-button {
  margin: 3%;
}

.example-selected-value {
  margin: 15px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><mat-card><div class="logo">
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRE3x0vsDn1R5O0v7QKVvJNMJK2txXUv8IIsY-2t4R8ore5AjMk0g" alt="image">
  <br>
  <br>
  <p>your return request has been confirmed. please tell us a convenient time to schedule the pick up</p>
</div></mat-card>
<mat-card class="login-form">
<form class="example-container" (ngSubmit)="onSubmit(f)" #f="ngForm">
  <strong>Pick up your preferred date</strong>
  <mat-radio-group class="example-radio-group" name="selectedDate" [(ngModel)]="selectedDate" required>
  <mat-radio-button class="example-radio-button"
     *ngFor="let date of dateOptions" [value]="date" ngDefaultControl>
    {{date}}
  </mat-radio-button>
</mat-radio-group>
<br><br>
<strong>Select a preferred time</strong>
<mat-radio-group
 class="example-radio-group" name="selectedTime" [(ngModel)]="selectedTime" required>
  <mat-radio-button class="example-radio-button"
    *ngFor="let time of timeOptions" [value]="time" ngDefaultControl>
    {{time}}
  </mat-radio-button>
</mat-radio-group>
<hr>
<mat-checkbox class="checkbox" name="confirmation" [(ngModel)]="confirmation" required>
  <span class="confirm-text">I confirm the above selected date and time as the preferred slot for return pick up.</span>
</mat-checkbox>
<hr>
<button mat-raised-button color="accent"  type="submit"  [disabled]="!f.valid">Submit</button>
</form>
</mat-card></code>```

edit: this is index.html

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Myntra</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://storage.googleapis.com/code.getmdl.io/1.1.0/material.indigo-pink.min.css" rel="stylesheet" /
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

</head>
<body>
  <app-root></app-root>
</body>
</html>
</code>```

答:
Try this

```<code>    <div id="complete">
     Put your code here
    </div>
     html,body{  height:100%; width:100%; margin:0; padding:0;}
    #complete{
       height:100%;
       width:100%;
       overflow:hidden;
              }
</code>```

If you want to have scrollbar then you can keep overflow as auto.
Do not miss html before body.
Hope this helps!!

Body:
I am designing a web page for the mobile first time. I have given 100% width and height so that content will render at the full page regardless of mobile screen size. but still, as you can see from the screenshot, there is empty space below and on the right side. Also even one of my checkbox content is even crossing the width of the page. I have tried putting that content in a span tag and defining a class and putting something like max-width: 20 px or something but it is not having any effect whatsoever. below my code snippet of HTML and css

/* style.css */
/* You can add global styles to this file, and also import other style files */
@import "~@angular/material/prebuilt-themes/indigo-pink.css";

body {
 margin: 0;
height: 100%;
width: 100%;
}

/* this page css */

mat-card{
width: 100%;
}

img{
padding: 2%;
text-align: center;
width:5%;
height: 5%;
}

.logo {
  margin: 10%;
 text-align: center;

}

.confirm-text {
max-width: 30px;
   display: block;
}

.example-container {
  display: flex;
  flex-direction: column;
}

.example-container>* {
  width: 100%;
}

.example-right-align {
  text-align: right;
}

input.example-right-align::-webkit-outer-spin-button,
input.example-right-align::-webkit-inner-spin-button {
  display: none;
}

.example-radio-group {
  display: inline-flex;
  flex-direction: column;
}
.checkbox {
display: block;
flex-direction: column;
padding-left:4%;
}

strong {
padding-left: 4%;
}
p {
  padding-left: 4%;
}

.example-radio-button {
  margin: 3%;
}

.example-selected-value {
  margin: 15px 0;
}

<mat-card>

your return request has been confirmed. please tell us a convenient time to schedule the pick up

</mat-card>
<mat-card class="login-form">
<form class="example-container" (ngSubmit)="onSubmit(f)" #f="ngForm">
  Pick up your preferred date
  <mat-radio-group class="example-radio-group" name="selectedDate" [(ngModel)]="selectedDate" required>
  <mat-radio-button class="example-radio-button"
     *ngFor="let date of dateOptions" [value]="date" ngDefaultControl>
    {{date}}
  </mat-radio-button>
</mat-radio-group>

Select a preferred time
<mat-radio-group
 class="example-radio-group" name="selectedTime" [(ngModel)]="selectedTime" required>
  <mat-radio-button class="example-radio-button"
    *ngFor="let time of timeOptions" [value]="time" ngDefaultControl>
    {{time}}
  </mat-radio-button>
</mat-radio-group>

<mat-checkbox class="checkbox" name="confirmation" [(ngModel)]="confirmation" required>
  I confirm the above selected date and time as the preferred slot for return pick up.
</mat-checkbox>

<button mat-raised-button color="accent"  type="submit"  [disabled]="!f.valid">Submit</button>
</form>
</mat-card>

edit: this is index.html

<!doctype html>

  <meta charset="utf-8">
  <title>Myntra</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://storage.googleapis.com/code.getmdl.io/1.1.0/material.indigo-pink.min.css" rel="stylesheet" /
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <app-root></app-root>

Body:
Try this

    <div id="complete">
     Put your code here
    </div>
     html,body{  height:100%; width:100%; margin:0; padding:0;}
    #complete{
       height:100%;
       width:100%;
       overflow:hidden;
              }

If you want to have scrollbar then you can keep overflow as auto.
Do not miss html before body.
Hope this helps!!


问:
Error - This version of Visual Studio is unable to open the following projects
I have installed Python package for VS.NET 2013 from the VS itself. After that i could not open any C++ Project. I got this Error Message:

Full Text:

Unsupported

This version of Visual Studio is unable to open the following projects.vcxproj The project types may not be installed or this version of Visual Studio may not support them.
For more information on enabling these project types or otherwise migrating your assets, please see the details in the "Migration Report" displayed after clicking OK.

```<code> - PROJECT_NAME, "C:\xx\xx\xx\xx\xx\PROJECT_NAME.vcxproj"
</code>```

Non-functional changes required

Visual Studio will automatically make non-functional changes to the following projects in order to enable them to open in Visual Studio 2013, Visual Studio 2012, and Visual Studio 2010 SP1. Project behavior will not be impacted.
     - ImageRegistrationEngine, "C:\xx\xx\xx\xx\PROJECT_NAME.sln"

EDIT:

The project was created on the same machine using the exactly same version of VS.NET..

BTW, I still can open C# projects but not C++ ones.

答:
Opened Developer Command Prompt for VS2013 in administrator mode and executed devenv /Setup (while VS is closed).
Then VS started working as expected.</p>

Body:
I have installed Python package for VS.NET 2013 from the VS itself. After that i could not open any C++ Project. I got this Error Message:

Full Text:

Unsupported

This version of Visual Studio is unable to open the following projects.vcxproj The project types may not be installed or this version of Visual Studio may not support them.
For more information on enabling these project types or otherwise migrating your assets, please see the details in the "Migration Report" displayed after clicking OK.

 - PROJECT_NAME, "C:\xx\xx\xx\xx\xx\PROJECT_NAME.vcxproj"

Non-functional changes required

Visual Studio will automatically make non-functional changes to the following projects in order to enable them to open in Visual Studio 2013, Visual Studio 2012, and Visual Studio 2010 SP1. Project behavior will not be impacted.
     - ImageRegistrationEngine, "C:\xx\xx\xx\xx\PROJECT_NAME.sln"

EDIT:

The project was created on the same machine using the exactly same version of VS.NET..

BTW, I still can open C# projects but not C++ ones.


问:
reassign a new "character" to a key, so that it gets printed instead of the default letter for the key
I'm in the process of developing a text editor that has a "macro system," where the user can reassign values to the keys on their keyboard -- so that when they press the letter a, it might print the letter "z" instead. (Really, it'll be used for math symbols, not other letters).

Can anyone get me started on the Java code to reassign a value to a key within a JTextPane?

If you need more details, let me know.

Thank you!

So far, this is what I have:

```<code>public void keyPressed(KeyEvent evt) {
//Called when a key is pressed.

//Intercept the key before the default value is printed.
//1. Suppress the original character. Do this in the KeyEvent object
//by setting the doit property to false in your listener if the key
//matches a macro.

    jTextPane1.addKeyListener(new KeyAdapter() {
public void keyPressed(keyEvent event) {
if (event.getKeyCode() == KeyEvent.VK_A) {
//Perform an action when A is pressed and there is a macro.
if(macroA == true)
{
    keyPressed.doit() = false;
}
}
}
else if (event.getKeyCode() == KeyEvent.VK_B) {
//Perform an action when B is pressed if there is a macro.
if(macroB == true)
{
    keyPressed.doit() = false;
}
}
}
});
</code>```

I'm working on how to implement it with "creating" the macro, checking to see if a macro exists.

If you have any more advice, I would appreciate it.

Thank you.

答:
I haven't done any Swing development in a while, but I think you're looking for a KeyListener.
There's an example here: http://download.oracle.com/javase/tutorial/uiswing/events/keylistener.html

Your back end would need to map the key inputs with your macros and intercept the key input and insert the macro instead.

Body:
I'm in the process of developing a text editor that has a "macro system," where the user can reassign values to the keys on their keyboard -- so that when they press the letter a, it might print the letter "z" instead. (Really, it'll be used for math symbols, not other letters).

Can anyone get me started on the Java code to reassign a value to a key within a JTextPane?

If you need more details, let me know.

Thank you!

So far, this is what I have:

public void keyPressed(KeyEvent evt) {
//Called when a key is pressed.

//Intercept the key before the default value is printed.
//1. Suppress the original character. Do this in the KeyEvent object
//by setting the doit property to false in your listener if the key
//matches a macro.

    jTextPane1.addKeyListener(new KeyAdapter() {
public void keyPressed(keyEvent event) {
if (event.getKeyCode() == KeyEvent.VK_A) {
//Perform an action when A is pressed and there is a macro.
if(macroA == true)
{
    keyPressed.doit() = false;
}
}
}
else if (event.getKeyCode() == KeyEvent.VK_B) {
//Perform an action when B is pressed if there is a macro.
if(macroB == true)
{
    keyPressed.doit() = false;
}
}
}
});

I'm working on how to implement it with "creating" the macro, checking to see if a macro exists.

If you have any more advice, I would appreciate it.

Thank you.

ContentLicense: CC BY-SA 2.5


问:
Cloud Firestore : DexArchiveMergerException Unable to merge dex
when I include:

compile 'com.firebaseui:firebase-ui-firestore:3.1.0'

build fails. firestore version 3.0.0 is same result.

without this code, build is success.

Is there duplicated module? please help me.

Error:Execution failed for task
  ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge
    dex

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.android"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        // firebase
        resConfigs "auto"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    // volley
    compile 'com.android.volley:volley:1.0.0'

    // firebase, map, location
    implementation 'com.google.android.gms:play-services-maps:11.4.2'
    implementation 'com.google.android.gms:play-services-location:11.4.2'

    // firebase storage
    compile 'com.google.firebase:firebase-storage:11.4.2'

    // FirebaseUI for Firebase Auth
    compile 'com.firebaseui:firebase-ui-auth:3.1.0'

    // Required only if Facebook login support is required
    compile 'com.facebook.android:facebook-login:4.27.0'

    // Required only if Twitter login support is required
    compile("com.twitter.sdk.android:twitter-core:3.0.0@aar") { transitive = true }

    // glide
    compile 'com.github.bumptech.glide:glide:4.3.1'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'

    // FirebaseUI Storage
    compile 'com.firebaseui:firebase-ui-storage:3.1.0'

    // Firebase cloud message
    compile 'com.google.firebase:firebase-messaging:11.4.2'

    // FirebaseUI for Cloud Firestore
    compile 'com.firebaseui:firebase-ui-firestore:3.1.0'
}

// firebase
apply plugin: 'com.google.gms.google-services'
</code>```

```<code>buildscript {

    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        //firebase
        classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

        // glide
        mavenCentral()
        maven { url 'https://maven.google.com' }

        // firebase twitter login
        maven { url 'https://maven.fabric.io/public' }

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
There is nothig wrong with your code. I had the same problem a few day ago and I solved it very simply like this:

```<code>1. Clean
2. Rebuild
</code>```

Don't forget also to have the following lines of code in your build.gradle file (Module: app).

```<code>android {
    defaultConfig {
       multiDexEnabled true
    }
}
</code>```

If it still does not work as explained above, just delete the .gradle directory and then run your app again.

ContentLicense: CC BY-SA 4.0

Body:
when I include:

compile 'com.firebaseui:firebase-ui-firestore:3.1.0'

build fails. firestore version 3.0.0 is same result.

without this code, build is success.

Is there duplicated module? please help me.

Error:Execution failed for task
  ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge
    dex

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.android"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        // firebase
        resConfigs "auto"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    // volley
    compile 'com.android.volley:volley:1.0.0'

    // firebase, map, location
    implementation 'com.google.android.gms:play-services-maps:11.4.2'
    implementation 'com.google.android.gms:play-services-location:11.4.2'

    // firebase storage
    compile 'com.google.firebase:firebase-storage:11.4.2'

    // FirebaseUI for Firebase Auth
    compile 'com.firebaseui:firebase-ui-auth:3.1.0'

    // Required only if Facebook login support is required
    compile 'com.facebook.android:facebook-login:4.27.0'

    // Required only if Twitter login support is required
    compile("com.twitter.sdk.android:twitter-core:3.0.0@aar") { transitive = true }

    // glide
    compile 'com.github.bumptech.glide:glide:4.3.1'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'

    // FirebaseUI Storage
    compile 'com.firebaseui:firebase-ui-storage:3.1.0'

    // Firebase cloud message
    compile 'com.google.firebase:firebase-messaging:11.4.2'

    // FirebaseUI for Cloud Firestore
    compile 'com.firebaseui:firebase-ui-firestore:3.1.0'
}

// firebase
apply plugin: 'com.google.gms.google-services'

buildscript {

    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        //firebase
        classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

        // glide
        mavenCentral()
        maven { url 'https://maven.google.com' }

        // firebase twitter login
        maven { url 'https://maven.fabric.io/public' }

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Body:
There is nothig wrong with your code. I had the same problem a few day ago and I solved it very simply like this:

1. Clean
2. Rebuild

Don't forget also to have the following lines of code in your build.gradle file (Module: app).

android {
    defaultConfig {
       multiDexEnabled true
    }
}

If it still does not work as explained above, just delete the .gradle directory and then run your app again.


问:
Simultaneously move wpf and c++ windows
I have a main form which is developed in wpf. We have used DragMove to move the window when user clicks on some areas in the window.

We also have another window which is developed in c++ and is designed like an add-on sidebar and is a separate process.

I want that the c++ window should also move when I am moving the main form.
I have the handle of both the windows and can pass win32 messages.

Can someone tell how I can intercept the move commands in main form and also pass them to the extra window.

答:
To intercept the movement of your WPF application you can listen for the event named Window.LocationChanged.

Using the SetWindowPos function you can manipulate a window handle. You will have to find this handling by using EnumWindows based on the process id of the C++ application.

Title: Simultaneously move wpf and c++ windows


问:
Removing subarrays that share a key-value pair with another multidimensional array
I have 2 arrays as below. I want to remove data from array2 if array1 has the stu_id. final array should be like result_array.

```<code>$array1 = Array
(
    [0] => Array
        (
            [stu_id] => 1
            [name] => mr.a
        )
    [1] => Array
        (
            [stu_id] => 3
            [name] => mr.b
        )
)

$array2 = Array
(
    [0] => Array
        (
            [id] => 1
            [stu_id] => 1
            [data] => abc
        )
    [1] => Array
        (
            [id] => 2
            [stu_id] => 2
            [data] => xyz
        )
    [3] => Array
        (
            [id] => 3
            [stu_id] => 3
            [data] => aaa
        )
)

$result_array = Array
(
    [0] => Array
        (
            [id] => 2
            [stu_id] => 2
            [data] => xyz
        )
)
</code>```

I tried array_diff, $result_array = array_diff($array2, $array1);  but it's not working.

Please help me to do this.

答:
Temporarily assign keys using array_column() with stud_id (NULL retains the full subarray data), then use array_diff_key() to filter, and array_values() to reset the keys:

Code: (Demo)

```<code>$array1=[
    ['stu_id'=>1,'name'=>'mr.a'],
    ['stu_id'=>3,'name'=>'mr.b']
];

$array2=[
    ['id'=>1,'stu_id'=>1,'data'=>'abc'],
    ['id'=>2,'stu_id'=>2,'data'=>'xyz'],
    ['id'=>3,'stu_id'=>3,'data'=>'aaa']
];

//var_export(array_column($array1,NULL,'stu_id'));
//var_export(array_column($array2,NULL,'stu_id'));
var_export(array_values(array_diff_key(array_column($array2,NULL,'stu_id'),array_column($array1,NULL,'stu_id'))));
</code>```

Output:

```<code>array (
  0 =>
  array (
    'id' => 2,
    'stu_id' => 2,
    'data' => 'xyz',
  ),
)
</code>```

If you'd like to use a foreach loop structure, generate a filtering array of stu_id's from $array1 and write a conditional check on each iteration of $array2.  This method doesn't not modify the original arrays, so they can be reused "down script".

Code:

```<code>$stu_ids=array_column($array1,'stu_id');
foreach($array2 as $row){
    if(!in_array($row['stu_id'],$stu_ids)){
        $result[]=$row;  // auto-index the qualifying subarrays
    }
}
var_export($result);
// same result as above method
</code>```

Body:
I have 2 arrays as below. I want to remove data from array2 if array1 has the stu_id. final array should be like result_array.

$array1 = Array
(
    [0] => Array
        (
            [stu_id] => 1
            [name] => mr.a
        )
    [1] => Array
        (
            [stu_id] => 3
            [name] => mr.b
        )
)

$array2 = Array
(
    [0] => Array
        (
            [id] => 1
            [stu_id] => 1
            [data] => abc
        )
    [1] => Array
        (
            [id] => 2
            [stu_id] => 2
            [data] => xyz
        )
    [3] => Array
        (
            [id] => 3
            [stu_id] => 3
            [data] => aaa
        )
)

$result_array = Array
(
    [0] => Array
        (
            [id] => 2
            [stu_id] => 2
            [data] => xyz
        )
)

I tried array_diff, $result_array = array_diff($array2, $array1);  but it's not working.

Please help me to do this.

Body:
Temporarily assign keys using array_column() with stud_id (NULL retains the full subarray data), then use array_diff_key() to filter, and array_values() to reset the keys:

Code: (Demo)

$array1=[
    ['stu_id'=>1,'name'=>'mr.a'],
    ['stu_id'=>3,'name'=>'mr.b']
];

$array2=[
    ['id'=>1,'stu_id'=>1,'data'=>'abc'],
    ['id'=>2,'stu_id'=>2,'data'=>'xyz'],
    ['id'=>3,'stu_id'=>3,'data'=>'aaa']
];

//var_export(array_column($array1,NULL,'stu_id'));
//var_export(array_column($array2,NULL,'stu_id'));
var_export(array_values(array_diff_key(array_column($array2,NULL,'stu_id'),array_column($array1,NULL,'stu_id'))));

Output:

array (
  0 =>
  array (
    'id' => 2,
    'stu_id' => 2,
    'data' => 'xyz',
  ),
)

If you'd like to use a foreach loop structure, generate a filtering array of stu_id's from $array1 and write a conditional check on each iteration of $array2.  This method doesn't not modify the original arrays, so they can be reused "down script".

Code:

$stu_ids=array_column($array1,'stu_id');
foreach($array2 as $row){
    if(!in_array($row['stu_id'],$stu_ids)){
        $result[]=$row;  // auto-index the qualifying subarrays
    }
}
var_export($result);
// same result as above method


问:
Override Enum metaclass initialization
Although pylint raises a warning on enum.Enum(value=..., names=...), I see from the enum doc that one could programmatically create an Enum like the following

```<code>import re
import enum
import termios

def termios_baud_rates():
    regexp = r"(?:^|,)B(?P<rate>\d+)"
    rates = sorted(map(int, re.findall(regexp, ",".join(dir(termios)))))
    return {"B{:d}".format(r): r for r in rates}

BAUD_RATES = enum.Enum("BAUD_RATES", termios_baud_rates())
</code>```

But I'd also like to add methods:

```<code>@classmethod
def valid_rate(cls, value):
    return (any(value == item.value for item in cls))
</code>```

I think this should involve overloading metaclass __prepare__(mcls, names, bases) to augment bases with the names dict, but apparently bases is not how the Enum attributes are created. Anyone have any tips?

答:
You can also use nonlocal to avoid needing the aenum package:

```<code>import re
import enum
import termios

regexp = r"(?:^|,)B(?P<rate>\d+)"
rates = sorted(map(int, re.findall(regexp, ",".join(dir(termios)))))

value = None

class BaudRate(enum.Enum):
    nonlocal value
    for value in rates:
        locals()['B%d' % value] = value

    @classmethod
    def valid_rate(cls, value):
        return (any(value == item.value for item in cls))
</code>```

Title: Override Enum metaclass initialization

Body:
Although pylint raises a warning on enum.Enum(value=..., names=...), I see from the enum doc that one could programmatically create an Enum like the following

import re
import enum
import termios

def termios_baud_rates():
    regexp = r"(?:^|,)B(?P<rate>\d+)"
    rates = sorted(map(int, re.findall(regexp, ",".join(dir(termios)))))
    return {"B{:d}".format(r): r for r in rates}

BAUD_RATES = enum.Enum("BAUD_RATES", termios_baud_rates())

But I'd also like to add methods:

@classmethod
def valid_rate(cls, value):
    return (any(value == item.value for item in cls))

I think this should involve overloading metaclass __prepare__(mcls, names, bases) to augment bases with the names dict, but apparently bases is not how the Enum attributes are created. Anyone have any tips?

Body:
You can also use nonlocal to avoid needing the aenum package:

import re
import enum
import termios

regexp = r"(?:^|,)B(?P<rate>\d+)"
rates = sorted(map(int, re.findall(regexp, ",".join(dir(termios)))))

value = None

class BaudRate(enum.Enum):
    nonlocal value
    for value in rates:
        locals()['B%d' % value] = value

    @classmethod
    def valid_rate(cls, value):
        return (any(value == item.value for item in cls))


问:
Conflicting layout constraints, translatesAutoresizingMaskIntoConstraints not working
First of all, this is what I want to achieve:

The view needs to be centered, with a height of 200. The trailing an leading anchors should touch the layoutmargins. I am creating my constraints programatically.

```<code>import UIKit

class CustomView: UIView {

    var dialogView : UIView!

    func show()
    {
        UIApplication.shared.delegate?.window??.rootViewController?.view.addSubview(self)
        dialogView = UIView()
        dialogView.translatesAutoresizingMaskIntoConstraints = false

        dialogView.backgroundColor = .red
        addSubview(dialogView)

        let dialogViewCenterYConstraint = dialogView.centerYAnchor.constraint(equalTo: self.centerYAnchor)
        dialogViewCenterYConstraint.isActive = true

        let dialogViewHeightConstraint = dialogView.heightAnchor.constraint(equalToConstant: 200)
        dialogViewHeightConstraint.isActive = true

        let margins = self.layoutMarginsGuide

        let dialogViewLeadingConstraint = dialogView.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
        dialogViewLeadingConstraint.isActive = true

        let dialogViewTrailingConstraint = dialogView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
        dialogViewTrailingConstraint.isActive = true
    }

    override func layoutSubviews() {
        frame = UIScreen.main.bounds
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        CustomView().show()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

It is working, but it also prints the following warning:

```<code>[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSAutoresizingMaskLayoutConstraint:0x60000009ee60 h=--& v=--& ArtAlertView.CustomView:0x7f9f86c0f770.width == 0   (active)>",
    "<NSLayoutConstraint:0x60000009ed20 UIView:0x7f9f86c100d0.leading == UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'.leading   (active)>",
    "<NSLayoutConstraint:0x60000009ed70 UIView:0x7f9f86c100d0.trailing == UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'.trailing   (active)>",
    "<NSLayoutConstraint:0x60000009eb90 'UIView-leftMargin-guide-constraint' H:|-(8)-[UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'](LTR)   (active, names: '|':ArtAlertView.CustomView:0x7f9f86c0f770 )>",
    "<NSLayoutConstraint:0x60000009ec30 'UIView-rightMargin-guide-constraint' H:[UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide']-(8)-|(LTR)   (active, names: '|':ArtAlertView.CustomView:0x7f9f86c0f770 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x60000009ed70 UIView:0x7f9f86c100d0.trailing == UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'.trailing   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
</code>```

I noticed one of the constraints is an NSAutoresizingMaskLayoutConstraint. I thought setting translatesAutoresizingMaskIntoConstraints to false would get rid of these.

Any thoughts?

答:
Because you create new CustomView without frame, when you called show a new dialogView will be added to it and layout with |-margin-[dialogView]-margin-|, this requires CustomView's width >= 2 * margin. so you will get this layout warning.

There are 2 way to fix this issue:

1.when you initial a new CustomView give it a frame where frame.width >= margin * 2.

2.give leading and trailing constraint of dialogView a lower layout priority.

Body:
First of all, this is what I want to achieve:

The view needs to be centered, with a height of 200. The trailing an leading anchors should touch the layoutmargins. I am creating my constraints programatically.

import UIKit

class CustomView: UIView {

    var dialogView : UIView!

    func show()
    {
        UIApplication.shared.delegate?.window??.rootViewController?.view.addSubview(self)
        dialogView = UIView()
        dialogView.translatesAutoresizingMaskIntoConstraints = false

        dialogView.backgroundColor = .red
        addSubview(dialogView)

        let dialogViewCenterYConstraint = dialogView.centerYAnchor.constraint(equalTo: self.centerYAnchor)
        dialogViewCenterYConstraint.isActive = true

        let dialogViewHeightConstraint = dialogView.heightAnchor.constraint(equalToConstant: 200)
        dialogViewHeightConstraint.isActive = true

        let margins = self.layoutMarginsGuide

        let dialogViewLeadingConstraint = dialogView.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
        dialogViewLeadingConstraint.isActive = true

        let dialogViewTrailingConstraint = dialogView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
        dialogViewTrailingConstraint.isActive = true
    }

    override func layoutSubviews() {
        frame = UIScreen.main.bounds
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        CustomView().show()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

It is working, but it also prints the following warning:

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSAutoresizingMaskLayoutConstraint:0x60000009ee60 h=--& v=--& ArtAlertView.CustomView:0x7f9f86c0f770.width == 0   (active)>",
    "<NSLayoutConstraint:0x60000009ed20 UIView:0x7f9f86c100d0.leading == UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'.leading   (active)>",
    "<NSLayoutConstraint:0x60000009ed70 UIView:0x7f9f86c100d0.trailing == UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'.trailing   (active)>",
    "<NSLayoutConstraint:0x60000009eb90 'UIView-leftMargin-guide-constraint' H:|-(8)-[UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'](LTR)   (active, names: '|':ArtAlertView.CustomView:0x7f9f86c0f770 )>",
    "<NSLayoutConstraint:0x60000009ec30 'UIView-rightMargin-guide-constraint' H:[UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide']-(8)-|(LTR)   (active, names: '|':ArtAlertView.CustomView:0x7f9f86c0f770 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x60000009ed70 UIView:0x7f9f86c100d0.trailing == UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'.trailing   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

I noticed one of the constraints is an NSAutoresizingMaskLayoutConstraint. I thought setting translatesAutoresizingMaskIntoConstraints to false would get rid of these.

Any thoughts?


问:
Update syntax SQLite in ionic 2
I have this script for update my SQLite table,
I don't know why it doesn't work I have edited my query script but still doesn't work</p>

```<code>try{
    this.sqlite.create({
    name: 'msc.db',
    location: 'default'
  })
  .then((db: SQLiteObject) => {
     db.executeSql('update member set email = '+email+', phone= '+phone+'',{})
      .then(() => console.log('Truncate Table Success'))
      .catch(e => console.log(e));
  })
}catch(err){
  alert(err)
}
</code>```

答:
Always use a parameterized query. Check sample here. You are using Cordova-sqlite-storage with the ionic-native SQLite.</p>

```<code>try{
    this.sqlite.create({
    name: 'msc.db',
    location: 'default'
  })
  .then((db: SQLiteObject) => {

     db.executeSql('update member set email = ?, phone= ?',[email,phone])
      .then(() => console.log('Truncate Table Success'))
      .catch(e => console.log(e));
  })
}catch(err){
  alert(err)
}
</code>```

Title: Update syntax SQLite in ionic 2

Body:
I have this script for update my SQLite table,
I don't know why it doesn't work I have edited my query script but still doesn't work

try{
    this.sqlite.create({
    name: 'msc.db',
    location: 'default'
  })
  .then((db: SQLiteObject) => {
     db.executeSql('update member set email = '+email+', phone= '+phone+'',{})
      .then(() => console.log('Truncate Table Success'))
      .catch(e => console.log(e));
  })
}catch(err){
  alert(err)
}

Body:
Always use a parameterized query. Check sample here. You are using Cordova-sqlite-storage with the ionic-native SQLite.

try{
    this.sqlite.create({
    name: 'msc.db',
    location: 'default'
  })
  .then((db: SQLiteObject) => {

     db.executeSql('update member set email = ?, phone= ?',[email,phone])
      .then(() => console.log('Truncate Table Success'))
      .catch(e => console.log(e));
  })
}catch(err){
  alert(err)
}


问:
Keep an HTML element from spanning multiple pages when printed
I have the following HTML that I would like to keep from being broken up when spanning multiple pages. The problem is that if I use page-break-before or after, it will put each element on it's own page. The other problem I'm having is that if I set display: block on either the cell CSS class or the wrap class, the DIV or LI still gets broken up. I have a print media CSS file and a CSS file for the screen as well. I want to keep the
 element and its contents from being broken up.

```<code>        <div class="pad">
        <h1 style="text-align: center; margin: 10px 0">

            Work Orders for Jan 05, 2011
        </h1>
        <p class="printHidden">
            <a href="/orders/print-all/date/2011-01-05">Print All Work Orders</a>
        </p>
        <ul class="workorders">
            <li class="cell">
                <div class="wrap" id="146">

                    <div class="scheduled">
                        <p>
                            <strong>Work Order:</strong> <a href="/orders/view/work-order/146">158801</a>
                        </p>
                        <p>
                            <strong>Client:</strong> Client Name
                        </p><br>

                        <b>Resources</b>
                        <ul>
                            <li>
                                <a href="/resources/view/resource-id/5" id="Person-5">Mikell McLaindon</a>
                            </li>
                            <li>
                                <a href="/resources/view/resource-id/9" id="Person-9">Jose Copper</a>

                            </li>
                        </ul>
                    </div>
                    <div class="unschedule printHidden">
                        <h1 style="text-align: center; margin: 10px 0 10px; font-size: 12px; font-weight: bold;">
                            Unschedule Resource for 15880-PW
                        </h1>
                    </div>
                </div>
            </li>
            {... removed for brevity ...}
</code>```

答:
EDIT: PROPER SOLUTION

See: http://www.w3schools.com/css/pr_print_pagebi.asp
So if you add the following to your CSS it should fix your problem:

```<code>@media print
{
    div.pad { page-break-inside:avoid; }
}
</code>```

All the major desktop browsers now support this.

However, there is also page-break-after:avoid and page-break-before:avoid which you can add to every element within the .pad class in order to produce the same result in some older versions of browsers.

```<code>@media print
{
    div.pad * {
        page-break-after:avoid;
        page-break-before:avoid;
    }
}
</code>```

http://www.w3schools.com/Css/pr_print_pagebb.asp

http://www.w3schools.com/css/pr_print_pageba.asp

OLD ANSWER:

It sounds like you're trying to fit something on a page that doesn't fit on a page.  I would try adding a stylesheet with media="print"...

```<code><link rel="stylesheet" href="css/print.css" type="text/css" media="print" charset="utf-8" />
</code>```

...that reduces the font size, padding, etc. of all of these elements so that you CAN put a page break before this section and have it fit on the page.

Body:
I have the following HTML that I would like to keep from being broken up when spanning multiple pages. The problem is that if I use page-break-before or after, it will put each element on it's own page. The other problem I'm having is that if I set display: block on either the cell CSS class or the wrap class, the DIV or LI still gets broken up. I have a print media CSS file and a CSS file for the screen as well. I want to keep the
 element and its contents from being broken up.

            Work Orders for Jan 05, 2011

            Print All Work Orders

                            Work Order: 158801

                            Client: Client Name

                        Resources

                                Mikell McLaindon

                                Jose Copper

                            Unschedule Resource for 15880-PW

            {... removed for brevity ...}

Body:
EDIT: PROPER SOLUTION

See: http://www.w3schools.com/css/pr_print_pagebi.asp
So if you add the following to your CSS it should fix your problem:

@media print
{
    div.pad { page-break-inside:avoid; }
}

All the major desktop browsers now support this.

However, there is also page-break-after:avoid and page-break-before:avoid which you can add to every element within the .pad class in order to produce the same result in some older versions of browsers.

@media print
{
    div.pad * {
        page-break-after:avoid;
        page-break-before:avoid;
    }
}

http://www.w3schools.com/Css/pr_print_pagebb.asp

http://www.w3schools.com/css/pr_print_pageba.asp

OLD ANSWER:

It sounds like you're trying to fit something on a page that doesn't fit on a page.  I would try adding a stylesheet with media="print"...

<link rel="stylesheet" href="css/print.css" type="text/css" media="print" charset="utf-8" />

...that reduces the font size, padding, etc. of all of these elements so that you CAN put a page break before this section and have it fit on the page.


问:
how to auto numbering and repeat after new year in ASP.NET MVC
this for my controller to auto numbering

```<code>[HttpPost]
public ActionResult Index (updown viewModel)
{
    var number = db.updowns.OrderByDescending(x => x.tanggal).Select(z => z.tanggal).FirstOrDefault() ?? "00000";
    var lastPO = int.Parse(number.Substring(5, 5));
    item.tanggal = "EMOC-" + (++lastPO).ToString("00000") + "-S2/" + DateTime.Now.Year;

    db.updowns.Add(item);
    db.SaveChanges();
}
</code>```

I want after new year, the number 00000 will repeat to 00001 again

for example record in 2016

```<code>EMOC-00001-S2/2016
EMOC-00002-S2/2016
EMOC-00003-S2/2016
</code>```

and after new year will reapet the number to 00001 again like this

```<code>EMOC-00001-S2/2017
EMOC-00002-S2/2017
EMOC-00003-S2/2017
</code>```

can anyone help me, please write with code too to make me more understand..

sorry for my bad english

答:
something like this </p>

```<code> [HttpPost]
    public ActionResult Index (updown viewModel)
    {
        using (var dbContextTransaction = db.BeginTransaction())
        {
           var year =  DateTime.Now.Year("D4");
           var lastPO = db.updowns
               .Where(x => (x=> x.tangal.Substring(22 /* is it 22 ? */).Equals(year))
               .OrderByDescending(x => x.tanggal)
               .FirstOrDefault()?.tanggal.Substring(5, 5) ?? "00000";

           item.tanggal = "EMOC-" + (lastPO+1).ToString("00000")
                       + "-S2/" + DateTime.Now.Year;

           db.updowns.Add(item);
           db.SaveChanges();
       }
    }
</code>```

Body:
this for my controller to auto numbering

[HttpPost]
public ActionResult Index (updown viewModel)
{
    var number = db.updowns.OrderByDescending(x => x.tanggal).Select(z => z.tanggal).FirstOrDefault() ?? "00000";
    var lastPO = int.Parse(number.Substring(5, 5));
    item.tanggal = "EMOC-" + (++lastPO).ToString("00000") + "-S2/" + DateTime.Now.Year;

    db.updowns.Add(item);
    db.SaveChanges();
}

I want after new year, the number 00000 will repeat to 00001 again

for example record in 2016

EMOC-00001-S2/2016
EMOC-00002-S2/2016
EMOC-00003-S2/2016

and after new year will reapet the number to 00001 again like this

EMOC-00001-S2/2017
EMOC-00002-S2/2017
EMOC-00003-S2/2017

can anyone help me, please write with code too to make me more understand..

sorry for my bad english

Body:
something like this

 [HttpPost]
    public ActionResult Index (updown viewModel)
    {
        using (var dbContextTransaction = db.BeginTransaction())
        {
           var year =  DateTime.Now.Year("D4");
           var lastPO = db.updowns
               .Where(x => (x=> x.tangal.Substring(22 /* is it 22 ? */).Equals(year))
               .OrderByDescending(x => x.tanggal)
               .FirstOrDefault()?.tanggal.Substring(5, 5) ?? "00000";

           item.tanggal = "EMOC-" + (lastPO+1).ToString("00000")
                       + "-S2/" + DateTime.Now.Year;

           db.updowns.Add(item);
           db.SaveChanges();
       }
    }


问:
insert javascript var to thymeleaf url
How to insert JavaScript variable to thymeleaf URL?

example:

```<code>var i = x;
var actionCheck = /*[[@{/page/page1?action=add&param2=i}]]*/ '/memberrki/checkCardNum?action=add&param2=i}';
</code>```

param2 must be filled from var i ?

This is what I expected:

```<code>/memberrki/checkCardNum?action=add&param2=x
</code>```

答:
Simple perform some string concatenation

```<code>var i = x;
var actionCheck = '/memberrki/checkCardNum?action=add&param2=' + i;
</code>```

Or using ES6 template literals:

```<code>var i = x;
var actionCheck = `/memberrki/checkCardNum?action=add&param2=${i}`;
</code>```

Title: insert javascript var to thymeleaf url

Body:
How to insert JavaScript variable to thymeleaf URL?

example:

var i = x;
var actionCheck = /*[[@{/page/page1?action=add&param2=i}]]*/ '/memberrki/checkCardNum?action=add&param2=i}';

param2 must be filled from var i ?

This is what I expected:

/memberrki/checkCardNum?action=add&param2=x

Body:
Simple perform some string concatenation

var i = x;
var actionCheck = '/memberrki/checkCardNum?action=add&amp;param2=' + i;

Or using ES6 template literals:

var i = x;
var actionCheck = `/memberrki/checkCardNum?action=add&amp;param2=${i}`;


问:
Using bash, how do you make a classpath out of all files in a directory?
This will be a really simple freebie for a bash guru:

Question

Using bash, how do you make a classpath out of all files in a directory?

Details

Given a directory:

```<code>LIB=/path/to/project/dir/lib
</code>```

that contains nothing but *.jar files such as:

```<code>junit-4.8.1.jar
jurt-3.2.1.jar
log4j-1.2.16.jar
mockito-all-1.8.5.jar
</code>```

I need to create a colon-separated classpath variable in the form:

```<code>CLASSPATH=/path/to/project/dir/lib/junit-4.8.1.jar:/path/to/project/dir/lib/jurt-3.2.1.jar:/path/to/project/dir/lib/log4j-1.2.16.jar:/path/to/project/dir/lib/mockito-all-1.8.5.jar
</code>```

Some seudo-code that nearly expresses the logic I'm looking for would be along the lines of:

```<code>for( each file in directory ) {
   classpath = classpath + ":" + LIB + file.name
}
</code>```

What is a simple way to accomplish this via bash script?

答:
Bestest

Everything is better with awk =)

```<code>CLASSPATH=$(awk '$0=lib"/"FILENAME' ORS=":" lib=$LIB *.jar)
</code>```

Body:
This will be a really simple freebie for a bash guru:

Question

Using bash, how do you make a classpath out of all files in a directory?

Details

Given a directory:

LIB=/path/to/project/dir/lib

that contains nothing but *.jar files such as:

junit-4.8.1.jar
jurt-3.2.1.jar
log4j-1.2.16.jar
mockito-all-1.8.5.jar

I need to create a colon-separated classpath variable in the form:

CLASSPATH=/path/to/project/dir/lib/junit-4.8.1.jar:/path/to/project/dir/lib/jurt-3.2.1.jar:/path/to/project/dir/lib/log4j-1.2.16.jar:/path/to/project/dir/lib/mockito-all-1.8.5.jar

Some seudo-code that nearly expresses the logic I'm looking for would be along the lines of:

for( each file in directory ) {
   classpath = classpath + ":" + LIB + file.name
}

What is a simple way to accomplish this via bash script?

Body:
Bestest

Everything is better with awk =)

CLASSPATH=$(awk '$0=lib"/"FILENAME' ORS=":" lib=$LIB *.jar)


问:
Click to display none/block with conditionals
I don't know why the else conditional isn't working, I have tried multiple methods.

```<code>if($('hiddendDiv').attr('style') === 'display:none') {
    $('buttonDiv').click(function() {
        $('hiddendDiv').attr('style',"display:block");
    });
} else {
    $('body').click(function(){
        $('hiddendDiv').attr('style',"display:none");
    });
}
</code>```

hiddendDiv has style="display:none"

When I click the buttonDiv, the hiddenDiv gets display: block, and after that when I click anywhere on the page (to close hiddenDiv), the hiddenDiv doesn't get display: none.

I am trying to make a
 that opens when I click a button, and closes when I click anywhere on the page.

答:
$(document).on('click', '#test', function () {
    if ($('#text').hasClass("disabled")) {
        $('#text').css("display", "none");
        $('#text').removeClass('disabled');
    }
    else
    {
        $('#text').css("display", "block");
        $('#text').addClass('disabled');
    }

});```

Body:
I don't know why the else conditional isn't working, I have tried multiple methods.

if($('hiddendDiv').attr('style') === 'display:none') {
    $('buttonDiv').click(function() {
        $('hiddendDiv').attr('style',"display:block");
    });
} else {
    $('body').click(function(){
        $('hiddendDiv').attr('style',"display:none");
    });
}

hiddendDiv has style="display:none"

When I click the buttonDiv, the hiddenDiv gets display: block, and after that when I click anywhere on the page (to close hiddenDiv), the hiddenDiv doesn't get display: none.

I am trying to make a
 that opens when I click a button, and closes when I click anywhere on the page.


问:
Read int OR float from file in C
Let's consider a file of less than 10 numbers which can either int or float. I want to read them and add them to an array.

The issue I'm facing is that I can do that well if I have only ints for example,  but it messes things up whenever it reaches a float

in file.data

```<code>11
22
33.3
44
55
</code>```

my code :

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void usage(char * message) ;

int main(int argc, char * argv[]){

    //opening the file
    FILE * flux = fopen("file.data", "r");
    if (!flux) usage("error opening the file");

    int array[10]; //array to host the data
    int i=0;
    int lu;

    while ((lu = fscanf(flux, "%i", &array[i])) !=EOF && i<10){
        printf("lu %i\n", lu );
        printf("array[%i] %i\n", i, array[i] );
        printf("\n");
        i++;
    }

    return 0 ; }

void usage(char * message) { fprintf(stderr, "%s\n", message) ; exit(1) ;}
</code>```

output :

```<code>lu 1
array[0] 11

lu 1
array[1] 22

lu 1
array[2] 33

lu 0
array[3] 0

lu 0
array[4] 4196464

lu 0
array[5] 0

lu 0
array[6] 4195936

lu 0
array[7] 0

lu 0
array[8] 904651696

lu 0
array[9] 32766
</code>```

How can I use fscanf so that it doesn't get bogged down when it reaches a float?

(I can tell that it doesn't seem right to declare an array of int and to try to input some float... any way around that?)

edit:
my goal is to be able to read my array and print its content with their index, for example with my data :

```<code>0. 11
1. 22
2. 33.3
3. 44
4. 55
</code>```

答:
Do you only need integers? If so you can read float and convert them into integers before putting them in the array:</p>

```<code>float tmp;
while ((lu = fscanf(flux, "%f", &tmp)) !=EOF && i<10){
    array[i] = (int)tmp; //you could use some rounding here
    printf("lu %i\n", lu );
    printf("array[%i] %i\n", i, array[i] );
    printf("\n");
    i++;
}
</code>```

Title: Read int OR float from file in C

Body:
Let's consider a file of less than 10 numbers which can either int or float. I want to read them and add them to an array.

The issue I'm facing is that I can do that well if I have only ints for example,  but it messes things up whenever it reaches a float

in file.data

11
22
33.3
44
55

my code :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void usage(char * message) ;

int main(int argc, char * argv[]){

    //opening the file
    FILE * flux = fopen("file.data", "r");
    if (!flux) usage("error opening the file");

    int array[10]; //array to host the data
    int i=0;
    int lu;

    while ((lu = fscanf(flux, "%i", &array[i])) !=EOF && i<10){
        printf("lu %i\n", lu );
        printf("array[%i] %i\n", i, array[i] );
        printf("\n");
        i++;
    }

    return 0 ; }

void usage(char * message) { fprintf(stderr, "%s\n", message) ; exit(1) ;}

output :

lu 1
array[0] 11

lu 1
array[1] 22

lu 1
array[2] 33

lu 0
array[3] 0

lu 0
array[4] 4196464

lu 0
array[5] 0

lu 0
array[6] 4195936

lu 0
array[7] 0

lu 0
array[8] 904651696

lu 0
array[9] 32766

How can I use fscanf so that it doesn't get bogged down when it reaches a float?

(I can tell that it doesn't seem right to declare an array of int and to try to input some float... any way around that?)

edit:
my goal is to be able to read my array and print its content with their index, for example with my data :

0. 11
1. 22
2. 33.3
3. 44
4. 55

Body:
Do you only need integers? If so you can read float and convert them into integers before putting them in the array:

float tmp;
while ((lu = fscanf(flux, "%f", &tmp)) !=EOF && i<10){
    array[i] = (int)tmp; //you could use some rounding here
    printf("lu %i\n", lu );
    printf("array[%i] %i\n", i, array[i] );
    printf("\n");
    i++;
}


问:
Lodash groupBy with moment
I am trying to group a bunch of dates by today, this week, this month and then previous months. However before I even get to this point I am struggling to get even a basic grouping by month.

```<code>const data = [{
 campaign: "Charles",
 company_ID: "1",
 coreURL: "http://www.test77.com",
 createdAt: "2017-11-06T20:45:56.931Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-09-06T20:45:56.931Z",
 _id: "6gsb42PSSJt7PgsDG"
}, {
 campaign: "Charles",
 company_ID: "1",
 coreURL: "http://www.test66,com",
 createdAt: "2017-11-06T20:46:27.744Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-10-06T20:46:27.744Z",
 _id: "Md4wCnEsrQrWApnLS"
}, {
 campaign: "Gary",
 company_ID: "1",
 coreURL: "http://www.test55,com",
 createdAt: "2017-11-06T20:46:27.744Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-07-06T20:46:27.744Z",
 _id: "5p44uiwRgqp35YXRf"
}
];

const grouper = 'updatedAt';

let groupedData = _
  .chain(data)
  .groupBy(datum => moment(datum.grouper).format("MM"))
</code>```

EDIT: However this only seems to group by "11" (todays Month)

Any help would be really appreciated

答:
```<code>let groupedData = _
.chain(data)
.groupBy(record => moment(record.updatedAt).format("MM"))
.value();
</code>```

Title: Lodash groupBy with moment

Body:
I am trying to group a bunch of dates by today, this week, this month and then previous months. However before I even get to this point I am struggling to get even a basic grouping by month.

const data = [{
 campaign: "Charles",
 company_ID: "1",
 coreURL: "http://www.test77.com",
 createdAt: "2017-11-06T20:45:56.931Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-09-06T20:45:56.931Z",
 _id: "6gsb42PSSJt7PgsDG"
}, {
 campaign: "Charles",
 company_ID: "1",
 coreURL: "http://www.test66,com",
 createdAt: "2017-11-06T20:46:27.744Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-10-06T20:46:27.744Z",
 _id: "Md4wCnEsrQrWApnLS"
}, {
 campaign: "Gary",
 company_ID: "1",
 coreURL: "http://www.test55,com",
 createdAt: "2017-11-06T20:46:27.744Z",
 owner: "K7xTxu7PRDCuhFZRC",
 updatedAt: "2017-07-06T20:46:27.744Z",
 _id: "5p44uiwRgqp35YXRf"
}
];

const grouper = 'updatedAt';

let groupedData = _
  .chain(data)
  .groupBy(datum => moment(datum.grouper).format("MM"))

EDIT: However this only seems to group by "11" (todays Month)

Any help would be really appreciated


问:
How to round off timestamp in milliseconds to nearest seconds?
How to round off the current timestamp in milliseconds to seconds?

If this is the current timestamp in milliseconds I have -

```<code>1384393612958
</code>```

The if I am rounding off to nearest second then will it be like this?

```<code>Time in MS rounded off to nearest Second = 1384393612000
</code>```

I might need to do this both in Java and C++.

答:
```<code>This is needed to convert java date object to mysql datetime formatted string in sql queries.
</code>```

Conversion:

```<code>Calendar cal = Calendar.getInstance();
cal.setTime(this.id.getCreatedOn());
if (cal.get(Calendar.MILLISECOND) >= 500 ) {
  System.out.println("Round off milliseconds to seconds");
  cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) + 1);
}
Date roundedCreatedOn = cal.getTime();
</code>```

Actual query string contains:

createdOn = '" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(roundedCreatedOn)+ "'"

Body:
How to round off the current timestamp in milliseconds to seconds?

If this is the current timestamp in milliseconds I have -

1384393612958

The if I am rounding off to nearest second then will it be like this?

Time in MS rounded off to nearest Second = 1384393612000

I might need to do this both in Java and C++.

Body:
This is needed to convert java date object to mysql datetime formatted string in sql queries.

Conversion:

Calendar cal = Calendar.getInstance();
cal.setTime(this.id.getCreatedOn());
if (cal.get(Calendar.MILLISECOND) >= 500 ) {
  System.out.println("Round off milliseconds to seconds");
  cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) + 1);
}
Date roundedCreatedOn = cal.getTime();

Actual query string contains:

createdOn = '" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(roundedCreatedOn)+ "'"


问:
Grails searchable plugin
In my Grails app, I have the following domain class that is indexed by the Searchable plugin:

```<code>class Foo implements Serializable {

    BookletCategory bookletCategory
    Date lastUpdated
    static hasMany = [details: BookletRootDetail]

    static searchable = {
        bookletCategory component: true
        id name: 'bookletRootId'
        lastUpdated index: 'no'
    }
}
</code>```

When I retrieve instances of this class, the details property is always null, even though there are details instances in the database. My conclusion is that the details field is not being stored in the Lucene index. I tried adding this field to the index without making it a searchable property by adding the following to the searchable closure:

```<code>details index: 'no'
</code>```

However it seems this is only valid for simple properties such as lastUpdated. Is there any way that I can ensure this property is populated when I retrieve instances of Foo from the index? Ideally I would like to do this without actually making details a searchable field?

答:
You need to make sure that BookletRootDetail is searchable and then in Foo put it as a searchable component.

Something like:

```<code>class Foo implements Serializable {

    BookletCategory bookletCategory
    Date lastUpdated
    static hasMany = [details: BookletRootDetail]

    static searchable = {
        bookletCategory component: true
        id name: 'bookletRootId'
        lastUpdated index: 'no'
        details component: true
    }
}
</code>```

Then

```<code>class BookletRootDetail {
  static searchable = true
}
</code>```

You don't need BookletRootDetail to have a belongsTo relation with Foo.

Title: Grails searchable plugin

Body:
In my Grails app, I have the following domain class that is indexed by the Searchable plugin:

class Foo implements Serializable {

    BookletCategory bookletCategory
    Date lastUpdated
    static hasMany = [details: BookletRootDetail]

    static searchable = {
        bookletCategory component: true
        id name: 'bookletRootId'
        lastUpdated index: 'no'
    }
}

When I retrieve instances of this class, the details property is always null, even though there are details instances in the database. My conclusion is that the details field is not being stored in the Lucene index. I tried adding this field to the index without making it a searchable property by adding the following to the searchable closure:

details index: 'no'

However it seems this is only valid for simple properties such as lastUpdated. Is there any way that I can ensure this property is populated when I retrieve instances of Foo from the index? Ideally I would like to do this without actually making details a searchable field?

Body:
You need to make sure that BookletRootDetail is searchable and then in Foo put it as a searchable component.

Something like:

class Foo implements Serializable {

    BookletCategory bookletCategory
    Date lastUpdated
    static hasMany = [details: BookletRootDetail]

    static searchable = {
        bookletCategory component: true
        id name: 'bookletRootId'
        lastUpdated index: 'no'
        details component: true
    }
}

Then

class BookletRootDetail {
  static searchable = true
}

You don't need BookletRootDetail to have a belongsTo relation with Foo.


问:
Java script Popup window is opening with fullscreen in Windows10+IE Edge
In Windows10 with IE edge when I want to open a popup with below code its always showing full screen pop up window.Ideally by default 'fullscreen=no' but same code is working in windows7 with IE11.

Sample code :

```<code>myaddress=url //to for popupwindows
win = window.open(myaddress,"test","width=500,height=500,location=no,status=no,menubar=no,toolbar=no,resizable=no,scrollbars=1");
</code>```

As I am new to javascript could you please help me on this

Thanks,
SPradhan

答:
It depend on how do you create this. For example, in button onClick listener:

Html:

```<code><input id='foo' type=button value="Click me" />
</code>```

And in JavaScript:

```<code>var e = document.getElementById('foo');
e.onclick = test;

function test(){
  window.open('google.com',"test","width=500,height=500,location=no,status=no,menubar=no,toolbar=no,resizable=no,scrollbars=1");
}
</code>```

Fiddle:
https://jsfiddle.net/jackyle/rdo4py0s/

Body:
In Windows10 with IE edge when I want to open a popup with below code its always showing full screen pop up window.Ideally by default 'fullscreen=no' but same code is working in windows7 with IE11.

Sample code :

myaddress=url //to for popupwindows
win = window.open(myaddress,"test","width=500,height=500,location=no,status=no,menubar=no,toolbar=no,resizable=no,scrollbars=1");

As I am new to javascript could you please help me on this

Thanks,
SPradhan

Body:
It depend on how do you create this. For example, in button onClick listener:

Html:

<input id='foo' type=button value="Click me" />

And in JavaScript:

var e = document.getElementById('foo');
e.onclick = test;

function test(){
  window.open('google.com',"test","width=500,height=500,location=no,status=no,menubar=no,toolbar=no,resizable=no,scrollbars=1");
}

Fiddle:
https://jsfiddle.net/jackyle/rdo4py0s/


问:
How to get current displayed date range in full calendar jquery
I have implemented fullcalendar in my application. I am facing a problem for getting current displayed date range.
I want to get currently displayed date range in full calendar.
Please suggest me a proper solution.

For example please take a look on this image

In this I want to get "20 Sept" and "26 Sept".

答:
```<code>$('#mycalendar').fullCalendar('getView').start.format('DD MMM');
$('#mycalendar').fullCalendar('getView').end.format('DD MMM');
</code>```


问:
Leaflet map is not showing the line from gpx file
I am having a weird issue with the leaflet.js map. For some reason, the trail line does not appear on the map even though it shows all the markers. It works fine in a standalone simple html page but whenever I embed this in the bootstrap template it breaks. My MVC .chtml page has the following code and jquery is referenced from the Layout page.

```<code>     <script src="https://maps.googleapis.com/maps/api/js?key=<key>" async defer></script>
    <link rel="stylesheet" href="http://unpkg.com/leaflet@1.2.0/dist/leaflet.css" />
    <script src="http://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/leaflet-easybutton@2.0.0/src/easy-button.css">
    <script src="https://unpkg.com/leaflet-easybutton@2.0.0/src/easy-button.js"></script>
    <script src='~/Scripts/Leaflet.GoogleMutant.js'></script>
    <script src="~/Scripts/leaflet.markercluster-src.js"></script>
    <link href="~/Content/MarkerCluster.css" rel="stylesheet" />
    <link href="~/Content/MarkerCluster.Default.css" rel="stylesheet" />
    <script src="~/Scripts/app/GPX.js"></script>
     <div id="mapView">
                        <!-- This is the div that will contain the Google Map -->
                        <div id="lmap"></div>

                    </div>
<scripts>
    $(function(e){

        var lcontrol = new L.control.layers();
        var eb = new L.control.layers();
        //initialize map
        var map = null;
        var markers = [];
        var latlng = L.latLng(-30.81881, 116.16596);
       //set the layers
        var roadMutant = L.gridLayer.googleMutant({ type: 'roadmap' });
        var satMutant = L.gridLayer.googleMutant({ maxZoom: 24, type: 'satellite' });
        var terrainMutant = L.gridLayer.googleMutant({ maxZoom: 24, type: 'terrain' });
        var hybridMutant = L.gridLayer.googleMutant({ maxZoom: 24, type: 'hybrid' });

        map = new L.map('lmap', {
            center: latlng, zoom: 6, maxZoom: 18, scrollwheel: false, layers: [roadMutant],
            streetViewControl: false, scrollWheelZoom: false,
        });

        var track = new L.GPX("/media/fells_loop.gpx", {
            async: true
        }).on("loaded", function (e) {
            map.fitBounds(e.target.getBounds());
        });
        map.addLayer(track);

        map.on('focus', function () { map.scrollWheelZoom.enable(); });
        map.on('blur', function () { map.scrollWheelZoom.disable(); });

    var baseLayers = {
            "Streets": roadMutant,
            "Satellite": satMutant,
            "Terrain": terrainMutant,
            "Hybrid": hybridMutant,

        };

    map.addControl(new L.Control.Layers(baseLayers, { 'GPX': track }, { collapsed: true }));
}
</scripts>
</code>```

The clustering use jQuery get request to fetch data like below -

```<code> markers = L.markerClusterGroup({ chunkedLoading: true, spiderfyOnMaxZoom: true, maxClusterRadius: 100, showCoverageOnHover: true });

        //map.eachLayer(function (layer) {
        //    map.removeLayer(layer);
        //});
        L.Map.include({
            'clearLayers': function () {
                this.eachLayer(function (layer) {
                    this.removeLayer(layer);
                }, this);
            }
        });

    //clear markers and remove all layers
        markers.clearLayers();
        var h = $(window).height();
        var w = $(window).width();

    var atype = $('input:checkbox:checked.gp1').map(function () {
        return this.value;
    }).get(); // ["18", "55", "10"]

    var st = atype + "";
    //fetch data
    $.ajax({
        type: "GET",
        url: appUrl + "/Home/map",
        data: {'atype': st},
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded',
        success: function (data) {

            $.each(data, function (i, item) {
                var img = (item.IconUrl).replace("~", "");
                var dpawIcon = L.icon({ iconUrl: appUrl + img, iconSize: [42, 42] });
                var id;
                var marker = L.marker(L.latLng(item.Latitude, item.Longitude), { icon: dpawIcon }, { title: item.Name });
                var content = "<div class='infoDiv'><h3><img src='" + appUrl + img + "' width='24' />" + item.Name + "</h3><p>" + item.Title + "</p><a href='#' data-value='" + item.AlertId + "' class='btn btn-success btn-sm' data-toggle='modal' data-target='#alertDetails'>Details</a></div>";
                id = marker._leaflet_id;
                marker.bindPopup(content);
                markers.addLayer(marker);

            });
        }

    })
   .done(function () {
       $(".loadingOverlay").hide();

      // $("#lmap").height(h-100).width(w-210);
       map.invalidateSize(true);

   });
</code>```

Thanks in advance for your help.

答:
Finally, I found the problem after separating all css, js and other scripts files to narrow down to the root cause of the issue. It was actually the custom CSS file which has svg width attribute was set to 100%. I have removed that line and it is working fine now. Removed the following line.

```<code>svg { width: 100%; }
</code>```

Hope this might help others with the similar issues.

Body:
I am having a weird issue with the leaflet.js map. For some reason, the trail line does not appear on the map even though it shows all the markers. It works fine in a standalone simple html page but whenever I embed this in the bootstrap template it breaks. My MVC .chtml page has the following code and jquery is referenced from the Layout page.

    <link rel="stylesheet" href="http://unpkg.com/leaflet@1.2.0/dist/leaflet.css" />

    <link rel="stylesheet" href="https://unpkg.com/leaflet-easybutton@2.0.0/src/easy-button.css">

    <link href="~/Content/MarkerCluster.css" rel="stylesheet" />
    <link href="~/Content/MarkerCluster.Default.css" rel="stylesheet" />

The clustering use jQuery get request to fetch data like below -

 markers = L.markerClusterGroup({ chunkedLoading: true, spiderfyOnMaxZoom: true, maxClusterRadius: 100, showCoverageOnHover: true });

        //map.eachLayer(function (layer) {
        //    map.removeLayer(layer);
        //});
        L.Map.include({
            'clearLayers': function () {
                this.eachLayer(function (layer) {
                    this.removeLayer(layer);
                }, this);
            }
        });

    //clear markers and remove all layers
        markers.clearLayers();
        var h = $(window).height();
        var w = $(window).width();

    var atype = $('input:checkbox:checked.gp1').map(function () {
        return this.value;
    }).get(); // ["18", "55", "10"]

    var st = atype + "";
    //fetch data
    $.ajax({
        type: "GET",
        url: appUrl + "/Home/map",
        data: {'atype': st},
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded',
        success: function (data) {

            $.each(data, function (i, item) {
                var img = (item.IconUrl).replace("~", "");
                var dpawIcon = L.icon({ iconUrl: appUrl + img, iconSize: [42, 42] });
                var id;
                var marker = L.marker(L.latLng(item.Latitude, item.Longitude), { icon: dpawIcon }, { title: item.Name });
                var content = "

" + item.Name + "

" + item.Title + "
Details
";
                id = marker._leaflet_id;
                marker.bindPopup(content);
                markers.addLayer(marker);

            });
        }

    })
   .done(function () {
       $(".loadingOverlay").hide();

      // $("#lmap").height(h-100).width(w-210);
       map.invalidateSize(true);

   });

Thanks in advance for your help.

Body:
Finally, I found the problem after separating all css, js and other scripts files to narrow down to the root cause of the issue. It was actually the custom CSS file which has svg width attribute was set to 100%. I have removed that line and it is working fine now. Removed the following line.

svg { width: 100%; }

Hope this might help others with the similar issues.


问:
return self.user as foreignkey
I have a model with foreignkeys. For this model I want to set the 'def str' as the user.

I have done this

```<code>from django.contrib.auth import get_user_model

User = get_user_model()

class Rosters(models.Model):
        place = models.ForeignKey('Places')
        position = models.ForeignKey('Positions', blank=True, null=True)
        user = models.ForeignKey(User, related_name='roster')
        validfrom = models.DateTimeField(blank=True, null=True)
        validto = models.DateTimeField(blank=True, null=True)

        def __str__(self):
            return self.user
</code>```

This will fetch username and show in admin pages. But when I try to create a new Roster. I get a TypeError __str__ returned non-string (type User)

I can remove the 'def str...' and create a Roster with no problem. But each Roster shows as Object in admin pages. So I can add back the 'def str..' to see the usernames of each roster.

I want them to always display as usernames. And I can't figure out why it's not working when I'm adding rosters.

答:
As your error show:

```<code>TypeError __str__ returned non-string (type User)
</code>```

The __str__ method should return a str, and here, you are returning an object (User).

You should return return self.user.__str__ instead (The str representation of the user).

Title: return self.user as foreignkey

Body:
I have a model with foreignkeys. For this model I want to set the 'def str' as the user.

I have done this

from django.contrib.auth import get_user_model

User = get_user_model()

class Rosters(models.Model):
        place = models.ForeignKey('Places')
        position = models.ForeignKey('Positions', blank=True, null=True)
        user = models.ForeignKey(User, related_name='roster')
        validfrom = models.DateTimeField(blank=True, null=True)
        validto = models.DateTimeField(blank=True, null=True)

        def __str__(self):
            return self.user

This will fetch username and show in admin pages. But when I try to create a new Roster. I get a TypeError __str__ returned non-string (type User)

I can remove the 'def str...' and create a Roster with no problem. But each Roster shows as Object in admin pages. So I can add back the 'def str..' to see the usernames of each roster.

I want them to always display as usernames. And I can't figure out why it's not working when I'm adding rosters.

Body:
As your error show:

TypeError __str__ returned non-string (type User)

The __str__ method should return a str, and here, you are returning an object (User).

You should return return self.user.__str__ instead (The str representation of the user).


问:
Adding dynamic row to ngTable not displaying
I have created an application with ngTable using grouping functionality, The application is working fine but the problem is that when I add dynamic data (rows) to the table, its not reflecting dynamically, unless or otherwise when we click the table title for sorting or when we click the pagination

I have recreated the problem within a plunker, there you can find a button, when clicked one Dynamic row is added but not reflecting within the table

PLUNKER

```<code>  <body ng-app="main" ng-controller="DemoCtrl">
  <button ng-click="addDynamicDatas()">Add Datas</button>
    <table ng-table="tableParamsOne" class="table">
      <tbody ng-repeat="group in $groups">
        <tr class="ng-table-group" ng-hide="group.data[0].role==='None'">
          <td>
              <strong>{{ group.value }}</strong>
          </td>
        </tr>

        <tr ng-repeat="user in group.data">
          <td sortable="name" data-title="'Name'">
               <span ng-class="{'bold-text': user.role=='None'}" ng-show="user.role==='None'"> {{user.name}}</span>
            </td>
          <td sortable="age" data-title="'Age'">
                {{user.age}}
            </td>
        </tr>
      </tbody>
    </table>
  </body>
</code>```

add function

```<code>$scope.addDynamicDatas = function()
{
   $scope.myDataOne.push({name: "Abcd", age: 10, role: 'Administrator'});
}
</code>```

Can anyone please tell me some solution for this?

答:
I am also using ng-table(@4.0.0) to make local/client-side insertion/deletion after a successful server submit and got the similar problem of update ng-table. @Bradley's answer above does not work directly. So I chased the source code and found that the reload() called the getData(). After insert a row into the target rowset (ctrl.tbContents.rows in my case), I have to add bellow line in mytbParams definition to make ctrl.tbParams.reload() work:

```<code>getData: function() {
  return ngTableDefaultGetData(ctrl.tbContents.rows, ctrl.tbParams);
}
</code>```

Note to inject the ngTableDefaultGetData.

Body:
I have created an application with ngTable using grouping functionality, The application is working fine but the problem is that when I add dynamic data (rows) to the table, its not reflecting dynamically, unless or otherwise when we click the table title for sorting or when we click the pagination

I have recreated the problem within a plunker, there you can find a button, when clicked one Dynamic row is added but not reflecting within the table

PLUNKER

  <button ng-click="addDynamicDatas()">Add Datas</button>

              {{ group.value }}

                {{user.name}}

                {{user.age}}

add function

$scope.addDynamicDatas = function()
{
   $scope.myDataOne.push({name: "Abcd", age: 10, role: 'Administrator'});
}

Can anyone please tell me some solution for this?

Body:
I am also using ng-table(@4.0.0) to make local/client-side insertion/deletion after a successful server submit and got the similar problem of update ng-table. @Bradley's answer above does not work directly. So I chased the source code and found that the reload() called the getData(). After insert a row into the target rowset (ctrl.tbContents.rows in my case), I have to add bellow line in mytbParams definition to make ctrl.tbParams.reload() work:

getData: function() {
  return ngTableDefaultGetData(ctrl.tbContents.rows, ctrl.tbParams);
}

Note to inject the ngTableDefaultGetData.


问:
Centering the navbar links
I have tried most of the approach, but I'm unable to center align the links in my navbar.

.navbar-nav {
  margin: 30px 20px !important;
}

a {
  /* color: #fff !important;*/
  font-family: 'Caesar Dressing';
  font-size: 18px;
  padding: 10px 30px !important;
}

a:hover {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

.active {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<body>
  <div class="container-fluid bg">
    <nav class="navbar">
      <div class="container-fluid">
        <ul class="nav navbar-nav">
          <li class="active">Home</li>
          <li>About</li>
          <li>Education</li>
          <li>Contact</li>
        </ul>
      </div>
    </nav>
  </div>
</body></code>```

this is what I'm getting

But I want all the 4 links to be vertically centered on the screen

答:
```<code>.navbar-nav > li > a
{
  text-align :center;
}
</code>```

add thin to your css.

Title: Centering the navbar links

Body:
I have tried most of the approach, but I'm unable to center align the links in my navbar.

.navbar-nav {
  margin: 30px 20px !important;
}

a {
  /* color: #fff !important;*/
  font-family: 'Caesar Dressing';
  font-size: 18px;
  padding: 10px 30px !important;
}

a:hover {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

.active {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

Home

About

Education

Contact

this is what I'm getting

But I want all the 4 links to be vertically centered on the screen

Body:
.navbar-nav > li > a
{
  text-align :center;
}

add thin to your css.


答:
you can only return string from __str__ not user which is an object.

```<code>def __str__(self):
    return self.user.username
</code>```

Title: return self.user as foreignkey

Body:
you can only return string from __str__ not user which is an object.

def __str__(self):
    return self.user.username


问:
How to run google tests completely isolated from each other?
I want to use Address Sanitizer to detect runtime errors while unit tests are running. However, Address Sanitizer terminates the app when it finds the first error so I can't see an information of all found runtime errors in one report. It would be possible if I could run google tests isolated from each other, and termination of one test woudn't influence other ones.</p>

答:
You can run specific test cases in Google Test, one by one.

From: https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#running-a-subset-of-the-tests

By default, a Google Test program runs all tests the user has defined.
  Sometimes, you want to run only a subset of the tests (e.g. for
  debugging or quickly verifying a change). If you set the GTEST_FILTER
  environment variable or the --gtest_filter flag to a filter string,
  Google Test will only run the tests whose full names (in the form of
  TestCaseName.TestName) match the filter.

The format of a filter is a ':'-separated list of wildcard patterns
  (called the positive patterns) optionally followed by a '-' and
  another ':'-separated pattern list (called the negative patterns). A
  test matches the filter if and only if it matches any of the positive
  patterns but does not match any of the negative patterns.

A pattern may contain '' (matches any string) or '?' (matches any
  single character). For convenience, the filter '-NegativePatterns'
  can be also written as '-NegativePatterns'.

For example:

./foo_test Has no flag, and thus runs all its tests.

./foo_test --gtest_filter=* Also runs everything, due to the single
  match-everything * value.

./foo_test --gtest_filter=FooTest.* Runs everything in test case
  FooTest.

./foo_test --gtest_filter=Null:Constructor Runs any test whose
  full name contains either "Null" or "Constructor".

./foo_test --gtest_filter=-DeathTest. Runs all non-death tests.

./foo_test --gtest_filter=FooTest.*-FooTest.Bar Runs everything in
  test case FooTest except FooTest.Bar.