问:
How to count the number of clicks for button
How to count the number of clicks for CAT or DOG button in my program and save to log.txt  </p>

```<code>from Tkinter import *

import Tkinter as tk

import sys

stdoutOrigin=sys.stdout
sys.stdout = open("log.txt", "w")

master = Tk()
Label(master, text='Who is your favourate animal ?? ').grid(row=0)

Button(master, text='CAT' ,).grid(row=1, sticky=W, pady=4)
Button(master, text='DOG' ,).grid(row=1,column=1,sticky=W, pady=4)
mainloop()

sys.stdout.close()
sys.stdout=stdoutOrigin
</code>```

答:
```<code>cats = 0
dogs = 0
def cat():
    with open("log.txt").read() as contents:
        file = open("log.txt", "w")
        file.write(str(int(contents.split()[0]) + 1) + "\n" + contents.split()[1])
        file.close()
def dog():
    with open("log.txt").read() as contents:
        file = open("log.txt", "w")
        file.write(contents.split()[0] + "\n" + str(int(contents.split()[1]) + 1))
        file.close()
Button(master, text='CAT' , command=cat).grid(row=1, sticky=W, pady=4)
Button(master, text='DOG' , command=dog).grid(row=1,column=1,sticky=W, pady=4)
</code>```

Body:
How to count the number of clicks for CAT or DOG button in my program and save to log.txt

from Tkinter import *

import Tkinter as tk

import sys

stdoutOrigin=sys.stdout
sys.stdout = open("log.txt", "w")

master = Tk()
Label(master, text='Who is your favourate animal ?? ').grid(row=0)

Button(master, text='CAT' ,).grid(row=1, sticky=W, pady=4)
Button(master, text='DOG' ,).grid(row=1,column=1,sticky=W, pady=4)
mainloop()

sys.stdout.close()
sys.stdout=stdoutOrigin


来源: stackexchange

问:
How to add a asp-page-handler dynamically to a  tag in asp.net core?
bool result=true;

if the result is true then:

```<code><a asp-route-pageIndex="1">1</a>
</code>```

if the result is false then:

```<code><a>1</a>
</code>```

how to do it?

答:
```<code>@{
   //just for illustration
    var result = true;
    var pageIndex = 1;
}
@if (result)
{
    <a asp-route-pageIndex="@pageIndex">@pageIndex</a>
}
else
{
    <a>1</a>
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
bool result=true;

if the result is true then:

1

if the result is false then:

1

how to do it?


问:
Why do Python io streams not close on __del__?
Up until now, I have been making an egregious error in my Python development: I have been assuming that streams get closed once their corresponding objects go out of scope. Specifically, I assumed that when a file or some instance of a class inheriting io.IOBase invoked __del__, it would run the object's close method. However, upon executing the following code I noticed that this was certainly not the case.

def wrap_close(old_close):
    def new_close(*args, **kwargs):
        print("closing")
        return old_close(*args, **kwargs)
    return new_close

f = open("tmp.txt")
f.close = wrap_close(f.close)
f.close() # prints "closing"

f = open("tmp.txt")
f.close = wrap_close(f.close)
del(f) # nothing printed
```

My question is, what is the benefit of not closing a file or stream automatically when its __del__ method is invoked? It seems like the implementation would be trivial, but I imagine there has to be a reason for allowing streams to stay open after their corresponding object goes out of scope.

答:
self.close keeps a reference on self, so you're writing self.close = lambda: self.close(), creating a circular reference. As a result:

del does nothing, CPython will not reclaim the object until an actual GC collection happens, either implicitly at some point or through an explicit gc.collect()

CPython has to break the cycle, so by the time it comes around to collecting the object it might have removed the attribute from it

You can see this very clearly if you replace your strong references to old_close by weak ones:

def wrap_close(old_close):
    old_close = weakref.ref(old_close)
    def new_close(*args, **kwargs):
        print("closing")
        c = old_close()
        if c:
            c(*args, **kwargs)
    return new_close

f = open('/dev/zero')
f.close = wrap_close(f.close)
f.close() # prints "closing"

f = open('/dev/zero')
f.close = wrap_close(f.close)
del f # nothing printed
```

prints "closing" not just twice but thrice:

when close() is called explicitly

when the first f is garbaged (as the second one is created)

when the second one is del'd

My question is, what is the benefit of not closing a file or stream automatically when its del method is invoked?

Python absolutely closes the file object when it's finalised.

Body:
Up until now, I have been making an egregious error in my Python development: I have been assuming that streams get closed once their corresponding objects go out of scope. Specifically, I assumed that when a file or some instance of a class inheriting io.IOBase invoked __del__, it would run the object's close method. However, upon executing the following code I noticed that this was certainly not the case.

def wrap_close(old_close):
    def new_close(*args, **kwargs):
        print("closing")
        return old_close(*args, **kwargs)
    return new_close

f = open("tmp.txt")
f.close = wrap_close(f.close)
f.close() # prints "closing"

f = open("tmp.txt")
f.close = wrap_close(f.close)
del(f) # nothing printed

My question is, what is the benefit of not closing a file or stream automatically when its __del__ method is invoked? It seems like the implementation would be trivial, but I imagine there has to be a reason for allowing streams to stay open after their corresponding object goes out of scope.

Body:
self.close keeps a reference on self, so you're writing self.close = lambda: self.close(), creating a circular reference. As a result:

del does nothing, CPython will not reclaim the object until an actual GC collection happens, either implicitly at some point or through an explicit gc.collect()

CPython has to break the cycle, so by the time it comes around to collecting the object it might have removed the attribute from it

You can see this very clearly if you replace your strong references to old_close by weak ones:

def wrap_close(old_close):
    old_close = weakref.ref(old_close)
    def new_close(*args, **kwargs):
        print("closing")
        c = old_close()
        if c:
            c(*args, **kwargs)
    return new_close

f = open('/dev/zero')
f.close = wrap_close(f.close)
f.close() # prints "closing"

f = open('/dev/zero')
f.close = wrap_close(f.close)
del f # nothing printed

prints "closing" not just twice but thrice:

when close() is called explicitly

when the first f is garbaged (as the second one is created)

when the second one is del'd

My question is, what is the benefit of not closing a file or stream automatically when its del method is invoked?

Python absolutely closes the file object when it's finalised.


问:
Adapt my js code to an input
I have this javascript code that creates a slider:

http://jsfiddle.net/samccone/ZMkkd/

Now, i want to use this code on a checkbox input. the problem is that the code creates a child element that slides in it's parent using a css position, and an input cannot have a child.

My idea was to use background-position and just slide the background of the input from left to right using css instead of using real positioning.

How can I adapt this script? It is quite easy I think but after a couple of tries I just gave up, i'm not good enough :).

Thanks for your help,

Christopher

答: You might need to store some data in object properties (or the .data() api), but your background position idea should work just fine. Just replace your calls to .offset().left with .css('background-position') (you'll have to split and parseInt the string it returns tho) and keep plugin' away at it.

ContentLicense: CC BY-SA 3.0

Title: Adapt my js code to an input


问:
Using set as a way to reorder iterable
I have two tuples a and b and also a dictionary d

```<code>a=('C', 'G')
b=('G', 'C')
d={('G', 'C'): 'T'}
</code>```

I want d[a] and d[b] to return 'T'.

For that I used set() because I thought that set() was fixing the order of the elements of a iterable object (and removing the duplicates but I don't care about that).

So I did:

```<code>tuple(set(a)) in d  # return True
tuple(set(b)) in d  # return True
# I did tuple(set()) because set() alone is not hashable and so cannot be used directly
</code>```

This works, until it doesn't. And so I discover than sometimes

```<code>set(('C', 'G'))
{'C', 'G'}
</code>```

and sometimes it does not

```<code>set(('C', 'G'))
{'G', 'C'}
</code>```

I understand that set() orders the element as it wants but I expected that the order would always be the same with a given set of elements.

So my questions are:

Why it's not the case?

How can I solve my initial problem?

答:
The set is built on some data structure that offers allows efficient checks of membership.  The consequence is that Python loses the original ordering specified in the code when instantiating this structure.

If you really only have the two labels, I would probably just explicitly specify both values.

```<code>a=('C', 'G')
b=('G', 'C')
d={a: 'T', b: 'T'}
</code>```

To solve a larger version of this problem, you will need to set the value of both order separately.  For a larger problem, I would use a comprehension with a double loop

```<code>lbls = ['a', 'b', 'c']
{(f, s):'T' for f in lbls for s in lbls if f != s}
</code>```

Title: Using set as a way to reorder iterable

Body:
I have two tuples a and b and also a dictionary d

a=('C', 'G')
b=('G', 'C')
d={('G', 'C'): 'T'}

I want d[a] and d[b] to return 'T'.

For that I used set() because I thought that set() was fixing the order of the elements of a iterable object (and removing the duplicates but I don't care about that).

So I did:

tuple(set(a)) in d  # return True
tuple(set(b)) in d  # return True
# I did tuple(set()) because set() alone is not hashable and so cannot be used directly

This works, until it doesn't. And so I discover than sometimes

set(('C', 'G'))
{'C', 'G'}

and sometimes it does not

set(('C', 'G'))
{'G', 'C'}

I understand that set() orders the element as it wants but I expected that the order would always be the same with a given set of elements.

So my questions are:

Why it's not the case?

How can I solve my initial problem?

Body:
The set is built on some data structure that offers allows efficient checks of membership.  The consequence is that Python loses the original ordering specified in the code when instantiating this structure.

If you really only have the two labels, I would probably just explicitly specify both values.

a=('C', 'G')
b=('G', 'C')
d={a: 'T', b: 'T'}

To solve a larger version of this problem, you will need to set the value of both order separately.  For a larger problem, I would use a comprehension with a double loop

lbls = ['a', 'b', 'c']
{(f, s):'T' for f in lbls for s in lbls if f != s}


问:
EE 5.x - How to suppress login/logout confirmation page
on EE 2.x the Freemember addon allowed to directly redirect the user after login/logout to a specified page (avoiding the default login/logout confirmation page).

Since the Freemember addon is EOL, how can I achieve the same thing on EE 5.x ?

答:
You could use the member_member_login_single hook in a simple extension and redirect it with php.</p>

```<code>function member_member_login_single($hook_data)
{
    if(isset($_POST['RET'])){
          header('location: '.$_POST['RET']);
          exit;
    }
}
</code>```

Body:
You could use the member_member_login_single hook in a simple extension and redirect it with php.

function member_member_login_single($hook_data)
{
    if(isset($_POST['RET'])){
          header('location: '.$_POST['RET']);
          exit;
    }
}


问:
Python - Construction of a two-dimensional list of random integers, shows repetition, that should not be there
i am fairly new to python, and this is the first hurdle i came across.
Here is what's happening:

```<code>from random import randint

empty = [[0]*9]*9

def randomboard():
  board = empty
  for x in range(0,8):
    for y in range(0,8):
      nextInt = randint(0,29) - 20
      #nextInt = 0 if nextInt < 0 else nextInt
      board[x][y] = nextInt
  return board

def printboard(board):
  for x in range(0,8):
    print(board[x])
  print("----")

printboard(empty)
printboard(randomboard())
</code>```

The Output is the following:

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

What the Code should do:
Create an Empty 9x9 board. Fill it with random values. Then print the result.

As you can see, the first axis keeps repeating, even though i feel like this should not be the case and i can only try to fathom why it is.
Here are a couple of possibilities:

-The RNG Seed resets after every iteration of the first loop:
I wouldn't even know what to do in this case, and it would seem very unintuitive for this to happen.

-I have been doing something weird during the construction of the random list.Possibly some false syntax, that i have been taking over from java:
I have been looking into other code examples, and the code snippet still seems good to me. Maybe i'm not seeing something, that you do.

-The printboard function just prints the first row over and over:
I already tried to substitute the funtion for "print(board)", but that also returns the repeating list.

-Something totally different, that i have been overlooking

At this point, i'd really appreciate your help.

Thank you in advance!

答:
I think you are doing a list of references to the same object. Have a look at this post: Python initializing a list of lists.

My solution for your problem would look like a little different. I would not start with an empty list, just add what I need:

def randomboard():
    board = []
    for x in range(0,8):
        newline = []
            for y in range(0,8):
                newline.append(randint(0,29) - 20)
        board.append(newline)
    return board
```

Body:
i am fairly new to python, and this is the first hurdle i came across.
Here is what's happening:

from random import randint

empty = [[0]*9]*9

def randomboard():
  board = empty
  for x in range(0,8):
    for y in range(0,8):
      nextInt = randint(0,29) - 20
      #nextInt = 0 if nextInt < 0 else nextInt
      board[x][y] = nextInt
  return board

def printboard(board):
  for x in range(0,8):
    print(board[x])
  print("----")

printboard(empty)
printboard(randomboard())

The Output is the following:

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

What the Code should do:
Create an Empty 9x9 board. Fill it with random values. Then print the result.

As you can see, the first axis keeps repeating, even though i feel like this should not be the case and i can only try to fathom why it is.
Here are a couple of possibilities:

-The RNG Seed resets after every iteration of the first loop:
I wouldn't even know what to do in this case, and it would seem very unintuitive for this to happen.

-I have been doing something weird during the construction of the random list.Possibly some false syntax, that i have been taking over from java:
I have been looking into other code examples, and the code snippet still seems good to me. Maybe i'm not seeing something, that you do.

-The printboard function just prints the first row over and over:
I already tried to substitute the funtion for "print(board)", but that also returns the repeating list.

-Something totally different, that i have been overlooking

At this point, i'd really appreciate your help.

Thank you in advance!


问:
Execute a function after rendering of Graph completes
I want to execute a function after the successful rendering of a Graph. SuccessfulRendering() is running before the display completes. Any Idea how can we do this? I want to take the screenshot of the screen in SuccessfulRendering() function after the display completes, that's why I've to wait for the graph to be rendered completely.

Code:

```<code>import React, { Component } from 'react';
import { render } from 'react-dom';
import HighchartsReact from 'highcharts-react-official';
import Highcharts from 'highcharts';

class LineChart extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // To avoid unnecessary update keep all options in the state.
      chartOptions: {
        xAxis: {
          categories: ['A', 'B', 'C'],
        },
        series: [
          { data: [1, 2, 3] }
        ]
      },
      hoverData: null
    };
  }

  SuccessfulRendering=()=>{
    console.log('Successfully rendered!!')
  }

  updateSeries = () => {
    // The chart is updated only with new options.
    this.setState({
      chartOptions: {
        series: [
          { data: [Math.random() * 5, 2, 1]}
        ]
      }
    },()=>{
      this.SuccessfulRendering()
    });

  }

  render() {
    const { chartOptions, hoverData } = this.state;

    return (
      <div>
        <HighchartsReact
          highcharts={Highcharts}
          options={chartOptions}
        />
      <h3>Hovering over {hoverData}</h3>
      <button onClick={this.updateSeries.bind(this)}>Update Series</button>
      </div>
    )
  }
}

render(<LineChart />, document.getElementById('root'),()=>{
});

</code>```

答: Have you tried using the callback? Check it here

Body:
I want to execute a function after the successful rendering of a Graph. SuccessfulRendering() is running before the display completes. Any Idea how can we do this? I want to take the screenshot of the screen in SuccessfulRendering() function after the display completes, that's why I've to wait for the graph to be rendered completely.

Code:

import React, { Component } from 'react';
import { render } from 'react-dom';
import HighchartsReact from 'highcharts-react-official';
import Highcharts from 'highcharts';

class LineChart extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // To avoid unnecessary update keep all options in the state.
      chartOptions: {
        xAxis: {
          categories: ['A', 'B', 'C'],
        },
        series: [
          { data: [1, 2, 3] }
        ]
      },
      hoverData: null
    };
  }

  SuccessfulRendering=()=>{
    console.log('Successfully rendered!!')
  }

  updateSeries = () => {
    // The chart is updated only with new options.
    this.setState({
      chartOptions: {
        series: [
          { data: [Math.random() * 5, 2, 1]}
        ]
      }
    },()=>{
      this.SuccessfulRendering()
    });

  }

  render() {
    const { chartOptions, hoverData } = this.state;

    return (

        <HighchartsReact
          highcharts={Highcharts}
          options={chartOptions}
        />

Hovering over {hoverData}

      <button onClick={this.updateSeries.bind(this)}>Update Series</button>

    )
  }
}

render(<LineChart />, document.getElementById('root'),()=>{
});


问:
Error: An uncaught Exception was encountered
I receive this error:

An uncaught Exception was encountered Type: ArgumentCountError

Message: Too few arguments to function
  Home::cadastroOrcamentoCliente(), 0 passed in
  C:\xampp\htdocs\sistema_financas_old\system\core\CodeIgniter.php on
  line 532 and exactly 6 expected

Filename:
  C:\xampp\htdocs\sistema_financas_old\application\controllers\Home.php

Line Number: 1116

Backtrace:

File: C:\xampp\htdocs\sistema_financas_old\index.php Line: 315
  Function: require_once

This is my code:

```<code>//Inicio de desenvolvimento new window client.
    //New Página para gerar pedido de cliente.
    function cadastroOrcamentoCliente($cpfcnpj=null, $tipo_pessoa=null, $dados = null, $id_pf, $id_cliente, $id_cadastro) {
        $tipo_login = $this->session->userdata('tipo_login');
        if ($tipo_login == '1' || $tipo_login == '4' || $tipo_login == '5') {
            $dadosPessoa['tipo_pessoa'] = null;
            $dadosOrcamento['str'] = $this->load->view('admin/compras/popup_cadastro', $dadosPessoa, true);
            if ($tipo_pessoa == 1) {
                $dadosOrcamento['cpf'] = $cpfcnpj;
                $dadosOrcamento['cnpj'] = null;
            } else if ($tipo_pessoa == 2) {
                $dadosOrcamento['cpf'] = null;
                $dadosOrcamento['cnpj'] = $cpfcnpj;
            } else {
                $dadosOrcamento['cpf'] = $cpfcnpj;
                $dadosOrcamento['cnpj'] = $cpfcnpj;
            }

            if ($this->alteracao->editEndereco($id_cadastro) && $this->alteracao->editPessoaFisica($id_pf) &&
                $this->alteracao->editCliente($id_cliente) && $this->alteracao->editCadastroComum($id_cadastro) && $this->alteracao->editarDadosBancarios($id_cadastro)) {
            $data_cad = date("d/m/Y");
            $hora_cad = date("H:i:s");
            $this->alteracao->cadastroHistorico('Dados do cliente editados', $id_cadastro, $data_cad, $hora_cad);
            $this->alteracao->mensagemAlerta("Dados alterados com sucesso!", 1, "home/cadastros", $id_cadastro);

            $dadosOrcamento['orcamento'] = $this->compras_m->buscarOrcamentoAtual($this->session->userdata('id_orcamento'));
            $this->load->view('admin/head');
            $dadosBarra['dadosB'] = $this->financeiro->listaContas();
            $this->load->view('admin/barraSuperior', $dadosBarra);
            $dadosLogo['logo'] = $this->adm->retornaLogo();
            $this->load->view('admin/menu', $dadosLogo);
            $this->load->view('admin/vendas/cadastro_orcamento_cliente', $dadosOrcamento);
            $this->load->view('admin/footer');
        } else {
            $dados['mensagem'] = null;
            $this->paginas($dados);
        }
    }
    }
</code>```

im calling here

```<code> <form method="post" action="<?php echo site_url('pedido/cadastroOrcamentoVendaCliente') ?>">
</code>```

just create a new screen and need additional to the project

答:
This:

```<code>function cadastroOrcamentoCliente($cpfcnpj=null, $tipo_pessoa=null, $dados = null, $id_pf,
                                  $id_cliente, $id_cadastro)
</code>```

is fundamentally wrong to begin with.

https://www.php.net/manual/en/functions.arguments.php#functions.arguments.default:

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.

You need to change the order of your arguments here - the ones without default values need to come first, and the ones with only after that:

```<code>function cadastroOrcamentoCliente($id_pf, $id_cliente, $id_cadastro, $cpfcnpj=null,
                                  $tipo_pessoa=null, $dados = null)
</code>```

And then you will still have to provide values for at least the first three of them in your actual call of that function.

Body:
I receive this error:

An uncaught Exception was encountered Type: ArgumentCountError

Message: Too few arguments to function
  Home::cadastroOrcamentoCliente(), 0 passed in
  C:\xampp\htdocs\sistema_financas_old\system\core\CodeIgniter.php on
  line 532 and exactly 6 expected

Filename:
  C:\xampp\htdocs\sistema_financas_old\application\controllers\Home.php

Line Number: 1116

Backtrace:

File: C:\xampp\htdocs\sistema_financas_old\index.php Line: 315
  Function: require_once

This is my code:

//Inicio de desenvolvimento new window client.
    //New Página para gerar pedido de cliente.
    function cadastroOrcamentoCliente($cpfcnpj=null, $tipo_pessoa=null, $dados = null, $id_pf, $id_cliente, $id_cadastro) {
        $tipo_login = $this->session->userdata('tipo_login');
        if ($tipo_login == '1' || $tipo_login == '4' || $tipo_login == '5') {
            $dadosPessoa['tipo_pessoa'] = null;
            $dadosOrcamento['str'] = $this->load->view('admin/compras/popup_cadastro', $dadosPessoa, true);
            if ($tipo_pessoa == 1) {
                $dadosOrcamento['cpf'] = $cpfcnpj;
                $dadosOrcamento['cnpj'] = null;
            } else if ($tipo_pessoa == 2) {
                $dadosOrcamento['cpf'] = null;
                $dadosOrcamento['cnpj'] = $cpfcnpj;
            } else {
                $dadosOrcamento['cpf'] = $cpfcnpj;
                $dadosOrcamento['cnpj'] = $cpfcnpj;
            }

            if ($this->alteracao->editEndereco($id_cadastro) && $this->alteracao->editPessoaFisica($id_pf) &&
                $this->alteracao->editCliente($id_cliente) && $this->alteracao->editCadastroComum($id_cadastro) && $this->alteracao->editarDadosBancarios($id_cadastro)) {
            $data_cad = date("d/m/Y");
            $hora_cad = date("H:i:s");
            $this->alteracao->cadastroHistorico('Dados do cliente editados', $id_cadastro, $data_cad, $hora_cad);
            $this->alteracao->mensagemAlerta("Dados alterados com sucesso!", 1, "home/cadastros", $id_cadastro);

            $dadosOrcamento['orcamento'] = $this->compras_m->buscarOrcamentoAtual($this->session->userdata('id_orcamento'));
            $this->load->view('admin/head');
            $dadosBarra['dadosB'] = $this->financeiro->listaContas();
            $this->load->view('admin/barraSuperior', $dadosBarra);
            $dadosLogo['logo'] = $this->adm->retornaLogo();
            $this->load->view('admin/menu', $dadosLogo);
            $this->load->view('admin/vendas/cadastro_orcamento_cliente', $dadosOrcamento);
            $this->load->view('admin/footer');
        } else {
            $dados['mensagem'] = null;
            $this->paginas($dados);
        }
    }
    }

im calling here

 <form method="post" action="<?php echo site_url('pedido/cadastroOrcamentoVendaCliente') ?>">

just create a new screen and need additional to the project

Body:
This:

function cadastroOrcamentoCliente($cpfcnpj=null, $tipo_pessoa=null, $dados = null, $id_pf,
                                  $id_cliente, $id_cadastro)

is fundamentally wrong to begin with.

https://www.php.net/manual/en/functions.arguments.php#functions.arguments.default:

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.

You need to change the order of your arguments here - the ones without default values need to come first, and the ones with only after that:

function cadastroOrcamentoCliente($id_pf, $id_cliente, $id_cadastro, $cpfcnpj=null,
                                  $tipo_pessoa=null, $dados = null)

And then you will still have to provide values for at least the first three of them in your actual call of that function.


问:
How can I develop for iPhone using a Windows development machine?
Is there any way to tinker with the iPhone SDK on a Windows machine? Are there plans for an iPhone SDK version for Windows?

The only other way I can think of doing this is to run a Mac VM image on a VMWare server running on Windows, although I'm not too sure how legal this is.

答:
A devkit that allows one to develop iPhone apps in Objective-C, C++ or just plain C with Visual Studio:

Check it out at iOS build env

You can build iPhone apps directly within Visual Studio (2008, 2010, Express).

Pretty neat, it even builds IPA files for your app after a successful compilation. The code works as is on jailbroken devices, for the rest of the planet I believe the final compilation & submission to the App Store has to be done on a Mac. But still, it enables you to develop using a well-known IDE.

OwnerDisplayName: ryanmcc


问:
admin.site.register(Question) doesn't work
i am new to Django and python, and i want to start django admin with official exercises

i'm okay with running server. but questions doesn't show up.

my code is :

admin.py

```<code>from django.contrib import admin
from .models import Question

admin.site.register(Question)
</code>```

thank you for reading my question

答:
Want to have something like this, check out https://docs.djangoproject.com/en/3.0/ref/contrib/admin/ for more info</p>

```<code>from django.contrib import admin
from .models import Question

class QuestionAdmin(admin.ModelAdmin):
    pass
admin.site.register(Question, QuestionAdmin)
</code>```

Body:
i am new to Django and python, and i want to start django admin with official exercises

i'm okay with running server. but questions doesn't show up.

my code is :

admin.py

from django.contrib import admin
from .models import Question

admin.site.register(Question)

thank you for reading my question

Body:
Want to have something like this, check out https://docs.djangoproject.com/en/3.0/ref/contrib/admin/ for more info

from django.contrib import admin
from .models import Question

class QuestionAdmin(admin.ModelAdmin):
    pass
admin.site.register(Question, QuestionAdmin)


问:
How to loop over jq unique array in bash?
I'm trying to loop over unique names and commit messages from a github json object.  However when there are spaces in the arrays bash will treat them as individual array items

```<code>#!/usr/bin/env bash

commits='[
  {
    "author": {
      "email": "email@example.com",
      "name": "Chris",
      "username": "chris"
    },
    "committer": {
      "email": "email@example.com",
      "name": "Chris",
      "username": "chris"
    },
    "message": "commit message 1"
  },
  {
    "author": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "committer": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "message": "commit message 2"
  },
    {
    "author": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "committer": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "message": "commit message 3"
  }
]'

authors=$( jq -rc '[.[].author.name] | unique | @sh' <<<"${commits}" )
echo "authors: $authors"

# this works
for author in $authors
do
  echo "author: $author"
done

echo "------------"

# this does not
messages=$( jq -rc '[.[].message] | unique | @sh' <<<"${commits}" )
echo "messages: $messages"

for message in $messages
do
  echo "message: $message"
done
</code>```

Which outputs

```<code>authors: 'Chris' 'John'
author: 'Chris'
author: 'John'
------------
messages: 'commit message 1' 'commit message 2' 'commit message 3'
message: 'commit
message: message
message: 1'
message: 'commit
message: message
message: 2'
message: 'commit
message: message
message: 3'
</code>```

While I expect:

```<code>authors: 'Chris' 'John'
author: 'Chris'
author: 'John'
------------
messages: 'commit message 1' 'commit message 2' 'commit message 3'
message: 'commit message 1'
message: 'commit message 2'
message: 'commit message 3'
</code>```

答:
Works with change ' ' to '_' and back

```<code>messages=$( jq -rc '[.[].message] | unique | @sh' <<<"${commits}" )
messages="${messages// /_}"
messages=(${messages//"'_'"/"' '"})
echo "messages: ${messages[@]//_/ }"
for message in "${messages[@]//_/ }"
do
  echo " message: $message"
done
</code>```

Or like this

```<code>IFS=$'\n' messages=( $(jq -rc '.[].message' <<<"${commits}") )
printf   "messages: "; printf "'%s' " "${messages[@]}"; echo
printf   " message: '%s' \n"          "${messages[@]}"
</code>```

And we could do something like that

```<code>     IFS=$'\n'
 authors=($(jq -rc '.[].author.name' <<<"${commits}"))
messages=($(jq -rc '.[].message'     <<<"${commits}"))
printf " authors | "; printf "'%s' " "${authors[@]}" ; echo
printf "  author | '%s' \n"          "${authors[@]}"
echo   "---------+---------"
printf "messages | "; printf "'%s' " "${messages[@]}"; echo
printf " message | '%s' \n"          "${messages[@]}"
</code>```

To output like this

```<code> authors | 'Chris' 'John' 'John'
  author | 'Chris'
  author | 'John'
  author | 'John'
---------+---------
messages | 'commit message 1' 'commit message 2' 'commit message 3'
 message | 'commit message 1'
 message | 'commit message 2'
 message | 'commit message 3'
</code>```

Body:
I'm trying to loop over unique names and commit messages from a github json object.  However when there are spaces in the arrays bash will treat them as individual array items

#!/usr/bin/env bash

commits='[
  {
    "author": {
      "email": "email@example.com",
      "name": "Chris",
      "username": "chris"
    },
    "committer": {
      "email": "email@example.com",
      "name": "Chris",
      "username": "chris"
    },
    "message": "commit message 1"
  },
  {
    "author": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "committer": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "message": "commit message 2"
  },
    {
    "author": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "committer": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "message": "commit message 3"
  }
]'

authors=$( jq -rc '[.[].author.name] | unique | @sh' <<<"${commits}" )
echo "authors: $authors"

# this works
for author in $authors
do
  echo "author: $author"
done

echo "------------"

# this does not
messages=$( jq -rc '[.[].message] | unique | @sh' <<<"${commits}" )
echo "messages: $messages"

for message in $messages
do
  echo "message: $message"
done

Which outputs

authors: 'Chris' 'John'
author: 'Chris'
author: 'John'
------------
messages: 'commit message 1' 'commit message 2' 'commit message 3'
message: 'commit
message: message
message: 1'
message: 'commit
message: message
message: 2'
message: 'commit
message: message
message: 3'

While I expect:

authors: 'Chris' 'John'
author: 'Chris'
author: 'John'
------------
messages: 'commit message 1' 'commit message 2' 'commit message 3'
message: 'commit message 1'
message: 'commit message 2'
message: 'commit message 3'

Body:
Works with change ' ' to '_' and back

messages=$( jq -rc '[.[].message] | unique | @sh' <<<"${commits}" )
messages="${messages// /_}"
messages=(${messages//"'_'"/"' '"})
echo "messages: ${messages[@]//_/ }"
for message in "${messages[@]//_/ }"
do
  echo " message: $message"
done

Or like this

IFS=$'\n' messages=( $(jq -rc '.[].message' <<<"${commits}") )
printf   "messages: "; printf "'%s' " "${messages[@]}"; echo
printf   " message: '%s' \n"          "${messages[@]}"

And we could do something like that

     IFS=$'\n'
 authors=($(jq -rc '.[].author.name' <<<"${commits}"))
messages=($(jq -rc '.[].message'     <<<"${commits}"))
printf " authors | "; printf "'%s' " "${authors[@]}" ; echo
printf "  author | '%s' \n"          "${authors[@]}"
echo   "---------+---------"
printf "messages | "; printf "'%s' " "${messages[@]}"; echo
printf " message | '%s' \n"          "${messages[@]}"

To output like this

 authors | 'Chris' 'John' 'John'
  author | 'Chris'
  author | 'John'
  author | 'John'
---------+---------
messages | 'commit message 1' 'commit message 2' 'commit message 3'
 message | 'commit message 1'
 message | 'commit message 2'
 message | 'commit message 3'


问:
llvm pass to flatten (some) nested loops
I want to automatically rewrite simple nested loops as non nested ones.
For example, I have the following code:

```<code>if (y >= 0)
{
    while (x>y)
    {
        x -= y+1;
        for (z=y; z>0; z--) /* nothing */;
    }
}

</code>```

And I would like some llvm magic to happen so that it becomes:

```<code>if (y >= 0)
{
    bool outer = true;
    while (x>y)
    {
        if (outer) { z = y;                  }
        if (z > 0) { z--;     outer = false; }
        else       { x-= y+1; outer = true;  }
    }
}
</code>```

Am I being over optimistic thinking such a pass exists?
I tried writing opt --help > /tmp/passes.txt && grep "loop" /tmp/passes.txt
but there are so many loop passes I don't know where to start.

答:
This optimization is called loop fusion. I haven't tried your code but Polly should be able to fuse such loops. Polly is the polyhedral compiler framework that ships with LLVM but it should build with LLVM by default. If it does not then you'd need to pass  -DLLVM_POLLY_BUILD:BOOL=ON to cmake to build polly with llvm.

Here's the documentation on how to invoke polly optimizations with clang/llvm.

https://polly.llvm.org/docs/UsingPollyWithClang.html#optimizing-with-polly

Body:
I want to automatically rewrite simple nested loops as non nested ones.
For example, I have the following code:

if (y >= 0)
{
    while (x>y)
    {
        x -= y+1;
        for (z=y; z>0; z--) /* nothing */;
    }
}

And I would like some llvm magic to happen so that it becomes:

if (y >= 0)
{
    bool outer = true;
    while (x>y)
    {
        if (outer) { z = y;                  }
        if (z > 0) { z--;     outer = false; }
        else       { x-= y+1; outer = true;  }
    }
}

Am I being over optimistic thinking such a pass exists?
I tried writing opt --help > /tmp/passes.txt && grep "loop" /tmp/passes.txt
but there are so many loop passes I don't know where to start.


问:
argparse: how to get all arguments after specific key?
for example:

python foo.py --foo foo --bar bar --args -a 5 --baz 6
```

--foo and --bar are regular arguments, but --args is special, it should contain list of args after it: [-a, 5, --baz, 6].

I remember that something similar exists but I cannot remember how it is called.

答:
Try to use argparse.REMAINDER:

```<code>import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--foo')
parser.add_argument('--bar')
parser.add_argument('--args', nargs=argparse.REMAINDER)

print(parser.parse_args())
</code>```

When running python foo.py --foo foo --bar bar --args -a 5 --baz 6 this returns:

```<code>Namespace(args=['-a', '5', '--baz', '6'], bar='bar', foo='foo')
</code>```

Body:
for example:

python foo.py --foo foo --bar bar --args -a 5 --baz 6

--foo and --bar are regular arguments, but --args is special, it should contain list of args after it: [-a, 5, --baz, 6].

I remember that something similar exists but I cannot remember how it is called.

Body:
Try to use argparse.REMAINDER:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--foo')
parser.add_argument('--bar')
parser.add_argument('--args', nargs=argparse.REMAINDER)

print(parser.parse_args())

When running python foo.py --foo foo --bar bar --args -a 5 --baz 6 this returns:

Namespace(args=['-a', '5', '--baz', '6'], bar='bar', foo='foo')


问:
does DateTime keep itself updated in C#?
I am trying to create a folder based off of the current month/day using DateTime. After i initialize a new DateTime( 2011, 5, 16, 1, 1, 30); will this keep itself updated or reset every time the program is ran?</p>

答: Why don't you just use DateTime.Now

Body: Why don't you just use DateTime.Now


问:
Deploying spring boot application to heroku - error message "No web processes running"
I created a spring boot web application (in IntelliJ IDEA), which runs locally without problems.

I then built an artifact (Build -> Build Artifacts... -> my_app:jar -> Build), which created a jar file in directory "out".

I tried to deploy the app to heroku following exactly the steps described in this walkthrough by heroku: https://devcenter.heroku.com/articles/deploying-spring-boot-apps-to-heroku

Note: the walkthrough does not mention a Procfile so I didn't create one.

When opening the app's address in the browser I faced an "Application error".

The logs show that building the app was successful but there are apparently "No web processes running":

2020-02-06T20:42:19.262364+00:00 app[api]: Release v1 created by user
  michaels@icloud.com 2020-02-06T20:42:19.598724+00:00 app[api]:
  Release v2 created by user michaels@icloud.com
  2020-02-06T20:42:19.262364+00:00 app[api]: Initial release by user
  michaels@icloud.com 2020-02-06T20:42:19.598724+00:00 app[api]:
  Enable Logplex by user michaels@icloud.com
  2020-02-06T20:46:11.000000+00:00 app[api]: Build started by user
  michaels@icloud.com 2020-02-06T20:46:56.626428+00:00 app[api]:
  Release v3 created by user michaels@icloud.com
  2020-02-06T20:46:56.626428+00:00 app[api]: Deploy 93b6dfea by user
  michaels@icloud.com 2020-02-06T20:47:04.000000+00:00 app[api]:
  Build succeeded 2020-02-06T20:48:22.485742+00:00 heroku[router]:
  at=error code=H14 desc="No web processes running" method=GET path="/"
  host=my-app.herokuapp.com
  request_id=22e30a92-5094-4f8b-a51c-3f21177b19dc fwd="95.88.203.176"
  dyno= connect= service= status=503 bytes= protocol=https

I checked whether a dyno was running using the following command:

```<code>heroku ps
</code>```

Result:

No dynos on ⬢ infinite-sky-81114

I then ran the following command to start a dyno:

```<code>heroku ps:scale web=1
</code>```

Result:

Scaling dynos... !  ▸    Couldn't find that process type (web).

So the application doesn't run because there is no dyno - but I am not able to start a dyno.

How can I make this work?

答:
a more flexible approach is to use the Heroku Container Registry which allows to run your Docker-based application.

This approach allows to run the very same application image you build/test locally and does not require to add Heroku-specific configuration (Procfile).

Prerequisites

Working Docker and Heroku client, and ensure your account is already authenticated:

login to Heroku heroku login

login to  Container Registry heroku container:login

Define Docker image

Create a Dockerfile

```<code>FROM adoptopenjdk/openjdk11:latest

RUN mkdir -p /software
ADD target/myapp.jar /software/myapp.jar
CMD java -Dserver.port=$PORT $JAVA_OPTS -jar /software/myapp.jar
</code>```

Note: injecting the env variable $PORT is necessary to run the SpringBoot application on Heroku

build the image

```<code>docker build -t mydomain/myapp .
</code>```

and test locally

```<code>docker run -it --name myapp -p 8886:8886 mydomain/myapp
</code>```

Note: in the example above your application.properties defines server.port=8886 to use 8886 as port of your Spring Boot application

Tag, push and deploy to Heroku

Next tag the image then push it to Heroku:

```<code>docker tag mydomain/myapp registry.heroku.com/myapp/web
docker push registry.heroku.com/myapp/web
</code>```

Finally the application can start:

```<code>heroku container:release web -a myapp
</code>```

You can also scale up (or down) the application:

```<code># undeploy
heroku ps:scale web=0 --app myapp
</code>```

Reference

See https://devcenter.heroku.com/articles/container-registry-and-runtime

Body:
I created a spring boot web application (in IntelliJ IDEA), which runs locally without problems.

I then built an artifact (Build -> Build Artifacts... -> my_app:jar -> Build), which created a jar file in directory "out".

I tried to deploy the app to heroku following exactly the steps described in this walkthrough by heroku: https://devcenter.heroku.com/articles/deploying-spring-boot-apps-to-heroku

Note: the walkthrough does not mention a Procfile so I didn't create one.

When opening the app's address in the browser I faced an "Application error".

The logs show that building the app was successful but there are apparently "No web processes running":

2020-02-06T20:42:19.262364+00:00 app[api]: Release v1 created by user
  michaels@icloud.com 2020-02-06T20:42:19.598724+00:00 app[api]:
  Release v2 created by user michaels@icloud.com
  2020-02-06T20:42:19.262364+00:00 app[api]: Initial release by user
  michaels@icloud.com 2020-02-06T20:42:19.598724+00:00 app[api]:
  Enable Logplex by user michaels@icloud.com
  2020-02-06T20:46:11.000000+00:00 app[api]: Build started by user
  michaels@icloud.com 2020-02-06T20:46:56.626428+00:00 app[api]:
  Release v3 created by user michaels@icloud.com
  2020-02-06T20:46:56.626428+00:00 app[api]: Deploy 93b6dfea by user
  michaels@icloud.com 2020-02-06T20:47:04.000000+00:00 app[api]:
  Build succeeded 2020-02-06T20:48:22.485742+00:00 heroku[router]:
  at=error code=H14 desc="No web processes running" method=GET path="/"
  host=my-app.herokuapp.com
  request_id=22e30a92-5094-4f8b-a51c-3f21177b19dc fwd="95.88.203.176"
  dyno= connect= service= status=503 bytes= protocol=https

I checked whether a dyno was running using the following command:

heroku ps

Result:

No dynos on ⬢ infinite-sky-81114

I then ran the following command to start a dyno:

heroku ps:scale web=1

Result:

Scaling dynos... !  ▸    Couldn't find that process type (web).

So the application doesn't run because there is no dyno - but I am not able to start a dyno.

How can I make this work?

Body:
a more flexible approach is to use the Heroku Container Registry which allows to run your Docker-based application.

This approach allows to run the very same application image you build/test locally and does not require to add Heroku-specific configuration (Procfile).

Prerequisites

Working Docker and Heroku client, and ensure your account is already authenticated:

login to Heroku heroku login

login to  Container Registry heroku container:login

Define Docker image

Create a Dockerfile

FROM adoptopenjdk/openjdk11:latest

RUN mkdir -p /software
ADD target/myapp.jar /software/myapp.jar
CMD java -Dserver.port=$PORT $JAVA_OPTS -jar /software/myapp.jar

Note: injecting the env variable $PORT is necessary to run the SpringBoot application on Heroku

build the image

docker build -t mydomain/myapp .

and test locally

docker run -it --name myapp -p 8886:8886 mydomain/myapp

Note: in the example above your application.properties defines server.port=8886 to use 8886 as port of your Spring Boot application

Tag, push and deploy to Heroku

Next tag the image then push it to Heroku:

docker tag mydomain/myapp registry.heroku.com/myapp/web
docker push registry.heroku.com/myapp/web

Finally the application can start:

heroku container:release web -a myapp

You can also scale up (or down) the application:

# undeploy
heroku ps:scale web=0 --app myapp

Reference

See https://devcenter.heroku.com/articles/container-registry-and-runtime


问:
Error during cmake build : CXX compiler must support Cilk
I am trying to install cilk++ according to this website and am at the steps in section "Cilk Plus Runtime". When I go to build, I get the following output:

```<code>$ cmake -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_INSTALL_PREFIX=./install ..
CMake Error at CMakeLists.txt:132 (message):
  CXX compiler must support Cilk.

-- Configuring incomplete, errors occurred!
See also "/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/cilkrts-0.1.2/build/CMakeFiles/CMakeOutput.log".
See also "/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/cilkrts-0.1.2/build/CMakeFiles/CMakeError.log".
</code>```

I thought clang and clang++ (which I checked with --version are indeed installed) would be sufficient. Do I need to update clang and clang++? There are no troubleshooting steps on the instructions website, so I'm not sure what I need to do to finally get cilk++ up and running on my laptop.

Thanks in advance,

Anthony

答:
Expanding on my comment:

When you configure this Cilk Plus Runtime with CMake, CMake first verifies the compiler by attempting to compile a simple test program (see here). If the compilation fails, CMake prints the error you see:

```<code>CMake Error at CMakeLists.txt:132 (message):
  CXX compiler must support Cilk.
</code>```

On the Intel Cilk Plus runtime Github page (cilkrts), it has some compiler requirements listed for those trying to build this library:

You need the CMake tool and a C/C++ compiler that supports the Cilk language extensions. The requirements for each operating systems are:

Common: CMake 3.4.3 or later Make tools such as make

Linux: Tapir/LLVM compiler, or GCC* 4.9.2 or later (depracated), or Cilk-enabled branch of Clang*/LLVM* (http://cilkplus.github.io), or Intel(R) C++ Compiler v12.1 or later (depracated)

OS X: Tapir/LLVM compiler, or Cilk-enabled branch of Clang*/LLVM* (http://cilkplus.github.io), or Intel C++ Compiler v12.1 or later (depracated)

Since you are using Clang as your compiler, be sure it is a Cilk-enabled branch of Clang, as specified in the requirements. Or, you can try to use the Tapir/LLVM compiler.

Body:
I am trying to install cilk++ according to this website and am at the steps in section "Cilk Plus Runtime". When I go to build, I get the following output:

$ cmake -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_INSTALL_PREFIX=./install ..
CMake Error at CMakeLists.txt:132 (message):
  CXX compiler must support Cilk.

-- Configuring incomplete, errors occurred!
See also "/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/cilkrts-0.1.2/build/CMakeFiles/CMakeOutput.log".
See also "/Users/anthonymcknight/Documents/cubing/bfs/lab4/cilk/cilkrts-0.1.2/build/CMakeFiles/CMakeError.log".

I thought clang and clang++ (which I checked with --version are indeed installed) would be sufficient. Do I need to update clang and clang++? There are no troubleshooting steps on the instructions website, so I'm not sure what I need to do to finally get cilk++ up and running on my laptop.

Thanks in advance,

Anthony

Body:
Expanding on my comment:

When you configure this Cilk Plus Runtime with CMake, CMake first verifies the compiler by attempting to compile a simple test program (see here). If the compilation fails, CMake prints the error you see:

CMake Error at CMakeLists.txt:132 (message):
  CXX compiler must support Cilk.

On the Intel Cilk Plus runtime Github page (cilkrts), it has some compiler requirements listed for those trying to build this library:

You need the CMake tool and a C/C++ compiler that supports the Cilk language extensions. The requirements for each operating systems are:

Common: CMake 3.4.3 or later Make tools such as make

Linux: Tapir/LLVM compiler, or GCC* 4.9.2 or later (depracated), or Cilk-enabled branch of Clang*/LLVM* (http://cilkplus.github.io), or Intel(R) C++ Compiler v12.1 or later (depracated)

OS X: Tapir/LLVM compiler, or Cilk-enabled branch of Clang*/LLVM* (http://cilkplus.github.io), or Intel C++ Compiler v12.1 or later (depracated)

Since you are using Clang as your compiler, be sure it is a Cilk-enabled branch of Clang, as specified in the requirements. Or, you can try to use the Tapir/LLVM compiler.


问:
How to append in json file at specific position
I'm trying to append JSON objects to a file at specific position but I'm unable to do it as required. I get result but without "," separating the values, so they are separate JSON objects.

I want to loop through JSON objects and append the result to a file and separate it with "," and it is a valid JSON. Here is what I tried

```<code>
auto js_text = R"(
{
  "a": "all_items",
  "b": []
}
        )";
    std::ofstream js_file("test.json");
    js_file << std::setw(4) << js_text << std::endl;
    std::ifstream in("test4.json");
    json js_file = json::parse(in);
    std::ifstream load_url("url_file.json");
    json url_file = json::parse(load_url);
   for (auto& endpoint : url_file["url_list"])
        {
    std::string url = endpoint["url"].get<std::string>();
    auto r = cpr::Get(cpr::Url{ url });
    json j = json::parse(r.text); // r gets a nested json objects from parsed url
    for (auto& td : j["b"])
     {
      json value = j["b"][0];
      json data = js_file;
      data["b"][0] = value;
      std::ofstream output;
      output.open("test.json",std::ios_base::app );
      output << std::setw(4) << data << std::endl;
}

</code>```

Result I want is

```<code>{
  "a": "all_items",
  "b": [
    {
      "c": "xxx",
      "d": "yyy"
    },
    {
      "e": "zzz"
    }
  ]
}

</code>```

Updated Code: after Botje valuable input.

```<code>     auto js_text = R"(
        {
           "a": "abc",
             "b": [ ]
           }
           )";

    json js_file = json::parse(js_text);

     std::ifstream load_url("url_file.json");
    json url_file = json::parse(load_url);

    for (auto& endpoint : url_file["url_list"])
     {
      std::string url = endpoint["url"].get<std::string>();
      auto r = cpr::Get(cpr::Url{ url });
      json j = json::parse(r.text); // j contains results from multiple HTTP requests that has json objects.
       for (auto& elem : j["b"])
            {
              json jd = j["b"];
              js_file["b"].emplace_back(std::move(td));
              std::cout << "jd:" << jd.dump(4) << std::endl;
         }
       }

      std::ofstream output;
      output.open("test.json",std::ios_base::app );
      output << std::setw(4) << js_file << std::endl;
    }

</code>```

Hope this help others.

答:
As I understand your question, you want to make multiple HTTP requests and collect all objects under each response's "b" key into an array.

Here, we skip the HTTP part and assume each element of r_texts is one response object.

```<code>std::vector<std::string> r_texts = {
    R"({
        "b": [{
            "c": "xxx",
            "d": "yyy"
        }]
    })",
    R"({
        "b": [{
            "e": "zzz"
        }]
    })",
};
</code>```

This produces the output you wanted, then:

```<code>auto js_text = R"(
{
  "a": "abc",
  "b": []
}
)";

int main() {
    json js_file = json::parse(js_text);
    for (auto& r_text: r_texts) {
        // r_text is now the contents of one "HTTP response"
        json j = json::parse(r_text);
        // Loop over all objects inside the "b" key
        for (auto & elem: j["b"]) {
            // And use emplace_back+move to detach the object from `j`
            // and move it to the back of `js_file["b"]`.
            js_file["b"].emplace_back(std::move(elem));
        }
    }

    std::ofstream output;
    output.open("test.json",std::ios_base::app );
    output << std::setw(4) << js_file << std::endl;
}
</code>```

Body:
I'm trying to append JSON objects to a file at specific position but I'm unable to do it as required. I get result but without "," separating the values, so they are separate JSON objects.

I want to loop through JSON objects and append the result to a file and separate it with "," and it is a valid JSON. Here is what I tried

auto js_text = R"(
{
  "a": "all_items",
  "b": []
}
        )";
    std::ofstream js_file("test.json");
    js_file << std::setw(4) << js_text << std::endl;
    std::ifstream in("test4.json");
    json js_file = json::parse(in);
    std::ifstream load_url("url_file.json");
    json url_file = json::parse(load_url);
   for (auto& endpoint : url_file["url_list"])
        {
    std::string url = endpoint["url"].get<std::string>();
    auto r = cpr::Get(cpr::Url{ url });
    json j = json::parse(r.text); // r gets a nested json objects from parsed url
    for (auto& td : j["b"])
     {
      json value = j["b"][0];
      json data = js_file;
      data["b"][0] = value;
      std::ofstream output;
      output.open("test.json",std::ios_base::app );
      output << std::setw(4) << data << std::endl;
}

Result I want is

{
  "a": "all_items",
  "b": [
    {
      "c": "xxx",
      "d": "yyy"
    },
    {
      "e": "zzz"
    }
  ]
}

Updated Code: after Botje valuable input.

     auto js_text = R"(
        {
           "a": "abc",
             "b": [ ]
           }
           )";

    json js_file = json::parse(js_text);

     std::ifstream load_url("url_file.json");
    json url_file = json::parse(load_url);

    for (auto& endpoint : url_file["url_list"])
     {
      std::string url = endpoint["url"].get<std::string>();
      auto r = cpr::Get(cpr::Url{ url });
      json j = json::parse(r.text); // j contains results from multiple HTTP requests that has json objects.
       for (auto& elem : j["b"])
            {
              json jd = j["b"];
              js_file["b"].emplace_back(std::move(td));
              std::cout << "jd:" << jd.dump(4) << std::endl;
         }
       }

      std::ofstream output;
      output.open("test.json",std::ios_base::app );
      output << std::setw(4) << js_file << std::endl;
    }

Hope this help others.

Body:
As I understand your question, you want to make multiple HTTP requests and collect all objects under each response's "b" key into an array.

Here, we skip the HTTP part and assume each element of r_texts is one response object.

std::vector<std::string> r_texts = {
    R"({
        "b": [{
            "c": "xxx",
            "d": "yyy"
        }]
    })",
    R"({
        "b": [{
            "e": "zzz"
        }]
    })",
};

This produces the output you wanted, then:

auto js_text = R"(
{
  "a": "abc",
  "b": []
}
)";

int main() {
    json js_file = json::parse(js_text);
    for (auto& r_text: r_texts) {
        // r_text is now the contents of one "HTTP response"
        json j = json::parse(r_text);
        // Loop over all objects inside the "b" key
        for (auto & elem: j["b"]) {
            // And use emplace_back+move to detach the object from `j`
            // and move it to the back of `js_file["b"]`.
            js_file["b"].emplace_back(std::move(elem));
        }
    }

    std::ofstream output;
    output.open("test.json",std::ios_base::app );
    output << std::setw(4) << js_file << std::endl;
}


问:
Simple Search Using PHP and MySQL PROBLEM
I have a simple search bar problem thats driving me crazy!

I've followed a simple walk through and for the life of me cant get the thing running.
https://owlcation.com/stem/Simple-search-PHP-MySQL

Im using XAMPP localHost, created the tutorial search database & articles table they requestd and still nothing...

But all I seem to get right now is...
...

```<code>Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\searchBar\search.php:2 Stack trace: #0 {main} thrown in C:\xampp\htdocs\searchBar\search.php on line 2
</code>```

...

with the search.php code looking like this-

...

```<code><?php
    mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
    /*
        localhost - it's location of the mysql server, usually localhost
        root - your username
        third is your password

        if connection fails it will stop loading the page and display an error
    */

    mysql_select_db("tutorial_search") or die(mysql_error());
    /* tutorial_search is the name of database we've created */
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Search results</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<?php
    $query = $_GET['query'];
    // gets value sent over search form

    $min_length = 3;
    // you can set minimum length of the query if you want

    if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then

        $query = htmlspecialchars($query);
        // changes characters used in html to their equivalents, for example: < to >

        $query = mysql_real_escape_string($query);
        // makes sure nobody uses SQL injection

        $raw_results = mysql_query("SELECT * FROM articles
            WHERE (`title` LIKE '%".$query."%') OR (`text` LIKE '%".$query."%')") or die(mysql_error());

        // * means that it selects all fields, you can also write: `id`, `title`, `text`
        // articles is the name of our table

        // '%$query%' is what we're looking for, % means anything, for example if $query is Hello
        // it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
        // or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'

        if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following

            while($results = mysql_fetch_array($raw_results)){
            // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop

                echo "<p><h3>".$results['title']."</h3>".$results['text']."</p>";
                // posts results gotten from database(title and text) you can also show id ($results['id'])
            }

        }
        else{ // if there is no matching rows do following
            echo "No results";
        }

    }
    else{ // if query length is less than minimum
        echo "Minimum length is ".$min_length;
    }
?>
</body>
</html>
</code>```

...

if someone could help it would be appreciated as I feel a bit stupid right now.

Cheers, Dave.

答:
You seem to follow an old tutorial.
According to https://www.php.net/manual/en/function.mysql-connect.php was removed starting from PHP version 7. You should use mysqli_connect.</p>

Body:
I have a simple search bar problem thats driving me crazy!

I've followed a simple walk through and for the life of me cant get the thing running.
https://owlcation.com/stem/Simple-search-PHP-MySQL

Im using XAMPP localHost, created the tutorial search database & articles table they requestd and still nothing...

But all I seem to get right now is...
...

Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\searchBar\search.php:2 Stack trace: #0 {main} thrown in C:\xampp\htdocs\searchBar\search.php on line 2

...

with the search.php code looking like this-

...

<?php
    mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
    /*
        localhost - it's location of the mysql server, usually localhost
        root - your username
        third is your password

        if connection fails it will stop loading the page and display an error
    */

    mysql_select_db("tutorial_search") or die(mysql_error());
    /* tutorial_search is the name of database we've created */
?>

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

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

<?php
    $query = $_GET['query'];
    // gets value sent over search form

    $min_length = 3;
    // you can set minimum length of the query if you want

    if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then

        $query = htmlspecialchars($query);
        // changes characters used in html to their equivalents, for example: < to >

        $query = mysql_real_escape_string($query);
        // makes sure nobody uses SQL injection

        $raw_results = mysql_query("SELECT * FROM articles
            WHERE (`title` LIKE '%".$query."%') OR (`text` LIKE '%".$query."%')") or die(mysql_error());

        // * means that it selects all fields, you can also write: `id`, `title`, `text`
        // articles is the name of our table

        // '%$query%' is what we're looking for, % means anything, for example if $query is Hello
        // it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
        // or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'

        if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following

            while($results = mysql_fetch_array($raw_results)){
            // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop

                echo "

".$results['title']."
".$results['text']."
";
                // posts results gotten from database(title and text) you can also show id ($results['id'])
            }

        }
        else{ // if there is no matching rows do following
            echo "No results";
        }

    }
    else{ // if query length is less than minimum
        echo "Minimum length is ".$min_length;
    }
?>

...

if someone could help it would be appreciated as I feel a bit stupid right now.

Cheers, Dave.


问:
WCF bindings/security configuration for Intranet that uses Mac and Windows?
What bindings and security configurations are best for an environment with Windows and Mac Computers?</p>

答:
BasicHttpBinding will probably have the greatest reach. Just about every platform supports it, since the data is simply sent as an HTTP POST to a specific Uri -- any platform which has a web browser can use this binding.

You can do an HTTPs binding with BasicHttpBinding as well -- so you can still secure your data. You can also use security like TransportWithMessageCredential to provide username/password validation.


问:
Search data from API using ID
I want to fetch data from an API using as a parameter ID of a post from that API.
I created this app:

   import React, {useEffect, useState} from 'react';

const GetData = () => {
        let [inputVal, setInputVal] = useState('');
        let [idApi, setidApi] = useState("");
        let [res, setRes] = useState('loading...');

        function searchInfo(e) {
            setInputVal(e.target.value);
            // console.log(inputVal);
        }

        useEffect(() => {
            getInfo();
            console.log("re")
        }, [idApi])
        const getInfo = () => {
            const fetchData = async () => {
                setidApi(inputVal)
                const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${idApi}`);
                const data = await response.json();
                const r = data[0].title;
                setRes(r);
                console.log(r)
            };
            fetchData();
        };

        return (

{res}

                <input onChange={searchInfo} type="text" className='input-search'/>
                <button onClick={getInfo}>Fetch</button>

        );
    }
;

export default GetData;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

Clicking on the button i want to set the idApi using the input value (inputVal), and to get the data what will correspond with the setted ID. For this i wrote this code: setidApi(inputVal), but it doesn't work. Who can explain how to solve the issue?

答:
You have to change order for setting value then calling api like below:</p>

```<code>const getInfo = () => {
        const fetchData = async () => {
          setidApi(inputVal)
            const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${idApi}`);
            const data = await response.json();

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

Title: Search data from API using ID

Body:
I want to fetch data from an API using as a parameter ID of a post from that API.
I created this app:

   import React, {useEffect, useState} from 'react';

const GetData = () => {
        let [inputVal, setInputVal] = useState('');
        let [idApi, setidApi] = useState("");
        let [res, setRes] = useState('loading...');

        function searchInfo(e) {
            setInputVal(e.target.value);
            // console.log(inputVal);
        }

        useEffect(() => {
            getInfo();
            console.log("re")
        }, [idApi])
        const getInfo = () => {
            const fetchData = async () => {
                setidApi(inputVal)
                const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${idApi}`);
                const data = await response.json();
                const r = data[0].title;
                setRes(r);
                console.log(r)
            };
            fetchData();
        };

        return (

{res}

                <input onChange={searchInfo} type="text" className='input-search'/>
                <button onClick={getInfo}>Fetch</button>

        );
    }
;

export default GetData;

Clicking on the button i want to set the idApi using the input value (inputVal), and to get the data what will correspond with the setted ID. For this i wrote this code: setidApi(inputVal), but it doesn't work. Who can explain how to solve the issue?

Body:
You have to change order for setting value then calling api like below:

const getInfo = () => {
        const fetchData = async () => {
          setidApi(inputVal)
            const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${idApi}`);
            const data = await response.json();

            console.log(data)
        };
        fetchData();
    };


问:
Oracle 19C database issue
I have a package working fine in 11g version.

But when I deploy the same package in 19c version, the behavior is different.

PFB the description.

Package specification has an cursor and created a table type with cursor%rowtype.
Having a pipelined function which returns the table type.

Using the function with table clause

```<code>select * from table(function)
</code>```

so that the return value can act as a table and I can read the result with column names.

In 11g, the function is returning the column headers same as the cursor column names.
But in 19c, the function is returning column headers like 'Attr_1, Attr_2, etc'.

I need the function to return the column headers as the cursor columns names.

Note: Code can't be shared as it is very sensitive.

Sample:
PFB the sample.

```<code>Create table tb_test (id number, description varchar2 (50));

create or replace package pkg_test is
    cursor cur_test is
        select *
        from tb_test
        where 1=2;
    type typ_cur_test is table of cur_test%rowtype;
    function fn_test(p_rows in number) return typ_cur_test pipelined;
end;

create or replace package body pkg_test is
    function fn_test(p_rows in number) return typ_cur_test pipelined as
    l_tab typ_cur_test := cur_typ_test();
    begin
        for i in 1..p_rows loop l_tab.extend;
            l_tab(i).Id := i;
            l_tab(i). Description := 'test';
            pipe roe(l_tab(i));
        end loop;
    return ;
    end;
end pkg_test;

Select * from table(pkg_test.fn_test(2));
</code>```

In 11g, the above select gives column headers as "id, description", but in 19c i am getting as "ATTR_1, ATTR_2".

Please help.

答:
Solution for your issue could be:

```<code>create or replace package pkg_test is
    cursor cur_test is
        select *
        from tb_test
        where 1=2;
    type typ_cur_test is table of {tb_test}%rowtype;
    function fn_test(p_rows in number) return typ_cur_test pipelined;
end;
</code>```

Was able to reproduce the explained behavior. On 19c -> Attr_1, Attr_2 on 11 -> ID, Description

Workaround I found is use base table/view%rowtype instead of cursor%rowtype.

Title: Oracle 19C database issue

Body:
I have a package working fine in 11g version.

But when I deploy the same package in 19c version, the behavior is different.

PFB the description.

Package specification has an cursor and created a table type with cursor%rowtype.
Having a pipelined function which returns the table type.

Using the function with table clause

select * from table(function)

so that the return value can act as a table and I can read the result with column names.

In 11g, the function is returning the column headers same as the cursor column names.
But in 19c, the function is returning column headers like 'Attr_1, Attr_2, etc'.

I need the function to return the column headers as the cursor columns names.

Note: Code can't be shared as it is very sensitive.

Sample:
PFB the sample.

Create table tb_test (id number, description varchar2 (50));

create or replace package pkg_test is
    cursor cur_test is
        select *
        from tb_test
        where 1=2;
    type typ_cur_test is table of cur_test%rowtype;
    function fn_test(p_rows in number) return typ_cur_test pipelined;
end;

create or replace package body pkg_test is
    function fn_test(p_rows in number) return typ_cur_test pipelined as
    l_tab typ_cur_test := cur_typ_test();
    begin
        for i in 1..p_rows loop l_tab.extend;
            l_tab(i).Id := i;
            l_tab(i). Description := 'test';
            pipe roe(l_tab(i));
        end loop;
    return ;
    end;
end pkg_test;

Select * from table(pkg_test.fn_test(2));

In 11g, the above select gives column headers as "id, description", but in 19c i am getting as "ATTR_1, ATTR_2".

Please help.

Body:
Solution for your issue could be:

create or replace package pkg_test is
    cursor cur_test is
        select *
        from tb_test
        where 1=2;
    type typ_cur_test is table of {tb_test}%rowtype;
    function fn_test(p_rows in number) return typ_cur_test pipelined;
end;

Was able to reproduce the explained behavior. On 19c -> Attr_1, Attr_2 on 11 -> ID, Description

Workaround I found is use base table/view%rowtype instead of cursor%rowtype.


问:
Why can't I connect to http server on localhost through a browser?
I wrote a very simple Java http server for exercising purposes. I test it with cURL and everything seems to work fine but when I try to send a request from a browser

```<code>http://localhost:6666/
</code>```

the server does not respond. I even put a marking System.out.println() at the point when the server socket accepts a connection which doesn't seem to fire when i try to hit the server through a browser. Please help me out with this.
Thanks :)

EDIT:
Part of the code:

```<code>public class Server {

    private ServerSocket serverSocket;
    private Socket socket;
    public Server() {
        try {
            serverSocket = new ServerSocket(6666);
            while (true) {
                socket = serverSocket.accept();
                System.out.println("Whoop! Connection!");
                Request request = new Request(socket);
                request.run();
            }
        } catch (IOException e) {
            e.printStackTrace();
          }
    }
}
</code>```

Where Request is a class which extends Thread in order to handle multiple requests

答:
Browsers only understand http and some other protocols, such as ftp.
Your serverSocket does not implement any protocol.
If you want to see something, maybe you can try in console

```<code># telnet localhost 6666
</code>```

EDIT

Here another question (and answer) for a correct implementation of an HTTP server:
A Simple Http Server with Java/Socket?

Body:
I wrote a very simple Java http server for exercising purposes. I test it with cURL and everything seems to work fine but when I try to send a request from a browser

http://localhost:6666/

the server does not respond. I even put a marking System.out.println() at the point when the server socket accepts a connection which doesn't seem to fire when i try to hit the server through a browser. Please help me out with this.
Thanks :)

EDIT:
Part of the code:

public class Server {

    private ServerSocket serverSocket;
    private Socket socket;
    public Server() {
        try {
            serverSocket = new ServerSocket(6666);
            while (true) {
                socket = serverSocket.accept();
                System.out.println("Whoop! Connection!");
                Request request = new Request(socket);
                request.run();
            }
        } catch (IOException e) {
            e.printStackTrace();
          }
    }
}

Where Request is a class which extends Thread in order to handle multiple requests

Body:
Browsers only understand http and some other protocols, such as ftp.
Your serverSocket does not implement any protocol.
If you want to see something, maybe you can try in console

# telnet localhost 6666

EDIT

Here another question (and answer) for a correct implementation of an HTTP server:
A Simple Http Server with Java/Socket?


答: Try DateTime.Now - it will always get the current time.</p>

Title: does DateTime keep itself updated in C#?

Body: I am trying to create a folder based off of the current month/day using DateTime. After i initialize a new DateTime( 2011, 5, 16, 1, 1, 30); will this keep itself updated or reset every time the program is ran?


问:
How to unwrap more than one Map<String,String> to Json
How to unwrap more than one Map to JSON. Example

```<code>public class Class {
Map<String,String> firstMap;
Map<String,String> secondMap;
}
</code>```

I can use @JsonAnyGetter only for one Map  field. I know also that I can use custom Serializer, but I've got more fields in class for which I don't want to change the deserialization method.
Preferable JSON output:

```<code>{
    "Name": "Name",
    "LastName": "LastName",
    "firstMapKey": "firstMapValue"
    "secondMapKey": "secondMapValue"
}
</code>```

Instead of:

```<code>{
    "Name": "Name",
    "LastName": "LastName",
    "firstMap": {
        "firstMapKey": "firstMapValue"
    },
    "secondMap": {
        "secondMapKey": "secondMapValue"
    }
}
</code>```

答:
@JonK helped me: I've added one additional Map and merge both Maps into it. For the additional map, I used @JsonAnyGetter and @JsonIgnore for both Maps used to merge.</p>

```<code>public class Class {
    @JsonIgnore
    Map<String,String> firstMap;
    @JsonIgnore
    Map<String,String> secondMap;

    Map<String,String> compositeMap

    @JsonAnyGetter
    public Map<String, String> getCompositeMap() {
        return compositeMap;
    }

    @JsonAnySetter
    public void setCompositeMap(Map<String, String> compositeMap) {
        this.compositeMap = compositeMap;
    }

}
</code>```

Body:
How to unwrap more than one Map to JSON. Example

public class Class {
Map<String,String> firstMap;
Map<String,String> secondMap;
}

I can use @JsonAnyGetter only for one Map  field. I know also that I can use custom Serializer, but I've got more fields in class for which I don't want to change the deserialization method.
Preferable JSON output:

{
    "Name": "Name",
    "LastName": "LastName",
    "firstMapKey": "firstMapValue"
    "secondMapKey": "secondMapValue"
}

Instead of:

{
    "Name": "Name",
    "LastName": "LastName",
    "firstMap": {
        "firstMapKey": "firstMapValue"
    },
    "secondMap": {
        "secondMapKey": "secondMapValue"
    }
}

Body:
@JonK helped me: I've added one additional Map and merge both Maps into it. For the additional map, I used @JsonAnyGetter and @JsonIgnore for both Maps used to merge.

public class Class {
    @JsonIgnore
    Map<String,String> firstMap;
    @JsonIgnore
    Map<String,String> secondMap;

    Map<String,String> compositeMap

    @JsonAnyGetter
    public Map<String, String> getCompositeMap() {
        return compositeMap;
    }

    @JsonAnySetter
    public void setCompositeMap(Map<String, String> compositeMap) {
        this.compositeMap = compositeMap;
    }

}


问:
C++ usual arithmetic conversions not converting
First, I'd like to point out that I did read some of the other answers with generally similar titles. However, those either refer to what I assume is an older version of the standard, or deal with promotions, not conversions.

I've been crawling through "C++ Crash Course", where the author states the following in the chapter exploring built-in operators:

If none of the floating-point promotion rules apply, you then check
whether either argument is signed. If so, both operands become signed.
Finally, as with the promotion rules for floating-point types, the size of the
largest operand is used to promote the other operand: ...

If I read the standard correctly, this is not true, because, as per cppreference.com,

If both operands are signed or both are unsigned, the operand with lesser conversion rank is converted to the operand with the greater integer conversion rank

Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type.

Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signed operand's type

Otherwise, both operands are converted to the unsigned counterpart of the signed operand's type.

What confuses me even more is the fact that the following code:

```<code>printf("Size of int is %d bytes\n", sizeof(int));
printf("Size of short is %d bytes\n", sizeof(short));
printf("Size of long is %d bytes\n", sizeof(long));
printf("Size of long long is %d bytes\n", sizeof(long long));
unsigned int x = 4000000000;
signed int y = -1;
signed long z = x + y;
printf("x + y = %ld\n", z);
</code>```

produces the following output:

```<code>Size of int is 4 bytes
Size of short is 2 bytes
Size of long is 8 bytes
Size of long long is 8 bytes
x + y = 3999999999
</code>```

As I understand the standard, y should have been converted to unsigned int, leading to an incorrect result. The result is correct, which leads me to assume that no conversion happens in this case. Why? I would be grateful for any clafirication on this matter. Thank you.

(I would also appreciate someone telling me that I won't ever need this kind of arcane knowledge in real life, even if it's not true - just for the peace of mind.)

答:
From the output of the first print statement from your code snippet it is evident that since the size of int is 4 bytes, the unsigned int values can range from 0 to 4,294,967,295. (2^32-1)

The declaration below is hence perfectly valid:

unsigned int x = 4000000000;
```

<p>Remember here that declaring x as an unsigned integer gives itself twice the (+ve) range of a signed counterpart, but it falls in exactly the same range and hence conversions between them are possible. </p>

<pre class="lang-cpp prettyprint-override"><code>signed int y = -1;
signed long z = x + y;
printf("x + y = %ld\n", z);
</code>```

Hence for the rest of the code above, it doesn't matter here whether the operands of y and z are signed (+ve/-ve) or unsigned (+ve) because you are dealing with an unsigned integer in the first place, for which the signed integers will be converted to their corresponding unsigned integer versions by adding UINTMAX+1 to the signed version.
Here UINTMAX stands for the largest unsigned value which is added with the smallest power of 2 (2^0=1). The end result would obviously be larger than values we can store, hence it is taken as modulo to collect the correct unsigned int.

However, if you were to convert x to signed instead:

signed int x = 4000000000;
int y = -1;
long z = x + y;
printf("x + y = %ld\n", z);
```

<p>you would get what you might have expected:</p>

```x + y = -294967297
```

Body:
First, I'd like to point out that I did read some of the other answers with generally similar titles. However, those either refer to what I assume is an older version of the standard, or deal with promotions, not conversions.

I've been crawling through "C++ Crash Course", where the author states the following in the chapter exploring built-in operators:

If none of the floating-point promotion rules apply, you then check
whether either argument is signed. If so, both operands become signed.
Finally, as with the promotion rules for floating-point types, the size of the
largest operand is used to promote the other operand: ...

If I read the standard correctly, this is not true, because, as per cppreference.com,

If both operands are signed or both are unsigned, the operand with lesser conversion rank is converted to the operand with the greater integer conversion rank

Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type.

Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signed operand's type

Otherwise, both operands are converted to the unsigned counterpart of the signed operand's type.

What confuses me even more is the fact that the following code:

printf("Size of int is %d bytes\n", sizeof(int));
printf("Size of short is %d bytes\n", sizeof(short));
printf("Size of long is %d bytes\n", sizeof(long));
printf("Size of long long is %d bytes\n", sizeof(long long));
unsigned int x = 4000000000;
signed int y = -1;
signed long z = x + y;
printf("x + y = %ld\n", z);

produces the following output:

Size of int is 4 bytes
Size of short is 2 bytes
Size of long is 8 bytes
Size of long long is 8 bytes
x + y = 3999999999

As I understand the standard, y should have been converted to unsigned int, leading to an incorrect result. The result is correct, which leads me to assume that no conversion happens in this case. Why? I would be grateful for any clafirication on this matter. Thank you.

(I would also appreciate someone telling me that I won't ever need this kind of arcane knowledge in real life, even if it's not true - just for the peace of mind.)

Body:
From the output of the first print statement from your code snippet it is evident that since the size of int is 4 bytes, the unsigned int values can range from 0 to 4,294,967,295. (2^32-1)

The declaration below is hence perfectly valid:

unsigned int x = 4000000000;

Remember here that declaring x as an unsigned integer gives itself twice the (+ve) range of a signed counterpart, but it falls in exactly the same range and hence conversions between them are possible.

signed int y = -1;
signed long z = x + y;
printf("x + y = %ld\n", z);

Hence for the rest of the code above, it doesn't matter here whether the operands of y and z are signed (+ve/-ve) or unsigned (+ve) because you are dealing with an unsigned integer in the first place, for which the signed integers will be converted to their corresponding unsigned integer versions by adding UINTMAX+1 to the signed version.
Here UINTMAX stands for the largest unsigned value which is added with the smallest power of 2 (2^0=1). The end result would obviously be larger than values we can store, hence it is taken as modulo to collect the correct unsigned int.

However, if you were to convert x to signed instead:

signed int x = 4000000000;
int y = -1;
long z = x + y;
printf("x + y = %ld\n", z);

you would get what you might have expected:

x + y = -294967297


答:
When you give specific parameters in your DateTime instantiation, you will get the same date/time.

If you want to use the current time, and have that update each time you run the program, use DateTime.Now.


问:
Does linealization in scala affect the way binding of internal types occur?
```<code>trait Root { type T <: Root }
trait A extends Root { type T <: A }
trait B extends Root { type T <: B }
trait C extends A with B
</code>```

The above code does not compile because the binding of type T in C is type T <: B
which obviously fails to subsume the binding type T <: A of T in type A.
Why is the type T of C bound to type T<:B and not type T<:A? Is it because of linealization?

答:
Following the principle of Liskov. C being a subtype of A, B and Root has to satisfy all those contracts.

Thus, it has to have a inner type T which has to be a subtype of A, B and Root.

So, it is not bounded to T <: B or can not be bounded to T <: A, it has to be bounded to both.

For some reason, the compiler can't infer a proper type for T or maybe it simply decides that it is better in this case for the user to be explicit instead of inferring.

Body:
trait Root { type T <: Root }
trait A extends Root { type T <: A }
trait B extends Root { type T <: B }
trait C extends A with B

The above code does not compile because the binding of type T in C is type T <: B
which obviously fails to subsume the binding type T <: A of T in type A.
Why is the type T of C bound to type T<:B and not type T<:A? Is it because of linealization?


问:
How to access Accessors value in withPivot() In Laravel - belongsToMany Relationship
I Have added one Accessor for Date formatting.

public function getFormattedDateAttribute()
{
    return Carbon::parse($this->review_date)->format('d M Y');
}
```

<p>I want to access this field in with pivot Table</p>

<pre class="lang-php prettyprint-override"><code>/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function fileGuestReviewers()
{
    return $this->belongsToMany(GuestReviewer::class, 'stage_file_reviewers')
        ->withPivot(['status','formatted_date']);
}
</code>```

Also, I already added this: protected $appends = ['formatted_date'];

Getting Error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'stage_file_reviewers.formatted_date'

答:
WithPivot() deals with database columns, you have defined a mutator which is executed after the database query. Therefor you need to include the underlying property it is using.

Therefor changing this should help your problem.

```<code>->withPivot(['status','review_date']);
</code>```

You would be able to access your field like so.

```<code>$model->fileGuestReviewers->first()->formattedDate;
</code>```

Body:
I Have added one Accessor for Date formatting.

public function getFormattedDateAttribute()
{
    return Carbon::parse($this->review_date)->format('d M Y');
}

I want to access this field in with pivot Table

/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function fileGuestReviewers()
{
    return $this->belongsToMany(GuestReviewer::class, 'stage_file_reviewers')
        ->withPivot(['status','formatted_date']);
}

Also, I already added this: protected $appends = ['formatted_date'];

Getting Error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'stage_file_reviewers.formatted_date'

Body:
WithPivot() deals with database columns, you have defined a mutator which is executed after the database query. Therefor you need to include the underlying property it is using.

Therefor changing this should help your problem.

->withPivot(['status','review_date']);

You would be able to access your field like so.

$model->fileGuestReviewers->first()->formattedDate;


问:
Merging split history in git
I have been toying with rebase a bit, trying to split and combine history as described here:
https://git-scm.com/book/en/v2/Git-Tools-Replace

Here is my test repository with split history:
https://github.com/defufna/split-history

Note that "initial commit" and "Added description" commits both point to the same tree. What I'm trying to do is merge these two histories (while maintaining merges). I used this:

```<code>git rebase --rebase-merges --onto history 94da9b0f
</code>```

This works, but I'm getting a conflict at 084dae5. This is a merge that resolves modify/delete conflict, and it requires me to manually resolve this conflict.

I am doing this in preparation for much larger repo merge, where I will have to do something similar but with 50k commits, so I would like to avoid manual conflict resolution.
I am aware that git replace could solve my problem, but I'm curious if it is possible to do it without replacement. I would also like to keep sha values of commits in history branch.

Edit:

So I've managed to do what I want, but I'm not sure how good this idea is.
I've added -i to rebase, and when I got todo file, I've changed every

```<code>merge -C 9751be2 Merge # Merge
</code>```

line into:

```<code>exec git checkout `git commit-tree '9751be2^{tree}' -p HEAD -p refs/rewritten/Merge -m Merge`
</code>```

I'm basically telling git whenever it encounters a merge to reuse tree from original merge.

It works as expected (for now), but it's a lot slower. Is there a better way to do this?

答:
Note that "initial commit"[94da] and "Added description"[c00e] commits both point to the same tree

Is there a better way to do this?

Much.

```<code>git replace --graft 94da c00e^
git filter-branch master
</code>```

and you're done.

git rebase exists to re-apply changes onto different base content, producing snapshots with new content.  You already have all the snapshots you want, you only need to rewire the ancestry.  git replace --graft does it locally, allowing you to experiment casually.  git filter-branch exists to bake in rewired ancestry while applying any super-easy content changes -- but you don't even have any of those. You just want to rewire the master history.

Title: Merging split history in git

Body:
I have been toying with rebase a bit, trying to split and combine history as described here:
https://git-scm.com/book/en/v2/Git-Tools-Replace

Here is my test repository with split history:
https://github.com/defufna/split-history

Note that "initial commit" and "Added description" commits both point to the same tree. What I'm trying to do is merge these two histories (while maintaining merges). I used this:

git rebase --rebase-merges --onto history 94da9b0f

This works, but I'm getting a conflict at 084dae5. This is a merge that resolves modify/delete conflict, and it requires me to manually resolve this conflict.

I am doing this in preparation for much larger repo merge, where I will have to do something similar but with 50k commits, so I would like to avoid manual conflict resolution.
I am aware that git replace could solve my problem, but I'm curious if it is possible to do it without replacement. I would also like to keep sha values of commits in history branch.

Edit:

So I've managed to do what I want, but I'm not sure how good this idea is.
I've added -i to rebase, and when I got todo file, I've changed every

merge -C 9751be2 Merge # Merge

line into:

exec git checkout `git commit-tree '9751be2^{tree}' -p HEAD -p refs/rewritten/Merge -m Merge`

I'm basically telling git whenever it encounters a merge to reuse tree from original merge.

It works as expected (for now), but it's a lot slower. Is there a better way to do this?

Body:
Note that "initial commit"[94da] and "Added description"[c00e] commits both point to the same tree

Is there a better way to do this?

Much.

git replace --graft 94da c00e^
git filter-branch master

and you're done.

git rebase exists to re-apply changes onto different base content, producing snapshots with new content.  You already have all the snapshots you want, you only need to rewire the ancestry.  git replace --graft does it locally, allowing you to experiment casually.  git filter-branch exists to bake in rewired ancestry while applying any super-easy content changes -- but you don't even have any of those. You just want to rewire the master history.


答: A DateTime(2011, 5, 16, 1, 1, 30); is an object which gets initialized with the date you provide as a constructor. The date will always stay the same. If you want to get the current date then you need to use DateTime.Now.


问:
display records for first day from selcted date range and end date from selected date range.Date range could be any date
I need to show open and close stock for a user input date range.

For open stock it should take the stock in first day from selected date range and close stock it should take stock in end date from selected date range.

Let say I have data from 3rd Jan. to 30th Jan. (in database) and user has selected date range (1st Jan. to 31st Jan.) so in open stock it should display stock for 3rd Jan. and in close stock it should display stock for 30th Jan.

How can I do this in SAP HANA Studio?

答:
making a guess on how your source data look. I made an attempt to solve your problem.</p>

```<code>with data as (
--here are some example data
select to_date('2019-12-31','yyyy-mm-dd') d ,-1 stock from dual union all
select to_date('2020-01-03','yyyy-mm-dd') d ,1 stock from dual union all
select to_date('2020-01-04','yyyy-mm-dd') d ,2 stock from dual union all
select to_date('2020-01-30','yyyy-mm-dd') d ,3 stock from dual union all
select to_date('2020-02-01','yyyy-mm-dd') d ,2 stock from dual
)
,filt_data as (
select * from data
where d between to_date('2020-01-01','yyyy-mm-dd') and to_date('2020-01-31','yyyy-mm-dd')
)
, min_date as(
select min(d) d from filt_data
)
, max_date as(
select max(d) d from filt_data
)
select (select d from filt_data where d = (select d from min_date)) open_stock_date
      ,(select stock from filt_data where d = (select d from min_date)) open_stock
      ,(select d from filt_data where d = (select d from max_date)) close_stock_date
      ,(select stock from filt_data where d = (select d from max_date)) close_stock
from  dual ;
</code>```

Body:
making a guess on how your source data look. I made an attempt to solve your problem.

with data as (
--here are some example data
select to_date('2019-12-31','yyyy-mm-dd') d ,-1 stock from dual union all
select to_date('2020-01-03','yyyy-mm-dd') d ,1 stock from dual union all
select to_date('2020-01-04','yyyy-mm-dd') d ,2 stock from dual union all
select to_date('2020-01-30','yyyy-mm-dd') d ,3 stock from dual union all
select to_date('2020-02-01','yyyy-mm-dd') d ,2 stock from dual
)
,filt_data as (
select * from data
where d between to_date('2020-01-01','yyyy-mm-dd') and to_date('2020-01-31','yyyy-mm-dd')
)
, min_date as(
select min(d) d from filt_data
)
, max_date as(
select max(d) d from filt_data
)
select (select d from filt_data where d = (select d from min_date)) open_stock_date
      ,(select stock from filt_data where d = (select d from min_date)) open_stock
      ,(select d from filt_data where d = (select d from max_date)) close_stock_date
      ,(select stock from filt_data where d = (select d from max_date)) close_stock
from  dual ;