问:
Just insert a new key - value on a mysql json field on Laravel
I work with Laravel and I try to add an entry to a MySQL field in JSON format ...

This field contains (for example), this:

```<code>        {
            "df2jay22p1f1nb31b161jf2jay22p5":
            {
                "type": "texte-image",
                "contenu": "Texte de test",
                "position": "2"
            },
            "df2jay1w251p1nb31a2f24f2jay1w256":
            {
                "type": "contenu-seul",
                "contenu": "Contenu de test",
                "position": "1"
            }
        }
</code>```

My goal is to arrive at this:

```<code>            {
            "df2jay22p1f1nb31b161jf2jay22p5":
            {
                "type": "texte-image",
                "contenu": "Texte de test",
                "position": "2",
                "image": "/url/to/img.jpg"
            },
            "df2jay1w251p1nb31a2f24f2jay1w256":
            {
                "type": "contenu-seul",
                "contenu": "Contenu de test",
                "position": "1"
            }
        }
</code>```

My controller works like this:

```<code>$page = new Page();
        $page->contenu = $request->input('composants'); // Json field
        $page->save();

        foreach($page->contenu as $i => $element){
            if ( $request->hasFile("composants." . $i . ".image") ){
                $image =  $request->file("composants." . $i . ".image");
                // ... image processing, save on directory, etc...
            }
        }
</code>```

I would therefore like to take up the content of

```<code>$page->contenu
</code>```

and add the value of "image" to it but I can't realize it ...

Thank you in advance :)

答:
Here is an example that you can adapt to your code:</p>

```<code>$json = '{
            "df2jay22p1f1nb31b161jf2jay22p5":
            {
                "type": "texte-image",
                "contenu": "Texte de test",
                "position": "2"
            },
            "df2jay1w251p1nb31a2f24f2jay1w256":
            {
                "type": "contenu-seul",
                "contenu": "Contenu de test",
                "position": "1"
            }
}';

$arr = json_decode($json, true);
$arr['df2jay22p1f1nb31b161jf2jay22p5']['image'] = "/url/to/img.jpg";
$json = json_encode($arr);
echo '```';
print_r(json_decode($json, true));
echo '```';
</code>```

Body:
I work with Laravel and I try to add an entry to a MySQL field in JSON format ...

This field contains (for example), this:

        {
            "df2jay22p1f1nb31b161jf2jay22p5":
            {
                "type": "texte-image",
                "contenu": "Texte de test",
                "position": "2"
            },
            "df2jay1w251p1nb31a2f24f2jay1w256":
            {
                "type": "contenu-seul",
                "contenu": "Contenu de test",
                "position": "1"
            }
        }

My goal is to arrive at this:

            {
            "df2jay22p1f1nb31b161jf2jay22p5":
            {
                "type": "texte-image",
                "contenu": "Texte de test",
                "position": "2",
                "image": "/url/to/img.jpg"
            },
            "df2jay1w251p1nb31a2f24f2jay1w256":
            {
                "type": "contenu-seul",
                "contenu": "Contenu de test",
                "position": "1"
            }
        }

My controller works like this:

$page = new Page();
        $page->contenu = $request->input('composants'); // Json field
        $page->save();

        foreach($page->contenu as $i => $element){
            if ( $request->hasFile("composants." . $i . ".image") ){
                $image =  $request->file("composants." . $i . ".image");
                // ... image processing, save on directory, etc...
            }
        }

I would therefore like to take up the content of

$page->contenu

and add the value of "image" to it but I can't realize it ...

Thank you in advance :)

Body:
Here is an example that you can adapt to your code:

$json = '{
            "df2jay22p1f1nb31b161jf2jay22p5":
            {
                "type": "texte-image",
                "contenu": "Texte de test",
                "position": "2"
            },
            "df2jay1w251p1nb31a2f24f2jay1w256":
            {
                "type": "contenu-seul",
                "contenu": "Contenu de test",
                "position": "1"
            }
}';

$arr = json_decode($json, true);
$arr['df2jay22p1f1nb31b161jf2jay22p5']['image'] = "/url/to/img.jpg";
$json = json_encode($arr);
echo '<pre>';
print_r(json_decode($json, true));
echo '</pre>';


来源: stackexchange

问:
Dynamic content inside fancybox via get
I have multiple instances of fancybox working at the same time like this:

```<code><a class="grupito" href="?id=1#various1">Group 1</a>
<a class="grupito" href="?id=2#various1">Group 2</a>
<a class="grupito" href="?id=3#various1">Group 3</a>
</code>```

Showing the following div:

```<code><div style="display: none;">
   <div id="various1">
       //Select that shows the people from the group here depending on the id
       //of the link with a $_GET['id'] variable (from database)
   </div>
</div>
</code>```

With this call:

```<code>$("a.grupito").fancybox({
            'titlePosition'     : 'inside',
            'transitionIn'      : 'none',
            'transitionOut'     : 'none'
        });
});
</code>```

This doesn't work for me. Fancybox says "The requested content cannot be loaded.
Please try again later.". If I get rid of the ?id=1 part of the href it will show up but it won't have the content that I need. Is this that I'm trying even possible with fancybox?

EDIT: In fact, checking it with firebug I see I'm getting a 404 error. Anyone can point me out in the right direction to see how I can achieve this?

答:
If I understand your questions properly I think you may need to rethink your approach. I'm not sure what you are trying to achieve by adding ?id=1 to your anchor. Fancybox shows content that is already loaded on the page. Once the HTML page has been rendered and sent to the browser, PHP plays no role in what happens on the client side.

You need to render all the content for each of the boxes when the page loads and then reference them within your internal links as posted below. Fancybox only deals with content that has been loaded on to the page, so you need to figure out the content of each box during it's initial rendering.

```<code><a class="grupito" href="#various1">Group 1</a>
<a class="grupito" href="#various2">Group 2</a>
<a class="grupito" href="#various3">Group 3</a>

<div style="display: none;">
   <div id="various1">
       //The content from group 1
   </div>
   <div id="various2">
       //The content from group 2
   </div>
   <div id="various3">
       //The content from group 3
   </div>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Dynamic content inside fancybox via get

Body:
I have multiple instances of fancybox working at the same time like this:

Group 1
Group 2
Group 3

Showing the following div:

       //Select that shows the people from the group here depending on the id
       //of the link with a $_GET['id'] variable (from database)

With this call:

$("a.grupito").fancybox({
            'titlePosition'     : 'inside',
            'transitionIn'      : 'none',
            'transitionOut'     : 'none'
        });
});

This doesn't work for me. Fancybox says "The requested content cannot be loaded.
Please try again later.". If I get rid of the ?id=1 part of the href it will show up but it won't have the content that I need. Is this that I'm trying even possible with fancybox?

EDIT: In fact, checking it with firebug I see I'm getting a 404 error. Anyone can point me out in the right direction to see how I can achieve this?

Body:
If I understand your questions properly I think you may need to rethink your approach. I'm not sure what you are trying to achieve by adding ?id=1 to your anchor. Fancybox shows content that is already loaded on the page. Once the HTML page has been rendered and sent to the browser, PHP plays no role in what happens on the client side.

You need to render all the content for each of the boxes when the page loads and then reference them within your internal links as posted below. Fancybox only deals with content that has been loaded on to the page, so you need to figure out the content of each box during it's initial rendering.

<a class="grupito" href="#various1">Group 1</a>
<a class="grupito" href="#various2">Group 2</a>
<a class="grupito" href="#various3">Group 3</a>

<div style="display: none;">
   <div id="various1">
       //The content from group 1
   </div>
   <div id="various2">
       //The content from group 2
   </div>
   <div id="various3">
       //The content from group 3
   </div>
</div>


问:
Allocation of ... exeeds 10% of system memory
I am currently having an issue with my Tensorflow model.

When starting my trained model I get the following warnings:

Tensorflow will start, but it takes 4 minutes to start and after starting it starts showing "not responding" and crashes. My guess is that this is related to the issue mentioned above.

Does anyone have a solution?

system specs:
Windows 10 64 bit,
16GB Ram,
6 cores,
Virtual machine (Hyper V)

training specs:
Ubuntu 18.04 LTS,
32GB Ram,
6 cores,
virtual machine (Hyper V)

答:
Did you do the math? The sizes in your screenshot alone combined are already over 20 GB. If that's on your system with 16GB RAM you are seariously swapping memory to disk, which will make everything slow/unresponsive/crash as you mention.

Solutions: add more RAM, or use less RAM...

ContentLicense: CC BY-SA 4.0


问:
Remove Bottom 3 scores in file
```<code>numberofbands = int(input("How many bands are there in the competition? "))

print("Input each band’s name pressing enter after each one")

file = open("scores.txt","w")
for loop in range(numberofbands):
  name = input("\nEnter the name of the band: ")
  votes = input("Enter how many votes that band received: ")
  file.write(name + "," + votes + "," + "\n")
file.close()

number_of_lines = len(open("scores.txt").readlines(  ))

def removebottom3():
#code to remove bottom 3 here

removebottom3()
</code>```

The first part writes the band's name and score to the file.

I want the code to remove the lowest 3 scoring bands from the file. There will be a function for that.
How can I do this?
Thanks in advance.

答:
since you are already reading all the lines from the file,

```<code>number_of_lines = len(open("scores.txt").readlines(  ))
</code>```

you can use sorted to sort your lines by score,

```<code>lines = open("scores.txt").readlines()
sorted(lines,
       key=lambda x : float(x.split(",")[1]),
       reverse = True)
</code>```

Title: Remove Bottom 3 scores in file

Body:
numberofbands = int(input("How many bands are there in the competition? "))

print("Input each band’s name pressing enter after each one")

file = open("scores.txt","w")
for loop in range(numberofbands):
  name = input("\nEnter the name of the band: ")
  votes = input("Enter how many votes that band received: ")
  file.write(name + "," + votes + "," + "\n")
file.close()

number_of_lines = len(open("scores.txt").readlines(  ))

def removebottom3():
#code to remove bottom 3 here

removebottom3()

The first part writes the band's name and score to the file.

I want the code to remove the lowest 3 scoring bands from the file. There will be a function for that.
How can I do this?
Thanks in advance.

Body:
since you are already reading all the lines from the file,

number_of_lines = len(open("scores.txt").readlines(  ))

you can use sorted to sort your lines by score,

lines = open("scores.txt").readlines()
sorted(lines,
       key=lambda x : float(x.split(",")[1]),
       reverse = True)


问:
Update single state object from more than one React Date Picker input
Trying to update state object data from two React Date Pickers embedded in bigger contolled form but can't do this. Any ideas what am I missing? Thank you in advance.

Live preview here: https://codesandbox.io/s/autumn-https-nyr28?file=/src/App.js

export default function App() {
  const [data, setData] = useState({
    async: true,
    from: "",
    to: ""
  });

  const handleChange = event => {
    let target = event.target;
    let value = target.type === "checkbox" ? target.checked : target.value;
    let name = target.name;
    setData(previousSearchData => ({
      ...previousSearchData,
      [name]: value
    }));
  };

  const handleSubmit = event => {
    event.preventDefault();
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit}>
      Checkbox:{" "}
      <input
        name="async"
        type="checkbox"
        checked={data.checkbox}
        onChange={handleChange}
      />

      From:{" "}
      <ReactDatePicker
        name="from"
        selected={data.from}
        onChange={handleChange}
        timeInputLabel="Start time:"
        dateFormat="yyyy/MM/dd h:mm aa"
        showTimeInput
      />
      To:{" "}
      <ReactDatePicker
        name="to"
        selected={data.to}
        onChange={handleChange}
        timeInputLabel="End time:"
        dateFormat="yyyy/MM/dd h:mm aa"
        showTimeInput
      />
      <input type="submit" value="submit" />
    </form>
  );
}```

答:
This plugin does not send a js event object after it gets its input changed, it sends a js Date object, as you can see in the oficial page:

```<code><DatePicker selected={startDate} onChange={date => setStartDate(date)} />
</code>```

You will need to create a handler function specifically for inputs of this kind.

Something like:

```<code><DatePicker selected={startDate} onChange={date => handleDatePickerChange('startDate', date)} />
</code>```

...

```<code>const handleDatePickerChange = (name, date) => {
    setData(previousSearchData => ({
      ...previousSearchData,
      [name]: date
    }));
};
</code>```

Body:
This plugin does not send a js event object after it gets its input changed, it sends a js Date object, as you can see in the oficial page:

<DatePicker selected={startDate} onChange={date => setStartDate(date)} />

You will need to create a handler function specifically for inputs of this kind.

Something like:

<DatePicker selected={startDate} onChange={date => handleDatePickerChange('startDate', date)} />

...

const handleDatePickerChange = (name, date) => {
    setData(previousSearchData => ({
      ...previousSearchData,
      [name]: date
    }));
};


问:
onError img function is not working/triggered in React component
I've written React components to replace the html twig components which are currently being used in a Symfony project that I'm working on. However, not every instance of an Article brings back an image url and this stops the page from loading for these particular articles.

Here's what I've got for the article component:

function ArticleImage({ articleImageUrl, articleImageAlt, articleImageCaption }) {

  const addDefaultSrc = (e) => {
    e.target.src="https://upload.wikimedia.org/wikipedia/commons/8/8b/Flag_of_.svg";
    e.target.onerror = null;
  };

  return (

      {articleImageCaption}

  );
}

export default ArticleImage;```

答:
Don't update DOM directly. Just change state.

Example

const { useState, useEffect } = React;

const App = () => {
  const [{url, alt}, setImage] = useState({
    url: 'https://i.picsum.photos/id/-1/100/100.jpg',
    alt: 'test'
  })

  const onError = () => {
    setImage(image => ({
      ...image,
      url: 'https://i.picsum.photos/id/194/100/100.jpg'
    }))
  }

  return

}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div></code>```

Body:
Don't update DOM directly. Just change state.

Example

const { useState, useEffect } = React;

const App = () => {
  const [{url, alt}, setImage] = useState({
    url: 'https://i.picsum.photos/id/-1/100/100.jpg',
    alt: 'test'
  })

  const onError = () => {
    setImage(image => ({
      ...image,
      url: 'https://i.picsum.photos/id/194/100/100.jpg'
    }))
  }

  return <div>
    <img src={url} onError={onError} alt={alt}/>
  </div>
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );

<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>


问:
Contenteditable paragraphs in html
I am creating a contenteditable paragraph in html. I have a button which on clicking will make the text bold. The first time it is clicked the text should change to bold,and the next time it is clicked ,the text should be normal(not bolder).This is similar to the Stack overflow question editor.html code:

```<code>    <button type="button" id="bold" onclick="bold()">B</button>
    <div id="content">
       <p id="hey" contenteditable="true">Hi how are you</p>
    </div>
</code>```

JS:

```<code>        let boldClick=0;
        let p=document.getElementById('hey');
        function bold(){
           if(boldClick%2==0){

             p.innerHTML=p.innerHTML+' <span contenteditable="true">'+' boldtext'+'</span>';
           }
           else{
              let pNew=document.createElement('p');
              pNew.setAttribute("contenteditable","true");
              document.getElementById('content').appendChild(pNew);
           }
           boldClick++;
        }
</code>```

CSS:

```<code>        #bold{
            font-weight: bold;
        }
        span{
            font-weight: bold;
            background-color: grey;
        }
        p{
            display: inline;
        }
</code>```

I can make the text bolder by clicking the button.Bolder texts must be inside the span element and non-bolder texts must be outside span but inside
  p element.How do I solve it?

答:
the shortest way. Create a class named Bold. Add the properties you want to this class. Select elements with Javascript and assign a function to have this class.
In general , creating a class with css and using javascript is the simplest way to solve problems, which element of this class should be added when.

let clicked = false;

function bold() {
  let paragraph = document.getElementById("paragraph");
  let span = document.getElementById("span");

  if (clicked) {
    span.contentEditable = false;
    span.classList.remove("bold");
    clicked = false;
  } else {
    span.contentEditable = true;
    span.classList.add("bold");
    clicked = true;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  display: inline;
}

.bold {
  font-weight: bold;
}</code>```

<button type="button" id="bold-button" onclick="bold()">B</button>

Hi how are you
    how are you

```

Title: Contenteditable paragraphs in html

Body:
I am creating a contenteditable paragraph in html. I have a button which on clicking will make the text bold. The first time it is clicked the text should change to bold,and the next time it is clicked ,the text should be normal(not bolder).This is similar to the Stack overflow question editor.html code:

    <button type="button" id="bold" onclick="bold()">B</button>

Hi how are you

JS:

        let boldClick=0;
        let p=document.getElementById('hey');
        function bold(){
           if(boldClick%2==0){

             p.innerHTML=p.innerHTML+' '+' boldtext'+'';
           }
           else{
              let pNew=document.createElement('p');
              pNew.setAttribute("contenteditable","true");
              document.getElementById('content').appendChild(pNew);
           }
           boldClick++;
        }

CSS:

        #bold{
            font-weight: bold;
        }
        span{
            font-weight: bold;
            background-color: grey;
        }
        p{
            display: inline;
        }

I can make the text bolder by clicking the button.Bolder texts must be inside the span element and non-bolder texts must be outside span but inside
  p element.How do I solve it?

Body:
the shortest way. Create a class named Bold. Add the properties you want to this class. Select elements with Javascript and assign a function to have this class.
In general , creating a class with css and using javascript is the simplest way to solve problems, which element of this class should be added when.

let clicked = false;

function bold() {
  let paragraph = document.getElementById("paragraph");
  let span = document.getElementById("span");

  if (clicked) {
    span.contentEditable = false;
    span.classList.remove("bold");
    clicked = false;
  } else {
    span.contentEditable = true;
    span.classList.add("bold");
    clicked = true;
  }
}

p {
  display: inline;
}

.bold {
  font-weight: bold;
}

<button type="button" id="bold-button" onclick="bold()">B</button>
<div id="content">
  <p id="paragraph">Hi how are you
    <span id="span">how are you</span>
  </p>
</div>


问:
Questions about interrupt handler
I'm currently developing a simple ARM firmware.
Among them, I'm making a part related to interrupts.
I connected the IRQ exception vector in the exception vector table with the interrupt handler in the interrupt controller as follows:

```<code>__attribute__ ((interrupt ("IRQ"))) void Irq_Handler(void)
{
   interrupt_handler();
}
</code>```

And it converted to ARM assembly code:

```<code>sub    lr, lr, #4
push   {r0, r1, r2, r3, r4, fp, ip, lr}
add    fp, sp, #28
bl     0 <interrupt_hanlder>
sub    sp, fp, #28
ldm    sp!, {r0, r1, r2, r3, r4, fp, ip, pc}^
</code>```

I have several questions for this assembly code:

Why it pushes registers "r0, r1, r2, r3, r4, fp, ip, lr" to the stack?

It pushes 8 registers to the stack. But why it subtracts not 32(4*8) but 28(4*7)?

I don't know the meaning of '^' at the end of 6th line.

Thanks!

答:
Why it pushes registers "r0, r1, r2, r3, r4, fp, ip, lr" to the stack?

This is done because these registers may be modified by the function interrupt_handler(). An interrupt interrupts a running program anywhere. For example here:

```<code>ldm r0, {r2, r3}
                 <=== The interrupt interrupts the program here
add r1, r2, r3
</code>```

If the interrupt modified some registers (in the example: r2 or r3), the program which has been interrupted would not be running correctly anymore.

For this reason the interrupt must restore all registers to their original values.

The function interrupt_handler() will not modify registers r5, r6, ..., so the interrupt handler does not need to restore these registers.

It pushes 8 registers to the stack. But why it subtracts not 32(4*8) but 28(4*7)?

For some reason the fp register shall contain the value sp+28. Maybe it shall point to the stored value of the lr register.

The instruction sub sp, fp, #28 will restore the value of sp assuming that the value of fp did not change since the instruction add fp, sp, #28.

In your case, sp did not change, so the instruction is redundant.

I don't know the meaning of ^ at the end of 6th line.

The ^ is used for the ldm and stm instructions and has two different effects.

One of the two effects is that loading the pc register will also load the psr register.

To return from an interrupt, you must restore the psr register.

Note that in early ARM CPUs, the register r15 contained both the pc register (which was only 24 bits wide) and the psr register (which was 8 bits wide). A ldm without ^ would keep the 8 psr bits of the register r15 unchanged while using ^ would load all 32 bits from memory.

In current ARM CPUs this is no longer the case. However, using the ^ still restores the value of the psr register when loading the pc using ldm.

Title: Questions about interrupt handler

Body:
I'm currently developing a simple ARM firmware.
Among them, I'm making a part related to interrupts.
I connected the IRQ exception vector in the exception vector table with the interrupt handler in the interrupt controller as follows:

__attribute__ ((interrupt ("IRQ"))) void Irq_Handler(void)
{
   interrupt_handler();
}

And it converted to ARM assembly code:

sub    lr, lr, #4
push   {r0, r1, r2, r3, r4, fp, ip, lr}
add    fp, sp, #28
bl     0 <interrupt_hanlder>
sub    sp, fp, #28
ldm    sp!, {r0, r1, r2, r3, r4, fp, ip, pc}^

I have several questions for this assembly code:

Why it pushes registers "r0, r1, r2, r3, r4, fp, ip, lr" to the stack?

It pushes 8 registers to the stack. But why it subtracts not 32(4*8) but 28(4*7)?

I don't know the meaning of '^' at the end of 6th line.

Thanks!

Body:
Why it pushes registers "r0, r1, r2, r3, r4, fp, ip, lr" to the stack?

This is done because these registers may be modified by the function interrupt_handler(). An interrupt interrupts a running program anywhere. For example here:

ldm r0, {r2, r3}
                 <=== The interrupt interrupts the program here
add r1, r2, r3

If the interrupt modified some registers (in the example: r2 or r3), the program which has been interrupted would not be running correctly anymore.

For this reason the interrupt must restore all registers to their original values.

The function interrupt_handler() will not modify registers r5, r6, ..., so the interrupt handler does not need to restore these registers.

It pushes 8 registers to the stack. But why it subtracts not 32(4*8) but 28(4*7)?

For some reason the fp register shall contain the value sp+28. Maybe it shall point to the stored value of the lr register.

The instruction sub sp, fp, #28 will restore the value of sp assuming that the value of fp did not change since the instruction add fp, sp, #28.

In your case, sp did not change, so the instruction is redundant.

I don't know the meaning of ^ at the end of 6th line.

The ^ is used for the ldm and stm instructions and has two different effects.

One of the two effects is that loading the pc register will also load the psr register.

To return from an interrupt, you must restore the psr register.

Note that in early ARM CPUs, the register r15 contained both the pc register (which was only 24 bits wide) and the psr register (which was 8 bits wide). A ldm without ^ would keep the 8 psr bits of the register r15 unchanged while using ^ would load all 32 bits from memory.

In current ARM CPUs this is no longer the case. However, using the ^ still restores the value of the psr register when loading the pc using ldm.


问:
Removing unnecessary nodes in graph
I have a graph that has two distinct classes of nodes, class A nodes and class B nodes.

Class A nodes are not connected to any other A nodes and class B nodes aren’t connected to any other B nodes, but B nodes are connected to A nodes and vice versa. Some B nodes are connected to lots of A nodes and most A nodes are connected to lots of B nodes.

I want to eliminate as many of the A nodes as possible from the graph.

I must keep all of the B nodes, and they must still be connected to at least one A node (preferably only one A node).

I can eliminate an A node when it has no B nodes connected only to it. Are there any algorithms that could find an optimal, or at least close to optimal, solution for which A nodes I can remove?

答:
Despite this is an old question, I see it has not been correctly answered yet.

An analogous question to this one has also been answered earlier in this post.

The problem you are presenting here is indeed the Minimum Set Cover Problem, which is one of the well-known NP-hard problems. From the Wikipedia, the Minimum Set Cover Problem can be formulated as:

Given a set of elements {1,2,...,n} (called the universe) and a collection S of m sets whose union equals the universe, the set cover problem is to identify the smallest sub-collection of S whose union equals the universe. For example, consider the universe U={1,2,3,4,5} and the collection of sets S={{1,2,3},{2,4},{3,4},{4,5}}. Clearly the union of S is U. However, we can cover all of the elements with the following, smaller number of sets: {{1,2,3},{4,5}}.

In your formulation, B nodes represent the elements in the universe, A nodes represent the sets and edges between A nodes and B nodes determine which elements (B nodes) belong to each set (A node). Then, the minimum set cover is equivalent to the minimum number of A nodes so that they are connected to all B nodes. Consequently, the maximum number of A nodes which can be removed from the graph while being connected to every B node are those which do not belong to the minimum set cover.

Since it is NP-hard, there is no polinomial time algorithm for computing the optimum, but a simple greedy algorithm can efficiently provide approximate solutions with tight bounds to the optimum. From the Wikipedia:

There is a greedy algorithm for polynomial time approximation of set covering that chooses sets according to one rule: at each stage, choose the set that contains the largest number of uncovered elements.

Title: Removing unnecessary nodes in graph


问:
make main thread wait for other threads to finish
I have the following Switch class that basically toggles isOn

what i want to in main is make thread1 and thread2, start them,
then sleep for 5 seconds, and after that interrupt them, i think i did this the correct

aside from main thread should wait for both threads to finish, that's where i added

```<code>thread1.join()
thread2.join()
</code>```

but that leads to the threads running forever and no exception thrown, how should i do that? or is main already waiting for them to finish?

```<code>public class Switch implements Runnable {
    private static boolean isOn;
    private String name;
    private static final Object lockedObject = new Object();

    public Switch(String name) {
        this.name = name;
    }

    public void toggle() {
        System.out.println(name + ": " + isOn);
        synchronized (lockedObject) {
            isOn = !isOn;
        }
    }

    @Override
    public void run() {
        while (true) {
            if (Thread.currentThread().isInterrupted()) {
                break;
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
            synchronized (lockedObject) {
                toggle();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Switch switch1 = new Switch("switch1");
        Switch switch2 = new Switch("switch2");
        Thread thread1 = new Thread(switch1);
        Thread thread2 = new Thread(switch2);
        thread1.start();
        thread2.start();
//        thread1.join();
//        thread2.join();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread1.interrupt();
        thread2.interrupt();
    }
}
</code>```

答:
You need to put the following line in the catch block:

```<code>Thread.currentThread().interrupt();
</code>```

Also, you do not need the following lines:

```<code>if (Thread.currentThread().isInterrupted()) {
    break;
}
</code>```

Demo:

```<code>public class Switch implements Runnable {
    private static boolean isOn;
    private String name;
    private static final Object lockedObject = new Object();

    public Switch(String name) {
        this.name = name;
    }

    public void toggle() {
        System.out.println(name + ": " + isOn);
        synchronized (lockedObject) {
            isOn = !isOn;
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();// Add this line
                break;
            }
            synchronized (lockedObject) {
                toggle();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Switch switch1 = new Switch("switch1");
        Switch switch2 = new Switch("switch2");
        Thread thread1 = new Thread(switch1);
        Thread thread2 = new Thread(switch2);
        thread1.start();
        thread2.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread1.interrupt();
        thread2.interrupt();
    }
}
</code>```

Body:
I have the following Switch class that basically toggles isOn

what i want to in main is make thread1 and thread2, start them,
then sleep for 5 seconds, and after that interrupt them, i think i did this the correct

aside from main thread should wait for both threads to finish, that's where i added

thread1.join()
thread2.join()

but that leads to the threads running forever and no exception thrown, how should i do that? or is main already waiting for them to finish?

public class Switch implements Runnable {
    private static boolean isOn;
    private String name;
    private static final Object lockedObject = new Object();

    public Switch(String name) {
        this.name = name;
    }

    public void toggle() {
        System.out.println(name + ": " + isOn);
        synchronized (lockedObject) {
            isOn = !isOn;
        }
    }

    @Override
    public void run() {
        while (true) {
            if (Thread.currentThread().isInterrupted()) {
                break;
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
            synchronized (lockedObject) {
                toggle();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Switch switch1 = new Switch("switch1");
        Switch switch2 = new Switch("switch2");
        Thread thread1 = new Thread(switch1);
        Thread thread2 = new Thread(switch2);
        thread1.start();
        thread2.start();
//        thread1.join();
//        thread2.join();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread1.interrupt();
        thread2.interrupt();
    }
}

Body:
You need to put the following line in the catch block:

Thread.currentThread().interrupt();

Also, you do not need the following lines:

if (Thread.currentThread().isInterrupted()) {
    break;
}

Demo:

public class Switch implements Runnable {
    private static boolean isOn;
    private String name;
    private static final Object lockedObject = new Object();

    public Switch(String name) {
        this.name = name;
    }

    public void toggle() {
        System.out.println(name + ": " + isOn);
        synchronized (lockedObject) {
            isOn = !isOn;
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();// Add this line
                break;
            }
            synchronized (lockedObject) {
                toggle();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Switch switch1 = new Switch("switch1");
        Switch switch2 = new Switch("switch2");
        Thread thread1 = new Thread(switch1);
        Thread thread2 = new Thread(switch2);
        thread1.start();
        thread2.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread1.interrupt();
        thread2.interrupt();
    }
}


问:
How to upload folders on GitHub
How can I upload folders to GitHub?  I have all of my code in a folder, containing 98 files, on my desktop.  I know how to upload files, but it there a way to upload the entire folder?

Thanks!

答:
You can also use the command line, Change directory where your folder is located then type the following :</p>
```<code>git init
git add <folder1> <folder2> <etc.>
git commit -m "Your message about the commit"
git remote add origin https://github.com/yourUsername/yourRepository.git
git push -u origin master
git push origin master
</code>```

Title: How to upload folders on GitHub

Body:
You can also use the command line, Change directory where your folder is located then type the following :

git init
git add <folder1> <folder2> <etc.>
git commit -m "Your message about the commit"
git remote add origin https://github.com/yourUsername/yourRepository.git
git push -u origin master
git push origin master


问:
Filtering an array of objects based on another array of objects in javascript
I have an array of messages like

```<code>oldMessages = [ {id:1,message:'message_A'} , {id:2,message:'message_B'} ]
</code>```

and another array as

```<code>newMessages = [ {id:1,message:'message_A'} , {id:2,message:'message_B'} , {id:3,message:'message_C'} ]

</code>```

How do I get only the part {id:3,message:'message_c'} by comparing oldMessages with newMessages?
I must compare them based on their id only.

答:
You can easily do this using array .find() method like:

const oldMessages = [ {id:1,message:'message_A'} , {id:2,message:'message_B'} ]
const newMessages = [ {id:1,message:'message_A'},{id:2,message:'message_B'} , {id:3,message:'message_C'} ]
const data = newMessages.find(r=> !oldMessages.map(x=>x.id).includes(r.id))

console.log( data )```

Body:
I have an array of messages like

oldMessages = [ {id:1,message:'message_A'} , {id:2,message:'message_B'} ]

and another array as

newMessages = [ {id:1,message:'message_A'} , {id:2,message:'message_B'} , {id:3,message:'message_C'} ]

How do I get only the part {id:3,message:'message_c'} by comparing oldMessages with newMessages?
I must compare them based on their id only.


问:
Recurrent problem using scipy.optimize.fmin
I am encountering some problems when translating the following code from MATLAB to Python:

Matlab code snippet:

   x=M_test %M_test is a 1x3 array that holds the adjustment points for the function
   y=R_test %R_test is also a 1x3 array
   >> M_test=[0.513,7.521,13.781]
   >> R_test=[2.39,3.77,6.86]

   expo3= @(b,x) b(1).*(exp(-(b(2)./x).^b(3)));
   NRCF_expo3= @(b) norm(y-expo3(b,x));
   B0_expo3=[fcm28;1;1];
   B_expo3=fminsearch(NRCF_expo3,B0_expo3);
   Data_raw.fcm_expo3=(expo3(B_expo3,Data_raw.M));
```

<p>The translated (python) code:</p>

<pre class="lang-py prettyprint-override"><code>   expo3=lambda x,M_test: x[0]*(1-exp(-1*(x[1]/M_test)**x[2]))
   NRCF_expo3=lambda R_test,x,M_test: np.linalg.norm(R_test-expo3,ax=1)
   B_expo3=scipy.optimize.fmin(func=NRCF_expo3,x0=[fcm28,1,1],args=(x,))
</code>```

For clarity, the object function 'expo3' wants to go through the adjustment points defined by M_test.
'NRCF_expo3' is the function that wants to be minimised, which is basically the error between R_test and the drawn exponential function.

When I run the code, I obtain the following error message:

```<code>B_expo3=scipy.optimize.fmin(func=NRCF_expo3,x0=[fcm28,1,1]),args=(x,))
NameError: name 'x' is not defined
</code>```

There are a lot of similar questions that I have perused.

If I delete the 'args' from the optimization function, as numpy/scipy analog of matlab's fminsearch
 seems to indicate it is not necessary, I obtain the error:

```<code>line 327, in function_wrapper
return function(*(wrapper_args+args))
TypeError: <lambda>() missing 2 required positional arguments: 'x' and 'M_test'
</code>```

There are a lot of other modifications that I have tried, following examples like Using scipy to minimize a function that also takes non variational parameters or those found in Open source examples, but nothing works for me.

I expect this is probably quite obvious, but I am very new to Python and I feel like I am looking for a needle in a haystack. What am I not seeing?

Any help would be really appreciated. I can also provide more code, if that is necessary.

答:
I think you shouldn't use lambdas in your code, make instead a single target function with your three parameters (see PEP8). There is a lot of missing information in you post, but for what I can infer, you want something like this:</p>

```<code>from scipy.optimize import fmin

# Define parameters

M_TEST = np.array([0.513, 7.521, 13.781])
X_ARR = np.array([2.39,3.77,6.86])
X0 = np.array([10, 1, 1])  # whatever your variable fcm28 is

def nrcf_exp3(r_test, m_test, x):
    expo3 = x[0] * (1 - np.exp(-(x[1] / m_test) ** x[2]))
    return np.linalg.norm(r_test - expo3)

fmin(nrcf_exp3, X0, args=(M_TEST, X_ARR))
</code>```

Body:
I am encountering some problems when translating the following code from MATLAB to Python:

Matlab code snippet:

   x=M_test %M_test is a 1x3 array that holds the adjustment points for the function
   y=R_test %R_test is also a 1x3 array
   >> M_test=[0.513,7.521,13.781]
   >> R_test=[2.39,3.77,6.86]

   expo3= @(b,x) b(1).*(exp(-(b(2)./x).^b(3)));
   NRCF_expo3= @(b) norm(y-expo3(b,x));
   B0_expo3=[fcm28;1;1];
   B_expo3=fminsearch(NRCF_expo3,B0_expo3);
   Data_raw.fcm_expo3=(expo3(B_expo3,Data_raw.M));

The translated (python) code:

   expo3=lambda x,M_test: x[0]*(1-exp(-1*(x[1]/M_test)**x[2]))
   NRCF_expo3=lambda R_test,x,M_test: np.linalg.norm(R_test-expo3,ax=1)
   B_expo3=scipy.optimize.fmin(func=NRCF_expo3,x0=[fcm28,1,1],args=(x,))

For clarity, the object function 'expo3' wants to go through the adjustment points defined by M_test.
'NRCF_expo3' is the function that wants to be minimised, which is basically the error between R_test and the drawn exponential function.

When I run the code, I obtain the following error message:

B_expo3=scipy.optimize.fmin(func=NRCF_expo3,x0=[fcm28,1,1]),args=(x,))
NameError: name 'x' is not defined

There are a lot of similar questions that I have perused.

If I delete the 'args' from the optimization function, as numpy/scipy analog of matlab's fminsearch
 seems to indicate it is not necessary, I obtain the error:

line 327, in function_wrapper
return function(*(wrapper_args+args))
TypeError: <lambda>() missing 2 required positional arguments: 'x' and 'M_test'

There are a lot of other modifications that I have tried, following examples like Using scipy to minimize a function that also takes non variational parameters or those found in Open source examples, but nothing works for me.

I expect this is probably quite obvious, but I am very new to Python and I feel like I am looking for a needle in a haystack. What am I not seeing?

Any help would be really appreciated. I can also provide more code, if that is necessary.

Body:
I think you shouldn't use lambdas in your code, make instead a single target function with your three parameters (see PEP8). There is a lot of missing information in you post, but for what I can infer, you want something like this:

from scipy.optimize import fmin

# Define parameters

M_TEST = np.array([0.513, 7.521, 13.781])
X_ARR = np.array([2.39,3.77,6.86])
X0 = np.array([10, 1, 1])  # whatever your variable fcm28 is

def nrcf_exp3(r_test, m_test, x):
    expo3 = x[0] * (1 - np.exp(-(x[1] / m_test) ** x[2]))
    return np.linalg.norm(r_test - expo3)

fmin(nrcf_exp3, X0, args=(M_TEST, X_ARR))


问:
Returning the response back to AJAX and showing the message
I'am trying to get the results from the PHP page to the AJAX so that the AJAX knows if it's successful or not.

I'am very new to AJAX so not sure if am correct or not.

MY AJAX is as follows:

if ($("#register_form").valid()) {
    var data1 = $('#register_form').serialize();
    $.ajax({
        type: "POST",
        url: "register.php",
        data: data1,captcha: grecaptcha.getResponse(),
        success: function(msg) {
            console.log(msg);
            //check if response is true

            if (msg == true) {
                $('.messagebox').hide();
                $('#alert-message').html(msg);
                $('.messagebox').slideDown('slow');
                $("#btn").text('Please Wait...'); // a
                top.location.href = "index.php?msg=login"; //redirection
                    alert('SUCCESS');

            } else {
                $('messagebox').fadeIn(1000, function(){
                    $("#alert-message").html(msg).show();
                    alert('FAILED');
                });
                }
        }
    });
```

<p>Register.php is as follows:     </p>

<pre class="lang-php prettyprint-override"><code>if (isset($_POST['g-recaptcha-response'])) {
    $secret = '';
    //get verify response data
    $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);

    $responseData = json_decode($verifyResponse);

        if($responseData->success == true) {
            //Success: do code to store your data...
            $result = true;
        } else {
          die($msg_recaptcha);
        }
          return $result;
    }
</code>```

If its success then it has to redirect to index.php?msg=login or else it has to show the error message. Can someone pls help me on this.

答:
Do try to send the data in the curly braces because due to , the code might consider the success as a part of data.

```<code> data: {data :data1,captcha: grecaptcha.getResponse()},
</code>```

And on the PHP page you should get the name of the posted data by which you have attached your data as

```<code>if (isset($_POST['captcha'])) {
            $secret = '';
            //get verify response data
            $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);

            $responseData = json_decode($verifyResponse);

                    if($responseData->success == true) {
                        //Success: do code to store your data...
                        $result = true;
                    } else {
                      die($msg_recaptcha);
                    }
                      return $result;
            }
</code>```

Body:
I'am trying to get the results from the PHP page to the AJAX so that the AJAX knows if it's successful or not.

I'am very new to AJAX so not sure if am correct or not.

MY AJAX is as follows:

if ($("#register_form").valid()) {
    var data1 = $('#register_form').serialize();
    $.ajax({
        type: "POST",
        url: "register.php",
        data: data1,captcha: grecaptcha.getResponse(),
        success: function(msg) {
            console.log(msg);
            //check if response is true

            if (msg == true) {
                $('.messagebox').hide();
                $('#alert-message').html(msg);
                $('.messagebox').slideDown('slow');
                $("#btn").text('Please Wait...'); // a
                top.location.href = "index.php?msg=login"; //redirection
                    alert('SUCCESS');

            } else {
                $('messagebox').fadeIn(1000, function(){
                    $("#alert-message").html(msg).show();
                    alert('FAILED');
                });
                }
        }
    });

Register.php is as follows:

if (isset($_POST['g-recaptcha-response'])) {
    $secret = '';
    //get verify response data
    $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);

    $responseData = json_decode($verifyResponse);

        if($responseData->success == true) {
            //Success: do code to store your data...
            $result = true;
        } else {
          die($msg_recaptcha);
        }
          return $result;
    }

If its success then it has to redirect to index.php?msg=login or else it has to show the error message. Can someone pls help me on this.

Body:
Do try to send the data in the curly braces because due to , the code might consider the success as a part of data.

 data: {data :data1,captcha: grecaptcha.getResponse()},

And on the PHP page you should get the name of the posted data by which you have attached your data as

if (isset($_POST['captcha'])) {
            $secret = '';
            //get verify response data
            $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);

            $responseData = json_decode($verifyResponse);

                    if($responseData->success == true) {
                        //Success: do code to store your data...
                        $result = true;
                    } else {
                      die($msg_recaptcha);
                    }
                      return $result;
            }


问:
can't make a programm that counts nonterminal nodes in a tree
This is a syntactic tree and it looks like this in the form of code

My program is supposed to count the number of non-terminal nodes on that tree. The idea is that every tree is a 2 tuple. On the first position stands the mother node as a string and on the second position stands either a string if there is a terminal node or a list with daughter trees of the mother node. They are recursive. The program should count the number of nonterminal nodes.
so the result should just be a number of nonterminal nodes, e.g. 9.

So far as I have understood, I should do this using recursion. But there are some things that I fail to do correctly to make my programm work. My code is:

```<code>tuple_list = []
second_tuple_elements = [a_tuple[1] for a_tuple in tuple_list]
print(second_tuple_elements)
def nonterminal(count):

    if second_tuple_elements == type(""):

        return 1

    if second_tuple_elements == type([]):
        for element in list:
            if element == type (""):
                return 1
            nonterminal = second_tuple_elements + element
</code>```

答:
There's no recursive call in your program -

def node_count(node):
  mother, children = node       # get parts of node tuple
  if isinstance(children, str): # mother of terminal node
    return 1                    # return 1 to count this mother
  else:                         # mother of non-terminal node
    return 1 + \                # return 1 plus...
      sum(node_count(x) for x in children) # the sum of each child node_count

my_tree = \
  ('S', [('NP', [('ART', 'die'), ('N', 'Katze')]), ('VP', [('V', 'jagt'), ('NP', [('ART', 'die'), ('N', 'Vögel')])])])

print(node_count(my_tree))
# 9
```

Body:
This is a syntactic tree and it looks like this in the form of code

My program is supposed to count the number of non-terminal nodes on that tree. The idea is that every tree is a 2 tuple. On the first position stands the mother node as a string and on the second position stands either a string if there is a terminal node or a list with daughter trees of the mother node. They are recursive. The program should count the number of nonterminal nodes.
so the result should just be a number of nonterminal nodes, e.g. 9.

So far as I have understood, I should do this using recursion. But there are some things that I fail to do correctly to make my programm work. My code is:

tuple_list = []
second_tuple_elements = [a_tuple[1] for a_tuple in tuple_list]
print(second_tuple_elements)
def nonterminal(count):

    if second_tuple_elements == type(""):

        return 1

    if second_tuple_elements == type([]):
        for element in list:
            if element == type (""):
                return 1
            nonterminal = second_tuple_elements + element


问:
How to convert from const char* to unsigned int c++
I am new in c++ programming and I have been trying to convert from const char* to unsigned int with no luck.
I have a:

```<code>const char* charVar;
</code>```

and i need to convert it to:

```<code>unsigned int uintVar;
</code>```

How can it be done in C++?

Thanks

答:
Try in this way</p>

```<code>#include<iostream>
#include <typeinfo>             //includes typeid

using namespace std;

int main(){

char a  = '3';
int k = 3;

const char* ptr = &a;

cout << typeid(*ptr).name() << endl;                    //prints the data type c = char
cout << typeid(*ptr-'0').name() << endl;                //prints the data type i = integer

cout << *ptr-'0' << endl;

return 0;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am new in c++ programming and I have been trying to convert from const char* to unsigned int with no luck.
I have a:

const char* charVar;

and i need to convert it to:

unsigned int uintVar;

How can it be done in C++?

Thanks

Body:
Try in this way

#include<iostream>
#include <typeinfo>             //includes typeid

using namespace std;

int main(){

char a  = '3';
int k = 3;

const char* ptr = &a;

cout << typeid(*ptr).name() << endl;                    //prints the data type c = char
cout << typeid(*ptr-'0').name() << endl;                //prints the data type i = integer

cout << *ptr-'0' << endl;

return 0;
}


问:
Sync or manage production dev and uat the right way
I am working on oracle 10.2. I am fairly new.

I have been given project to synchronize parameters & patches for our 3 main databases - production, development and testing, because there is a huge difference between them, parameters and patches wise.

We cannot replicate because the production is in Terabytes. And development and testing are fairly small databases. But my job is to keep them sync on daily basis. If anyone can point me in the right direction that would be great.

答: Use TOAD Database -> Compare -> Schemas (or Single Objects) and apply changes from DEV to UAT and from UAT to PROD, although generating patches in DEV and applying them to UAT and then to PROD would be better. </p>


问:
Last breaking changes to Ada
(Edited to narrow the question to Ada. Have posted other questions for Fortran and COBOL.)

I've spent some time in the past year dealing with changes to my code due to Python v2->v3 and R v3->v4 changes. It got me curious as to some of the older languages that are still in use.

I know Ada still sees occasional updates and functionality upgrades. I would assume that their mission-critical nature makes those changes smaller and more backward-compatible, but I don't really know and couldn't find it with a web search.

What and when were the last changes to Ada that was on the same rough order as the Python 2->3 changes?

答:
Ada pays a lot of attention to reverse compatibility, to avoid breaking existing code, when making changes.

Last formal Ada release was Ada-2012, there is another one (Ada-202X) in progress.

Ada-2012 has a lot that Ada-83 doesn't, but I'd be surprised if there was anything more than trivial work to build an Ada-83 project (or Ada-95 or Ada-2005) in Ada-2012.

There are some differences though : from Ada-83 to Ada-2012 As you can see, there's really not much to say for 30 years of development.

Title: Last breaking changes to Ada


答:
First off, please tag your post with java script instead of java, similar name, different language. Here is the code you should use:

```<code>let isBold = false;
let p=document.getElementById('hey');

function bold(){
    if(isBold == false){
        p.style.fontWeight = "bold";
        isBold = true;
    }
    else{
        p.style.fontWeight = "normal";
        isBold = false;
    }
}
</code>```

It changes the font weight (if it is bold or not) instead of the complex code you had. If you are just turning something on and off (bold or not) then use a boolean value (true + false) true will make it bold, false will make it normal. For HTML graphics, you should use CSS language. You can change the variable's CSS values by saying style then the thing you want to change.

Title: Contenteditable paragraphs in html

Body:
First off, please tag your post with java script instead of java, similar name, different language. Here is the code you should use:

let isBold = false;
let p=document.getElementById('hey');

function bold(){
    if(isBold == false){
        p.style.fontWeight = "bold";
        isBold = true;
    }
    else{
        p.style.fontWeight = "normal";
        isBold = false;
    }
}

It changes the font weight (if it is bold or not) instead of the complex code you had. If you are just turning something on and off (bold or not) then use a boolean value (true + false) true will make it bold, false will make it normal. For HTML graphics, you should use CSS language. You can change the variable's CSS values by saying style then the thing you want to change.


答:
You are quite off. Let me help you.

First, consider using Counter, it is meant for this kind of cases.
Second, try dividing the script logic into blocks (divide and conquer!), first get the data, then sort and remove the last 3, and only at the end write the results to a file.

Here is an example of the implementation.

```<code>from collections import Counter

numberofbands = int(input("How many bands are there in the competition? "))

print("Input each band’s name pressing enter after each one")

scores = Counter()

for n in range(numberofbands):
    name = input("\nEnter the name of the band: ")
    vote = input("Enter how many votes that band received: ")
    scores.update({name:int(votes)})

#remove the last 3
final = scores.most_common()[:-3]

#write to file
with open('scores.txt', 'w') as f:
    for name, vote in final:
        f.write(f'{name},{vote}\n')
</code>```

Title: Remove Bottom 3 scores in file

Body:
numberofbands = int(input("How many bands are there in the competition? "))

print("Input each band’s name pressing enter after each one")

file = open("scores.txt","w")
for loop in range(numberofbands):
  name = input("\nEnter the name of the band: ")
  votes = input("Enter how many votes that band received: ")
  file.write(name + "," + votes + "," + "\n")
file.close()

number_of_lines = len(open("scores.txt").readlines(  ))

def removebottom3():
#code to remove bottom 3 here

removebottom3()

The first part writes the band's name and score to the file.

I want the code to remove the lowest 3 scoring bands from the file. There will be a function for that.
How can I do this?
Thanks in advance.

Body:
You are quite off. Let me help you.

First, consider using Counter, it is meant for this kind of cases.
Second, try dividing the script logic into blocks (divide and conquer!), first get the data, then sort and remove the last 3, and only at the end write the results to a file.

Here is an example of the implementation.

from collections import Counter

numberofbands = int(input("How many bands are there in the competition? "))

print("Input each band’s name pressing enter after each one")

scores = Counter()

for n in range(numberofbands):
    name = input("\nEnter the name of the band: ")
    vote = input("Enter how many votes that band received: ")
    scores.update({name:int(votes)})

#remove the last 3
final = scores.most_common()[:-3]

#write to file
with open('scores.txt', 'w') as f:
    for name, vote in final:
        f.write(f'{name},{vote}\n')


问:
when I try to add files to the changelist I keep getting error files not in files(s) not in client view
When I am trying to add files from the command line I get the error saying files not in client view what does it mean ?</p>

```<code>createdCLNumber = p4.save_change(changeList)[0].split()[1]
>>> createdCLNumber
'1157539'
>>> p4.run_add("-c", createdCLNumber, "/Users/ciasto/ciasto_piekarz/sandbox/main/upgrade_tools/upgrade_gitlab")
Traceback (most recent call last):

P4.P4Exception: [P4#run] Warnings during command execution( "p4 add -c 1157539 /Users/ciasto/ciasto_piekarz/sandbox/main/upgrade_tools/upgrade_gitlab" )

        [Warning]: '/Users/ciasto/ciasto_piekarz/sandbox/main/upgrade_tools/upgrade_gitlab - file(s) not in client view.'
</code>```

答:
The error means that the file you are trying to add is not in your client view.

According to the error message, the local file is:

```<code>/Users/ciasto/ciasto_piekarz/sandbox/main/upgrade_tools/upgrade_gitlab
</code>```

Is this path under your client's Root, and does the View map it to a depot path?  If not, there's no defined depot path for it to be added to.

Unsolicited advice time: I would highly recommend gaining some basic familiarity with Perforce from the command line before trying to automate Perforce workflows with P4Python!  It's much easier to make corrections for simple beginner mistakes like this and gain an understanding of the core concepts (e.g. how to define client workspaces and use them to interact with depot files) if you're entering commands at an interactive prompt than if you have to modify a script and start over from scratch for each debugging session.  Everything you learn at the command line has a 1:1 mapping to the Python API, so the knowledge will transfer extremely well.  The API is designed for people who already have familiarity with Perforce commands and data models, so people who dive into it without knowing Perforce beforehand always end up feeling very lost.  I've seen it a hundred times.

(Almost every time I give this advice people ignore it because they "don't have time" to learn how to use the CLI before diving into writing their script, but I can guarantee you're going to end up spending about a month learning how to use Perforce via P4Python when you could have mastered it in a single afternoon of messing around in the terminal.)

Body:
When I am trying to add files from the command line I get the error saying files not in client view what does it mean ?

createdCLNumber = p4.save_change(changeList)[0].split()[1]
>>> createdCLNumber
'1157539'
>>> p4.run_add("-c", createdCLNumber, "/Users/ciasto/ciasto_piekarz/sandbox/main/upgrade_tools/upgrade_gitlab")
Traceback (most recent call last):

P4.P4Exception: [P4#run] Warnings during command execution( "p4 add -c 1157539 /Users/ciasto/ciasto_piekarz/sandbox/main/upgrade_tools/upgrade_gitlab" )

        [Warning]: '/Users/ciasto/ciasto_piekarz/sandbox/main/upgrade_tools/upgrade_gitlab - file(s) not in client view.'

Body:
The error means that the file you are trying to add is not in your client view.

According to the error message, the local file is:

/Users/ciasto/ciasto_piekarz/sandbox/main/upgrade_tools/upgrade_gitlab

Is this path under your client's Root, and does the View map it to a depot path?  If not, there's no defined depot path for it to be added to.

Unsolicited advice time: I would highly recommend gaining some basic familiarity with Perforce from the command line before trying to automate Perforce workflows with P4Python!  It's much easier to make corrections for simple beginner mistakes like this and gain an understanding of the core concepts (e.g. how to define client workspaces and use them to interact with depot files) if you're entering commands at an interactive prompt than if you have to modify a script and start over from scratch for each debugging session.  Everything you learn at the command line has a 1:1 mapping to the Python API, so the knowledge will transfer extremely well.  The API is designed for people who already have familiarity with Perforce commands and data models, so people who dive into it without knowing Perforce beforehand always end up feeling very lost.  I've seen it a hundred times.

(Almost every time I give this advice people ignore it because they "don't have time" to learn how to use the CLI before diving into writing their script, but I can guarantee you're going to end up spending about a month learning how to use Perforce via P4Python when you could have mastered it in a single afternoon of messing around in the terminal.)


问:
Generate JPG from SVG using Apache Batik
I'm trying to turn a .svg file into a .jpg or .png file. Right now I'm trying to use Apache Batik Transcoder (Link).

This is my code right now: (official code from here)

```<code>// Create a JPEG transcoder
JPEGTranscoder t = new JPEGTranscoder();

// Set the transcoding hints.
t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,
    new Float(.8));

// Create the transcoder input.
String svgURI = new File("C:/test.svg").toURL().toString();
TranscoderInput input = new TranscoderInput(svgURI);

// Create the transcoder output.
OutputStream ostream = new FileOutputStream("C:/out.jpg");
TranscoderOutput output = new TranscoderOutput(ostream);

// Save the image.
t.transcode(input, output);

// Flush and close the stream.
ostream.flush();
ostream.close();
System.exit(0);
</code>```

But it gives my this error:

Exception in thread "main" org.apache.batik.transcoder.TranscoderException: null

Enclosed Exception:

null

at org.apache.batik.transcoder.image.ImageTranscoder.transcode(Unknown Source)

at org.apache.batik.transcoder.XMLAbstractTranscoder.transcode(Unknown Source)

at org.apache.batik.transcoder.SVGAbstractTranscoder.transcode(Unknown Source)

at SaveAsJPEG.main(SaveAsJPEG.java:27)

I don't know what to do as this is the code from their website (!). So if you know how to solve it or have another idea how I can turn my .svg pictures into .jpg and .png's let me know.

答: this can be solved if you add batik-codec to maven instead of the transcoder.

Body:
I'm trying to turn a .svg file into a .jpg or .png file. Right now I'm trying to use Apache Batik Transcoder (Link).

This is my code right now: (official code from here)

// Create a JPEG transcoder
JPEGTranscoder t = new JPEGTranscoder();

// Set the transcoding hints.
t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,
    new Float(.8));

// Create the transcoder input.
String svgURI = new File("C:/test.svg").toURL().toString();
TranscoderInput input = new TranscoderInput(svgURI);

// Create the transcoder output.
OutputStream ostream = new FileOutputStream("C:/out.jpg");
TranscoderOutput output = new TranscoderOutput(ostream);

// Save the image.
t.transcode(input, output);

// Flush and close the stream.
ostream.flush();
ostream.close();
System.exit(0);

But it gives my this error:

Exception in thread "main" org.apache.batik.transcoder.TranscoderException: null

Enclosed Exception:

null

at org.apache.batik.transcoder.image.ImageTranscoder.transcode(Unknown Source)

at org.apache.batik.transcoder.XMLAbstractTranscoder.transcode(Unknown Source)

at org.apache.batik.transcoder.SVGAbstractTranscoder.transcode(Unknown Source)

at SaveAsJPEG.main(SaveAsJPEG.java:27)

I don't know what to do as this is the code from their website (!). So if you know how to solve it or have another idea how I can turn my .svg pictures into .jpg and .png's let me know.


问:
How to extract elements in an array with regard to an index?
I have a row A = [0 1 2 3 4] and an index I = [0 0 1 0 1]. I would like to extract the elements in A indexed by I, i.e. [2, 4].

My attempt:

```<code>import numpy as np
A = np.array([0, 1, 2, 3, 4])
index = np.array([0, 0, 1, 0, 1])
print(A[index])
</code>```

The result is not as I expected:

```<code>[0 0 1 0 1]
</code>```

Could you please elaborate on how to achieve my goal?

答:
A non-numpy way to achieve this, in case its useful - it uses zip to combine each pair of elements, and returns the first if the second is true:

[x[0] for x in zip(a, i) if x[1]]

Body:
I have a row A = [0 1 2 3 4] and an index I = [0 0 1 0 1]. I would like to extract the elements in A indexed by I, i.e. [2, 4].

My attempt:

import numpy as np
A = np.array([0, 1, 2, 3, 4])
index = np.array([0, 0, 1, 0, 1])
print(A[index])

The result is not as I expected:

[0 0 1 0 1]

Could you please elaborate on how to achieve my goal?


问:
Convert XML file using XSLT in Android
I am new to Android.

I want to convert a XML file to HTML format using XSLT to display it in android.

Can you please tell me some tutorials or examples to follow?

I also tried the codes in the Android: Convert xml using xslt
But it didn't work. I am not sure what is "StringOutputStream" there.

Thanks in advance.

答:
Put both your xml and xslt file in raw folder.
The generated html file will be stored in sdcard.
Use the following code.

```<code>import java.io.File;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

public class XsltTester extends Activity {

    private static String TAG = XsltTester.class.getSimpleName();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {

            Source xmlSource = new StreamSource(this.getResources().openRawResource(R.raw.weather));
            Source xsltSource = new StreamSource(this.getResources().openRawResource(R.raw.weatherxsl));

            TransformerFactory transFact = TransformerFactory.newInstance();
            Transformer trans = transFact.newTransformer(xsltSource);
//          FileOutputStream fo = new FileOutputStream(f);
//          fo.write(resizeBitMapImageToByteArray(photoAlbumBean));
//          fo.close();
            File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mydata.html");

//            OutputStream output = new StringOutputStream();
            StreamResult result = new StreamResult(f);
            trans.transform(xmlSource, result);

        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerFactoryConfigurationError e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code>```

Thanks
Deepak

Title: Convert XML file using XSLT in Android

Body:
Put both your xml and xslt file in raw folder.
The generated html file will be stored in sdcard.
Use the following code.

import java.io.File;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

public class XsltTester extends Activity {

    private static String TAG = XsltTester.class.getSimpleName();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {

            Source xmlSource = new StreamSource(this.getResources().openRawResource(R.raw.weather));
            Source xsltSource = new StreamSource(this.getResources().openRawResource(R.raw.weatherxsl));

            TransformerFactory transFact = TransformerFactory.newInstance();
            Transformer trans = transFact.newTransformer(xsltSource);
//          FileOutputStream fo = new FileOutputStream(f);
//          fo.write(resizeBitMapImageToByteArray(photoAlbumBean));
//          fo.close();
            File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mydata.html");

//            OutputStream output = new StringOutputStream();
            StreamResult result = new StreamResult(f);
            trans.transform(xmlSource, result);

        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerFactoryConfigurationError e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Thanks
Deepak


问:
java -version showing different version than in path
I have jdk12 and jdk8 on my computer installed. Usually jdk12 is set in the path.
To run some java programs I had set path to jdk8. Now after changing the path back to /jdk-12.0.1/bin, running java -version on cmd still returns

```<code>java version "1.8.0_251"
Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)
</code>```

答:
I decided to assemble my comments to an answer:

When calling java on the command line, the OS only uses the PATH environment variable to look for the command. The variable JAVA_HOME is not used here.

So you simply should examine the PATH variable: The directory C:\Program Files (x86)\Common Files\Oracle\Java\javapath is added to the PATH by the JDK installer. I would suggest to remove it, so you have better control what directories are part of the PATH.

Body:
I have jdk12 and jdk8 on my computer installed. Usually jdk12 is set in the path.
To run some java programs I had set path to jdk8. Now after changing the path back to /jdk-12.0.1/bin, running java -version on cmd still returns

java version "1.8.0_251"
Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)


问:
How do I store and retrieve a selected date object from datetimepicker to firebase?
This is code that that sends and receives the data from firebase respectively.

```<code>class Fire {
    addAppointment(currentDate, addComplete) {
            firebase.firestore()
                .collection("appointment")
                .add({
                    date: currentDate.date,
                    createdAt: firebase.firestore.FieldValue.serverTimestamp()
                }).then((snapshot) => snapshot.get())
                .then((dateInfo) => addComplete(dateInfo.data()))
                .catch((error) => alert(error));
        }

        getAppointment = async ({ dateRetreived }) => {
            var dateList = [];

            var snapshot = await firebase.firestore()
                .collection("appointment")
                .orderBy('createdAt')
                .get()

            snapshot.forEach((doc) => {
                const dateCreated = doc.data();
                dateCreated.id = doc.id;
                dateList.push(dateCreated);
            });

            dateRetreived(dateList);
        }
}

Fire.shared = new Fire();
export default Fire;
</code>```

This is the datetimepicker code that sends the "currentDate" to the code above. Note that onChange has been changed to handleChange.

```<code>class Booking extends Component {
    state = {
        isDatePickerVisible: false,
        date: new Date(),

    };

    showDateTimePicker = () => {
        this.setState({
            isDatePickerVisible: true
        })
    }

    hideDateTimePicker = () => {
        this.setState({
            isDatePickerVisible: false
        })
    }

    handleChange = (event, selectedDate) => {
        const currentDate = selectedDate || date;
        this.setState(prevState => ({
            currentDate: prevState.currentDate = currentDate
          }));
      };

    render() {
        return (
            <View>

                <View style={styles.picker}>
                    <Button
                        title="Show Date Picker" onPress={this.showDateTimePicker}
                    />
                    <DateTimePicker
                        cancelTextIOS={'Exit'}
                        confirmTextIOS={'OK'}
                        isVisible={this.state.isDatePickerVisible}
                        mode="date"
                        onConfirm={this.handleChange}
                        onCancel={this.hideDateTimePicker}
                        is24Hour={false}
                    />
                </View>

                <View style={styles.btn} >
                    <Button
                        onPress={() =>
                            Fire.shared.addAppointment(this.handleChange)
                        }
                        title="Book"
                    />
                </View>
            </View>

        )
    };
};

export default Booking;
</code>```

I get an error saying:

FirebaseError: function documentReference.set() called with invalid data. unsupported field value: undefined (found in field date)

I made a few changes to the code:

```<code>addAppointment(currentDate, addComplete) {
        firebase.firestore()
            .collection("appointment")
            .add({
                date: firebase.firestore.Timestamp.fromDate(new Date(currentDate)),
             ...
    }
</code>```

AND
On state:

```<code>   state = {
            isDatePickerVisible: false,
            Date: new Date(1598051730000),

        };
</code>```

On handling change

```<code>  handleChange = (event, selectedDate) => {
            const currentDate = selectedDate || Date;
            this.setState(prevState => ({
                currentDate: prevState.currentDate = currentDate
              }));
          };
</code>```

On DateTimePicker

```<code>onConfirm={this.handleChange}
</code>```

On Book button

```<code><Button onPress={() => {Fire.shared.addAppointment(this.handleChange)}}
                        title="Book"
                    />
</code>```

I don't get a  ReferenceError: date is not defined after selecting the date. When i press BOOK, no error happens and no data shows in Cloud Firestore.

答:
I struggled so much, that I brought the addAppointment method into the DatePicker.js file. This is what worked for me.</p>

```<code>const Booking = () => {
    const [date, setDate] = useState(new Date());
    const [mode, setMode] = useState('date');
    const [show, setShow] = useState(false);

    const showMode = currentMode => {
        setShow(true);
        setMode(currentMode);
    };

    const showDatepicker = () => {
        showMode('date');
    };

    const showTimepicker = () => {
        showMode('time');
    };

    const onChange = (event, date) => {
        const currentDate = date;
        setShow(Platform.OS === 'ios');
        setDate(currentDate);
        console.warn(currentDate);
    };

    const addAppointment = () => {
        firebase.firestore()
            .collection("appointment")
            .add({
                uid: firebase.auth().currentUser.uid,
                date: firebase.firestore.Timestamp.fromDate(date),
                createdAt: firebase.firestore.FieldValue.serverTimestamp()
            }).then((snapshot) => snapshot.get())
            .catch((error) => alert(error));
    }

    return (
        <View>
            <View>

                <View style={styles.picker}>
                    <Button onPress={showDatepicker} title="Show date picker!" />
                </View>
                <View style={styles.picker}>
                    <Button onPress={showTimepicker} title="Show time picker!" />
                </View>
                {show && (
                    <DateTimePicker
                        testID="dateTimePicker"
                        timeZoneOffsetInMinutes={0}
                        value={date}
                        mode={mode}
                        is24Hour={true}
                        display="default"
                        onChange={onChange}
                    />
                )}
            </View>

            <View style={styles.btn} >
                <Button
                    onPress={() => addAppointment(onChange)}
                    title="Book"
                />
            </View>
        </View >

    );
};

export default Booking;
</code>```

Body:
This is code that that sends and receives the data from firebase respectively.

class Fire {
    addAppointment(currentDate, addComplete) {
            firebase.firestore()
                .collection("appointment")
                .add({
                    date: currentDate.date,
                    createdAt: firebase.firestore.FieldValue.serverTimestamp()
                }).then((snapshot) => snapshot.get())
                .then((dateInfo) => addComplete(dateInfo.data()))
                .catch((error) => alert(error));
        }

        getAppointment = async ({ dateRetreived }) => {
            var dateList = [];

            var snapshot = await firebase.firestore()
                .collection("appointment")
                .orderBy('createdAt')
                .get()

            snapshot.forEach((doc) => {
                const dateCreated = doc.data();
                dateCreated.id = doc.id;
                dateList.push(dateCreated);
            });

            dateRetreived(dateList);
        }
}

Fire.shared = new Fire();
export default Fire;

This is the datetimepicker code that sends the "currentDate" to the code above. Note that onChange has been changed to handleChange.

class Booking extends Component {
    state = {
        isDatePickerVisible: false,
        date: new Date(),

    };

    showDateTimePicker = () => {
        this.setState({
            isDatePickerVisible: true
        })
    }

    hideDateTimePicker = () => {
        this.setState({
            isDatePickerVisible: false
        })
    }

    handleChange = (event, selectedDate) => {
        const currentDate = selectedDate || date;
        this.setState(prevState => ({
            currentDate: prevState.currentDate = currentDate
          }));
      };

    render() {
        return (
            <View>

                <View style={styles.picker}>
                    <Button
                        title="Show Date Picker" onPress={this.showDateTimePicker}
                    />
                    <DateTimePicker
                        cancelTextIOS={'Exit'}
                        confirmTextIOS={'OK'}
                        isVisible={this.state.isDatePickerVisible}
                        mode="date"
                        onConfirm={this.handleChange}
                        onCancel={this.hideDateTimePicker}
                        is24Hour={false}
                    />
                </View>

                <View style={styles.btn} >
                    <Button
                        onPress={() =>
                            Fire.shared.addAppointment(this.handleChange)
                        }
                        title="Book"
                    />
                </View>
            </View>

        )
    };
};

export default Booking;

I get an error saying:

FirebaseError: function documentReference.set() called with invalid data. unsupported field value: undefined (found in field date)

I made a few changes to the code:

addAppointment(currentDate, addComplete) {
        firebase.firestore()
            .collection("appointment")
            .add({
                date: firebase.firestore.Timestamp.fromDate(new Date(currentDate)),
             ...
    }

AND
On state:

   state = {
            isDatePickerVisible: false,
            Date: new Date(1598051730000),

        };

On handling change

  handleChange = (event, selectedDate) => {
            const currentDate = selectedDate || Date;
            this.setState(prevState => ({
                currentDate: prevState.currentDate = currentDate
              }));
          };

On DateTimePicker

onConfirm={this.handleChange}

On Book button

<Button onPress={() => {Fire.shared.addAppointment(this.handleChange)}}
                        title="Book"
                    />

I don't get a  ReferenceError: date is not defined after selecting the date. When i press BOOK, no error happens and no data shows in Cloud Firestore.

Body:
I struggled so much, that I brought the addAppointment method into the DatePicker.js file. This is what worked for me.

const Booking = () => {
    const [date, setDate] = useState(new Date());
    const [mode, setMode] = useState('date');
    const [show, setShow] = useState(false);

    const showMode = currentMode => {
        setShow(true);
        setMode(currentMode);
    };

    const showDatepicker = () => {
        showMode('date');
    };

    const showTimepicker = () => {
        showMode('time');
    };

    const onChange = (event, date) => {
        const currentDate = date;
        setShow(Platform.OS === 'ios');
        setDate(currentDate);
        console.warn(currentDate);
    };

    const addAppointment = () => {
        firebase.firestore()
            .collection("appointment")
            .add({
                uid: firebase.auth().currentUser.uid,
                date: firebase.firestore.Timestamp.fromDate(date),
                createdAt: firebase.firestore.FieldValue.serverTimestamp()
            }).then((snapshot) => snapshot.get())
            .catch((error) => alert(error));
    }

    return (
        <View>
            <View>

                <View style={styles.picker}>
                    <Button onPress={showDatepicker} title="Show date picker!" />
                </View>
                <View style={styles.picker}>
                    <Button onPress={showTimepicker} title="Show time picker!" />
                </View>
                {show && (
                    <DateTimePicker
                        testID="dateTimePicker"
                        timeZoneOffsetInMinutes={0}
                        value={date}
                        mode={mode}
                        is24Hour={true}
                        display="default"
                        onChange={onChange}
                    />
                )}
            </View>

            <View style={styles.btn} >
                <Button
                    onPress={() => addAppointment(onChange)}
                    title="Book"
                />
            </View>
        </View >

    );
};

export default Booking;


问:
Fixing a corrupted .MP4 file. which might be a 3gp file
I have a  file called input.MP4 and it is corrupted. It's from a CCTV camera. I tried everything, ffmpeg, VLC convert,  no luck. However, I used mediainfo and exiftool and extracted the following info. I am wondering if someone can figure out if I can use any of this info to fix it or convert it to a usable format. I have a copy of it here on my Google Drive

mediainfo gave me this:

```<code>General
Complete name                       : input.MP4
Format                              : MPEG-4
Format profile                      : 3GPP Media Release 5
Codec ID                            : 3gp5 (3gp5/3gp4/avc1/mp42/isom)
File size                           : 5.77 MiB
IsTruncated                         : Yes
</code>```

exiftool gave me this:

```<code>ExifTool Version Number          : 10.80
File Name                        : input.MP4
Directory                        : /home/tendi/Downloads
File Size                        : 5.8 MB
File Modification Date/Time      : 2018:07:21 19:09:03-04:00
File Access Date/Time            : 2018:07:21 19:30:48-04:00
File Inode Change Date/Time      : 2018:07:21 19:30:48-04:00
File Permissions                 : rw-rw-r--
File Type                        : 3GP
File Type Extension              : 3gp
MIME Type                        : video/3gpp
Major Brand                      : 3GPP Media (.3GP) Release 5
Minor Version                    : 0.0.0
Compatible Brands                : 3gp5, 3gp4, avc1, mp42, isom
Movie Data Size                  : 5899106
Movie Data Offset                : 44
</code>```

Any suggestions?

答:
I received a mp4 video with codec '3gp5', which seems to be a predecessor to isom/mp41 codec.  I transcoded it with:

```<code>ffmpeg -i input-3gp5.mp4 -vc mp42  output.mp4
</code>```

I was then able to play the video with html5 video tag.

Body:
I have a  file called input.MP4 and it is corrupted. It's from a CCTV camera. I tried everything, ffmpeg, VLC convert,  no luck. However, I used mediainfo and exiftool and extracted the following info. I am wondering if someone can figure out if I can use any of this info to fix it or convert it to a usable format. I have a copy of it here on my Google Drive

mediainfo gave me this:

General
Complete name                       : input.MP4
Format                              : MPEG-4
Format profile                      : 3GPP Media Release 5
Codec ID                            : 3gp5 (3gp5/3gp4/avc1/mp42/isom)
File size                           : 5.77 MiB
IsTruncated                         : Yes

exiftool gave me this:

ExifTool Version Number          : 10.80
File Name                        : input.MP4
Directory                        : /home/tendi/Downloads
File Size                        : 5.8 MB
File Modification Date/Time      : 2018:07:21 19:09:03-04:00
File Access Date/Time            : 2018:07:21 19:30:48-04:00
File Inode Change Date/Time      : 2018:07:21 19:30:48-04:00
File Permissions                 : rw-rw-r--
File Type                        : 3GP
File Type Extension              : 3gp
MIME Type                        : video/3gpp
Major Brand                      : 3GPP Media (.3GP) Release 5
Minor Version                    : 0.0.0
Compatible Brands                : 3gp5, 3gp4, avc1, mp42, isom
Movie Data Size                  : 5899106
Movie Data Offset                : 44

Any suggestions?

Body:
I received a mp4 video with codec '3gp5', which seems to be a predecessor to isom/mp41 codec.  I transcoded it with:

ffmpeg -i input-3gp5.mp4 -vc mp42  output.mp4

I was then able to play the video with html5 video tag.


问:
How to get the desired character by split or substring method in stringArray JS?
There is an array and there are strings that are different from each other but contain operations.All of the strings have a large operator and a small operator.I want to separate the characters from the operator and later.

My example Array;

```<code>[definitions1<=3123,definitions31241>=32414,definitions123213123>=12]
</code>```

The result I want;

```<code>[<=3123,>=32414,>=12]
</code>```

When i try with split method like this,

(split(<).pop()) or (split(>).pop())

Result = [=3123,=32414,=12]  i could not get (<,>) operator.

When i tried with subStr, I cannot give standard start and finish parameters because strings are different lengths.

I would be glad if someone shows regular expression method or a simpler way.

答:
```<code>var arr= ['definitions1<=3123','definitions31241>=32414','definitions123213123>=12']

var newarr=arr.map(x=> x.split('='))
 finalarray=[]
newarr.forEach(array => {
    resu=array[0].includes('<') ?finalarray.push('<='+array[1]):finalarray.push('>='+array[1])

});
               console.log(finalarray)
</code>```

Body:
There is an array and there are strings that are different from each other but contain operations.All of the strings have a large operator and a small operator.I want to separate the characters from the operator and later.

My example Array;

[definitions1<=3123,definitions31241>=32414,definitions123213123>=12]

The result I want;

[<=3123,>=32414,>=12]

When i try with split method like this,

(split(<).pop()) or (split(>).pop())

Result = [=3123,=32414,=12]  i could not get (<,>) operator.

When i tried with subStr, I cannot give standard start and finish parameters because strings are different lengths.

I would be glad if someone shows regular expression method or a simpler way.


问:
Compilers and argument order of evaluation in C++
Okay, I'm aware that the standard dictates that a C++ implementation may choose in which order arguments of a function are evaluated, but are there any implementations that actually 'take advantage' of this in a scenario where it would actually affect the program?

Classic Example:

```<code>int i = 0;
foo(i++, i++);
</code>```

Note: I'm not looking for someone to tell me that the order of evaluation can't be relied on, I'm well aware of that. I'm only interested in whether any compilers actually do evaluate out of a left-to-right order because my guess would be that if they did lots of poorly written code would break (rightly so, but they would still probably complain).

答: I expect that most modern compilers would attempt to interleave the instructions computing the arguments, given that they are required by the C++ standard to be independent and thus lack any interdependencies.  Doing this should help to keep a deeply-pipelined CPU's execution units full and thereby increase throughput.  (At least I would expect that a compiler that claims to be an optimising compiler would do so when optimisation flags are given.)</p>

OwnerDisplayName: Cypherjb

Body:
Okay, I'm aware that the standard dictates that a C++ implementation may choose in which order arguments of a function are evaluated, but are there any implementations that actually 'take advantage' of this in a scenario where it would actually affect the program?

Classic Example:

int i = 0;
foo(i++, i++);

Note: I'm not looking for someone to tell me that the order of evaluation can't be relied on, I'm well aware of that. I'm only interested in whether any compilers actually do evaluate out of a left-to-right order because my guess would be that if they did lots of poorly written code would break (rightly so, but they would still probably complain).


问:
PHP version in HostGator
I have one problem with my project, when try to upload a new version in my host (HostGator).

This is the error:

PHP Startup: SourceGuardian: Unable to initialize module

Module compiled with module API=20131226

PHP compiled with module API=20100525

These options need to match

I change in cPanel the version of PHP 5.4 to 5.6, but when I check the version of PHP in server from connection with putty, I receive the follow message:

PHP 5.4.45 (cli) (built: Apr 17 2017 15:59:08)

Copyright (c) 1997-2014 The PHP Group

Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies

    with the ionCube PHP Loader (enabled) + Intrusion Protection from ioncube24.com (unconfigured) v10.2.4, Copyright (c) 2002-2018, by ionCube Ltd.

    with Zend Guard Loader v3.3, Copyright (c) 1998-2013, by Zend Technologies

Maybe this can be the problem? I read about this error, but I cant get a solution. I don't know if I doing something wrong.

答:
Just add this lines to your .htaccess for newer versions of php to work:

For PHP 7.2:

```<code>AddHandler application/x-httpd-ea-php72 .php .php7 .phtml
</code>```

For PHP 7.3:

```<code>AddHandler application/x-httpd-ea-php73 .php .php7 .phtml
</code>```

Title: PHP version in HostGator

Body:
Just add this lines to your .htaccess for newer versions of php to work:

For PHP 7.2:

AddHandler application/x-httpd-ea-php72 .php .php7 .phtml

For PHP 7.3:

AddHandler application/x-httpd-ea-php73 .php .php7 .phtml