问:
Table inside other table row in ReactJS
I have to build something between tree and table. I have folder, subfolders and elements. There is one folder, which keeps inside all subfolders. Informations rendering correctly, but react is ignoring part of my code.

```<code>const Folder = (props) => {
    return (
        <tr key={props.id}>
            <td className='w1_20'><input type='checkbox'/></td>
            <td className='w1_10'>{props.id}</td>
            <td className='w5_10'><a href=''>{props.name}</a></td>
            <td className='w2_10'/>
            <td className='w3_20'/>
        </tr>
    )
};
</code>```

This is my folder component.

```<code>const Subfolder = (props) => {
    return (
        <tr>
            <td className='p-0 bt-0' colSpan='5'>
                <table className='table table-hover w-100'>
                    <tbody>
                    {props.children}
                    </tbody>
                </table>
            </td>
        </tr>
    )
};
</code>```

This is my subfolder component.

```<code>const Segment = (props) => {
    return (
        <tr key={props.element.id}>
            <td className='w1_20'><input type='checkbox'/></td>
            <td className='w1_10'>{props.element.id}</td>
            <td className='w5_10'>{props.element.name}</td>
            <td className='w2_10'>{props.element.value}</td>
            <td className='w3_20'/>
        </tr>
    )
};
</code>```

This is element.

The structure should looks like:

Each subfolder should be next row after the folder row and it contains table inside (this is really important, as later I need to be able to manipulate these tables). Inside subfolders, can be element rows or another subfolder.

I know, that subfolders should have key also, but the major problem for me now is that React completely ignore, that inside subfolder td element I'm using another table with props children.

```<code>return (
    <tbody>
        <Folder id={1} name="Folder" />
        <Subfolder>
            <Subfolder>
                <Segment segment={{id: 1, name: "Element"}}/>
            </Subfolder>
        </Subfolder>
    </tbody>
);
</code>```

If I try to use it this way, it works fine. But to parse my API response I have function, where I push each element inside array, which I return at the end.

```<code>const InitTable = (props) => {
    let table = [];

    const mapResponse = (data) => {
        if (data) {
            if (data['folder']) {
                table = [...table, <Folder key={data.folder.id} id={data.folder.id} name={data.folder.name}/>];

                let sf = data['children'].map((item) => {
                    if (item) {
                        return mapResponse(item);
                    }
                });

                table = [...table, <Subfolder>{sf}</Subfolder>];

            } else if (data['segment']) {
                if (data['statistics']) {
                    table = [...table, <Segment statistics={data['statistics']} segment={data['segment']}/>];
                }
            }
        }
    };

    if (props.segments) {
        mapResponse(props.segments.root);
    }

    return (
        <tbody>
        {table}
        </tbody>
    );
};
</code>```

I need to create chunk of JSX and render at the end, so i check type of each object in the API response and push different component to the array. The main problem is that then, React completely ignore my tables inside td elements are render all as regular table.

When I'm expecting something more like:

I know the easiest way is to build it as normal string and later use dangerouslySetInnerHTML() method, but I want to avoid it.

答:
It seems like there are 2 issues

<Segment segment={{id: 1, name: "Element"}}/> takes a element prop, but your passing it a segment

You method for creating the main tbody is adding to the same array instead of returning a new one.

```<code>const InitTable = props => {
  const mapResponse = data => {
    if (data) {
      if (data['folder']) {
        let sf = data['children'].map(item => {
          if (item) {
            return mapResponse(item);
          }
        });

        return [
          <Folder
            key={data.folder.id}
            id={data.folder.id}
            name={data.folder.name}
          />,
          <Subfolder>{sf}</Subfolder>,
        ];
      } else if (data['segment']) {
        if (data['statistics']) {
          return [
            <Segment
              statistics={data['statistics']}
              element={data['segment']}
            />,
          ];
        }
      }
    }
  };

  return (
    <tbody>
      {mapResponse(props.segments.root)}
    </tbody>
  );
};
</code>```

https://codesandbox.io/s/gJJ2Lm2vD

Title: Table inside other table row in ReactJS

Body:
I have to build something between tree and table. I have folder, subfolders and elements. There is one folder, which keeps inside all subfolders. Informations rendering correctly, but react is ignoring part of my code.

const Folder = (props) => {
    return (

            <input type='checkbox'/>
            {props.id}
            {props.name}

    )
};

This is my folder component.

const Subfolder = (props) => {
    return (

                    {props.children}

    )
};

This is my subfolder component.

const Segment = (props) => {
    return (

            <input type='checkbox'/>
            {props.element.id}
            {props.element.name}
            {props.element.value}

    )
};

This is element.

The structure should looks like:

Each subfolder should be next row after the folder row and it contains table inside (this is really important, as later I need to be able to manipulate these tables). Inside subfolders, can be element rows or another subfolder.

I know, that subfolders should have key also, but the major problem for me now is that React completely ignore, that inside subfolder td element I'm using another table with props children.

return (

        <Folder id={1} name="Folder" />
        <Subfolder>
            <Subfolder>
                <Segment segment={{id: 1, name: "Element"}}/>
            </Subfolder>
        </Subfolder>

);

If I try to use it this way, it works fine. But to parse my API response I have function, where I push each element inside array, which I return at the end.

const InitTable = (props) => {
    let table = [];

    const mapResponse = (data) => {
        if (data) {
            if (data['folder']) {
                table = [...table, <Folder key={data.folder.id} id={data.folder.id} name={data.folder.name}/>];

                let sf = data['children'].map((item) => {
                    if (item) {
                        return mapResponse(item);
                    }
                });

                table = [...table, <Subfolder>{sf}</Subfolder>];

            } else if (data['segment']) {
                if (data['statistics']) {
                    table = [...table, <Segment statistics={data['statistics']} segment={data['segment']}/>];
                }
            }
        }
    };

    if (props.segments) {
        mapResponse(props.segments.root);
    }

    return (

        {table}

    );
};

I need to create chunk of JSX and render at the end, so i check type of each object in the API response and push different component to the array. The main problem is that then, React completely ignore my tables inside td elements are render all as regular table.

When I'm expecting something more like:

I know the easiest way is to build it as normal string and later use dangerouslySetInnerHTML() method, but I want to avoid it.

Body:
It seems like there are 2 issues

<Segment segment={{id: 1, name: "Element"}}/> takes a element prop, but your passing it a segment

You method for creating the main tbody is adding to the same array instead of returning a new one.

const InitTable = props => {
  const mapResponse = data => {
    if (data) {
      if (data['folder']) {
        let sf = data['children'].map(item => {
          if (item) {
            return mapResponse(item);
          }
        });

        return [
          <Folder
            key={data.folder.id}
            id={data.folder.id}
            name={data.folder.name}
          />,
          <Subfolder>{sf}</Subfolder>,
        ];
      } else if (data['segment']) {
        if (data['statistics']) {
          return [
            <Segment
              statistics={data['statistics']}
              element={data['segment']}
            />,
          ];
        }
      }
    }
  };

  return (
    <tbody>
      {mapResponse(props.segments.root)}
    </tbody>
  );
};

https://codesandbox.io/s/gJJ2Lm2vD


来源: stackexchange

问:
Swap a Web App using xPlat CLI in ARM mode
I know how to swap a slot using xPlat CLI in asm mode:

```<code>azure site swap 'sitename' 'slotname'
</code>```

However, how can I swap a slot using xPlat CLI in ARM mode?

Note: Im not looking for Azure CLI 2.0

答:
Just try to use azure webapp config set --slot

You could get more help by using azure webapp config set --slot -h.

```<code>root@shui:~# azure webapp config set --slot -h
help:    Set webapp configuration
example:  webapp config set RGName WebAppName --alwayson true --numberofworkers 1
help:
help:    Usage: webapp config set [options] <resource-group> <name>
help:      --slot <slot>                                                the name of the slot
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know how to swap a slot using xPlat CLI in asm mode:

azure site swap 'sitename' 'slotname'

However, how can I swap a slot using xPlat CLI in ARM mode?

Note: Im not looking for Azure CLI 2.0

Body:
Just try to use azure webapp config set --slot

You could get more help by using azure webapp config set --slot -h.

root@shui:~# azure webapp config set --slot -h
help:    Set webapp configuration
example:  webapp config set RGName WebAppName --alwayson true --numberofworkers 1
help:
help:    Usage: webapp config set [options] <resource-group> <name>
help:      --slot <slot>                                                the name of the slot


问:
Issue with Fluent nhibernate and the type Decimal
I am encoutering an issue with the decimal type and fluent nhibernate.

Here is my problem:

I have a class with a property:

```<code>public virtual decimal? Amount { get; set; }
</code>```

In my mapping I have :

```<code>Map(x => x.Amount, "SOMETHING").Length(8).Precision(19).Scale(4).CustomSqlType("money");
</code>```

The Nhibernate mapping I get is:

```<code><property name="Amount" type="System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
  <column name="SOMETHING" length="8" sql-type="money" precision="19" scale="4" />
</property>
</code>```

And what I get when I try to update this value with a sql server 2000 is:

```<code>Disallowed implicit conversion from data type varchar to data type money, table 'ANYTABLE, column '...'. Use the CONVERT function to run this query.
</code>```

I am using MsSqlConfiguration.MsSql2000 to configure fluent hibernate and version 1.1.0.0 of fluent nhibernate.

Thanks for your help!

答:
I forgot to say, the problem is that  in the request generated, I have:

```<code>UPDATE [A_TABLE]
SET    ....
   AMOUNT = '6118,2200' /* @p1_0 */,
   ....
</code>```

and it should be

```<code>   AMOUNT = 6118.22
</code>```

I am using NH3 as well.

ContentLicense: CC BY-SA 2.5

Body:
I am encoutering an issue with the decimal type and fluent nhibernate.

Here is my problem:

I have a class with a property:

public virtual decimal? Amount { get; set; }

In my mapping I have :

Map(x => x.Amount, "SOMETHING").Length(8).Precision(19).Scale(4).CustomSqlType("money");

The Nhibernate mapping I get is:

<property name="Amount" type="System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
  <column name="SOMETHING" length="8" sql-type="money" precision="19" scale="4" />
</property>

And what I get when I try to update this value with a sql server 2000 is:

Disallowed implicit conversion from data type varchar to data type money, table 'ANYTABLE, column '...'. Use the CONVERT function to run this query.

I am using MsSqlConfiguration.MsSql2000 to configure fluent hibernate and version 1.1.0.0 of fluent nhibernate.

Thanks for your help!

Body:
I forgot to say, the problem is that  in the request generated, I have:

UPDATE [A_TABLE]
SET    ....
   AMOUNT = '6118,2200' /* @p1_0 */,
   ....

and it should be

   AMOUNT = 6118.22

I am using NH3 as well.


问:
AutoMapper define mapping level
```<code>public class Foo
{
    public string Baz { get; set; }
    public List<Bar> Bars { get; set; }
}
</code>```

When I map the class above, is there any way to define how deep I want automapper to map objects? Some pseudo code of what I'm after:

```<code>var mapped = Mapper.Map<FooDTO>(foo, opt => { levels: 0 });
// result = { Baz: "" }

var mapped = Mapper.Map<FooDTO>(foo, opt => { levels: 1 });
// result = { Baz: "", Bars: [{ Blah: "" }] }

 var mapped = Mapper.Map<FooDTO>(foo, opt => { levels: 2 });
// result = { Baz: "", Bars: [{ Blah: "", Buzz: [{ Baz: "" }] }] }

// etc...
</code>```

I'm currently using automapper 3.3 due to a nuget dependency.

答:
You can do it by providing a value at runtime as was answered in question: How to ignore a property based on a runtime condition?.

Configuration:

```<code>Mapper.CreateMap<Foo, FooDTO>().ForMember(e => e.Bars,
    o => o.Condition(c => !c.Options.Items.ContainsKey("IgnoreBars")));
</code>```

Usage:

```<code>Mapper.Map<FooDTO>(foo, opts => { opts.Items["IgnoreBars"] = true; });
</code>```

Same configuration approach you can apply for all your nested objects that you call levels.

If you want to achieve same behavior for your DB Entities you can use ExplicitExpansion approach as described in this answer: Is it possible to tell automapper to ignore mapping at runtime?.

Configuration:

```<code>Mapper.CreateMap<Foo, FooDTO>()
    .ForMember(e => e.Bars, o => o.ExplicitExpansion());
</code>```

Usage:

```<code>dbContext.Foos.Project().To<FooDTO>(membersToExpand: d => d.Bars);
</code>```

Title: AutoMapper define mapping level

Body:
public class Foo
{
    public string Baz { get; set; }
    public List<Bar> Bars { get; set; }
}

When I map the class above, is there any way to define how deep I want automapper to map objects? Some pseudo code of what I'm after:

var mapped = Mapper.Map<FooDTO>(foo, opt => { levels: 0 });
// result = { Baz: "" }

var mapped = Mapper.Map<FooDTO>(foo, opt => { levels: 1 });
// result = { Baz: "", Bars: [{ Blah: "" }] }

 var mapped = Mapper.Map<FooDTO>(foo, opt => { levels: 2 });
// result = { Baz: "", Bars: [{ Blah: "", Buzz: [{ Baz: "" }] }] }

// etc...

I'm currently using automapper 3.3 due to a nuget dependency.

Body:
You can do it by providing a value at runtime as was answered in question: How to ignore a property based on a runtime condition?.

Configuration:

Mapper.CreateMap<Foo, FooDTO>().ForMember(e => e.Bars,
    o => o.Condition(c => !c.Options.Items.ContainsKey("IgnoreBars")));

Usage:

Mapper.Map<FooDTO>(foo, opts => { opts.Items["IgnoreBars"] = true; });

Same configuration approach you can apply for all your nested objects that you call levels.

If you want to achieve same behavior for your DB Entities you can use ExplicitExpansion approach as described in this answer: Is it possible to tell automapper to ignore mapping at runtime?.

Configuration:

Mapper.CreateMap<Foo, FooDTO>()
    .ForMember(e => e.Bars, o => o.ExplicitExpansion());

Usage:

dbContext.Foos.Project().To<FooDTO>(membersToExpand: d => d.Bars);


问:
keyset and key different data type
I am seeing a unique situation where my keyset and key of a LinkedHashSet are containing different data types as shown below

As you can see that the key is a String and the keyset is a long.

Following code is failing because of that:

```<code>modifiedRowKeys.toArray(new Long[modifiedRowKeys.size()]);
</code>```

I get ArrayStoreException for String values.

I was able to replicate this from Angular application where i am sending a Map<Long, Map<String,Object>> to my Spring server which contains the data as shared in the pic.

Edit 1:

Please see following strange behavior in eclipse:

Could it be an issue with Jackson Mapper which we are using for conversion of objects ?

Edit 2:

The following code fails with ClassCastException saying

String cannot be cast to Long

```<code>Set<Long> modifiedRowKeys = modifiedRowMap.keySet();
Long[] periodDateArray = new Long[modifiedRowKeys.size()];

int count = 0;
Iterator<Long> keyIterator = modifiedRowKeys.iterator();
while(keyIterator.hasNext()){
    Long key = keyIterator.next();
    System.out.println("key instanceof Long : " + (key instanceof Long));
    periodDateArray[count++] = Long.valueOf(key);
}
</code>```

This seems pretty straight forward logic !

Edit 3:

I have recreated the problem as follows:

```<code>    public static void main(String[] args) {

        CollectionsToArray collectionsToArray = new CollectionsToArray();

        Map<String, Map<String, Object>> mapOfNumbers = collectionsToArray.prepareStrangeNumbersSetFromMapOfMap();

        Object obj = mapOfNumbers;
        collectionsToArray.convertMapToKeySetToArray(obj);

    }

    private Map<String, Map<String, Object>> prepareStrangeNumbersSetFromMapOfMap() {
        Map<String, Map<String, Object>> longNumberMap = new LinkedHashMap<>();

        Map<String, Object> stringValueMap = new HashMap<>();
        stringValueMap.put("Adams", "Adithya");
        stringValueMap.put("Edge", 80);

        longNumberMap.put("1488376800000", stringValueMap);

        return longNumberMap;
    }

    private void convertMapToKeySetToArray(Object obj) {
        Map<Long, Map<String, Object>> mapOfNumbers = (Map<Long, Map<String, Object>>) obj;
        Set<Long> stringNumbers = mapOfNumbers.keySet();

        convertLongKeySetToArray(stringNumbers);
    }

    private void convertLongKeySetToArray(Set<Long> stringNumbers) {
        Long[] stringNumbersArray = stringNumbers.toArray(new Long[0]);
        Arrays.sort(stringNumbersArray);

        System.out.println(stringNumbersArray);
    }
</code>```

答:
You are confusing something, that key is a String, but keySet is actually a Set that uses toString to show the output with [].

```<code> Set<String> set = new HashSet<>();
 set.add("1");
 set.add("2");
 System.out.println(set); // [1, 2]
</code>```

So you have a String and a Set (not a long).

And this fails because String is known to not be a Long at compile-time, no runtime check is needed (also add the missing parentheses):

```<code>System.out.println("key instanceof Long" + (s instanceof Long));
</code>```

Title: keyset and key different data type

Body:
I am seeing a unique situation where my keyset and key of a LinkedHashSet are containing different data types as shown below

As you can see that the key is a String and the keyset is a long.

Following code is failing because of that:

modifiedRowKeys.toArray(new Long[modifiedRowKeys.size()]);

I get ArrayStoreException for String values.

I was able to replicate this from Angular application where i am sending a Map<Long, Map<String,Object>> to my Spring server which contains the data as shared in the pic.

Edit 1:

Please see following strange behavior in eclipse:

Could it be an issue with Jackson Mapper which we are using for conversion of objects ?

Edit 2:

The following code fails with ClassCastException saying

String cannot be cast to Long

Set<Long> modifiedRowKeys = modifiedRowMap.keySet();
Long[] periodDateArray = new Long[modifiedRowKeys.size()];

int count = 0;
Iterator<Long> keyIterator = modifiedRowKeys.iterator();
while(keyIterator.hasNext()){
    Long key = keyIterator.next();
    System.out.println("key instanceof Long : " + (key instanceof Long));
    periodDateArray[count++] = Long.valueOf(key);
}

This seems pretty straight forward logic !

Edit 3:

I have recreated the problem as follows:

    public static void main(String[] args) {

        CollectionsToArray collectionsToArray = new CollectionsToArray();

        Map<String, Map<String, Object>> mapOfNumbers = collectionsToArray.prepareStrangeNumbersSetFromMapOfMap();

        Object obj = mapOfNumbers;
        collectionsToArray.convertMapToKeySetToArray(obj);

    }

    private Map<String, Map<String, Object>> prepareStrangeNumbersSetFromMapOfMap() {
        Map<String, Map<String, Object>> longNumberMap = new LinkedHashMap<>();

        Map<String, Object> stringValueMap = new HashMap<>();
        stringValueMap.put("Adams", "Adithya");
        stringValueMap.put("Edge", 80);

        longNumberMap.put("1488376800000", stringValueMap);

        return longNumberMap;
    }

    private void convertMapToKeySetToArray(Object obj) {
        Map<Long, Map<String, Object>> mapOfNumbers = (Map<Long, Map<String, Object>>) obj;
        Set<Long> stringNumbers = mapOfNumbers.keySet();

        convertLongKeySetToArray(stringNumbers);
    }

    private void convertLongKeySetToArray(Set<Long> stringNumbers) {
        Long[] stringNumbersArray = stringNumbers.toArray(new Long[0]);
        Arrays.sort(stringNumbersArray);

        System.out.println(stringNumbersArray);
    }

Body:
You are confusing something, that key is a String, but keySet is actually a Set that uses toString to show the output with [].

 Set<String> set = new HashSet<>();
 set.add("1");
 set.add("2");
 System.out.println(set); // [1, 2]

So you have a String and a Set (not a long).

And this fails because String is known to not be a Long at compile-time, no runtime check is needed (also add the missing parentheses):

System.out.println("key instanceof Long" + (s instanceof Long));


问:
not able to fetch values from struct type channel in Go lang
With reference to  this example, i want to add a pre-defined delay between job initialization and termination. I have stored the data i.e. jobid and waittime in map. Then i have copied the entire map in a channel of same struct type as map. But i am not able to fetch the map values in go routine calls. Please help me, I am new to Go.</p>

```<code>package main

import "fmt"

type Vertex struct {
id, waitime int
}

var m = map[int]Vertex{
1:  {1, 1000},
2:  {2, 2000},
3:  {3, 1000},
4:  {4, 2000},
5:  {5, 1000},
6:  {6, 2000},
7:  {7, 1000},
8:  {8, 2000},
9:  {9, 1000},
10: {10, 2000},
}

func worker(w int, jobs <-chan Vertex, results chan<- int) {
for j := 1; j <= len(m); j++ {
    a, b := <-jobs.id, <-jobs.waitime
    fmt.Println("worker", w, "started job", a)
    //time.Sleep(time.Sleep(time.Duration(b)))
    fmt.Println("worker", w, "finished job", a)
    results <- j * 2
  }
}

func main() {
//n := 5
jobs := make(chan Vertex, 100)
results := make(chan int, 100)

for w := 1; w <= 5; w++ {
    go worker(w, jobs, results)
}
fmt.Println(len(m))
for j := 1; j <= len(m); j++ {
    jobs <- m[j]
}
//close(jobs)

for a := 1; a <= len(m); a++ {
    <-results
}
}
</code>```

答:
Change:

```<code>a, b := <-jobs.id, <-jobs.waitime
</code>```

to:

```<code>job := <-jobs
a, b := job.id, job.waitime
</code>```

jobs is a channel not a Vertex.

Body:
With reference to  this example, i want to add a pre-defined delay between job initialization and termination. I have stored the data i.e. jobid and waittime in map. Then i have copied the entire map in a channel of same struct type as map. But i am not able to fetch the map values in go routine calls. Please help me, I am new to Go.

package main

import "fmt"

type Vertex struct {
id, waitime int
}

var m = map[int]Vertex{
1:  {1, 1000},
2:  {2, 2000},
3:  {3, 1000},
4:  {4, 2000},
5:  {5, 1000},
6:  {6, 2000},
7:  {7, 1000},
8:  {8, 2000},
9:  {9, 1000},
10: {10, 2000},
}

func worker(w int, jobs <-chan Vertex, results chan<- int) {
for j := 1; j <= len(m); j++ {
    a, b := <-jobs.id, <-jobs.waitime
    fmt.Println("worker", w, "started job", a)
    //time.Sleep(time.Sleep(time.Duration(b)))
    fmt.Println("worker", w, "finished job", a)
    results <- j * 2
  }
}

func main() {
//n := 5
jobs := make(chan Vertex, 100)
results := make(chan int, 100)

for w := 1; w <= 5; w++ {
    go worker(w, jobs, results)
}
fmt.Println(len(m))
for j := 1; j <= len(m); j++ {
    jobs <- m[j]
}
//close(jobs)

for a := 1; a <= len(m); a++ {
    <-results
}
}

Body:
Change:

a, b := <-jobs.id, <-jobs.waitime

to:

job := <-jobs
a, b := job.id, job.waitime

jobs is a channel not a Vertex.


问:
Python-3.x Count the frequency of a specific number from user input
I'm trying to make a program that will output how many times the number 7 appears from a series of numbers (of no particular range) inputted by the user. Each number would be a separate input, not as one.

I have searched far and wide but the solutions I found involved letters, words, or numbers from pre-made lists rather than int from user input and errored when I tried to modify for purpose. I'm sure I'm missing something really obvious but I can't figure out how to do this.

(I tried Counter, if num == 100, count(100), for i in range, etc etc - but I'm clearly on the wrong path)

My starting point was trying to modify this one that prints the highest number because I am aiming for a similar format:

```<code>x = 0
done = False
while not done:
    print("Enter a number (0 to end): ")
    y = input()
    num = int(y)
    if num != 0:
        if num > x:
            x = num
    else:
        done = True
print(str(x))
</code>```

Thank you for any advice with this.

答:
Try the following:</p>

```<code>x = ''
done = False
while not done:
    print("Enter a number (0 to end): ")
    y = input()
    if y != '0':
        x = x + y
    else:
        done = True

print(x.count('7'))
</code>```

Body:
I'm trying to make a program that will output how many times the number 7 appears from a series of numbers (of no particular range) inputted by the user. Each number would be a separate input, not as one.

I have searched far and wide but the solutions I found involved letters, words, or numbers from pre-made lists rather than int from user input and errored when I tried to modify for purpose. I'm sure I'm missing something really obvious but I can't figure out how to do this.

(I tried Counter, if num == 100, count(100), for i in range, etc etc - but I'm clearly on the wrong path)

My starting point was trying to modify this one that prints the highest number because I am aiming for a similar format:

x = 0
done = False
while not done:
    print("Enter a number (0 to end): ")
    y = input()
    num = int(y)
    if num != 0:
        if num > x:
            x = num
    else:
        done = True
print(str(x))

Thank you for any advice with this.

Body:
Try the following:

x = ''
done = False
while not done:
    print("Enter a number (0 to end): ")
    y = input()
    if y != '0':
        x = x + y
    else:
        done = True

print(x.count('7'))


问:
Is there a standard function for "do this if Just x"?
I have the following code:

```<code>doIf :: (a -> IO ()) -> Maybe a -> IO ()
doIf f x = case x of
  Just i -> f i
  Nothing -> return ()

main = do
  mapM_ (doIf print) [Just 3, Nothing, Just 4]
</code>```

which outputs:

```<code>3
4
</code>```

In other words, the Just values are printed, but Nothing values cause no action.  (And do not interrupt computation.)

Is there a standard function like this in the Haskell libraries?  Also, can this be made more generic?  I tried replacing IO () with m b but then return () does not work.  How do you generically write return () for any monad? (If possible..)  Can even the Maybe be generalized here?

Lastly, can I do away with the doIf function entirely?  Can I have an operator <#> that applies an argument unless Nothing?

```<code>print <#> Just 3
print <#> Nothing
</code>```

would output

```<code>3
</code>```

But I don't know if this is possible.

答:
Could you do somthing along the lines of:

```<code>main = do
  mapM_ print $ catMaybes [Just 3, Nothing, Just 4]
</code>```

See the documentation for catMaybes.

(NB: Untested code)

Body:
I have the following code:

doIf :: (a -> IO ()) -> Maybe a -> IO ()
doIf f x = case x of
  Just i -> f i
  Nothing -> return ()

main = do
  mapM_ (doIf print) [Just 3, Nothing, Just 4]

which outputs:

3
4

In other words, the Just values are printed, but Nothing values cause no action.  (And do not interrupt computation.)

Is there a standard function like this in the Haskell libraries?  Also, can this be made more generic?  I tried replacing IO () with m b but then return () does not work.  How do you generically write return () for any monad? (If possible..)  Can even the Maybe be generalized here?

Lastly, can I do away with the doIf function entirely?  Can I have an operator <#> that applies an argument unless Nothing?

print <#> Just 3
print <#> Nothing

would output

3

But I don't know if this is possible.

Body:
Could you do somthing along the lines of:

main = do
  mapM_ print $ catMaybes [Just 3, Nothing, Just 4]

See the documentation for catMaybes.

(NB: Untested code)


问:
Heroku/Rails: How to install the GNU Scientific Library (GSL) on Heroku?
I need to install the GSL library on Heroku running a Rails (4.0.2) app to use some gems that depend on it.

Goal:
Install the GSL library to work with GSL and Similarity gems in Heroku.

Tried approaches:

Installing Ruby / GSL in Heroku Application: Heroku crashes after deploy. GSL gem is unable to find the lib. Trace: http://pastebin.com/CPcMUdCa

Tomwolfe's Heroku's Ruby buildpack adapted for using couchbase: Same issue.

Building Dependency Binaries for Heroku Applications: Vulcan is deprecated. More info on Heroku's Devcenter and on Github

I've tried following these steps (compiling binaries):

GSL 1.15 downloaded from ftp://ftp.gnu.org/gnu/gsl/gsl-1.15.tar.gz

Uncompressed and cd gsl-1.15

./configure

make clean

make

sudo make install

It works on my local environment but not in Heroku. Heroku doesn't allow sudo but it allows access with heroku run. The problem is that the file system is ephemeral and the dyno will only live as long as your console session.

Update:

I've also tried building my own Heroku Buildpack but I couldn't make it work. I tried using multipacks.  I'm not a Heroku Buildpack expert so maybe it's the problem, I'm learning more about it to make a simple repository with an example and an extended explanation of this issue.

答:
I had to use gsl1.16 on heroku and here is how I solved it:

First added gsl1.16 buildpack to the lists of buildpacks like

```<code>heroku buildpacks:add --index:3 git://github.com/gregory/heroku-gsl-buildpack.git#gsl-1.16
</code>```

Which adds to my list of buildpacks, in my case got nodejs and ruby already. Hence --index=3

Then had to set LD_LIBRARY_PATH on heroku like

```<code>heroku config:set LD_LIBRARY_PATH=/app/vendor/gsl/lib
</code>```

which points to 1.16. Seen around that some people use /app/vendor/gsl1/lib but wasn't my case.

and that's it.

ContentLicense: CC BY-SA 4.0

Body:
I had to use gsl1.16 on heroku and here is how I solved it:

First added gsl1.16 buildpack to the lists of buildpacks like

heroku buildpacks:add --index:3 git://github.com/gregory/heroku-gsl-buildpack.git#gsl-1.16

Which adds to my list of buildpacks, in my case got nodejs and ruby already. Hence --index=3

Then had to set LD_LIBRARY_PATH on heroku like

heroku config:set LD_LIBRARY_PATH=/app/vendor/gsl/lib

which points to 1.16. Seen around that some people use /app/vendor/gsl1/lib but wasn't my case.

and that's it.


问:
How to show a 'grep' result with the complete path or file name
How can I get the complete file path when I use grep?

I use commands like

cat *.log | grep somethingtosearch
```

I need to show the result with the complete file path from where the matched result were taken out.

How can I do it?

答:
The easiest way to print full paths is to replace the relative start path with the absolute path:</p>
```<code>grep -r --include="*.sh" "pattern" ${PWD}
</code>```

Body:
How can I get the complete file path when I use grep?

I use commands like

cat *.log | grep somethingtosearch

I need to show the result with the complete file path from where the matched result were taken out.

How can I do it?

Body:
The easiest way to print full paths is to replace the relative start path with the absolute path:

grep -r --include="*.sh" "pattern" ${PWD}


问:
JavaScript capture MP3 playback duration and Countdown to submit at the end
I Have a object that is definite the duration of a media from this tag :

```<code><span class="mejs-duration">00:50</span>
</code>```

I try to capture the time to show the button to skip like this :

```<code><script type="text/javascript">var seconds = getElementsByClassName("mejs-duration")[0] ;  function decreaseTime(){ document.frm.submit.value=seconds; seconds--; if(seconds<0){ document.frm.submit.value='Submit'; document.frm.submit.disabled=false; return true; } setTimeout('decreaseTime()',1000); } window.onload = function() { document.frm.submit.value=seconds; setTimeout('decreaseTime()',1000); } </script><form name="frm" action="" metod="link"> <input type="submit" name="submit" disabled /> </form>
</code>```

But I have this error :
Uncaught ReferenceError: getElementsByClassName is not defined
    at ....

Where I mistake ?

Thank You in advance for Help me.

答: getElementsByClassName is a method on the document object and on HTML Element Node objects. It is not a global.

Body:
I Have a object that is definite the duration of a media from this tag :

00:50

I try to capture the time to show the button to skip like this :

<form name="frm" action="" metod="link"> <input type="submit" name="submit" disabled /> </form>

But I have this error :
Uncaught ReferenceError: getElementsByClassName is not defined
    at ....

Where I mistake ?

Thank You in advance for Help me.


问:
css footer always bottom of page
How do I make the footer always stay bottom of the page (no sticky)? My footer is at the bottom of the screen, but not on the page.

Here is an example of my code.

HTML

```<code><!DOCTYPE html>
<html>
<head>
     <meta http-equiv="Content-Type" content="text/html charset=utf-8"/>
     <link href="styles.css" type="text/css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="header">Header</div>
        <div class="body">Body</div>
        <div class="footer">Footer</div>
    </div>
</body>
</html>
</code>```

CSS

```<code>.footer {
    width:100%;
    height:109px;
    position:absolute;
    bottom:0;
    left:0;
    background-color: purple;
}
</code>```

答:
CSS “Always on the bottom” Footer

This footer will always be positioned at the bottom of the page, but not fixed

```

Title: css footer always bottom of page

Body:
How do I make the footer always stay bottom of the page (no sticky)? My footer is at the bottom of the screen, but not on the page.

Here is an example of my code.

HTML

<!DOCTYPE html>

     <meta http-equiv="Content-Type" content="text/html charset=utf-8"/>
     <link href="styles.css" type="text/css" rel="stylesheet">

Header

Body

Footer

CSS

.footer {
    width:100%;
    height:109px;
    position:absolute;
    bottom:0;
    left:0;
    background-color: purple;
}

Body:
<style>

.demo {
  margin: 0 auto;
  padding-top: 64px;
  max-width: 640px;
  width: 94%;
}

.footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  background-color: #efefef;
  text-align: center;
}
</style>
<div class="demo">
  <h1>CSS “Always on the bottom” Footer</h1>
</div>

<div class="footer">This footer will always be positioned at the bottom of the page, but <strong>not fixed</strong>
</div>


问:
Logical Operations on Big Integers in MySQL
I'm using Apache XAMPP server. I need to perform logical operations on big integers, something like 5 (101) & 2 (010) = 0 (000). Unfortunately my big integers exceeds the maximum of MySQL BIGINT which is 18446744073709551615.

An example of my used numbers is 455214730926009756012878233, so instead of BIGINT i used VARCHAR, i need to perform logical operations on this VARCHAR.
I tried something like

```<code>SELECT number FROM table WHERE number & 12 = 12
</code>```

it doesn't return the right rows.
And  when i try something like

```<code>SELECT number FROM table WHERE number &  455214730926009756012878233 = 455214730926009756012878233
</code>```

it gives me no rows, while it should return the row in which the number is '455214730926009756012878233'

So, what is the right way to do logical operations on real big integers like this in MySQL?

答:
There is nothing built in to do binary operations on VARCHAR. And as VARCHAR is  a text type, I wouldn't consider it appropriate anyway.

Better store the numbers in a numeric type, e.g. DECIMAL(39,0). For bitwise operations split this into two 64 bit parts:

```<code>select
  (455214730926009756012878231 DIV 18446744073709551616) as highbits,
  (455214730926009756012878231 %   18446744073709551616) as lowbits,
  (455214730926009756012878231 %   18446744073709551616) % 12
</code>```

18446744073709551616 is 2^64. Don't use POW(2, 64). This function is buggy and results in an incorrect 18446744073709552000 (in MySQL 5.7.2 at least; I suppose MySQL uses approximate math with approximate datatypes here).

Body:
I'm using Apache XAMPP server. I need to perform logical operations on big integers, something like 5 (101) & 2 (010) = 0 (000). Unfortunately my big integers exceeds the maximum of MySQL BIGINT which is 18446744073709551615.

An example of my used numbers is 455214730926009756012878233, so instead of BIGINT i used VARCHAR, i need to perform logical operations on this VARCHAR.
I tried something like

SELECT number FROM table WHERE number & 12 = 12

it doesn't return the right rows.
And  when i try something like

SELECT number FROM table WHERE number &  455214730926009756012878233 = 455214730926009756012878233

it gives me no rows, while it should return the row in which the number is '455214730926009756012878233'

So, what is the right way to do logical operations on real big integers like this in MySQL?

Body:
There is nothing built in to do binary operations on VARCHAR. And as VARCHAR is  a text type, I wouldn't consider it appropriate anyway.

Better store the numbers in a numeric type, e.g. DECIMAL(39,0). For bitwise operations split this into two 64 bit parts:

select
  (455214730926009756012878231 DIV 18446744073709551616) as highbits,
  (455214730926009756012878231 %   18446744073709551616) as lowbits,
  (455214730926009756012878231 %   18446744073709551616) % 12

18446744073709551616 is 2^64. Don't use POW(2, 64). This function is buggy and results in an incorrect 18446744073709552000 (in MySQL 5.7.2 at least; I suppose MySQL uses approximate math with approximate datatypes here).


问:
got data from function to array not working in swift 3
I can get the JSON data but I can not add the JSON data to abcArr. I have count the abcArr witch is 0 in the viewDidLoad().

I'm copy the coding in below.

Thank you for your help.

my coding:

```<code>class MapDetailViewController: UIViewController {
    var abcArr = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        getInfo()
        print("1: \(abcArr.count)")//output = 0
    }

    func getInfo() {
        //MARK: get News data JSON
        jsonURL = "http://json/abc.json"

        if let url = NSURL(string: jsonURL) {
            URLSession.shared.dataTask(with: url as URL, completionHandler: { (data, response, error) in
                if let error = error {
                    print("Error: \(error.localizedDescription)")
                } else {
                    if let data = data {
                        let json = JSON(data: data)
                        let jsonReturn = json["return"]
                        let abc = jsonReturn[i]["Lat"]
                        abcArr.append(abc)
                    } else {
                        print("no JSON data")
                    }
                }
            }).resume()
            print("2: \(abcArr.count)")//output = 0
        }
    }
}
</code>```

答:
Thank you for your solution Vadian.

Put the line print(abcArr.count) at the end of the completion handler.

```<code>class MapDetailViewController: UIViewController {
     var abcArr = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        getInfo()
    }

    func getInfo() {
        //MARK: get News data JSON
        jsonURL = "http://json/abc.json"

        if let url = NSURL(string: jsonURL) {
            URLSession.shared.dataTask(with: url as URL, completionHandler: { (data, response, error) in
                if let error = error {
                    print("Error: \(error.localizedDescription)")
                } else {
                    if let data = data {
                        let json = JSON(data: data)
                        let jsonReturn = json["return"]
                        let abc = jsonReturn[i]["Lat"]
                        abcArr.append(abc)
                    } else {
                        print("no JSON data")
                    }
                    print("1: \(abcArr.count)")// display abcArr of count
                }
            print("2: \(abcArr.count)")// display abcArr of count
            }).resume()
        }
    }
}
</code>```

my JSON:

```<code>{
    return: [{
        lat: "1111",
    }]
}
</code>```

Body:
I can get the JSON data but I can not add the JSON data to abcArr. I have count the abcArr witch is 0 in the viewDidLoad().

I'm copy the coding in below.

Thank you for your help.

my coding:

class MapDetailViewController: UIViewController {
    var abcArr = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        getInfo()
        print("1: \(abcArr.count)")//output = 0
    }

    func getInfo() {
        //MARK: get News data JSON
        jsonURL = "http://json/abc.json"

        if let url = NSURL(string: jsonURL) {
            URLSession.shared.dataTask(with: url as URL, completionHandler: { (data, response, error) in
                if let error = error {
                    print("Error: \(error.localizedDescription)")
                } else {
                    if let data = data {
                        let json = JSON(data: data)
                        let jsonReturn = json["return"]
                        let abc = jsonReturn[i]["Lat"]
                        abcArr.append(abc)
                    } else {
                        print("no JSON data")
                    }
                }
            }).resume()
            print("2: \(abcArr.count)")//output = 0
        }
    }
}

Body:
Thank you for your solution Vadian.

Put the line print(abcArr.count) at the end of the completion handler.

class MapDetailViewController: UIViewController {
     var abcArr = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        getInfo()
    }

    func getInfo() {
        //MARK: get News data JSON
        jsonURL = "http://json/abc.json"

        if let url = NSURL(string: jsonURL) {
            URLSession.shared.dataTask(with: url as URL, completionHandler: { (data, response, error) in
                if let error = error {
                    print("Error: \(error.localizedDescription)")
                } else {
                    if let data = data {
                        let json = JSON(data: data)
                        let jsonReturn = json["return"]
                        let abc = jsonReturn[i]["Lat"]
                        abcArr.append(abc)
                    } else {
                        print("no JSON data")
                    }
                    print("1: \(abcArr.count)")// display abcArr of count
                }
            print("2: \(abcArr.count)")// display abcArr of count
            }).resume()
        }
    }
}

my JSON:

{
    return: [{
        lat: "1111",
    }]
}


问:
Unable to checkout specific commit file
With this command git show 51eec182 path/to/filename

```<code>commit 51eec182c258b4525f0ba3a6303e3be349789f54
Author: Android <Android@MobileDEV>
Date:   Tue May 2 09:06:48 2017 +0700

    add methods to models

.....
.....
-this line is removed
+this line is added
.....
.....
</code>```

What I want is "this line is removed" is back

so I run this command

git checkout 51eec182 -- path/to/filename

But the "this line is removed" not back.

Anyway previously I run git reset HEAD path/to/filename

Where I'm doing wrong?

答:
The file's content is this line is added in the commit 51eec182c. this line is removed is in the commit previous of 51eec182. The previous commit is the parent of 51eec182. Since 51eec182 is not a merge-commit, it has only one parent. We can refer to this first parent by adding the symbol "^" right behind the commit hash, 51eec182^.

So git checkout 51eec182^ -- path/to/filename.

Title: Unable to checkout specific commit file

Body:
With this command git show 51eec182 path/to/filename

commit 51eec182c258b4525f0ba3a6303e3be349789f54
Author: Android <Android@MobileDEV>
Date:   Tue May 2 09:06:48 2017 +0700

    add methods to models

.....
.....
-this line is removed
+this line is added
.....
.....

What I want is "this line is removed" is back

so I run this command

git checkout 51eec182 -- path/to/filename

But the "this line is removed" not back.

Anyway previously I run git reset HEAD path/to/filename

Where I'm doing wrong?


问:
Converting VB code to C# using array and redim preserver keyword
This is my VB code:

```<code>If TxtStr(i) = "#" And TxtStr(i + 1) = "]" Then
    RefStr = RefStr & "]"
    ReDim Preserve RefStrLinks(1, RefStrLinkIndex)
    RefStrLinks(0, RefStrLinkIndex) = RefStr
    RefStr = RefStr.Replace("[#", String.Empty)
    RefStr = RefStr.Replace("#]", String.Empty)
    RefStrLinks(1, RefStrLinkIndex) = RefStr
    RefStrLinkIndex = RefStrLinkIndex + 1
    RefStr = String.Empty
    RefStrFound = False
End If
</code>```

This is my converted code in C#; RefStrLinks is declared as:

```<code>string[,] RefStrLinks = null;
</code>```

But this gives a compile error because of ReDim Preserve whenever I run this:

```<code>if (TxtStr[i].ToString() == "#" & TxtStr[i + 1].ToString() == "]")
{
    RefStr = RefStr + "]";
    Array.Resize<string>(ref RefStrLinks, RefStrLinkIndex + 1);
    RefStrLinks[0, RefStrLinkIndex] = RefStr;
    RefStr = RefStr.Replace("[#", string.Empty);
    RefStr = RefStr.Replace("#]", string.Empty);
    RefStrLinks(1, RefStrLinkIndex) = RefStr;
    RefStrLinkIndex = RefStrLinkIndex + 1;
    RefStr = string.Empty;
    RefStrFound = false;
}
</code>```

Does anybody understand why?

答:
Right; I think the real issue here is that you have a 2-dimensional array; RefStrLinks is not a string[], but rather is a string[,], with dimension 2 on the first axis. Array.Resize only works with vectors (a "vector" is a one-dimensional array with base index 0, i.e. string[]).

Frankly, I would replace all of this (re-dimming an array or using Array.Resize per element is absurdly expensive) with something like:

```<code>List<SomeBasicType> list = ...
...
// where "foo" and "bar" are the two values that you intend to store per item
var item = new SomeBasicType(foo, bar);
list.Add(item);
</code>```

where perhaps SomeBasicType is an immutable struct that takes two strings. Or more simply, in C# "current": value-type tuples:

```<code>// declare the list (change the names to something meaningful for your code)
var list = new List<(string name, string url)>();

// ... add values efficiently

string name = "whatever"; // your per-item code goes here
string url = "some value"; // and here
list.Add((name, url));

// ... show that we have the data

foreach(var item in list)
{
    Console.WriteLine($"{item.name} / {item.url}");
}
</code>```

Body:
This is my VB code:

If TxtStr(i) = "#" And TxtStr(i + 1) = "]" Then
    RefStr = RefStr & "]"
    ReDim Preserve RefStrLinks(1, RefStrLinkIndex)
    RefStrLinks(0, RefStrLinkIndex) = RefStr
    RefStr = RefStr.Replace("[#", String.Empty)
    RefStr = RefStr.Replace("#]", String.Empty)
    RefStrLinks(1, RefStrLinkIndex) = RefStr
    RefStrLinkIndex = RefStrLinkIndex + 1
    RefStr = String.Empty
    RefStrFound = False
End If

This is my converted code in C#; RefStrLinks is declared as:

string[,] RefStrLinks = null;

But this gives a compile error because of ReDim Preserve whenever I run this:

if (TxtStr[i].ToString() == "#" & TxtStr[i + 1].ToString() == "]")
{
    RefStr = RefStr + "]";
    Array.Resize<string>(ref RefStrLinks, RefStrLinkIndex + 1);
    RefStrLinks[0, RefStrLinkIndex] = RefStr;
    RefStr = RefStr.Replace("[#", string.Empty);
    RefStr = RefStr.Replace("#]", string.Empty);
    RefStrLinks(1, RefStrLinkIndex) = RefStr;
    RefStrLinkIndex = RefStrLinkIndex + 1;
    RefStr = string.Empty;
    RefStrFound = false;
}

Does anybody understand why?

Body:
Right; I think the real issue here is that you have a 2-dimensional array; RefStrLinks is not a string[], but rather is a string[,], with dimension 2 on the first axis. Array.Resize only works with vectors (a "vector" is a one-dimensional array with base index 0, i.e. string[]).

Frankly, I would replace all of this (re-dimming an array or using Array.Resize per element is absurdly expensive) with something like:

List<SomeBasicType> list = ...
...
// where "foo" and "bar" are the two values that you intend to store per item
var item = new SomeBasicType(foo, bar);
list.Add(item);

where perhaps SomeBasicType is an immutable struct that takes two strings. Or more simply, in C# "current": value-type tuples:

// declare the list (change the names to something meaningful for your code)
var list = new List<(string name, string url)>();

// ... add values efficiently

string name = "whatever"; // your per-item code goes here
string url = "some value"; // and here
list.Add((name, url));

// ... show that we have the data

foreach(var item in list)
{
    Console.WriteLine($"{item.name} / {item.url}");
}


问:
How to force full page navigation rather than virtual page navigation in SPA
We have a single page application and we just want to ensure that the user will always be working with the latest version of the web app.

Our simple, although hacky solution, is to detect all anchor clicks and check if the time since page load >= 24 hours. If it is we want to perform a 'full page' navigation rather than a 'virtual page' navigation. Ie, instead of going to #contact-us with no page refresh, we want to send the user to http://website.com#contact-us where a page refresh will occur.

In the function below I can detect a 'virtual' navigation that is about to be performed. But how can I then force a full page navigation and refresh? Should I change the anchor href attribute to the full website path then allow the event to propagate? Or should I just do window.location = ...;?

```<code>events: {
        'click a[href!=""]': 'onClick'
}

onClick: function(ev)
{
    try {

        var now                     = new Date()
        ,   hoursSinceLastRefresh   = Math.abs(now - this.lastRefresh) / 36e5
        ,   href                    = ev.currentTarget.attr('href')
        ,   isVirtualNavigation     = href.substr(0,1) === '#'
        ,   pageExpired             = hoursSinceLastRefresh >= 24;

        // if is internal navigation
        if (isVirtualNavigation && pageExpired)
            // How can I force a 'full page' navigation not a virtual navigation?

    }
    catch (ex) {

    }
}
</code>```

PS: what are the proper terms for the following:

When a user clicks the link href="#contact-us"> the page does not refresh but the user 'navigates' to a new page in the SPA. Whats the term for this? I've been calling this 'virtual page' navigation.

When a user clicks the link href="http://website.com#contact-us"> the page does refresh in the SPA. Whats the term for this? I've been calling this 'full page' navigation.

Note Our <link ..> and

答: Just do a window.location=... and the browser will do the rest ;)

Body:
We have a single page application and we just want to ensure that the user will always be working with the latest version of the web app.

Our simple, although hacky solution, is to detect all anchor clicks and check if the time since page load >= 24 hours. If it is we want to perform a 'full page' navigation rather than a 'virtual page' navigation. Ie, instead of going to #contact-us with no page refresh, we want to send the user to http://website.com#contact-us where a page refresh will occur.

In the function below I can detect a 'virtual' navigation that is about to be performed. But how can I then force a full page navigation and refresh? Should I change the anchor href attribute to the full website path then allow the event to propagate? Or should I just do window.location = ...;?

events: {
        'click a[href!=""]': 'onClick'
}

onClick: function(ev)
{
    try {

        var now                     = new Date()
        ,   hoursSinceLastRefresh   = Math.abs(now - this.lastRefresh) / 36e5
        ,   href                    = ev.currentTarget.attr('href')
        ,   isVirtualNavigation     = href.substr(0,1) === '#'
        ,   pageExpired             = hoursSinceLastRefresh >= 24;

        // if is internal navigation
        if (isVirtualNavigation && pageExpired)
            // How can I force a 'full page' navigation not a virtual navigation?

    }
    catch (ex) {

    }
}

PS: what are the proper terms for the following:

When a user clicks the link  the page does not refresh but the user 'navigates' to a new page in the SPA. Whats the term for this? I've been calling this 'virtual page' navigation.

When a user clicks the link  the page does refresh in the SPA. Whats the term for this? I've been calling this 'full page' navigation.

Note Our <link ..> and


问:
Convert .csv file into .dbf using Python?
How can I convert a .csv file into .dbf file using a python script? I found this piece of code online but I'm not certain how reliable it is. Are there any modules out there that have this functionality?</p>

答:
None that are well-polished, to my knowledge.  I have had to work with xBase files many times over the years, and I keep finding myself writing code to do it when I have to do it.  I have, somewhere in one of my backups, a pretty functional, pure-Python library to do it, but I don't know precisely where that is.

Fortunately, the xBase file format isn't all that complex.  You can find the specification on the Internet, of course.  At a glance the module that you linked to looks fine, but of course make copies of any data that you are working with before using it.

A solid, read/write, fully functional xBase library with all the bells and whistles is something that has been on my TODO list for a while... I might even get to it in what is left this year, if I'm lucky... (probably not, though, sadly).


问:
How can I efficiently store a grid of rectangles?
So I was thinking about making a building game with different shaped rectangles instead of just squares, but I can't figure out an efficient way to do this. For example, I don't want to have a grid of tiles like tetris that make up each shape. I want each piece to be one object with a width and height. For example a 2*3 piece wouldn't take up 6 tiles, it would just be a single rectangle. I have to be able to do organize the pieces efficiently and be able to get the piece at a certain coordinate. If I just used a two dimensional array of tiles it would use memory that I don't need.</p>

答:
Do the rectangles overlap?  If not, you can use the RectangleGrid class here: https://github.com/eyal0/OctoPrint-Slicer/blob/master/src/RectanglePacker.js#L10

Adding a rectangle is potentially slow but for your use case might work.
 Querying the rectangle at a given position is O(nlogn).


问:
Unable to import the database via PLESK
I'm trying to import my database via PLESK and still have the same errors:

enter image description here

ERROR 2006 (HY000) at line 1898: MySQL server has gone away

Traceback (most recent call last):

File "/usr/local/psa/admin/sbin/dbbackup", line 6, in

File "/usr/local/psa/lib/modules/python/dbbackup/dbbackup.py", line
100, in main restore(options, password)

File "/usr/local/psa/lib/modules/python/dbbackup/dbbackup.py", line
89, in restore

raise Exception("program 'mysql' finished with non-zero exit code:
%d" % p.returncode)

Exception: program 'mysql' finished with non-zero exit code: 1

I tried to enlarge memory_limit and upload_max_filesize in PLESK PHP Settings but it still doesn't work. I've also checked version of my MySQL (5.5.2) because I found it might be not supported by the latest version of Plesk, but it seems to be OK.

I am beginner in such subjects and I really don't know what to do. Please, rescue me :(

答:
It is timeout issue.
I would suggest increasing wait_timeout in my.cnf</p>

Title: Unable to import the database via PLESK


问:
no implicit conversion of Symbol into Integer Rails 5
I am working on a ruby app similar to reddit and have run into this error while adding user sign-up functionality.  I have a commit view with the following line of code that is causing the error:

```<code><%= button_to "Yes", {controller: 'users',
                          action: 'create',
                          params: params}, class: 'btn btn-success' %>
</code>```

To fix the error I changed the code like so:

```<code><%= button_to "Yes", {
                      controller: 'users',
                          action: 'create',
                          params: {
                               user {
                                     name: @user.name,
                                    email: @user.email,
                                 password: @user.password,
                    password_confirmation: @user.password_confirmation

                                     }
                                   }
                      },  class: 'btn btn-success' %>
</code>```

This fixes the problem but I would like to understand why the first line doesn't work and get advice on the best way to implement this.

the error gets thrown on @user.name =params[:user][:name].

Here is the full def in users controller:

```<code>def create
  @user = User.new
  @user.name = params[:user][:name]
  @user.email = params[:user][:email]
  @user.password = params[:user][:password]
  @user.password_confirmation = params[:user][:password_confirmation]
end
</code>```

From my server log I can see that user has been changed to a long string in params:

```<code>    Parameters {"authenticity_token"=>"xSeWlcW6Ix5kciNGi2/xAep2aRq0CmefI6lnieQutlolAsk/qXM+mGvWixvNfTMedHnstWDd29mbMThGF1FCqg==", "commit"=>"Sign up", "user"=>"email=ja%40j.com&name=jasonj&password=jjjjjj&password_confirmation=jjjjjj", "utf8"=>"✓"}
</code>```

答:
Maybe you should convert your params hash with this command 'symbolize_keys'

Example:

```<code>{"test"=>"hb", "test"=>"hb" }.symbolize_keys
</code>```

return

```<code>{test: "hb", test: "hb" }
</code>```

Body:
I am working on a ruby app similar to reddit and have run into this error while adding user sign-up functionality.  I have a commit view with the following line of code that is causing the error:

<%= button_to "Yes", {controller: 'users',
                          action: 'create',
                          params: params}, class: 'btn btn-success' %>

To fix the error I changed the code like so:

<%= button_to "Yes", {
                      controller: 'users',
                          action: 'create',
                          params: {
                               user {
                                     name: @user.name,
                                    email: @user.email,
                                 password: @user.password,
                    password_confirmation: @user.password_confirmation

                                     }
                                   }
                      },  class: 'btn btn-success' %>

This fixes the problem but I would like to understand why the first line doesn't work and get advice on the best way to implement this.

the error gets thrown on @user.name =params[:user][:name].

Here is the full def in users controller:

def create
  @user = User.new
  @user.name = params[:user][:name]
  @user.email = params[:user][:email]
  @user.password = params[:user][:password]
  @user.password_confirmation = params[:user][:password_confirmation]
end

From my server log I can see that user has been changed to a long string in params:

    Parameters {"authenticity_token"=>"xSeWlcW6Ix5kciNGi2/xAep2aRq0CmefI6lnieQutlolAsk/qXM+mGvWixvNfTMedHnstWDd29mbMThGF1FCqg==", "commit"=>"Sign up", "user"=>"email=ja%40j.com&name=jasonj&password=jjjjjj&password_confirmation=jjjjjj", "utf8"=>"✓"}

Body:
Maybe you should convert your params hash with this command 'symbolize_keys'

Example:

{"test"=>"hb", "test"=>"hb" }.symbolize_keys

return

{test: "hb", test: "hb" }


问:
DLookup statement from SQL to VBA
Please help to solve this statement: "Too few parameters expected 1".

The problem is on the

If(IsNull([tblMaintWO]![Technian1]),'', DLookup('Initial', tblEmployees, 'EmpID=' & [tblMaintWO]![Technian1])) AS TechnianA

I can't put the double quotes in the statement or it will show a red sentence and raise the error.

```<code>strSQL = "SELECT tblMaintWO.MWONo, tblMaintWO.TaskOpenDate, tblMaintWO.MTRStation, tblMaintWO.Task, tblMaintWO.RequestedPriority, tblMaintWO.WorkOrderStatus, tblMaintWO.Technian1, "
strSQL = strSQL & "IIf([CMFollowUp] = True, 'CM', IIf([PreventiveMaint] = True, 'PM', IIf([EIVO] = True, 'EI/VO', 'Other'))) AS TaskType, "
strSQL = strSQL & "IIf(IsNull([tblMaintWO]![Technian1]),'', DLookup('Initial', tblEmployees, 'EmpID=' & [tblMaintWO]![Technian1])) AS TechnianA "
strSQL = strSQL & "FROM tblMaintWO, tblEmployees;"
</code>```

答:
Try this:</p>

```<code>strSQL = "SELECT tblMaintWO.MWONo, tblMaintWO.TaskOpenDate, tblMaintWO.MTRStation, tblMaintWO.Task, tblMaintWO.RequestedPriority, tblMaintWO.WorkOrderStatus, tblMaintWO.Technian1, "
strSQL = strSQL & "IIf([CMFollowUp] = True, 'CM', IIf([PreventiveMaint] = True, 'PM', IIf([EIVO] = True, 'EI/VO', 'Other'))) AS TaskType, "
strSQL = strSQL & "IIf(IsNull([tblMaintWO]![Technian1]),'', DLookup('Initial', 'tblEmployees', 'EmpID=' & [tblMaintWO]![Technian1] & '')) AS TechnianA "
strSQL = strSQL & "FROM tblMaintWO, tblEmployees;"
</code>```

Title: DLookup statement from SQL to VBA

Body:
Please help to solve this statement: "Too few parameters expected 1".

The problem is on the

If(IsNull([tblMaintWO]![Technian1]),'', DLookup('Initial', tblEmployees, 'EmpID=' & [tblMaintWO]![Technian1])) AS TechnianA

I can't put the double quotes in the statement or it will show a red sentence and raise the error.

strSQL = "SELECT tblMaintWO.MWONo, tblMaintWO.TaskOpenDate, tblMaintWO.MTRStation, tblMaintWO.Task, tblMaintWO.RequestedPriority, tblMaintWO.WorkOrderStatus, tblMaintWO.Technian1, "
strSQL = strSQL & "IIf([CMFollowUp] = True, 'CM', IIf([PreventiveMaint] = True, 'PM', IIf([EIVO] = True, 'EI/VO', 'Other'))) AS TaskType, "
strSQL = strSQL & "IIf(IsNull([tblMaintWO]![Technian1]),'', DLookup('Initial', tblEmployees, 'EmpID=' & [tblMaintWO]![Technian1])) AS TechnianA "
strSQL = strSQL & "FROM tblMaintWO, tblEmployees;"

Body:
Try this:

strSQL = "SELECT tblMaintWO.MWONo, tblMaintWO.TaskOpenDate, tblMaintWO.MTRStation, tblMaintWO.Task, tblMaintWO.RequestedPriority, tblMaintWO.WorkOrderStatus, tblMaintWO.Technian1, "
strSQL = strSQL & "IIf([CMFollowUp] = True, 'CM', IIf([PreventiveMaint] = True, 'PM', IIf([EIVO] = True, 'EI/VO', 'Other'))) AS TaskType, "
strSQL = strSQL & "IIf(IsNull([tblMaintWO]![Technian1]),'', DLookup('Initial', 'tblEmployees', 'EmpID=' & [tblMaintWO]![Technian1] & '')) AS TechnianA "
strSQL = strSQL & "FROM tblMaintWO, tblEmployees;"


问:
How to efficiently concat QStrings
I want to concat a tree structure of QStrings into a single QString.

If I understand correctly, QStrings are immutable like Java-Strings, so similar reasons why you use Java's StringBuilder should apply.

Using the % operator seems only to improve the efficiency of a single statement, so would probably not help me much since I need to concat over several nested loops.

I could use a std::stringstream, but that would mean transforming each single QString into a C-string or std-string first, presumably with performance cost.

Would using a QTextStream help?

Or is there some better possibility?

答:
If you concatinate large ammount of string via + operator or append method, it is inefficient due to memory reallocations.
In order to avoid said reallocations you need to calculate amount of memory result of concatination need, allocate said amount to char* buffer, copy raw data of every string you concatinate in appropriate place in buffer (via memcpy for example). Then constract resulting string object from char* buffer.</p>

Title: How to efficiently concat QStrings


问:
When Developing the database then compolsury to define the primary key or forign key in each tables of the database?
When Developing the database then compolsury to  define the primary key or forign key in each tables of the databse if any tables that do not contain any unique field that time how can we connect the table with other table.
Suppose i have three tabe.

table1 Personel Detail

```<code>Emai_Address (PK)
Name
City
ContactNo
Land_Line_No
D_O_B
Gender
Marital_Status
Language_Known
</code>```

Table2 Professiona_Detail

```<code>Total_Experiance
Annual_Salary
Functional_Area
Current_Industry
Key_Skill
Resume_HeadLine
</code>```

Table3 WorkPreference

```<code>Specify Your Preference
Start Working
Prefered Location
Job Type
</code>```

The Obove Table1 contain the PK but Table2 or Table 3 does not contain any Pk Or FK then  how can connect this three table.

答:
No. It's not compulsory. But HIGHLY recommended!

Some SQL guru once said:

If it doesn't have a primary key, it's not a table!

Live by that statement!

And foreign keys will make your database more secure, and avoid "zombie" rows. Again: it's not compulsory or technically necessary by all means, but you'll get yourself into trouble if you don't know it right from the start! Trust me.... been there, cleaned up that mess......

OwnerDisplayName: harikrishna

Body:
When Developing the database then compolsury to  define the primary key or forign key in each tables of the databse if any tables that do not contain any unique field that time how can we connect the table with other table.
Suppose i have three tabe.

table1 Personel Detail

Emai_Address (PK)
Name
City
ContactNo
Land_Line_No
D_O_B
Gender
Marital_Status
Language_Known

Table2 Professiona_Detail

Total_Experiance
Annual_Salary
Functional_Area
Current_Industry
Key_Skill
Resume_HeadLine

Table3 WorkPreference

Specify Your Preference
Start Working
Prefered Location
Job Type

The Obove Table1 contain the PK but Table2 or Table 3 does not contain any Pk Or FK then  how can connect this three table.


问:
Call a function in Python file using Flask
I have python file called testing_file.py:

```<code>    from datetime import datetime
    import MySQLdb

    # Open database connection
    class DB():
        def __init__(self, server, user, password, db_name):
            db = MySQLdb.connect(server, user, password, db_name )
            self.cur = db.cursor()

        def time_statistic(self, start_date, end_date):

            time_list = {}

            sql = "SELECT activity_log.datetime, activity_log.user_id FROM activity_log"
            self.cur.execute(sql)
            self.date_data = self.cur.fetchall()
            for content in self.date_data:

                timestamp = str(content[0])
                datetime_object = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
                timestamps = datetime.strftime(datetime_object, "%Y-%m-%d")

                if start_dt <= timestamps and timestamps <= end_dt:
                    if timestamps not in time_list:
                        time_list[timestamps]=1
                    else:
                        time_list[timestamps]+=1

                    return json.dumps(time_list)

    start_date = datetime.strptime(str('2017-4-7'), '%Y-%m-%d')
    start_dt = datetime.strftime(start_date, "%Y-%m-%d")
    end_date = datetime.strptime(str('2017-5-4'), '%Y-%m-%d')
    end_dt = datetime.strftime(end_date, "%Y-%m-%d")

    db = DB("host","user_db","pass_db","db_name")
    db.time_statistic(start_date, end_date)
</code>```

I want to access the result (time_list) thru API using Flask. This is what i've wrote so far, doesn't work and also I've tried another way:

```<code>    from flask import Flask
    from testing_api import *

    app = Flask(__name__)

    @app.route("/")
    def get():
        db = DB("host","user_db","pass_db","db_name")
        d = db.time_statistic()
        return d

    if __name__ == "__main__":
        app.run(debug=True)
</code>```

Question: This is my first time work with API and Flask. Can anyone please help me thru this. Any hints are appreciated. Thank you

I've got empty list as result {}

答:
There are many things wrong with what you are doing.

1.> def get(self, DB) why self? This function does not belong to a class. It is not an instance function. self is a reference of the class instance when an instance method is called. Here not only it is not needed, it is plain and simple wrong.

2.> If you look into flask's routing declaration a little bit, you will see how you should declare a route with parameter. This is the link. In essence you should something like this

```<code>@app.route("/path/<variable>")
def route_func(variable):
    return variable
</code>```

3.> Finally, one more thing I would like to mention, Please do not call a regular python file test_<filename>.py unless you plan to use it as a unit testing file. This is very confusing.

Oh, and you have imported DB from your module already no need to pass it as a parameter to a function. It should be anyway available inside it.

Body:
I have python file called testing_file.py:

    from datetime import datetime
    import MySQLdb

    # Open database connection
    class DB():
        def __init__(self, server, user, password, db_name):
            db = MySQLdb.connect(server, user, password, db_name )
            self.cur = db.cursor()

        def time_statistic(self, start_date, end_date):

            time_list = {}

            sql = "SELECT activity_log.datetime, activity_log.user_id FROM activity_log"
            self.cur.execute(sql)
            self.date_data = self.cur.fetchall()
            for content in self.date_data:

                timestamp = str(content[0])
                datetime_object = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
                timestamps = datetime.strftime(datetime_object, "%Y-%m-%d")

                if start_dt <= timestamps and timestamps <= end_dt:
                    if timestamps not in time_list:
                        time_list[timestamps]=1
                    else:
                        time_list[timestamps]+=1

                    return json.dumps(time_list)

    start_date = datetime.strptime(str('2017-4-7'), '%Y-%m-%d')
    start_dt = datetime.strftime(start_date, "%Y-%m-%d")
    end_date = datetime.strptime(str('2017-5-4'), '%Y-%m-%d')
    end_dt = datetime.strftime(end_date, "%Y-%m-%d")

    db = DB("host","user_db","pass_db","db_name")
    db.time_statistic(start_date, end_date)

I want to access the result (time_list) thru API using Flask. This is what i've wrote so far, doesn't work and also I've tried another way:

    from flask import Flask
    from testing_api import *

    app = Flask(__name__)

    @app.route("/")
    def get():
        db = DB("host","user_db","pass_db","db_name")
        d = db.time_statistic()
        return d

    if __name__ == "__main__":
        app.run(debug=True)

Question: This is my first time work with API and Flask. Can anyone please help me thru this. Any hints are appreciated. Thank you

I've got empty list as result {}

Body:
There are many things wrong with what you are doing.

1.> def get(self, DB) why self? This function does not belong to a class. It is not an instance function. self is a reference of the class instance when an instance method is called. Here not only it is not needed, it is plain and simple wrong.

2.> If you look into flask's routing declaration a little bit, you will see how you should declare a route with parameter. This is the link. In essence you should something like this

@app.route("/path/<variable>")
def route_func(variable):
    return variable

3.> Finally, one more thing I would like to mention, Please do not call a regular python file test_<filename>.py unless you plan to use it as a unit testing file. This is very confusing.

Oh, and you have imported DB from your module already no need to pass it as a parameter to a function. It should be anyway available inside it.


问:
how to delete record through primary key in android
While deleting record through primary key, primary key get null value and record doesn't deleted.

Please look in to my code,

```<code> dataBase.delete(DbHelper.TABLE_PARKSAL_TABLELIST, DbHelper.PARKSALE_PrimeryID+ "=" + primarykeytableid, null);
</code>```

I want to delete whole row data with primary key as well. How to fix it? Thanks in advance.

答:
Checkout that you are passing each parameters and is not null like primarykeytable id cannot be null.

Or you can try this

```<code>db.delete(DbHelper.TABLE_PARKSAL_TABLELIST, DbHelper.PARKSALE_PrimeryID+"=?", new String[]{Integer.toString(id)});
</code>```

Body:
While deleting record through primary key, primary key get null value and record doesn't deleted.

Please look in to my code,

 dataBase.delete(DbHelper.TABLE_PARKSAL_TABLELIST, DbHelper.PARKSALE_PrimeryID+ "=" + primarykeytableid, null);

I want to delete whole row data with primary key as well. How to fix it? Thanks in advance.

Body:
Checkout that you are passing each parameters and is not null like primarykeytable id cannot be null.

Or you can try this

db.delete(DbHelper.TABLE_PARKSAL_TABLELIST, DbHelper.PARKSALE_PrimeryID+"=?", new String[]{Integer.toString(id)});


问:
Configuring log4j.xml in Tomcat
I would like to configure the logs for a simple app running in a tomcat and i'd like to send all logs except error level ones to one file, and the errors to other one.

How should i configure the log4j.xml to make it works?

```<code><appender name="regular-container" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="regularLogs.log" />
</appender>

<appender name="error-container" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="errorLogs.log" />
</appender>

<logger name="regular-container">
 ?????????????????????
</logger>

<logger name="error-container">
 ?????????????????????
</logger>
</code>```

答:
Try this log4j.xml:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
  xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="errorsOnly" class="org.apache.log4j.RollingFileAppender">
        <param name="file" value="errorLogs.log" />
        <param name="threshold" value="ERROR" />
    </appender>

    <appender name="regular" class="org.apache.log4j.RollingFileAppender">
        <param name="file" value="regularLogs.log" />
        <param name="threshold" value="DEBUG" />
    </appender>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="errorsOnly" />
        <appender-ref ref="regular" />
    </root>

</log4j:configuration>
</code>```

Note that this includes FATAL logging in errorsOnly, though I assume that's okay.  Having errorsOnly first with threshold set to ERROR means error level or above are handled by errorsOnly.  DEBUG or higher not yet  handled by errorsOnly are then handled by regular.  I found a similar issue providing another example.

Title: Configuring log4j.xml in Tomcat

Body:
I would like to configure the logs for a simple app running in a tomcat and i'd like to send all logs except error level ones to one file, and the errors to other one.

How should i configure the log4j.xml to make it works?

<appender name="regular-container" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="regularLogs.log" />
</appender>

<appender name="error-container" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="errorLogs.log" />
</appender>

<logger name="regular-container">
 ?????????????????????
</logger>

<logger name="error-container">
 ?????????????????????
</logger>

Body:
Try this log4j.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
  xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="errorsOnly" class="org.apache.log4j.RollingFileAppender">
        <param name="file" value="errorLogs.log" />
        <param name="threshold" value="ERROR" />
    </appender>

    <appender name="regular" class="org.apache.log4j.RollingFileAppender">
        <param name="file" value="regularLogs.log" />
        <param name="threshold" value="DEBUG" />
    </appender>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="errorsOnly" />
        <appender-ref ref="regular" />
    </root>

</log4j:configuration>

Note that this includes FATAL logging in errorsOnly, though I assume that's okay.  Having errorsOnly first with threshold set to ERROR means error level or above are handled by errorsOnly.  DEBUG or higher not yet  handled by errorsOnly are then handled by regular.  I found a similar issue providing another example.


问:
Dynamics CRM 2016 onpre - Incoming Email failure issues
Currently using Server-Side Synchronization for process email.

Server profile configured with POP3-SMTP profile type.

for gmail -

incoming: pop.gmail.com , outgoing: smtp.gmail.com

Authenticate for incoming: Credentials Specified by user or queue

Authenticate for outgoing: Credentials Specified in Email Server Profile

Incoming port: 995; SSL-Enabled; Authenticate protocol-Basic

Outgoing port: 587; SSL-Enabled; Authenticate protocol-Basic (test result success)

Outgoing port: 465; SSL-Enabled; Authenticate protocol-Basic (test result failure)

I had Approved the mailbox with system admin role

Specified Credentials for Email Processing in mailbox (email and password)

incoming email: Server-Side Synchronization or Email Router

outgoing email: Server-Side Synchronization or Email Router

Thats all the setting I had done in my dynamics crm 2016 on-premise.

the version of my crm is CRM2016 (8.0.0.1088) (DB 8.0.0.1088)

After approved the mailbox and test & enable mailbox. The result only outgoing is success(with port 587) and incoming is failure. My Gmail is able to receive the outgoing email.

The alert message for incoming failure is An unexpected error occurred while receiving email. Mailbox CRM Admin didn't synchronize. The owner of the associated email server profile gmail server has been notified.

Does anyone know what I missed to config or any solution can solve this problem?

答:
Some things to verify on GMail side in order for it to play nice with CRM:

POP has to be enabled

Allow Less Secure Apps

Unlock Captcha

port for pop.gmail.com in CRM mail setup should be 995

port for smtp.gmail.com in CRM mail setup should be 587 (you already got this right)


问:
Why wont my email validation work? PHP
I have used

```<code>if (!preg_match('/[a-z||0-9]@[a-z||0-9].[a-z]/', $email)) {
    [PRINT ERROR]
}
</code>```

&

```<code>if (!eregi( "^[0-9]+$", $email)) {
    [PRINT ERROR]
}
</code>```

&

```<code>if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    [PRINT ERROR]
}
</code>```

I have also tried taking out the ! and make it work backwards but for some reason NONE of those work to find out if it is valid. Any ideas why?...
I have it in an else if statement, Im not sure if that could be the cause..

I am using PHP

Title: Why wont my email validation work? PHP

Body:
I have used

if (!preg_match('/[a-z||0-9]@[a-z||0-9].[a-z]/', $email)) {
    [PRINT ERROR]
}

&

if (!eregi( "^[0-9]+$", $email)) {
    [PRINT ERROR]
}

&

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    [PRINT ERROR]
}

I have also tried taking out the ! and make it work backwards but for some reason NONE of those work to find out if it is valid. Any ideas why?...
I have it in an else if statement, Im not sure if that could be the cause..

I am using PHP

Body:
Try this from the Kohana source code:

function email($email)
{
    return (bool) preg_match('/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD', (string) $email);
}


问:
not able to fetch values from struct type channel in Go lang
With reference to  this example, i want to add a pre-defined delay between job initialization and termination. I have stored the data i.e. jobid and waittime in map. Then i have copied the entire map in a channel of same struct type as map. But i am not able to fetch the map values in go routine calls. Please help me, I am new to Go.</p>

```<code>package main

import "fmt"

type Vertex struct {
id, waitime int
}

var m = map[int]Vertex{
1:  {1, 1000},
2:  {2, 2000},
3:  {3, 1000},
4:  {4, 2000},
5:  {5, 1000},
6:  {6, 2000},
7:  {7, 1000},
8:  {8, 2000},
9:  {9, 1000},
10: {10, 2000},
}

func worker(w int, jobs <-chan Vertex, results chan<- int) {
for j := 1; j <= len(m); j++ {
    a, b := <-jobs.id, <-jobs.waitime
    fmt.Println("worker", w, "started job", a)
    //time.Sleep(time.Sleep(time.Duration(b)))
    fmt.Println("worker", w, "finished job", a)
    results <- j * 2
  }
}

func main() {
//n := 5
jobs := make(chan Vertex, 100)
results := make(chan int, 100)

for w := 1; w <= 5; w++ {
    go worker(w, jobs, results)
}
fmt.Println(len(m))
for j := 1; j <= len(m); j++ {
    jobs <- m[j]
}
//close(jobs)

for a := 1; a <= len(m); a++ {
    <-results
}
}
</code>```

答:
Couple of things are wrong with your code.

First, you can't access struct members directly off the channel. That is, this line is wrong:

```<code>a, b := <-jobs.id, <-jobs.waitime
</code>```

jobs is a channel. It does not have any members called id or waittime. These are the members of the struct Vertex it's supposed to transfer. Change this line to:

```<code>job := <-jobs
a, b := job.id, job.waitime
</code>```

But now, your code declares b but does not use it. To fix, uncomment the call to time.Sleep:

```<code>time.Sleep(time.Sleep(time.Duration(b))) !INCORRECT CALL
</code>```

But this call is completely wrong. time.Sleep expects an argument of type time.Duration and returns nothing. To fix, make the following changes:

```<code>time.Sleep(time.Duration(b) * time.Millisecond)
</code>```

This should get your code running.

Body:
With reference to  this example, i want to add a pre-defined delay between job initialization and termination. I have stored the data i.e. jobid and waittime in map. Then i have copied the entire map in a channel of same struct type as map. But i am not able to fetch the map values in go routine calls. Please help me, I am new to Go.

package main

import "fmt"

type Vertex struct {
id, waitime int
}

var m = map[int]Vertex{
1:  {1, 1000},
2:  {2, 2000},
3:  {3, 1000},
4:  {4, 2000},
5:  {5, 1000},
6:  {6, 2000},
7:  {7, 1000},
8:  {8, 2000},
9:  {9, 1000},
10: {10, 2000},
}

func worker(w int, jobs <-chan Vertex, results chan<- int) {
for j := 1; j <= len(m); j++ {
    a, b := <-jobs.id, <-jobs.waitime
    fmt.Println("worker", w, "started job", a)
    //time.Sleep(time.Sleep(time.Duration(b)))
    fmt.Println("worker", w, "finished job", a)
    results <- j * 2
  }
}

func main() {
//n := 5
jobs := make(chan Vertex, 100)
results := make(chan int, 100)

for w := 1; w <= 5; w++ {
    go worker(w, jobs, results)
}
fmt.Println(len(m))
for j := 1; j <= len(m); j++ {
    jobs <- m[j]
}
//close(jobs)

for a := 1; a <= len(m); a++ {
    <-results
}
}

Body:
Couple of things are wrong with your code.

First, you can't access struct members directly off the channel. That is, this line is wrong:

a, b := <-jobs.id, <-jobs.waitime

jobs is a channel. It does not have any members called id or waittime. These are the members of the struct Vertex it's supposed to transfer. Change this line to:

job := <-jobs
a, b := job.id, job.waitime

But now, your code declares b but does not use it. To fix, uncomment the call to time.Sleep:

time.Sleep(time.Sleep(time.Duration(b))) !INCORRECT CALL

But this call is completely wrong. time.Sleep expects an argument of type time.Duration and returns nothing. To fix, make the following changes:

time.Sleep(time.Duration(b) * time.Millisecond)

This should get your code running.


问:
Finding Middle index in an array if sum of both ends are equal?
I have done half of the coding and I am not sure what should be the next step:-

```<code>public class Middlexindex {
public static void main(String[] args)
{
     int sum=0;
    int[] myArray={1,2,3,3,2,1};
    for(int i=0; i<myArray.length; i++)
    {
        sum=sum+myArray[i];
    }
    System.out.println(sum);
    System.out.println(sum/2);
</code>```

Can anyone please tell me what I should do next to find the middle indexing in an array if sum of both ends are equal ?

答:
```<code>for (int i = 0; i < array.length; i++) {
    int first = 0;
    int k;
    for ( k = 0; k <= i; k++)
        first += array[k];

    int sum = 0;
    for (int j = i + 1; j < array.length; j++)
        sum += array[j];
    if (first == sum)
        System.out.println("your index is at ," + k );
}
</code>```

Body:
I have done half of the coding and I am not sure what should be the next step:-

public class Middlexindex {
public static void main(String[] args)
{
     int sum=0;
    int[] myArray={1,2,3,3,2,1};
    for(int i=0; i<myArray.length; i++)
    {
        sum=sum+myArray[i];
    }
    System.out.println(sum);
    System.out.println(sum/2);

Can anyone please tell me what I should do next to find the middle indexing in an array if sum of both ends are equal ?


问:
jQuery toggle with active class
I have a menu with "yes / no" options just like this.

The red color box containing word "yes" is my active button. I just want to show another options when users click yes. So I used jQuery toggle function.

When page load, it showing menu with options just like this.

But I don't want to show it until users click yes. I figured out the problem. It happened because yes button has an active class activated. That's why it showing its options. And also I need to hide that toggle menu options when click no.

I tried with jquery hide functions adding another class to no. It seems ok but expert advice needed.

```<code>$(".remove-toggle").click(function(){
 $(".wrap").hide();
});
</code>```

Working jsfiddle here.

答:
Just add this css.

```<code>.wrap {
   display: none;
 }
</code>```

Then, the .wrap class will not be visible at the beginning itself.

Here is the fiddle - https://jsfiddle.net/jkLank8b/12/

Title: jQuery toggle with active class

Body:
I have a menu with "yes / no" options just like this.

The red color box containing word "yes" is my active button. I just want to show another options when users click yes. So I used jQuery toggle function.

When page load, it showing menu with options just like this.

But I don't want to show it until users click yes. I figured out the problem. It happened because yes button has an active class activated. That's why it showing its options. And also I need to hide that toggle menu options when click no.

I tried with jquery hide functions adding another class to no. It seems ok but expert advice needed.

$(".remove-toggle").click(function(){
 $(".wrap").hide();
});

Working jsfiddle here.

Body:
Just add this css.

.wrap {
   display: none;
 }

Then, the .wrap class will not be visible at the beginning itself.

Here is the fiddle - https://jsfiddle.net/jkLank8b/12/


问:
Compare products in magento without logging in
I am not able to compare products in magento until i login into my account. I tried searching for solution of this, but couldn't find anything.

Thanks in advance.

答:
```<code>Run below commands in phpmyadmin.

TRUNCATE dataflow_batch_export;
TRUNCATE dataflow_batch_import;
TRUNCATE log_customer;
TRUNCATE log_quote;
TRUNCATE log_summary;
TRUNCATE log_summary_type;
TRUNCATE log_url;
TRUNCATE log_url_info;
TRUNCATE log_visitor;
TRUNCATE log_visitor_info;
TRUNCATE log_visitor_online;
TRUNCATE report_viewed_product_index;
TRUNCATE report_compared_product_index;
TRUNCATE report_event;
TRUNCATE index_event;
TRUNCATE catalog_compare_item;
</code>```

After this clear cache and hard refresh your browser.Hope this will help you.

Body:
Run below commands in phpmyadmin.

TRUNCATE dataflow_batch_export;
TRUNCATE dataflow_batch_import;
TRUNCATE log_customer;
TRUNCATE log_quote;
TRUNCATE log_summary;
TRUNCATE log_summary_type;
TRUNCATE log_url;
TRUNCATE log_url_info;
TRUNCATE log_visitor;
TRUNCATE log_visitor_info;
TRUNCATE log_visitor_online;
TRUNCATE report_viewed_product_index;
TRUNCATE report_compared_product_index;
TRUNCATE report_event;
TRUNCATE index_event;
TRUNCATE catalog_compare_item;

After this clear cache and hard refresh your browser.Hope this will help you.


问:
How to add an item to list in cycle in Elixir/Phoenix
I'm studying Elixir/Phoenix and there is a task in front of me. I need to filter results from database in a cycle. Something like this:

```<code>user = Repo.get_by(User, api_token: token)
rooms = Repo.all(Room)
result = []
if !Enum.empty?(rooms) do
  Enum.each rooms, fn room ->
    users = Poison.decode!(room.users)
    if Enum.member?(users, user.id) do
       result = result ++ [room]
    end
  end
end
json(conn, %{"rooms" => result})
</code>```

But this case don't allow me to append items to list, why? Because this is a functional language...
Is there a way to append items to list in a cycle?

Oh yeah, maybe you ask me "Why you just don't get objects from the database by user id?" I'll say that the room.users store json array encoded in string

答:
Whenever you want to select some items from a list, you can use Enum.filter/2. You can also use the in operator instead of Enum.member?/2.

```<code>user = Repo.get_by(User, api_token: token)
rooms = Repo.all(Room)
result = Enum.filter(rooms, fn room ->
  user.id in Poison.decode!(room.users)
end)
</code>```

You can also use for instead of Enum.filter/2:

```<code>result = for room <- rooms, user.id in Poison.decode!(room.users), do: room
</code>```

Body:
I'm studying Elixir/Phoenix and there is a task in front of me. I need to filter results from database in a cycle. Something like this:

user = Repo.get_by(User, api_token: token)
rooms = Repo.all(Room)
result = []
if !Enum.empty?(rooms) do
  Enum.each rooms, fn room ->
    users = Poison.decode!(room.users)
    if Enum.member?(users, user.id) do
       result = result ++ [room]
    end
  end
end
json(conn, %{"rooms" => result})

But this case don't allow me to append items to list, why? Because this is a functional language...
Is there a way to append items to list in a cycle?

Oh yeah, maybe you ask me "Why you just don't get objects from the database by user id?" I'll say that the room.users store json array encoded in string

Body:
Whenever you want to select some items from a list, you can use Enum.filter/2. You can also use the in operator instead of Enum.member?/2.

user = Repo.get_by(User, api_token: token)
rooms = Repo.all(Room)
result = Enum.filter(rooms, fn room ->
  user.id in Poison.decode!(room.users)
end)

You can also use for instead of Enum.filter/2:

result = for room <- rooms, user.id in Poison.decode!(room.users), do: room


问:
access s3 bucket from lambdaw when s3 has vpc restriction
I have a s3 bucket with vpc access restriction conditions

```<code>"Statement": [
     {
         "Sid": "Access-to-specific-VPC-only-xxxx",
         "Effect": "Deny",
         "Principal": "*",
         "Action": "s3:*",
         "Resource": [
             "arn:aws:s3:::xxxx",
             "arn:aws:s3:::xxxx/*"
         ],
         "Condition": {
             "NotIpAddress": {
                 "aws:SourceIp": "xxxx"
             },
             "StringNotEquals": {
                 "aws:sourceVpc": "vpc-xxxx"
             }
         }
     }
]
</code>```

Now I create a lambda function with a full s3 access role, and I find that the function (with simple boto3 get_object or download_file things like that) is access denied by s3. What should I add to the s3 policy to allow the function access?

The error message is

```<code>An error occurred (AccessDenied) when calling the ListObjects operation:
Access Denied: ClientError
 Traceback (most recent call last)
  File "/var/task/SampleFunctionTest.py", line 17, in handler\n
  for obj in my_bucket.objects.all():
 ...
  botocore.exceptions.ClientError: An error occurred (AccessDenied)
when calling the ListObjects operation: Access Denied
</code>```

答:
Is it in an option for you to put the Lambda function inside the same VPC? If so I'd go with that. Also you'd need to remove the NotIpAddress condition or add the CIDR block of the subnet your Lambda function is in.</p>

```<code>"NotIpAddress": {
    "aws:SourceIp": ["xxxx", "x-lambda-subnet-ip-range"]
}
</code>```

Body:
I have a s3 bucket with vpc access restriction conditions

"Statement": [
     {
         "Sid": "Access-to-specific-VPC-only-xxxx",
         "Effect": "Deny",
         "Principal": "*",
         "Action": "s3:*",
         "Resource": [
             "arn:aws:s3:::xxxx",
             "arn:aws:s3:::xxxx/*"
         ],
         "Condition": {
             "NotIpAddress": {
                 "aws:SourceIp": "xxxx"
             },
             "StringNotEquals": {
                 "aws:sourceVpc": "vpc-xxxx"
             }
         }
     }
]

Now I create a lambda function with a full s3 access role, and I find that the function (with simple boto3 get_object or download_file things like that) is access denied by s3. What should I add to the s3 policy to allow the function access?

The error message is

An error occurred (AccessDenied) when calling the ListObjects operation:
Access Denied: ClientError
 Traceback (most recent call last)
  File "/var/task/SampleFunctionTest.py", line 17, in handler\n
  for obj in my_bucket.objects.all():
 ...
  botocore.exceptions.ClientError: An error occurred (AccessDenied)
when calling the ListObjects operation: Access Denied

Body:
Is it in an option for you to put the Lambda function inside the same VPC? If so I'd go with that. Also you'd need to remove the NotIpAddress condition or add the CIDR block of the subnet your Lambda function is in.

"NotIpAddress": {
    "aws:SourceIp": ["xxxx", "x-lambda-subnet-ip-range"]
}


问:
How do I add a role via a C# bot in Discord?
The Discord API says nothing about adding roles. Is that possible?</p>

答:
Yes you can do that, look into the method under SocketGuildUser here.

You will see a method named AddRoleAsync() OR AddRolesAsync(). That is the one that you would be looking for.

The method takes in a IRole datatype, and that would be the role you want to assign the user to. Also, your SocketGuildUser should be the user you want to target.

[Also, this documentation and answer is based on Discord.NET Version 1 and above]


问:
odoo - 9 how to install custom module in odoo 9
I have installed odoo - 9 in my local , I cannot able to see my custom module in update module list. I have activated "Developer Mode" even though it is not appearing in my module list. I also updated the module list, Can anybody guide me to install "Custom Module"  .</p>

答:
To install a new module in Odoo you have to :

Take a acces right to your new module : chmod -R 755 custom_module

In admin user activate external carctirstique

restart the service service odoo restart

Update module list


问:
Get total cart woocommerce
I need to have the import of cart in woocommerce.
But i need the number without wc_price().
This is my code:

```<code>global $woocommerce;
$app=$woocommerce->cart->get_cart_total();
$app2=$woocommerce->cart->total;
</code>```

and it results:

```<code>app = $20.00
app2 = 0
</code>```

and the cart is of $20.00
Thanks.

答:
You can try</p>

```<code>global $woocommerce;
$Cart = WC()->cart->subtotal;
echo "CART : " . $Cart;
</code>```

Title: Get total cart woocommerce

Body:
I need to have the import of cart in woocommerce.
But i need the number without wc_price().
This is my code:

global $woocommerce;
$app=$woocommerce->cart->get_cart_total();
$app2=$woocommerce->cart->total;

and it results:

app = $20.00
app2 = 0

and the cart is of $20.00
Thanks.

Body:
You can try

global $woocommerce;
$Cart = WC()->cart->subtotal;
echo "CART : " . $Cart;


问:
Group and count in Rails
I know I've seen this before but I can't find anything now. I want to group a query by a certain column and be able to display how many are in each group. I got the first part down:

```<code>@line_items = @project.line_items.all(:group => "device_id")
</code>```

This is for my line item index view, which is just a table displaying the line items. How do I make a column in that table for "count" now that the line items are grouped by device?

答:
For only count pluck would be faster here rather than group

```<code>@project.line_items.pluck(:device_id).count

@project.line_items.pluck(:device_id).uniq.count
</code>```

Title: Group and count in Rails

Body:
I know I've seen this before but I can't find anything now. I want to group a query by a certain column and be able to display how many are in each group. I got the first part down:

@line_items = @project.line_items.all(:group => "device_id")

This is for my line item index view, which is just a table displaying the line items. How do I make a column in that table for "count" now that the line items are grouped by device?

Body:
For only count pluck would be faster here rather than group

@project.line_items.pluck(:device_id).count

@project.line_items.pluck(:device_id).uniq.count