问:
keys in object are undefined but object is not (react-redux)
So I have a strange issue with the data I'm fetching from an API. In my reducer I've set the initial state to an empty object and in my component's render method I'm accessing this fetched data using this.props.data.value.one.

The actual fetched data from the API look like this:

```<code>{data:
  {value: {one: '1'}}
}
</code>```

However when I try to console.log(this.props.data) it will log {value: {one: '1'}} after logging undefined a couple of times but will log this.props.data.value.one as undefined.

I'm doing similar stuff in my other reducers which are getting data from other API's and they work fine.

App.js Component:

```<code>@connect(store => store)
...
componentWillMount = () => {//API Call here}
render = () => {
 return (
    <div><p>{this.props.data.value.one}</p><div>
 )
}
</code>```

reducer.js:

```<code>...
export default function reducer(state={data: {}}, action) {
  ...
  case 'FETCHED_DATA':
    return {...state, data: action.data}
</code>```

action.js:

```<code>...
fetchData = user => dispatch => {
  //request.get...
     .then(res => dispatch({type: 'FETCHED_DATA', data: res.body.data})
}
</code>```

答: Since you have defined initial state as data: {}, and not as data : {value : ''}, and thus when you fetched data from the api data object is not initialized as data.value to access it. Setting it to the latter should work.</p>

Body:
So I have a strange issue with the data I'm fetching from an API. In my reducer I've set the initial state to an empty object and in my component's render method I'm accessing this fetched data using this.props.data.value.one.

The actual fetched data from the API look like this:

{data:
  {value: {one: '1'}}
}

However when I try to console.log(this.props.data) it will log {value: {one: '1'}} after logging undefined a couple of times but will log this.props.data.value.one as undefined.

I'm doing similar stuff in my other reducers which are getting data from other API's and they work fine.

App.js Component:

@connect(store => store)
...
componentWillMount = () => {//API Call here}
render = () => {
 return (

{this.props.data.value.one}

 )
}

reducer.js:

...
export default function reducer(state={data: {}}, action) {
  ...
  case 'FETCHED_DATA':
    return {...state, data: action.data}

action.js:

...
fetchData = user => dispatch => {
  //request.get...
     .then(res => dispatch({type: 'FETCHED_DATA', data: res.body.data})
}


来源: stackexchange

问:
Quote needed: Preprocessor usage is bad OO practice
I believe, that the usage of preprocessor directives like #if UsingNetwork is bad OO practice - other coworkers do not.
I think, when using an IoC container (e.g. Spring), components can be easily configured if programmed accordingly. In this context either a propery IsUsingNetwork can be set by the IoC container or, if the "using network" implementation behaves differently, another implementation of that interface should be implemented and injected (e.g.: IService, ServiceImplementation, NetworkingServiceImplementation).

Can somebody please provide citations of OO-Gurus or references in books which basically reads "Preprocessor usage is bad OO practice if you try to configure behaviour which should be configured via an IoC container"?

I need this citations to convince coworkers to refactor...

Edit: I do know and agree that using preprocessor directives to change targetplatform specific code during compilation is fine and that is what preprocessor directives are made for. However, I think that runtime-configuration should be used rather than compiletime-configuration to get good designed and testable classes and components. In other words: Using #defines and #if's beyond what they are meant for will lead to difficult to test code and badly designed classes.

Has anybody read something along these lines and can give me so I can refer to?

答: "The preprocessor is the incarnation of evil, and the cause of all pain on earth" -Robert (OO Guru)

OwnerDisplayName: tobsen

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: tobsen

OwnerDisplayName: Robert Gould

ContentLicense: CC BY-SA 2.5


问:
Big blank space HTML
In some area I have this big space between some sentence:

Is there a way to correct this with CSS?

HTML for a second example:

```<code><span style="color: rgb(197, 0, 0); text-align: justify; font-size: 14px;">
    <span id="MainContent_rptTest_lblTitle_2">Support to Efficient, Effictive and Transparent</span><br>
        <div style="color: rgb(197, 0, 0); text-align: justify; font-size: 12px;">
            <strong>
                <span id="MainContent_rptTest_lblDescription_2">September 2009 – January 2010</span></strong></div>
    </span>
</code>```

答: I'm guessing that the culprit is the css-style: text-align:justify which makes sure that each line of text is the same length</p>

Title: Big blank space HTML

Body:
In some area I have this big space between some sentence:

Is there a way to correct this with CSS?

HTML for a second example:

    Support to Efficient, Effictive and Transparent

                September 2009 – January 2010


问:
How to fill empty string with %20 from an array of strings ios
I have a String array which I found from JSON object. It's an Image array containing 4 images presently.I don't know how many images I will get in future.
My Question is the Image URL is not showing in my ImageView Because it contains some blank space with it.I have already checked if this space is replaced with %20 then I can happily use it in my ImageView.

Can Anyone Suggest me how can I replace all the blank space from all the image String URL which is there in this Image Array?

Please Found my Code for the same:-----

```<code>    NSArray* latest = [json objectForKey:@"BANNER"];

    NSMutableArray *data=[NSMutableArray new];

      if (!latest) {

        NSLog(@"Error parsing JSON: %@",error);
    }
       else{

        for(int i=0; i<latest.count ; i++)
        {
            NSDictionary *dict = [latest objectAtIndex:i];

            [data addObject:[dict objectForKey:@"url"]];
        }
        NSLog(@"data :%@",data);
        }
</code>```

# Pragma Mark: I have Found image array in the below format

```<code>data :(
    "https://xyz.in/mobile/1508139616-Food Offer Banner App (1).jpg",
    "https://xyz.in/mobile/1508163055-Serving  Banner app.jpg",
    "https://xyz.in/mobile/1508746128-Food App Banner Deal10.jpg",
    "https://xyz.in/mobile/1508746172-Food Banner Features.jpg"
)
</code>```

Pragma Mark: I want to convert "data" like this

```<code>data :(
    "https://xyz.in/mobile/1508139616-Food%20Offer%20Banner%20App%20(1).jpg",
    "https://xyz.in/mobile/1508163055-Serving%20Banne%20app.jpg",
    "https://xyz.in/mobile/1508746128-Food%20App%20Banner%20Deal10.jpg",
    "https://xyz.in/mobile/1508746172-Food%20Banner%20Features.jpg"
)
</code>```

I know this Question is already there but for single string only.But My Question is I want to convert the complete Array of String Url.
Please Help me Already Spent 3-4 days.

答:
You shouldn't just replace empty space with %20 there are other special characters that could cause issues with url. You must be using percent encoding. Something like this.

```<code>NSString *url = [dict objectForKey:@"url"];
url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
</code>```

Body:
I have a String array which I found from JSON object. It's an Image array containing 4 images presently.I don't know how many images I will get in future.
My Question is the Image URL is not showing in my ImageView Because it contains some blank space with it.I have already checked if this space is replaced with %20 then I can happily use it in my ImageView.

Can Anyone Suggest me how can I replace all the blank space from all the image String URL which is there in this Image Array?

Please Found my Code for the same:-----

    NSArray* latest = [json objectForKey:@"BANNER"];

    NSMutableArray *data=[NSMutableArray new];

      if (!latest) {

        NSLog(@"Error parsing JSON: %@",error);
    }
       else{

        for(int i=0; i<latest.count ; i++)
        {
            NSDictionary *dict = [latest objectAtIndex:i];

            [data addObject:[dict objectForKey:@"url"]];
        }
        NSLog(@"data :%@",data);
        }

# Pragma Mark: I have Found image array in the below format

data :(
    "https://xyz.in/mobile/1508139616-Food Offer Banner App (1).jpg",
    "https://xyz.in/mobile/1508163055-Serving  Banner app.jpg",
    "https://xyz.in/mobile/1508746128-Food App Banner Deal10.jpg",
    "https://xyz.in/mobile/1508746172-Food Banner Features.jpg"
)

Pragma Mark: I want to convert "data" like this

data :(
    "https://xyz.in/mobile/1508139616-Food%20Offer%20Banner%20App%20(1).jpg",
    "https://xyz.in/mobile/1508163055-Serving%20Banne%20app.jpg",
    "https://xyz.in/mobile/1508746128-Food%20App%20Banner%20Deal10.jpg",
    "https://xyz.in/mobile/1508746172-Food%20Banner%20Features.jpg"
)

I know this Question is already there but for single string only.But My Question is I want to convert the complete Array of String Url.
Please Help me Already Spent 3-4 days.

Body:
You shouldn't just replace empty space with %20 there are other special characters that could cause issues with url. You must be using percent encoding. Something like this.

NSString *url = [dict objectForKey:@"url"];
url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];


问:
dockerfile to run java exiting instantly
I have the following docker file to run my java application

```<code>FROM gidikern/rhel-oracle-jre

RUN mkdir /application
WORKDIR /application
CMD "java -Dspring.profiles.active=sprofileName -jar my.war --spring.config.location=./application.properties > app.log > 2>&1"
</code>```

and i'm running using docker-compose:

```<code> backend_app:
    restart: always
    image: my-app-runner:latest
    ports:
    - "8080:8080"
    volumes:
    - ./app/my.war:/application/my.war:Z
    - ./app/application.properties:/application/application.properties:Z
    - /srv/docker/backend_app/logs:/application/my.log:Z
    tty: true
</code>```

however when i start i get that my app exited with code 0 constantly.

I can't find what is wrong.

答:
The problem was actually with my base image gidikern/rhel-oracle-jre

I tested and even basic commands like ls didn't work..

Switched to openjdk for now and it is fine.

Body:
I have the following docker file to run my java application

FROM gidikern/rhel-oracle-jre

RUN mkdir /application
WORKDIR /application
CMD "java -Dspring.profiles.active=sprofileName -jar my.war --spring.config.location=./application.properties > app.log > 2>&1"

and i'm running using docker-compose:

 backend_app:
    restart: always
    image: my-app-runner:latest
    ports:
    - "8080:8080"
    volumes:
    - ./app/my.war:/application/my.war:Z
    - ./app/application.properties:/application/application.properties:Z
    - /srv/docker/backend_app/logs:/application/my.log:Z
    tty: true

however when i start i get that my app exited with code 0 constantly.

I can't find what is wrong.


问:
The AWS Access Key Id does not exist in our records
I created a new Access Key and configured that in the AWS CLI with aws configure. It created the .ini file in ~/.aws/config. When I run aws s3 ls it gives:

A client error (InvalidAccessKeyId) occurred when calling the ListBuckets operation: The AWS Access Key Id you provided does not exist in our records.

AmazonS3FullAccess policy is also attached to the user. How to fix this?

答:
you can configure profiles in the bash_profile file using

```<code><profile_name>
aws_access_key_id = <access_key>
aws_secret_access_key = <acces_key_secret>
</code>```

if you are using multiple profiles. then use:

```<code>aws s3 ls --profile <profile_name>
</code>```

Body:
you can configure profiles in the bash_profile file using

<profile_name>
aws_access_key_id = <access_key>
aws_secret_access_key = <acces_key_secret>

if you are using multiple profiles. then use:

aws s3 ls --profile <profile_name>


问:
List of pairs of lines from file [Java]
I am trying to create a simple method that would read the specified text file, line by line, and then it would print to the console every possible pair of those lines. I was trying to do that but it shows a strange result. My code looks like this:

```<code>public class MyList{
    List<String> elements = new LinkedList<>();

    public void createPairs() throws IOException {
        Scanner scanner = new Scanner(new File("file.txt"));
        scanner.useDelimeter("\n");
        while(scanner.hasNext()){
            elements.add(scanner.next());
        }
        scanner.close();

        for(String i: elements){
            for (String j:elements){
                System.out.println(i+" "+j);
            }
        }
    }
</code>```

For some reason it shows single lines looped lots of times and the for the last line it prints pairs properly. i.e. if the file.txt would contain:

```<code>1
2
3
</code>```

The result would be:

```<code>1
2
3
1
2
3
... //it loops for some time
3 1
3 2
3 3
</code>```

Reading the file to a list is probably fine because when I try to simply print the "elements" list it correctly shows each line of the file in separate List element.
I am not sure what am I doing wrong in here... Please help.

答:
You are using a Windows machine, aren't you?

On Windows, new line characters are represented by \r\n instead of \n. So when you press the Enter key when you create the file, you are actually creating \r\n characters.

This means that your text file looks like this to your code:

```<code>1\r\n2\r\n3
</code>```

Now, you try to use a scanner to read it, with the delimiter being \n. What happens is that it reads the following characters:

```<code>1\r
2\r
3
</code>```

Now, when you try to print the \r character, something quite different will happen. \r is a carriage return. This is one of those legacy characters from the typewriter era. On a typewriter, when you press the carriage return key, the "cursor" goes back to the start of the line, then you have to press the new line key to make it start a new line. So what happens if you only pressed the carriage return key? It will overwrite what is originally written at the start of the line! So the example below will only print "World".

```<code>System.out.println("Hello\rWorld");
</code>```

That's why you get this funky output.

To solve this, stop using delimiters and try nextLine on the scanner, that will always read a whole line, no matter the OS.

Title: List of pairs of lines from file [Java]

Body:
I am trying to create a simple method that would read the specified text file, line by line, and then it would print to the console every possible pair of those lines. I was trying to do that but it shows a strange result. My code looks like this:

public class MyList{
    List<String> elements = new LinkedList<>();

    public void createPairs() throws IOException {
        Scanner scanner = new Scanner(new File("file.txt"));
        scanner.useDelimeter("\n");
        while(scanner.hasNext()){
            elements.add(scanner.next());
        }
        scanner.close();

        for(String i: elements){
            for (String j:elements){
                System.out.println(i+" "+j);
            }
        }
    }

For some reason it shows single lines looped lots of times and the for the last line it prints pairs properly. i.e. if the file.txt would contain:

1
2
3

The result would be:

1
2
3
1
2
3
... //it loops for some time
3 1
3 2
3 3

Reading the file to a list is probably fine because when I try to simply print the "elements" list it correctly shows each line of the file in separate List element.
I am not sure what am I doing wrong in here... Please help.

Body:
You are using a Windows machine, aren't you?

On Windows, new line characters are represented by \r\n instead of \n. So when you press the Enter key when you create the file, you are actually creating \r\n characters.

This means that your text file looks like this to your code:

1\r\n2\r\n3

Now, you try to use a scanner to read it, with the delimiter being \n. What happens is that it reads the following characters:

1\r
2\r
3

Now, when you try to print the \r character, something quite different will happen. \r is a carriage return. This is one of those legacy characters from the typewriter era. On a typewriter, when you press the carriage return key, the "cursor" goes back to the start of the line, then you have to press the new line key to make it start a new line. So what happens if you only pressed the carriage return key? It will overwrite what is originally written at the start of the line! So the example below will only print "World".

System.out.println("Hello\rWorld");

That's why you get this funky output.

To solve this, stop using delimiters and try nextLine on the scanner, that will always read a whole line, no matter the OS.


问:
How to parse xml file using XMLReader
I have a "contacts.xml" file, its structure is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Contacts>
   <Contact>
      <ContactId>1</ContactId>
      <ContactName>Aditya  Kothari</ContactName>
      <MobilePhone1>NA</MobilePhone1>
      <MobilePhone2>NA</MobilePhone2>
      <OfficePhone1>NA</OfficePhone1>
      <OfficePhone2>NA</OfficePhone2>
      <OfficePhone3>NA</OfficePhone3>
      <HomePhone1>999-367-3944</HomePhone1>
      <HomePhone2>NA</HomePhone2>
      <TokenId>mtn</TokenId>
   </Contact>
   <Contact>
      <ContactId>2</ContactId>
      <ContactName>Jai  Mandloi </ContactName>
      <MobilePhone1>NA</MobilePhone1>
      <MobilePhone2>NA</MobilePhone2>
      <OfficePhone1>NA</OfficePhone1>
      <OfficePhone2>NA</OfficePhone2>
      <OfficePhone3>NA</OfficePhone3>
      <HomePhone1>800-742-9678</HomePhone1>
      <HomePhone2>NA</HomePhone2>
      <TokenId>mtn</TokenId>
   </Contact>
</Contacts>
</code>```

Now i am doing this-

```<code>File xmlFile = new File("E:\\contacts.xml");
InputStream is = new FileInputStream(xmlFile);
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(is);
while(reader.hasNext())
{
    if(reader.hasText()
    {
        System.out.println(reader.getText());
    }
    reader.next();
}
</code>```

I do not want values of "ContactId" and "TokenId" elements of xml.
How should i code?

答:
Recently i got this way-</p>

```<code>while(reader.hasNext())
{
   if(reader.getEventType()==XMLStreamConstants.START_ELEMENT)
   {
     if(!reader.getLocalName().equals("ContactId") && !reader.getLocalName().equals("TokenId") && !reader.getLocalName().equals("Contacts") && !reader.getLocalName().equals("Contact"))
     {
         System.out.println(reader.getElementText());
     }
   }
   reader.next();
}
</code>```

Title: How to parse xml file using XMLReader

Body:
I have a "contacts.xml" file, its structure is:

<?xml version="1.0" encoding="UTF-8"?>
<Contacts>
   <Contact>
      <ContactId>1</ContactId>
      <ContactName>Aditya  Kothari</ContactName>
      <MobilePhone1>NA</MobilePhone1>
      <MobilePhone2>NA</MobilePhone2>
      <OfficePhone1>NA</OfficePhone1>
      <OfficePhone2>NA</OfficePhone2>
      <OfficePhone3>NA</OfficePhone3>
      <HomePhone1>999-367-3944</HomePhone1>
      <HomePhone2>NA</HomePhone2>
      <TokenId>mtn</TokenId>
   </Contact>
   <Contact>
      <ContactId>2</ContactId>
      <ContactName>Jai  Mandloi </ContactName>
      <MobilePhone1>NA</MobilePhone1>
      <MobilePhone2>NA</MobilePhone2>
      <OfficePhone1>NA</OfficePhone1>
      <OfficePhone2>NA</OfficePhone2>
      <OfficePhone3>NA</OfficePhone3>
      <HomePhone1>800-742-9678</HomePhone1>
      <HomePhone2>NA</HomePhone2>
      <TokenId>mtn</TokenId>
   </Contact>
</Contacts>

Now i am doing this-

File xmlFile = new File("E:\\contacts.xml");
InputStream is = new FileInputStream(xmlFile);
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(is);
while(reader.hasNext())
{
    if(reader.hasText()
    {
        System.out.println(reader.getText());
    }
    reader.next();
}

I do not want values of "ContactId" and "TokenId" elements of xml.
How should i code?

Body:
Recently i got this way-

while(reader.hasNext())
{
   if(reader.getEventType()==XMLStreamConstants.START_ELEMENT)
   {
     if(!reader.getLocalName().equals("ContactId") && !reader.getLocalName().equals("TokenId") && !reader.getLocalName().equals("Contacts") && !reader.getLocalName().equals("Contact"))
     {
         System.out.println(reader.getElementText());
     }
   }
   reader.next();
}


问:
How to report if input is sanitized with OWASP Java HTML Sanitizer
I see in the API that it's possible but I can't figure out how to use that sanitize() method. There's even a forum post where someone says to use it but they don't explain how. In essence I have no idea what CTX means in that method signature. If someone can provide sample code of how to get a list of items that were sanitized that would be appreciated.

答:
You need to setup the HtmlChangeListener to catch all elements that are sanitized. The code then looks something like:

```<code>List<String> results = new ArrayList<String>();

HtmlChangeListener<List<String>> htmlChangeListener = new HtmlChangeListener<>()
{
    @Override
    public void discardedTag(List<String> context, String elementName)
    {
        context.add(elementName);
    }

    @Override
    public void discardedAttributes(List<String> context, String tagName, String... attributeNames)
    {
        context.add(tagName);
    }
};

String sanitizedHtml = POLICY_DEFINITION.sanitize(rawHtml, htmlChangeListener, results);
System.out.println("Sanitized elements include: " + String.join(",", results));
</code>```

Body:
You need to setup the HtmlChangeListener to catch all elements that are sanitized. The code then looks something like:

List<String> results = new ArrayList<String>();

HtmlChangeListener<List<String>> htmlChangeListener = new HtmlChangeListener<>()
{
    @Override
    public void discardedTag(List<String> context, String elementName)
    {
        context.add(elementName);
    }

    @Override
    public void discardedAttributes(List<String> context, String tagName, String... attributeNames)
    {
        context.add(tagName);
    }
};

String sanitizedHtml = POLICY_DEFINITION.sanitize(rawHtml, htmlChangeListener, results);
System.out.println("Sanitized elements include: " + String.join(",", results));


问:
What does synchronous vs asynchronous loading mean?
Reading from this site, I understand that using commonjs means that when the browser finishes downloading your files, it will have to load them up 1 by 1 as they depend on each other. But with AMD, it can load multiple ones at the same time so that even if file a depends on file b, it part of file a can be executed before file b is finished?

CommonJS Modules: The dominant implementation of this standard is in
  Node.js (Node.js modules have a few features that go beyond CommonJS).
  Characteristics: Compact syntax Designed for synchronous loading and
  servers

Asynchronous Module Definition (AMD): The most popular
  implementation of this standard is RequireJS. Characteristics:
  Slightly more complicated syntax, enabling AMD to work without eval()
  (or a compilation step) Designed for asynchronous loading and browsers

答:
Synchronous programming is executing code line by line. Same with loading.
It will load 1 by 1 whatever that you are loading.
Real world example: You are in a queue in cinema for a movie ticket.
Asynchronous would be many people in restaurant. You order food and other people order food. They dont need to wait for your order to finish.
Everyone can order but you dont know when the order will come. Same as with loading. You can load multiple things at the same time or different intervals but it doesnt guarantee that it will come in that order.
I hope the explanation is good enough.</p>


问:
How to update a panel outside a datable table in a tab from a commandbutton
please i have a commandbutton in a datatable that updates a panel. I get org.primefaces.expression.ComponentNotFoundException: Cannot find component for expression when i click on the commandbutton.

```<code><p:tab title="Register Vendor" id="tabtab">

    <p:panel id="ven">

        <h:panelGrid columns="6">
            <p:outputLabel value="Vendor Name: " for="vname"/>
            <p:inputText id="vname" required="true" value="#{bank.vendor_name}" />
            <p:message for="vname"/>

            <p:outputLabel value="Vendor Bank: " for="bank"/>
            <p:selectOneMenu id="bank" value="#{bank.bankmode.bankName}" required="true" requiredMessage="Bank required">

                <f:selectItem itemLabel="--Select Bank--" itemValue="" noSelectionOption="true"/>
                <f:selectItems value="#{bank.bankmodel}"
                               var="singlevalue"
                               itemLabel="#{singlevalue.bankName}"
                               itemValue="#{singlevalue.bankName}"/>
            </p:selectOneMenu>

            <p:message for="bank"/>

            <p:outputLabel value="Vendor Account Number: " for="anum"/>
            <p:inputText id="anum" required="true" value="#{bank.vendor_acct}" requiredMessage="Account Number required" />
            <p:message for="anum"/>

            <p:outputLabel value="Vendor Contact Address: " for="adress"/>
            <p:inputTextarea id="adress" required="true" value="#{bank.vendor_address}" requiredMessage="Contact Address required" />
            <p:message for="adress"/>

            <p:outputLabel value="Vendor Email Address: " for="email"/>
            <p:inputText id="email" required="true" label="email" size="40"
                         requiredMessage="Please enter your email address."
                         validatorMessage="Invalid email format"
                         value="#{bank.vendor_email}">

                <f:validateRegex
                    pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />

            </p:inputText>
            <p:message for="email" />

            <p:outputLabel value="Vendor Phone Number " for="pnum"/>
            <p:inputText id="pnum" required="true" value="#{bank.vendor_phone}" requiredMessage="Phone number required" />
            <p:message for="pnum"/>

            <p:commandButton value="save" process="@this vname,bank,anum,adress,email,pnum" update="singleTB,:templateForm:growl,ven" actionListener="#{bank.insertData}" />

        </h:panelGrid>

        <p:outputPanel style="margin-left: 800px;">
            <h:outputText value="Search all fields:" />
            <p:inputText id="globalFilter" style="width:150px; margin-right: 10px;" placeholder="Enter keyword" />
            <p:commandButton value="Search"/>
        </p:outputPanel>
    </p:panel>
    <p:panel id="singleTB">

        <p:dataTable var="ven_tab"
                     selectionMode="true"
                     rowKey="#{ven_tab.id}"
                     value="#{bank.vendorList}"
                     paginatorTemplate="{CurrentPageReport}
                     {FirstPageLink} {PreviousPageLink}
                     {PageLinks} {NextPageLink} {LastPageLink} "
                     paginator="true" style="margin-bottom:20px"
                     rowsPerPageTemplate="5,10,15">
            <p:column>
                <f:facet name="header">
                    <h:outputText value="Vendor Id"/>
                </f:facet>

                <h:outputText value="#{ven_tab.vendorId}"/>

            </p:column>

            <p:column>

                <f:facet name="header">
                    <h:outputText value="Vendor Name"/>
                </f:facet>
                <p:cellEditor>
                    <f:facet name="output"><h:outputText value="#{ven_tab.vendorName}"/></f:facet>
                    <f:facet name="input"><p:inputText value="#{ven_tab.vendorName}"  required="true"  requiredMessage="Name is required" style="width:96%"/></f:facet>
                </p:cellEditor>

            </p:column>

            <p:column>

                <f:facet name="header">
                    <h:outputText value="Vendor Phone Number"/>
                </f:facet>
                <h:outputText value="#{ven_tab.vendorPnum}"/>
            </p:column>

            <p:column>

                <f:facet name="header">
                    <h:outputText value="Vendor Email"/>
                </f:facet>
                <h:outputText value="#{ven_tab.vendorEmail}"/>

            </p:column>
            <p:column>

                <f:facet name="header">
                    <h:outputText value="Vendor Contact Address"/>
                </f:facet>
                <h:outputText value="#{ven_tab.vendorContact}"/>
            </p:column>
            <p:column>

                <f:facet name="header">
                    <h:outputText value="Vendor Bank"/>
                </f:facet>
                <h:outputText value="#{ven_tab.vendorBank}"/>
            </p:column>
            <p:column>
                <f:facet name="header">
                    <h:outputText value="Vendor Account Number"/>
                </f:facet>
                <h:outputText value="#{ven_tab.vendorAcct}"/>
            </p:column>
            <p:column style="width:32px" exportable="false">
                <f:facet name="header">Action</f:facet>
                <p:commandButton icon="ui-icon-edit" style="margin-left: -5px;" process="@this" update=":tabtab:ven,:templateForm:growl" actionListener="#{bank.select(ven_tab)}" />

            </p:column>

        </p:dataTable>
        <p:contextMenu for="singleTB" rendered="#{bank.status}" >
            <p:menuitem value="Delete" process="@this singleTB" update=":templateForm:growl,singleTB" icon="ui-icon-close" actionListener="#{bank.deleteCar}"/>
        </p:contextMenu>
        <p:panel style="margin-top:-50px; float: right;">
            <h3>Export table Data Only</h3>

            <h:commandLink immediate="true">
                <p:graphicImage value="/images/excel.png" />
                <p:dataExporter type="xls" target="singleTB " fileName="report" pageOnly="true"/>
            </h:commandLink>

            <h:commandLink immediate="true">
                <p:graphicImage value="/images/pdf.png" />
                <p:dataExporter type="pdf" target="singleTB" fileName="report" pageOnly="true" />
            </h:commandLink>

            <h:commandLink immediate="true">
                <p:graphicImage value="/images/csv.png" />
                <p:dataExporter type="csv" target="singleTB" fileName="report" pageOnly="true" />
            </h:commandLink>

            <h:commandLink immediate="true">
                <p:graphicImage value="/images/xml.png" />
                <p:dataExporter type="xml" target="singleTB" fileName="report" pageOnly="true" />
            </h:commandLink>
        </p:panel>

    </p:panel>

</p:tab>
</code>```

I have a masterpage that contains the form. Pls how do i resolve this issue. I have been on it for sometime now

答:
Even if the creator vote me down. The solution is :

```<code><p:tabView id="tabview">
            <p:tab title="Register Vendor" id="tabtab">

                <h:form id="tabForm">
                    <p:panel id="ven">
                    </p:panel>
                    <p:panel id="singleTB">
</code>```

.....

```<code><p:commandButton value="button" id="buttonInTable"
                                    icon="ui-icon-edit" style="margin-left: -5px;"
                                    update=":mainForm:tabview:tabForm:ven " />
</code>```

Body:
please i have a commandbutton in a datatable that updates a panel. I get org.primefaces.expression.ComponentNotFoundException: Cannot find component for expression when i click on the commandbutton.

        <h:panelGrid columns="6">

                <f:selectItem itemLabel="--Select Bank--" itemValue="" noSelectionOption="true"/>
                <f:selectItems value="#{bank.bankmodel}"
                               var="singlevalue"
                               itemLabel="#{singlevalue.bankName}"
                               itemValue="#{singlevalue.bankName}"/>

                <f:validateRegex
                    pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />

        </h:panelGrid>

            <h:outputText value="Search all fields:" />

                <f:facet name="header">
                    <h:outputText value="Vendor Id"/>
                </f:facet>

                <h:outputText value="#{ven_tab.vendorId}"/>

                <f:facet name="header">
                    <h:outputText value="Vendor Name"/>
                </f:facet>

                    <f:facet name="output"><h:outputText value="#{ven_tab.vendorName}"/></f:facet>
                    <f:facet name="input">
</f:facet>

                <f:facet name="header">
                    <h:outputText value="Vendor Phone Number"/>
                </f:facet>
                <h:outputText value="#{ven_tab.vendorPnum}"/>

                <f:facet name="header">
                    <h:outputText value="Vendor Email"/>
                </f:facet>
                <h:outputText value="#{ven_tab.vendorEmail}"/>

                <f:facet name="header">
                    <h:outputText value="Vendor Contact Address"/>
                </f:facet>
                <h:outputText value="#{ven_tab.vendorContact}"/>

                <f:facet name="header">
                    <h:outputText value="Vendor Bank"/>
                </f:facet>
                <h:outputText value="#{ven_tab.vendorBank}"/>

                <f:facet name="header">
                    <h:outputText value="Vendor Account Number"/>
                </f:facet>
                <h:outputText value="#{ven_tab.vendorAcct}"/>

                <f:facet name="header">Action</f:facet>

Export table Data Only

            <h:commandLink immediate="true">

            </h:commandLink>

            <h:commandLink immediate="true">

            </h:commandLink>

            <h:commandLink immediate="true">

            </h:commandLink>

            <h:commandLink immediate="true">

            </h:commandLink>

I have a masterpage that contains the form. Pls how do i resolve this issue. I have been on it for sometime now

Body:
Even if the creator vote me down. The solution is :

<p:tabView id="tabview">
            <p:tab title="Register Vendor" id="tabtab">

                <h:form id="tabForm">
                    <p:panel id="ven">
                    </p:panel>
                    <p:panel id="singleTB">

.....

<p:commandButton value="button" id="buttonInTable"
                                    icon="ui-icon-edit" style="margin-left: -5px;"
                                    update=":mainForm:tabview:tabForm:ven " />


问:
Hi, i need filter data from 4 table which stored as comma separated in table

Hi, As per image i have 3 table, 1. visits table in this table village_id value find in route_list villagemaster_id and if it available select doctors_id and using this doctors_id i need that all doctors name from user table using doctors id please give me solution.

答:
Change the type to number! It may help

<!DOCTYPE html>

<input type="number" name="a" ng-model="a" />
<input type="number" name="b" ng-model="b" />

Total in dollar: {{ a + b }}

```

ContentLicense: CC BY-SA 4.0

Body:
Change the type to number! It may help

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>

<div ng-app="" ng-init="a=2;b=5">
<input type="number" name="a" ng-model="a" />
<input type="number" name="b" ng-model="b" />

<p>Total in dollar: {{ a + b }}</p>
</div>

</body>
</html>


问:
How to add pixel like activity shortcuts in launcher icon?
Since the release of pixel series, there has been this feature to add activity shortcuts in application icon itself by long pressing the icon. I have been trying to find out a particular method by which these shortcuts can be implemented to make an app more interactive and user friendly.

答:
How to add pixel like activity shortcuts in launcher icon?

this option is available from Oreo version of android

follow this steps to create activity shortcuts in launcher icon

In your app's manifest file (AndroidManifest.xml), find an activity whose intent filters are set to the android.intent.action.MAIN action and the android.intent.category.LAUNCHER category.

Add a <meta-data> element to this activity that references the resource file where the app's shortcuts are defined:

```<code> <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.myapplication">
  <application ... >
     <activity
        android:name=".activity.TempActivity"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <meta-data android:name="android.app.shortcuts"
            android:resource="@xml/shortcuts" />

    </activity>
  </application>
</manifest>
</code>```

Create a new resource file: res/xml/shortcuts.xml.

In this new resource file, add a  root element, which contains a list of  elements. Each  element, in turn, contains information about a static shortcut, including its icon, its description labels, and the intents that it launches within the app:

```<code><shortcuts xmlns:android="http://schemas.android.com/apk/res/android">

    <shortcut
        android:enabled="true" // make sure shortcut is enabled true
        android:icon="@drawable/ic_check" // set icon here
        android:shortcutDisabledMessage="@string/collections" // message when shortcut is  disabled
        android:shortcutId="prem" // you need to give unique shortcutId
        android:shortcutLongLabel="@string/collections" // long lable for shortcut
        android:shortcutShortLabel="@string/collections">// short lable for shortcut
        <intent
            android:action="android.intent.action.VIEW"
            android:targetClass="com.prem.demoapp.activity.ChatActivity"
            android:targetPackage="com.prem.demoapp" /> // you need to provide here your Activity name and target package name you application

        <categories android:name="android.shortcut.conversation" />
    </shortcut>

    <shortcut
        android:enabled="true"
        android:icon="@drawable/ic_check"
        android:shortcutDisabledMessage="@string/app_name"
        android:shortcutId="compose"
        android:shortcutLongLabel="@string/app_name"
        android:shortcutShortLabel="@string/app_name">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetClass="com.prem.demoapp.activity.AccountSettingActivity"
            android:targetPackage="com.prem.demoapp" />

        <categories android:name="android.shortcut.conversation" />
    </shortcut>

</shortcuts>
</code>```

output of this shortcut

for more information please read App Shortcuts

Body:
How to add pixel like activity shortcuts in launcher icon?

this option is available from Oreo version of android

follow this steps to create activity shortcuts in launcher icon

In your app's manifest file (AndroidManifest.xml), find an activity whose intent filters are set to the android.intent.action.MAIN action and the android.intent.category.LAUNCHER category.

Add a <meta-data> element to this activity that references the resource file where the app's shortcuts are defined:

 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.myapplication">
  <application ... >
     <activity
        android:name=".activity.TempActivity"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <meta-data android:name="android.app.shortcuts"
            android:resource="@xml/shortcuts" />

    </activity>
  </application>
</manifest>

Create a new resource file: res/xml/shortcuts.xml.

In this new resource file, add a  root element, which contains a list of  elements. Each  element, in turn, contains information about a static shortcut, including its icon, its description labels, and the intents that it launches within the app:

<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">

    <shortcut
        android:enabled="true" // make sure shortcut is enabled true
        android:icon="@drawable/ic_check" // set icon here
        android:shortcutDisabledMessage="@string/collections" // message when shortcut is  disabled
        android:shortcutId="prem" // you need to give unique shortcutId
        android:shortcutLongLabel="@string/collections" // long lable for shortcut
        android:shortcutShortLabel="@string/collections">// short lable for shortcut
        <intent
            android:action="android.intent.action.VIEW"
            android:targetClass="com.prem.demoapp.activity.ChatActivity"
            android:targetPackage="com.prem.demoapp" /> // you need to provide here your Activity name and target package name you application

        <categories android:name="android.shortcut.conversation" />
    </shortcut>

    <shortcut
        android:enabled="true"
        android:icon="@drawable/ic_check"
        android:shortcutDisabledMessage="@string/app_name"
        android:shortcutId="compose"
        android:shortcutLongLabel="@string/app_name"
        android:shortcutShortLabel="@string/app_name">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetClass="com.prem.demoapp.activity.AccountSettingActivity"
            android:targetPackage="com.prem.demoapp" />

        <categories android:name="android.shortcut.conversation" />
    </shortcut>

</shortcuts>

output of this shortcut

for more information please read App Shortcuts


问:
iText PdfTemplate font size issue
I have a strange problem with iText & PdfTemplate.

I'm using PdfTemplate & Image to print the total Page number to the page footer.
I create a PdfTemplate, create an Image from the Template and put the image into a chunk, the chunk is added then to the table/phrase/paragraph, whatever component the parent is.

```<code>PdfTemplate tmp = PdfTemplate.createTemplate(writer, 20, 10);

Image img = null;
try
{
    img = Image.getInstance(tmp);
}
catch (BadElementException e)
{
}

return new Chunk(img, 0, 0);
</code>```

This Chunk returned is then added to the page (into a Phrase for example). The created PdfTemplate is saved into a list to get it later.

Then in the pageEventHelper (onCloseDocument), I fill the template with the total page number with the help of the ColumnText, like this:

```<code>PdfTemplateRecord rec = pagenums.get(i);
PdfTemplate tmp = rec.getTemplate();
Font font = CreatorHelper.getCurrentFont(rec.getFontContext());
if (font == null)
{
    font = new Font(defaultFont, 8f);
}

ColumnText columnText = new ColumnText(tmp);
columnText.setSimpleColumn(new Phrase(Integer.toString(pagenum), font), 0, -tmp.getHeight(), tmp.getWidth(), 0, 0, Element.ALIGN_LEFT);
columnText.setUseAscender(false);
try
{
    columnText.go();
}
catch (DocumentException e)
{
    log.error("Failed to render total page number", e);
}
</code>```

Everything is working just fine except two things:

1.) if you check the setSimpleColumn carefully, I had to set the Y position to -tmp.getHeight() (eg. -10) instead of 0. If I set the Y to 0, the text is drawn just above the line... Probably I messed up something with the image addition, or so, but don't know

2.) I have problems with the font sizing. Strange, but if the font size if bigger than 10f, the normal text, and the text in the template are identical. However if the font size is lower than 10f, the text in template gets smaller.
Here some image

(images in this order, font size: 6f, 8f, 9f, 10f, 14f, the "Page 1 of" is the normal text, and the number after the "of" comes with the template)

As you can see with 9f font size the template text is slightly smaller than the normal text, but after 10f the two texts are identical.

I searched if there is some rule between the PdfTemplate and Elements regarding font sizing, but did not found anything.

Any help is appretiated!

Thanks!

答:
Sorry to revive an old post:
This is in relation to inconsistent font size the page number [Page 1 of 1]

OP's comment of removing the Paragraph to get an equal font size did not work for me (on a similar image scaling issue).

Referring to this post here shows what could have gone wrong.

BUT:
  the first PDF (without the template) contains an "embedded subset" of
  the font "Georgia" (Ansi encoding). That's the correct way to use a font.
  The second PDF however, contains:
  - an embedded subset of Georgia (Ansi)
  - an embedded subset of Georgia (CID / Identity-H)
  - Georgia NOT EMBEDDED (Ansi)
  - Georgia-Bold NOT EMBEDDED (Ansi)

The two first fonts are OK, but as the two following fonts are not
embedded, my Adobe Reader had to look for the font Georgia on my
Operating System.

Hope this helps :)

P.S. When adding content to the template, the font can be set while adding the Phrase which allows the content of the template to have an independent font.

Title: iText PdfTemplate font size issue

Body:
I have a strange problem with iText & PdfTemplate.

I'm using PdfTemplate & Image to print the total Page number to the page footer.
I create a PdfTemplate, create an Image from the Template and put the image into a chunk, the chunk is added then to the table/phrase/paragraph, whatever component the parent is.

PdfTemplate tmp = PdfTemplate.createTemplate(writer, 20, 10);

Image img = null;
try
{
    img = Image.getInstance(tmp);
}
catch (BadElementException e)
{
}

return new Chunk(img, 0, 0);

This Chunk returned is then added to the page (into a Phrase for example). The created PdfTemplate is saved into a list to get it later.

Then in the pageEventHelper (onCloseDocument), I fill the template with the total page number with the help of the ColumnText, like this:

PdfTemplateRecord rec = pagenums.get(i);
PdfTemplate tmp = rec.getTemplate();
Font font = CreatorHelper.getCurrentFont(rec.getFontContext());
if (font == null)
{
    font = new Font(defaultFont, 8f);
}

ColumnText columnText = new ColumnText(tmp);
columnText.setSimpleColumn(new Phrase(Integer.toString(pagenum), font), 0, -tmp.getHeight(), tmp.getWidth(), 0, 0, Element.ALIGN_LEFT);
columnText.setUseAscender(false);
try
{
    columnText.go();
}
catch (DocumentException e)
{
    log.error("Failed to render total page number", e);
}

Everything is working just fine except two things:

1.) if you check the setSimpleColumn carefully, I had to set the Y position to -tmp.getHeight() (eg. -10) instead of 0. If I set the Y to 0, the text is drawn just above the line... Probably I messed up something with the image addition, or so, but don't know

2.) I have problems with the font sizing. Strange, but if the font size if bigger than 10f, the normal text, and the text in the template are identical. However if the font size is lower than 10f, the text in template gets smaller.
Here some image

(images in this order, font size: 6f, 8f, 9f, 10f, 14f, the "Page 1 of" is the normal text, and the number after the "of" comes with the template)

As you can see with 9f font size the template text is slightly smaller than the normal text, but after 10f the two texts are identical.

I searched if there is some rule between the PdfTemplate and Elements regarding font sizing, but did not found anything.

Any help is appretiated!

Thanks!


问:
Marshal XML sub-element under root with Go
is there a way to marshal XML in the following example such that the sub-elements under MyElement are marshaled under the root MyXML as follows:

```<code>type MyXML struct {
    XMLName xml.Name `xml:"myXML"`
    Element *MyElement `xml:",any"`
}

type MyElement struct {
    A string `xml:"a"`
    B string `xml:"b"`
    C string `xml:"c"`
}
</code>```

I’d like the following result:

```<code><myXML>
    <a>blah</a>
    <b>blah</b>
    <c>blah</c>
</myXML>
</code>```

If I marshal as is I get:

```<code><myXML>
    <Element>
        <a>blah</a>
        <b>blah</b>
        <c>blah</c>
    </Element>
</myXML>
</code>```

Is this possible by way of implementing the xml.Marshaler interface via the MyElement struct?

Thanks!

答:
You can make use of the XMLName field of type xml.Name on a struct to marshal it to the name you'd like.

```<code>type MyXML struct {
    XMLName xml.Name `xml:"myXML"`
    A       string   `xml:"a"`
    B       string   `xml:"b"`
    C       string   `xml:"c"`
}

func main() {
    testXML := MyXML{
        A: "test a",
        B: "test b",
        C: "test c",
    }
    xmlBytes, err := xml.Marshal(testXML)
    if err != nil {
        fmt.Printf("error parsing xml: %s", err)
        return
    }
    fmt.Println(string(xmlBytes))
}
</code>```

This example on Go Playground

Body:
is there a way to marshal XML in the following example such that the sub-elements under MyElement are marshaled under the root MyXML as follows:

type MyXML struct {
    XMLName xml.Name `xml:"myXML"`
    Element *MyElement `xml:",any"`
}

type MyElement struct {
    A string `xml:"a"`
    B string `xml:"b"`
    C string `xml:"c"`
}

I’d like the following result:

<myXML>
    blah
    blah
    <c>blah</c>
</myXML>

If I marshal as is I get:

<myXML>
    <Element>
        blah
        blah
        <c>blah</c>
    </Element>
</myXML>

Is this possible by way of implementing the xml.Marshaler interface via the MyElement struct?

Thanks!

Body:
You can make use of the XMLName field of type xml.Name on a struct to marshal it to the name you'd like.

type MyXML struct {
    XMLName xml.Name `xml:"myXML"`
    A       string   `xml:"a"`
    B       string   `xml:"b"`
    C       string   `xml:"c"`
}

func main() {
    testXML := MyXML{
        A: "test a",
        B: "test b",
        C: "test c",
    }
    xmlBytes, err := xml.Marshal(testXML)
    if err != nil {
        fmt.Printf("error parsing xml: %s", err)
        return
    }
    fmt.Println(string(xmlBytes))
}

This example on Go Playground


问:
How to align  value to center vertically?
I need to align td cell value to center, both horizontally and vertically.  has a rowspan attribute.

The output right now is like:

```<code>A  |  B  |  C  |  D
1  |  2  |  3  |  4
1  |  2  |  3  |
1  |  2  |  3  |
</code>```

Desired:

```<code>A  |  B  |  C  |  D
1  |  2  |  3  |
1  |  2  |  3  |  4
1  |  2  |  3  |
1  |  2  |  3  |
</code>```

答:
try:

```<code><td align="center" valign="middle">
</code>```

Title: How to align <td rowspan ="value"> value to center vertically?

Body:
I need to align td cell value to center, both horizontally and vertically.  has a rowspan attribute.

The output right now is like:

A  |  B  |  C  |  D
1  |  2  |  3  |  4
1  |  2  |  3  |
1  |  2  |  3  |

Desired:

A  |  B  |  C  |  D
1  |  2  |  3  |
1  |  2  |  3  |  4
1  |  2  |  3  |
1  |  2  |  3  |

Body:
try:

<td align="center" valign="middle">


问:
how to insert multiple lines in json array in database using php
I want to enter some details that included in JSON arrays to database.

Given below is my source code.

here is my data json array from the txt file

{

   "reader_name":"Biboy Pogi",
   "mac_address":"00:16:25:10:7E:85",
   "tag_reads":[

      {

         "antennaPort":1,
         "epc":"2015031687850100010105B5",
         "tid":"E280110520005A8B952F0886",
         "isHeartBeat":false
      }
   ]
}

{

   "reader_name":"Biboy Pogi",
   "mac_address":"00:16:25:10:7E:85",
   "tag_reads":[

      {

         "antennaPort":1,
         "epc":"2015031687850100010105B5",
         "tid":"E280110520005A8B952F0886",
         "isHeartBeat":false
      }
   ]
}

答:
You'r JSON is wrong and two times the same. Maybe you'll need it that way, but this one of them

```<code>{
  "reader_name": "Biboy Pogi",
  "mac_address": "00:16:25:10:7E:85",
  "tag_reads": [
      {
        "antennaPort": 1,
        "epc": "2015031687850100010105B5",
        "tid": "E280110520005A8B952F0886",
        "isHeartBeat": false
      }
  ]
}
</code>```

And you can't reach $antennaPort = $data['antennaPort']; that way. You have to call it like this

```<code>$antennaPort = $data['tag_reads']['antennaPort'];
$epc= $data['tag_reads'][0]['epc'];
$tid= $data['tag_reads'][0]['tid'];
</code>```

EDIT

Insert into you'r database like this

```<code>mysqli_query($con,$sql)
</code>```

After that, you should check for errors

```<code>if(!mysqli_query($con, $sql))
  die ('Error in query: ' . mysqli_error($con));
</code>```

Or you go in one line

```<code>mysqli_query($con, $sql) or die(mysqli_error());
</code>```

Body:
You'r JSON is wrong and two times the same. Maybe you'll need it that way, but this one of them

{
  "reader_name": "Biboy Pogi",
  "mac_address": "00:16:25:10:7E:85",
  "tag_reads": [
      {
        "antennaPort": 1,
        "epc": "2015031687850100010105B5",
        "tid": "E280110520005A8B952F0886",
        "isHeartBeat": false
      }
  ]
}

And you can't reach $antennaPort = $data['antennaPort']; that way. You have to call it like this

$antennaPort = $data['tag_reads']['antennaPort'];
$epc= $data['tag_reads'][0]['epc'];
$tid= $data['tag_reads'][0]['tid'];

EDIT

Insert into you'r database like this

mysqli_query($con,$sql)

After that, you should check for errors

if(!mysqli_query($con, $sql))
  die ('Error in query: ' . mysqli_error($con));

Or you go in one line

mysqli_query($con, $sql) or die(mysqli_error());


问:
React Native : Handling Async calls to sqllite db
I am having a bit of struggle trying to understand how async functions work in React Native.

In this example I am invoking a sqllite db call via a async call and get values of height and standard and return both these values as an object called result.

Values exist in sqllite db as can be seen in the console output shown below.

The method invoked from componentDidMount lifecycle method is an async method.

As can be seen I am using await to wait for the actual execution (aka getting data from sqllite) to complete.

Line X always returns as undefined.

Line Y does not seem to execute at all as the state does not get changed from the initial values of 100 & "asasd" at all.

I have eyeballed the code and I am not sure what I am missing here.

Can someone take a look at it and let me know ?

App.js

```<code>import React, { Component } from 'react';
import { View, Text } from 'react-native';
import {
  dropLogsTable,
  createLogsTable,
  getProfileHeightStandardfromDB,
  getProfileHeightStandardPremade,
  saveLogsRecord
} from '../src/helper';

export default class App extends Component {
  state = {
    logarray: [],
    profileobject: {profileheight: 100, profilestandard: "asasd"},

  };

  componentDidMount() {

    dropLogsTable();
    createLogsTable();
    this.fetchProfileData();

  }

  async fetchProfileData() {
    console.log('Before Profile Fetch');
    const result = await getProfileHeightStandardfromDB();
    console.log('After Profile Fetch');
    console.log('Height : '+result.profileheight);
    console.log('Standard: '+result.profilestandard);
    return result; //Line X
    this.setState({profileobject:result}); //Line Y
  }

  render() {
    return (
      <View>
        <Text>This is a test</Text>
        <Text>Profile Height : {this.state.profileobject.profileheight} </Text>
        <Text>Profile Standard : {this.state.profileobject.profilestandard}</Text>
      </View>
    );
  }
}
</code>```

helper.js

```<code>import { SQLite } from 'expo';

const db = SQLite.openDatabase({ name: 'swlt.db' });

let profileheight, profilestandard;

export function getProfileHeightStandardfromDB()
          {
        db.transaction(
          tx => {

            tx.executeSql('select standard, metricweight, metricheight, imperialheight, imperialweight, bmi, metricgoalweight, imperialgoalweight from profile', [], (_, { rows }) =>
              {
                //console.log(rows);
                console.log(rows);

                //console.log(parseFloat(rows._array[0].metricheight));
                profileheight = parseFloat(rows._array[0].metricheight);
                profilestandard = rows._array[0].standard;
                console.log('Profileheight ===>'+profileheight);
                console.log('Profilestandard ===>'+profilestandard);
              }
            );
          },
          null,
          null
        );

        const profileobject = {profileheight, profilestandard};
        console.log(profileobject);
        return profileobject;

      }
</code>```

Output from Device and Console

答:
You need to return data from getProfileHeightStandardfromDB , db.transaction is also async function, so code outside the db.transaction , will execute first before your console logs.

You need to change getProfileHeightStandardfromDB function like this :

```<code>export function getProfileHeightStandardfromDB() {
    return db.transaction(
        tx => {

            tx.executeSql('select standard, metricweight, metricheight, imperialheight, imperialweight, bmi, metricgoalweight, imperialgoalweight from profile', [], (_, {
                rows
            }) => {
                //console.log(rows);
                console.log(rows);

                //console.log(parseFloat(rows._array[0].metricheight));
                profileheight = parseFloat(rows._array[0].metricheight);
                profilestandard = rows._array[0].standard;
                console.log('Profileheight ===>' + profileheight);
                console.log('Profilestandard ===>' + profilestandard);
                const profileobject = {
                    profileheight,
                    profilestandard
                };
                console.log(profileobject);
                return profileobject;
            });
        },
        null,
        null
    );
}
</code>```

Also change the order of last two lines of fetchProfileData :

```<code>async fetchProfileData() {
    console.log('Before Profile Fetch');
    const result = await getProfileHeightStandardfromDB();
    console.log('After Profile Fetch');
    console.log('Height : '+result.profileheight);
    console.log('Standard: '+result.profilestandard);
    this.setState({profileobject:result}); //Line Y
    return result; //Line X
}
</code>```

Body:
I am having a bit of struggle trying to understand how async functions work in React Native.

In this example I am invoking a sqllite db call via a async call and get values of height and standard and return both these values as an object called result.

Values exist in sqllite db as can be seen in the console output shown below.

The method invoked from componentDidMount lifecycle method is an async method.

As can be seen I am using await to wait for the actual execution (aka getting data from sqllite) to complete.

Line X always returns as undefined.

Line Y does not seem to execute at all as the state does not get changed from the initial values of 100 & "asasd" at all.

I have eyeballed the code and I am not sure what I am missing here.

Can someone take a look at it and let me know ?

App.js

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import {
  dropLogsTable,
  createLogsTable,
  getProfileHeightStandardfromDB,
  getProfileHeightStandardPremade,
  saveLogsRecord
} from '../src/helper';

export default class App extends Component {
  state = {
    logarray: [],
    profileobject: {profileheight: 100, profilestandard: "asasd"},

  };

  componentDidMount() {

    dropLogsTable();
    createLogsTable();
    this.fetchProfileData();

  }

  async fetchProfileData() {
    console.log('Before Profile Fetch');
    const result = await getProfileHeightStandardfromDB();
    console.log('After Profile Fetch');
    console.log('Height : '+result.profileheight);
    console.log('Standard: '+result.profilestandard);
    return result; //Line X
    this.setState({profileobject:result}); //Line Y
  }

  render() {
    return (
      <View>
        <Text>This is a test</Text>
        <Text>Profile Height : {this.state.profileobject.profileheight} </Text>
        <Text>Profile Standard : {this.state.profileobject.profilestandard}</Text>
      </View>
    );
  }
}

helper.js

import { SQLite } from 'expo';

const db = SQLite.openDatabase({ name: 'swlt.db' });

let profileheight, profilestandard;

export function getProfileHeightStandardfromDB()
          {
        db.transaction(
          tx => {

            tx.executeSql('select standard, metricweight, metricheight, imperialheight, imperialweight, bmi, metricgoalweight, imperialgoalweight from profile', [], (_, { rows }) =>
              {
                //console.log(rows);
                console.log(rows);

                //console.log(parseFloat(rows._array[0].metricheight));
                profileheight = parseFloat(rows._array[0].metricheight);
                profilestandard = rows._array[0].standard;
                console.log('Profileheight ===>'+profileheight);
                console.log('Profilestandard ===>'+profilestandard);
              }
            );
          },
          null,
          null
        );

        const profileobject = {profileheight, profilestandard};
        console.log(profileobject);
        return profileobject;

      }

Output from Device and Console

Body:
You need to return data from getProfileHeightStandardfromDB , db.transaction is also async function, so code outside the db.transaction , will execute first before your console logs.

You need to change getProfileHeightStandardfromDB function like this :

export function getProfileHeightStandardfromDB() {
    return db.transaction(
        tx => {

            tx.executeSql('select standard, metricweight, metricheight, imperialheight, imperialweight, bmi, metricgoalweight, imperialgoalweight from profile', [], (_, {
                rows
            }) => {
                //console.log(rows);
                console.log(rows);

                //console.log(parseFloat(rows._array[0].metricheight));
                profileheight = parseFloat(rows._array[0].metricheight);
                profilestandard = rows._array[0].standard;
                console.log('Profileheight ===>' + profileheight);
                console.log('Profilestandard ===>' + profilestandard);
                const profileobject = {
                    profileheight,
                    profilestandard
                };
                console.log(profileobject);
                return profileobject;
            });
        },
        null,
        null
    );
}

Also change the order of last two lines of fetchProfileData :

async fetchProfileData() {
    console.log('Before Profile Fetch');
    const result = await getProfileHeightStandardfromDB();
    console.log('After Profile Fetch');
    console.log('Height : '+result.profileheight);
    console.log('Standard: '+result.profilestandard);
    this.setState({profileobject:result}); //Line Y
    return result; //Line X
}


问:
Cannot get object DateTimeField gte issue
I have an object

```<code>class Promo( models.Model ):
    name        = models.CharField(verbose_name="Name"))
    promo_name = models.CharField(verbose_name="Promo Name", max_length=255, null=True, default='')

    status  = models.CharField(
    max_length=255,
    choices=(
        ('publish', 'Published'),
        ('draft',  'Drafted')
    ), default='publish',)

    start_date  = models.DateTimeField(editable=True, auto_now=False, null=True, )
    expire_date = models.DateTimeField(editable=True, auto_now=False, null=True, )
    def __str__(self):
        return "%s" % (self.name, )
</code>```

My settings.py:

```<code>LANGUAGE_CODE   = 'en-us'
TIME_ZONE       = "Asia/Jakarta"
USE_I18N        = True
USE_L10N        = True
USE_TZ          = True
</code>```

One of the object value is:

When i filter only the status, it has no problem, but when i want to "get the Promo that have start_date greater than current_datetime, i keep failing, i don't know why, i tried to make the datetime into UTC format since Django seems to return the start_date as UTC timezone. But still fail.

My code:

```<code>    import pytz
    from django.utils import timezone

    the_promo   = Promo.objects.all().filter(status='publish').first()

    # test
    start_date = the_promo.start_date
    start_date_utc                      = start_date
    current_datetime_date_in_asia_jakarta = timezone.localtime(start_date_utc)
    current_datetime                    = datetime.now(pytz.timezone('Asia/Jakarta')
    current_datetime_utc                = datetime.now(pytz.timezone('UTC'))

    if current_datetime_utc > start_date_utc:
        b='bigger!'
    else:
        b='not bigger'

    the_promo_to_be_used2    = Promo.objects.all().filter(start_date__gte=current_datetime_utc, status='publish').first()
</code>```

Example values from debug:

```<code>start_date = 2017-11-17 06:17:49+00:00
start_date_utc = 2017-11-17 06:17:49+00:00
current_datetime = 2017-11-17 13:49:13.212000+07:00
current_datetime_utc = 2017-11-17 06:49:13.212000+00:00
b = 'bigger!' # this works how come the query does not work?
</code>```

but the_promo_to_be_used2 keeps getting None

答:
your can simply apply filter() on model. No need to use all().filter().
Also, It work for me:

Promo.objects.filter(status='publish', start_date__gte=curr_date).first()

where curr_date is  the datetime object contains today's date.

i.e curr_date = datetime.datetime(2017, 11, 17, 0, 0)

including exp_date into filter query and as per your latest comment.it will be:

Promo.objects.filter(status='publish', start_date__lte=curr_date, expiry_date__gte=curr_date).first()

Body:
I have an object

class Promo( models.Model ):
    name        = models.CharField(verbose_name="Name"))
    promo_name = models.CharField(verbose_name="Promo Name", max_length=255, null=True, default='')

    status  = models.CharField(
    max_length=255,
    choices=(
        ('publish', 'Published'),
        ('draft',  'Drafted')
    ), default='publish',)

    start_date  = models.DateTimeField(editable=True, auto_now=False, null=True, )
    expire_date = models.DateTimeField(editable=True, auto_now=False, null=True, )
    def __str__(self):
        return "%s" % (self.name, )

My settings.py:

LANGUAGE_CODE   = 'en-us'
TIME_ZONE       = "Asia/Jakarta"
USE_I18N        = True
USE_L10N        = True
USE_TZ          = True

One of the object value is:

When i filter only the status, it has no problem, but when i want to "get the Promo that have start_date greater than current_datetime, i keep failing, i don't know why, i tried to make the datetime into UTC format since Django seems to return the start_date as UTC timezone. But still fail.

My code:

    import pytz
    from django.utils import timezone

    the_promo   = Promo.objects.all().filter(status='publish').first()

    # test
    start_date = the_promo.start_date
    start_date_utc                      = start_date
    current_datetime_date_in_asia_jakarta = timezone.localtime(start_date_utc)
    current_datetime                    = datetime.now(pytz.timezone('Asia/Jakarta')
    current_datetime_utc                = datetime.now(pytz.timezone('UTC'))

    if current_datetime_utc > start_date_utc:
        b='bigger!'
    else:
        b='not bigger'

    the_promo_to_be_used2    = Promo.objects.all().filter(start_date__gte=current_datetime_utc, status='publish').first()

Example values from debug:

start_date = 2017-11-17 06:17:49+00:00
start_date_utc = 2017-11-17 06:17:49+00:00
current_datetime = 2017-11-17 13:49:13.212000+07:00
current_datetime_utc = 2017-11-17 06:49:13.212000+00:00
b = 'bigger!' # this works how come the query does not work?

but the_promo_to_be_used2 keeps getting None


答:
```<code>>>> import datetime
>>> start_date = datetime.datetime(2017,11,17,06,17)
>>> current_date = datetime.datetime(2017,11,17,13,49)
>>> start_date >= current_date  # start_date__gte=current_date
False
</code>```

Check your filters, change _gte to _lt according to desired logic. From what I see now, start_date is less then current date, so filter expression is working well, you just doing wrong filtering.

Title: Cannot get object DateTimeField gte issue

Body:
>>> import datetime
>>> start_date = datetime.datetime(2017,11,17,06,17)
>>> current_date = datetime.datetime(2017,11,17,13,49)
>>> start_date >= current_date  # start_date__gte=current_date
False

Check your filters, change _gte to _lt according to desired logic. From what I see now, start_date is less then current date, so filter expression is working well, you just doing wrong filtering.


答:
You can only use these shortcuts, if your application is targeting version 7.1+ (API level 25+).

There are three different types of these shortcuts, taken from the documentation:

Static shortcuts are defined in a resource file that is packaged into an APK. Therefore, you must wait until you update your entire app
  to change the details of these static shortcuts.

Dynamic shortcuts are published at runtime using the ShortcutManager
   API. During runtime, your app can publish, update, and remove its
   dynamic shortcuts.

Pinned shortcuts are published at runtime and also use the
  ShortcutManager API. During runtime, your app can attempt to pin the
  shortcut, at which time the user receives a confirmation dialog asking
  their permission to pin the shortcut. The pinned shortcut appears in
  supported launchers only if the user accepts the pinning request. (Only available on Android 8.0+)

These shortcuts reference at least one intent inside the app. I won't copy paste the tutorial from the documentation here, you can find everything you need to know here.

Title: How to add pixel like activity shortcuts in launcher icon?

Body: Since the release of pixel series, there has been this feature to add activity shortcuts in application icon itself by long pressing the icon. I have been trying to find out a particular method by which these shortcuts can be implemented to make an app more interactive and user friendly.


问:
Angular material .mat-icon-button class not present in style section in index.html
I am adding a mat-button in my angular component,

```<code><button mat-button class="toggle-button-navbar mat-icon-button" fxHide.lt-sm>
    <mat-icon>menu</mat-icon>
</button>
</code>```

The button is showing. I expect the .mat-icon-button css class to be included in a  section in the index.html. But it is not there. I am following a working example which does have the .mat-icon-button css class in an  section of the served index.html file (not in the styles.bundle.css file). In that working example, when I inspect the element, the .mat-icon-button css class shows as:

```<code>.mat-icon-button {
    padding: 0;
    min-width: 0;
    width: 40px;
    height: 40px;
    flex-shrink: 0;
    line-height: 40px;
    border-radius: 50%;
}
</code>```

I found out that this css class is packed in MatButton.decorators in the @angular/material/bundles/materical-button.umd.js file. However, I could not figure out how this css class showing up in the index.html of the working example, but not showing up in my index.html.

答:
Simply Import the MatButtonModule to solve this.
Make sure you also imported the MatIconModule.

Angular has to known that the mat-button attribute and the <mat-icon> tag.

The mat-button attribute applies a component. To register the component you have to import the MatButtonModule Module, which declares the mat-button component.

The <mat-icon> tag is a component. To register the mat-icon component you have to import the MatIconModule Module, which declares the component. This will create the mat-icon component and import the css rules.

To solve your Problem add following Code to your Module:

```<code>import {MatButtonModule} from '@angular/material/button';
import {MatIconModule} from '@angular/material/icon';
...
@NgModule({
  imports: [
    ...
    MatButtonModule,
    MatIconModule,
  ],
...
</code>```

For more Information about the mat-icon Module see:
https://material.angular.io/components/icon/api

For more Information about Component registration in Angular see:
https://angular.io/guide/architecture

Body:
I am adding a mat-button in my angular component,

<button mat-button class="toggle-button-navbar mat-icon-button" fxHide.lt-sm>
    <mat-icon>menu</mat-icon>
</button>

The button is showing. I expect the .mat-icon-button css class to be included in a  section in the index.html. But it is not there. I am following a working example which does have the .mat-icon-button css class in an  section of the served index.html file (not in the styles.bundle.css file). In that working example, when I inspect the element, the .mat-icon-button css class shows as:

.mat-icon-button {
    padding: 0;
    min-width: 0;
    width: 40px;
    height: 40px;
    flex-shrink: 0;
    line-height: 40px;
    border-radius: 50%;
}

I found out that this css class is packed in MatButton.decorators in the @angular/material/bundles/materical-button.umd.js file. However, I could not figure out how this css class showing up in the index.html of the working example, but not showing up in my index.html.

Body:
Simply Import the MatButtonModule to solve this.
Make sure you also imported the MatIconModule.

Angular has to known that the mat-button attribute and the <mat-icon> tag.

The mat-button attribute applies a component. To register the component you have to import the MatButtonModule Module, which declares the mat-button component.

The <mat-icon> tag is a component. To register the mat-icon component you have to import the MatIconModule Module, which declares the component. This will create the mat-icon component and import the css rules.

To solve your Problem add following Code to your Module:

import {MatButtonModule} from '@angular/material/button';
import {MatIconModule} from '@angular/material/icon';
...
@NgModule({
  imports: [
    ...
    MatButtonModule,
    MatIconModule,
  ],
...

For more Information about the mat-icon Module see:
https://material.angular.io/components/icon/api

For more Information about Component registration in Angular see:
https://angular.io/guide/architecture


问:
Angular 2 - hide bootstrap navbar on nav click
In mobile, clicking bootstrap navbar item does't hide the menu.

My menu button, which shows for mobiles:

```<code><button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
</code>```

Searching for this issue returned results unreleated to angular 2 and I have no idea how to implement them.

How I can I hide my navbar when user clicks a link?

```<code><li><a routerLink="/page">Click this should hide nav</a></li>
</code>```

答:
This is a limitation of navbar (https://github.com/valor-software/ngx-bootstrap/issues/540). So you need to manipulate the DOM element.

```<code><div class="navbar-header page-scroll">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" routerLink="/">
        <img src="assets/images/logo.png">
    </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
    <ul class="nav navbar-nav navbar-right" >
        <li class="hidden">
            <a></a>
        </li>
        <li><a routerLink="/" (click)="onMenuClick()">Home</a></li>
        <li><a routerLink="/about" (click)="onMenuClick()">About</a></li>
    </ul>
</div>
</code>```

And on .ts file your minimal code shoul be:

```<code>import { Component, ElementRef, Renderer } from '@angular/core';

export class HeaderComponent {
    constructor(private el: ElementRef, private renderer: Renderer) {
    }
    onMenuClick() {
        //this.el.nativeElement.querySelector('.navbar-ex1-collapse')  get the DOM
        //this.renderer.setElementClass('DOM-Element', 'css-class-you-want-to-add', false) if 3rd value is true
        //it will add the css class. 'in' class is responsible for showing the menu.
        this.renderer.setElementClass(this.el.nativeElement.querySelector('.navbar-ex1-collapse'), 'in', false);
    }
}
</code>```

Body:
In mobile, clicking bootstrap navbar item does't hide the menu.

My menu button, which shows for mobiles:

<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

Searching for this issue returned results unreleated to angular 2 and I have no idea how to implement them.

How I can I hide my navbar when user clicks a link?

Click this should hide nav

Body:
This is a limitation of navbar (https://github.com/valor-software/ngx-bootstrap/issues/540). So you need to manipulate the DOM element.

<div class="navbar-header page-scroll">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" routerLink="/">
        <img src="assets/images/logo.png">
    </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
    <ul class="nav navbar-nav navbar-right" >
        <li class="hidden">
            <a></a>
        </li>
        <li><a routerLink="/" (click)="onMenuClick()">Home</a></li>
        <li><a routerLink="/about" (click)="onMenuClick()">About</a></li>
    </ul>
</div>

And on .ts file your minimal code shoul be:

import { Component, ElementRef, Renderer } from '@angular/core';

export class HeaderComponent {
    constructor(private el: ElementRef, private renderer: Renderer) {
    }
    onMenuClick() {
        //this.el.nativeElement.querySelector('.navbar-ex1-collapse')  get the DOM
        //this.renderer.setElementClass('DOM-Element', 'css-class-you-want-to-add', false) if 3rd value is true
        //it will add the css class. 'in' class is responsible for showing the menu.
        this.renderer.setElementClass(this.el.nativeElement.querySelector('.navbar-ex1-collapse'), 'in', false);
    }
}


问:
using npm libraries in tabris-js app
I am new to programming and started with tabris-js mobile app development framework for pure javascript.
Tabris-js supports using npm modules an cordova plugins to extend.

I tried to import mqtt-js npm library into tabris-js app.
Locally installed the library to path;
project_folder/node_modules/mqtt/mqtt.js and added dependency in package.json.

When importing the module:

```<code>const mqtt = require('mqtt');
</code>```

The error is: could not parse the module .../mqtt.js

Isn't mqtt-js compatible with tabris-js or is this a global issue?

答:
From the document;
MQTT.js is a client library for the MQTT protocol, written in JavaScript for node.js and the browser.
To use MQTT.js in the browser see the browserify section.

I tested in the same way and this worked well.
Browserified node_modules/mqtt/mqtt.js module to a browsermqtt.js and required this bundle into my tabris-js app.
And use MQTT over Websockets port to the broker.

Title: using npm libraries in tabris-js app

Body:
I am new to programming and started with tabris-js mobile app development framework for pure javascript.
Tabris-js supports using npm modules an cordova plugins to extend.

I tried to import mqtt-js npm library into tabris-js app.
Locally installed the library to path;
project_folder/node_modules/mqtt/mqtt.js and added dependency in package.json.

When importing the module:

const mqtt = require('mqtt');

The error is: could not parse the module .../mqtt.js

Isn't mqtt-js compatible with tabris-js or is this a global issue?


问:
dash on alpine linux (in docker)
I'm trying to install dash in the (dockerized) alpine linux.
My Dockerfile follows:

```<code>FROM alpine:latest

RUN \
    echo "@community http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories && \
    apk add --no-cache --update dash
ENV SHELL dash

CMD dash
</code>```

the output I get:

```<code>Step 1/4 : FROM alpine:latest
 ---> 053cde6e8953
Step 2/4 : RUN echo "@community http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories &&     apk add --no-cache --update dash
 ---> Running in 680f3d4d7dda
fetch http://dl-cdn.alpinelinux.org/alpine/v3.6/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.6/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.6/community/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.6/community/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/edge/community/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/edge/community/x86_64/APKINDEX.tar.gz
ERROR: unsatisfiable constraints:
  dash-0.5.9.1-r0:
    masked in: @community
    satisfies: world[dash]
ERROR: Service 'dash_alpine' failed to build: The command '/bin/sh -c echo "@community http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories &&     apk add --no-cache --update dash' returned a non-zero code: 1
</code>```

however based on the alpine linux package search it seems to be available in the community repo: https://pkgs.alpinelinux.org/packages?name=dash&branch=edge&repo=&arch=&maintainer=

What should I change to make it working?

答:
I think your echo line is wrong.

This file works well for me.

```<code>FROM alpine:edge
RUN echo "http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories \
&& apk add -U --no-cache dash
</code>```

Title: dash on alpine linux (in docker)

Body:
I'm trying to install dash in the (dockerized) alpine linux.
My Dockerfile follows:

FROM alpine:latest

RUN \
    echo "@community http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories && \
    apk add --no-cache --update dash
ENV SHELL dash

CMD dash

the output I get:

Step 1/4 : FROM alpine:latest
 ---> 053cde6e8953
Step 2/4 : RUN echo "@community http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories &&     apk add --no-cache --update dash
 ---> Running in 680f3d4d7dda
fetch http://dl-cdn.alpinelinux.org/alpine/v3.6/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.6/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.6/community/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.6/community/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/edge/community/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/edge/community/x86_64/APKINDEX.tar.gz
ERROR: unsatisfiable constraints:
  dash-0.5.9.1-r0:
    masked in: @community
    satisfies: world[dash]
ERROR: Service 'dash_alpine' failed to build: The command '/bin/sh -c echo "@community http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories &&     apk add --no-cache --update dash' returned a non-zero code: 1

however based on the alpine linux package search it seems to be available in the community repo: https://pkgs.alpinelinux.org/packages?name=dash&branch=edge&repo=&arch=&maintainer=

What should I change to make it working?

Body:
I think your echo line is wrong.

This file works well for me.

FROM alpine:edge
RUN echo "http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories \
&& apk add -U --no-cache dash


问:
Big blank space HTML
In some area I have this big space between some sentence:

Is there a way to correct this with CSS?

HTML for a second example:

```<code><span style="color: rgb(197, 0, 0); text-align: justify; font-size: 14px;">
    <span id="MainContent_rptTest_lblTitle_2">Support to Efficient, Effictive and Transparent</span><br>
        <div style="color: rgb(197, 0, 0); text-align: justify; font-size: 12px;">
            <strong>
                <span id="MainContent_rptTest_lblDescription_2">September 2009 – January 2010</span></strong></div>
    </span>
</code>```

答:
Mess with the word-spacing property.

No guarantees ;)

Title: Big blank space HTML

Body:
In some area I have this big space between some sentence:

Is there a way to correct this with CSS?

HTML for a second example:

    Support to Efficient, Effictive and Transparent

                September 2009 – January 2010


问:
Splitting HTML file doesn't work
I'm trying to build very simple web page (one page , spited into 2 parts, each part will have it's own html file):

Welcome.html & Welcome.css:

```<code><html>

    <head>
        <link rel="stylesheet" type="text/css" href="Welcome.css">
    </head>

    <body id="bodyTag">

     <script type = "text/javascript"  src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script type = "text/javascript">
         $(document).ready(function(){

         });
      </script>

       <div id="top" w3-include-html="/Top.html">

       </div>

       <div id="bottom">
            bottom
        </div>

    </body>
</html>

#bottom {
    height: 50%;
    background-color: blue;
}

#top {
    height: 50%;
    background-color: orange;
}
</code>```

I want that Welcome.html file will get the top content from external html file

```<code>Top.html

<html>

  <head>
  </head>

  <body>
      Test -> TOP

  </body>
</html>
</code>```

But is seems that there is no request for Top.html file in the Node.js Log:

```<code>var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');

app.use(bodyParser.json())

/*
 *  Home page
 */
app.get('/', function (req, res) {
   clearLogScreen();
   console.log("[/] Got request for '/'");
   res.sendFile( __dirname + '/Welcome.html');
})

app.get('/Welcome.css', function(req, res) {
  console.log("[/Welcome] Got request for 'Welcome.css'");
  res.sendFile(__dirname + "/" + "Welcome.css");
});

app.get('/Top', function(req, res) {
  console.log("[/Top] Got request for 'Welcome.top'");
  res.sendFile(__dirname + "/" + "Top.html");
});

/*
 *  Startup
 */
var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port

   // start
   console.log("-----------------------------")
   console.log("Dirname: " + __dirname);
   console.log("App listening at http://%s:%s", host, port)
})
</code>```

I guess I'm missing something very easy, but can't find the mistake.

答:
I'm not sure what "w3-include-html" is, but if it does what it is supposed to do (based on the name), then try changing its value from "/Top.html" to "/Top". Or, alternatively, try changing the url route "/Top" to "/Top.html" in your express app.

One side note: Your included html ("Top.html") should not be a complete html. Try removing html, header and body tags. It should be a fragment.

Title: Splitting HTML file doesn't work

Body:
I'm trying to build very simple web page (one page , spited into 2 parts, each part will have it's own html file):

Welcome.html & Welcome.css:

        <link rel="stylesheet" type="text/css" href="Welcome.css">

            bottom

#bottom {
    height: 50%;
    background-color: blue;
}

#top {
    height: 50%;
    background-color: orange;
}

I want that Welcome.html file will get the top content from external html file

Top.html

      Test -> TOP

But is seems that there is no request for Top.html file in the Node.js Log:

var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');

app.use(bodyParser.json())

/*
 *  Home page
 */
app.get('/', function (req, res) {
   clearLogScreen();
   console.log("[/] Got request for '/'");
   res.sendFile( __dirname + '/Welcome.html');
})

app.get('/Welcome.css', function(req, res) {
  console.log("[/Welcome] Got request for 'Welcome.css'");
  res.sendFile(__dirname + "/" + "Welcome.css");
});

app.get('/Top', function(req, res) {
  console.log("[/Top] Got request for 'Welcome.top'");
  res.sendFile(__dirname + "/" + "Top.html");
});

/*
 *  Startup
 */
var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port

   // start
   console.log("-----------------------------")
   console.log("Dirname: " + __dirname);
   console.log("App listening at http://%s:%s", host, port)
})

I guess I'm missing something very easy, but can't find the mistake.


问:
Explicit conversion int to SqlInt32
Does anybody knows how to explicitly convert int to SqlInt32? Compiler throws error of conversion.</p>

```<code>using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    [SqlFunction()]
    static public int RarFiles(SqlString TARGET, SqlString SRC, SqlString SIZE)
    {
        ProcessStartInfo p = new ProcessStartInfo();
        p.FileName = @"C:\Program Files\WinRAR\rar.exe";
        p.Arguments = String.Format("a -cfg- -ep1 -idcdp -m5 -r -s -v{0} {1} {2}", SIZE, TARGET, SRC);
        Process x = Process.Start(p);
        SqlInt32 res = x.ExitCode;
        return res;
   }
}
</code>```

答:
```<code>public static implicit operator SqlInt32 (
    int x
)
</code>```

Parameters

```<code>x
</code>```

Type: System.Int32

An integer value.

Return Value

Type: System.Data.SqlTypes.SqlInt32

Title: Explicit conversion int to SqlInt32

Body:
Does anybody knows how to explicitly convert int to SqlInt32? Compiler throws error of conversion.

using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    [SqlFunction()]
    static public int RarFiles(SqlString TARGET, SqlString SRC, SqlString SIZE)
    {
        ProcessStartInfo p = new ProcessStartInfo();
        p.FileName = @"C:\Program Files\WinRAR\rar.exe";
        p.Arguments = String.Format("a -cfg- -ep1 -idcdp -m5 -r -s -v{0} {1} {2}", SIZE, TARGET, SRC);
        Process x = Process.Start(p);
        SqlInt32 res = x.ExitCode;
        return res;
   }
}

Body:
public static implicit operator SqlInt32 (
    int x
)

Parameters

x

Type: System.Int32

An integer value.

Return Value

Type: System.Data.SqlTypes.SqlInt32