问:
Html elements don't move
I am trying to personalise a web page to move an input text element.

Here's my code:

```<code><body>
    <h1>Todo List</h1>
    <input id="search" type="search">
    <input id='newTodo' type="text">

    <button>Add a todo</button>
    <script src="file.js"></script>
</body>

input {
    position: absolute;
    right: 0px;
    top: 0px;
}
</code>```

However, nothing moves. Is that related to input elements?

答:
It's working.

I believe you wrongly attached your styles, if code you pasted is exactly the same in your project, please try this:

```<code><body>
    <h1>Todo List</h1>
    <input id="search" type="search">
    <input id='newTodo' type="text">

    <button>Add a todo</button>
    <script src="file.js"></script>
</body>

<style>
input {
    position: absolute;
    right: 0px;
    top: 0px;
}
</style>
</code>```

Title: Html elements don't move

Body:
I am trying to personalise a web page to move an input text element.

Here's my code:

Todo List

    <input id="search" type="search">
    <input id='newTodo' type="text">

    <button>Add a todo</button>

input {
    position: absolute;
    right: 0px;
    top: 0px;
}

However, nothing moves. Is that related to input elements?

Body:
It's working.

I believe you wrongly attached your styles, if code you pasted is exactly the same in your project, please try this:

<body>
    <h1>Todo List</h1>
    <input id="search" type="search">
    <input id='newTodo' type="text">

    <button>Add a todo</button>
    <script src="file.js"></script>
</body>

<style>
input {
    position: absolute;
    right: 0px;
    top: 0px;
}
</style>


来源: stackexchange

问:
Stylesheet element works in Windows but not raspberry-pi
I'm writing a program on a Windows 10 machine and SSHing the code into the machine it will be running on - a Raspberry Pi running Raspbian. When applying some stylesheets to certain objects they look great on Windows, but certain elements aren't getting picked up on the Linux machine.

I've created a test program to show what is happening:

The only problem i'm having on the Raspbian machine is that the background isn't getting filled. The font size and color attributes are getting picked up fine. I've tried using .autoFillBackground() and .setAttribute(Qt.WA_StyledBackground) but neither yielded any results.

I've also tried a combination of QPushButton::active: and background:/background-color: without any luck.

Any ideas?

EDIT: PySide2 was installed using:

apt-get install python3-pyside2.qt3dcore python3-pyside2.qt3dinput python3-pyside2.qt3dlogic python3-pyside2.qt3drender python3-pyside2.qtcharts python3-pyside2.qtconcurrent python3-pyside2.qtcore python3-pyside2.qtgui python3-pyside2.qthelp python3-pyside2.qtlocation python3-pyside2.qtmultimedia python3-pyside2.qtmultimediawidgets python3-pyside2.qtnetwork python3-pyside2.qtopengl python3-pyside2.qtpositioning python3-pyside2.qtprintsupport python3-pyside2.qtqml python3-pyside2.qtquick python3-pyside2.qtquickwidgets python3-pyside2.qtscript python3-pyside2.qtscripttools python3-pyside2.qtsensors python3-pyside2.qtsql python3-pyside2.qtsvg python3-pyside2.qttest python3-pyside2.qttexttospeech python3-pyside2.qtuitools python3-pyside2.qtwebchannel python3-pyside2.qtwebsockets python3-pyside2.qtwidgets python3-pyside2.qtx11extras python3-pyside2.qtxml python3-pyside2.qtxmlpatterns python3-pyside2uic

from https://forum.qt.io/topic/112813/installing-pyside2-on-raspberry-pi

```<code>import sys

from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.btn1 = QPushButton("Button 1")
        self.btn2 = QPushButton("Button 2")

        self.btn1.setStyleSheet("""background: blue; color: yellow; border: 3px solid black""")
        self.btn2.setStyleSheet("background: red; color: white; font-size: 30px;")

        layout = QVBoxLayout()
        layout.addWidget(self.btn1)
        layout.addWidget(self.btn2)

        self.setLayout(layout)

app = QApplication(sys.argv)
window = Window()
window.show()
app.exec_()
</code>```

答:
Woo ok, so slight development. I've found that if you add a border the colour will fill. Bit odd but it works i guess. Its not ideal as the button loses its "pressed" state by doing this, but will mess about with it and see where i get.

"border: none;" also fills the background.

ContentLicense: CC BY-SA 4.0

Body:
I'm writing a program on a Windows 10 machine and SSHing the code into the machine it will be running on - a Raspberry Pi running Raspbian. When applying some stylesheets to certain objects they look great on Windows, but certain elements aren't getting picked up on the Linux machine.

I've created a test program to show what is happening:

The only problem i'm having on the Raspbian machine is that the background isn't getting filled. The font size and color attributes are getting picked up fine. I've tried using .autoFillBackground() and .setAttribute(Qt.WA_StyledBackground) but neither yielded any results.

I've also tried a combination of QPushButton::active: and background:/background-color: without any luck.

Any ideas?

EDIT: PySide2 was installed using:

apt-get install python3-pyside2.qt3dcore python3-pyside2.qt3dinput python3-pyside2.qt3dlogic python3-pyside2.qt3drender python3-pyside2.qtcharts python3-pyside2.qtconcurrent python3-pyside2.qtcore python3-pyside2.qtgui python3-pyside2.qthelp python3-pyside2.qtlocation python3-pyside2.qtmultimedia python3-pyside2.qtmultimediawidgets python3-pyside2.qtnetwork python3-pyside2.qtopengl python3-pyside2.qtpositioning python3-pyside2.qtprintsupport python3-pyside2.qtqml python3-pyside2.qtquick python3-pyside2.qtquickwidgets python3-pyside2.qtscript python3-pyside2.qtscripttools python3-pyside2.qtsensors python3-pyside2.qtsql python3-pyside2.qtsvg python3-pyside2.qttest python3-pyside2.qttexttospeech python3-pyside2.qtuitools python3-pyside2.qtwebchannel python3-pyside2.qtwebsockets python3-pyside2.qtwidgets python3-pyside2.qtx11extras python3-pyside2.qtxml python3-pyside2.qtxmlpatterns python3-pyside2uic

from https://forum.qt.io/topic/112813/installing-pyside2-on-raspberry-pi

import sys

from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.btn1 = QPushButton("Button 1")
        self.btn2 = QPushButton("Button 2")

        self.btn1.setStyleSheet("""background: blue; color: yellow; border: 3px solid black""")
        self.btn2.setStyleSheet("background: red; color: white; font-size: 30px;")

        layout = QVBoxLayout()
        layout.addWidget(self.btn1)
        layout.addWidget(self.btn2)

        self.setLayout(layout)

app = QApplication(sys.argv)
window = Window()
window.show()
app.exec_()


问:
What's the easiest way to set a variable to be what the user types as a command?
I'm making a discord bot that takes commands. I need it to set a variable to be equal to the int you type in, but I'm having trouble thinking of the solution. Currently it looks something like this:

```<code>switch(args[0]){
    case "test":

        if(args[1] == typeof 'number')
        {
            Functions.noOfPacks = args[1];
        }
</code>```

This doesn't work, however. Ideally, I want to be able to type !pack 2 and set the variable to 2.
I would do it through user input, but I don't want the bot to wait for input, as the commands won't work anymore. I know the function (in another file) works because it will loop twice if I set the variable to be 2 beforehand, for example.

答:
As a general rule whatever a user types in will be read by your code as a String.

Example:

document.querySelector('#box').onkeyup = function (e) {
  if (e.code !== 'Enter') return;

  const v = this.value

  if (Number.isNaN(+v)) {
    console.log(`${v} is not a number`)
    this.value = '' //clear the input when it is not a number
  } else {
    console.log(`${v} is a number`)
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="box">Type something in there and press Enter</label>
<input type="text" id="box" /></code>```

Body:
I'm making a discord bot that takes commands. I need it to set a variable to be equal to the int you type in, but I'm having trouble thinking of the solution. Currently it looks something like this:

switch(args[0]){
    case "test":

        if(args[1] == typeof 'number')
        {
            Functions.noOfPacks = args[1];
        }

This doesn't work, however. Ideally, I want to be able to type !pack 2 and set the variable to 2.
I would do it through user input, but I don't want the bot to wait for input, as the commands won't work anymore. I know the function (in another file) works because it will loop twice if I set the variable to be 2 beforehand, for example.

Body:
As a general rule whatever a user types in will be read by your code as a String.

Example:

document.querySelector('#box').onkeyup = function (e) {
  if (e.code !== 'Enter') return;

  const v = this.value

  if (Number.isNaN(+v)) {
    console.log(`${v} is not a number`)
    this.value = '' //clear the input when it is not a number
  } else {
    console.log(`${v} is a number`)
  }
}

<label for="box">Type something in there and press Enter</label>
<input type="text" id="box" />


问:
Joi validation on multiple queries with Nest.js
I'm trying to validate a GET request on Nest.js that has multiple queries using Joi. I understand how to use UsePipes and validate a single object on a single param. However I now have an endpoint that has the multiple queries, here is my controller:

  @Get(':cpId/search')
  @UsePipes(new JoiValidationPipe(queryDTOSchema))
  async getSomethingByFilters(
  @Param('cpId') cpId: string,
  @Query('startDate') startDate?: number,
  @Query('endDate') endDate?: number,
  @Query('el') el?: string,
  @Query('fields') fields?: string,
  @Query('keyword') keyword?: string,
  @Query('page') page?: number,
  @Query('limit') limit?: number,
  )...```

And UsePipes is now validating the same schema against each of the queries, and I don't understand how to validate each single query separately.

Is there a way to validate each query separately? I couldn't find any references and the only solution I can think of would be to transform all those queries into a single object, which is undesirable in this case.

答:
You can pass a pipe as the second argument of a query-decorator:

@Query('startDate', new JoiValidationPipe(joi.number())) startDate?: number
```

<p>But I personally would prefer validation as one query object, as it is easier to read and handle:</p>

<pre class="lang-js prettyprint-override"><code>@Get(':corporatePartnerId/search')
async getEmployeesByFilters(
  @Param('corporatePartnerId', new JoiValidationPipe(joi.string())) corporatePartnerId: string,
  @Query(new JoiValidationPipe(QueryDtoSchema)) query: QueryDto,
)
</code>```

Body:
I'm trying to validate a GET request on Nest.js that has multiple queries using Joi. I understand how to use UsePipes and validate a single object on a single param. However I now have an endpoint that has the multiple queries, here is my controller:

  @Get(':cpId/search')
  @UsePipes(new JoiValidationPipe(queryDTOSchema))
  async getSomethingByFilters(
  @Param('cpId') cpId: string,
  @Query('startDate') startDate?: number,
  @Query('endDate') endDate?: number,
  @Query('el') el?: string,
  @Query('fields') fields?: string,
  @Query('keyword') keyword?: string,
  @Query('page') page?: number,
  @Query('limit') limit?: number,
  )...

And UsePipes is now validating the same schema against each of the queries, and I don't understand how to validate each single query separately.

Is there a way to validate each query separately? I couldn't find any references and the only solution I can think of would be to transform all those queries into a single object, which is undesirable in this case.

Body:
You can pass a pipe as the second argument of a query-decorator:

@Query('startDate', new JoiValidationPipe(joi.number())) startDate?: number

But I personally would prefer validation as one query object, as it is easier to read and handle:

@Get(':corporatePartnerId/search')
async getEmployeesByFilters(
  @Param('corporatePartnerId', new JoiValidationPipe(joi.string())) corporatePartnerId: string,
  @Query(new JoiValidationPipe(QueryDtoSchema)) query: QueryDto,
)


问:
How to pause process run using Java's ProcessBuilder.start()?
Alright, so I'm writing this program that essentially batch runs other java programs for me (multiple times, varying parameters, parallel executions, etc).

So far the running part works great. Using ProcessBuilder's .start() method (equivalent to the Runtime.exec() I believe), it creates a separate java process and off it goes.

Problem is I would like to be able to pause/stop these processes once they've been started. With simple threads this is generally easy to do, however the external process doesn't seem to have any inbuilt functionality for waiting/sleeping, at least not from an external point of view.

My question(s) is this: Is there a way to pause a java.lang.Process object? If not, does anyone know of any related exec libraries that do contain this ability? Barring all of that, is extending Process a more viable alternative?

答:
A Process represents a separate process running on the machine. Java definitely does not allow you to pause them through java.lang.Process. You can forcibly stop them using Process.destroy(). For pausing, you will need the co-operation of the spawned process.

What sorts of processes are these? Did you write them?

ContentLicense: CC BY-SA 3.0


问:
Get the element with the highest occurrence in an array
I'm looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.

For example, in

```<code>['pear', 'apple', 'orange', 'apple']
</code>```

the 'apple' element is the most frequent one.

答:
There are a lot of answers already but just want to share with you what I came up with :)
Can't say this solution counts on any edge case but anyway )

```<code>const getMostFrequentElement = ( arr ) => {
  const counterSymbolKey = 'counter'
  const mostFrequentSymbolKey = 'mostFrequentKey'

  const result = arr.reduce( ( acc, cur ) => {
    acc[ cur ] = acc[ cur ] ? acc[ cur ] + 1 : 1

    if ( acc[ cur ] > acc[ Symbol.for( counterSymbolKey ) ] ) {
      acc[ Symbol.for( mostFrequentSymbolKey ) ] = cur
      acc[ Symbol.for( counterSymbolKey ) ] = acc[ cur ]
    }

    return acc
  }, {
    [ Symbol.for( mostFrequentSymbolKey ) ]: null,
    [ Symbol.for( counterSymbolKey ) ]: 0
  } )

  return result[ Symbol.for( mostFrequentSymbolKey ) ]
}
</code>```

Hope it will be helpful for someone )

Body:
I'm looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.

For example, in

['pear', 'apple', 'orange', 'apple']

the 'apple' element is the most frequent one.

Body:
There are a lot of answers already but just want to share with you what I came up with :)
Can't say this solution counts on any edge case but anyway )

const getMostFrequentElement = ( arr ) => {
  const counterSymbolKey = 'counter'
  const mostFrequentSymbolKey = 'mostFrequentKey'

  const result = arr.reduce( ( acc, cur ) => {
    acc[ cur ] = acc[ cur ] ? acc[ cur ] + 1 : 1

    if ( acc[ cur ] > acc[ Symbol.for( counterSymbolKey ) ] ) {
      acc[ Symbol.for( mostFrequentSymbolKey ) ] = cur
      acc[ Symbol.for( counterSymbolKey ) ] = acc[ cur ]
    }

    return acc
  }, {
    [ Symbol.for( mostFrequentSymbolKey ) ]: null,
    [ Symbol.for( counterSymbolKey ) ]: 0
  } )

  return result[ Symbol.for( mostFrequentSymbolKey ) ]
}

Hope it will be helpful for someone )


问:
How to resize the viewport of a Jscrollpanewhile it is visible?
I'm having a issue resizing the jpanel in a jscrollpane while it is visible. Here is my code:

```<code>for (String Id : SearchResultsMap.keySet())
        {
            JButton IdPanelButton = CreateIdPanelButton(Id);

            IdListPanel.add(IdPanelButton);
            IdPanelButton.addActionListener(new ActionListener(){
                @Override

                public void actionPerformed(ActionEvent e)
                {
                    ClearRecordDetails();
                    setRecordDetails(SearchResultsMap.get(Id));
                }
            });
        }
        IdListPanel.setPreferredSize(new Dimension(IdListPanel.getWidth(), (int) (SearchResultsMap.size()* CreateIdPanelButton("").getHeight())));
        IdListPanel.validate();

</code>```

What I'm basically doing is generating a list of buttons for the user to click on that will then display some information. The CreatIdPanelButton just create a new jbutton with visual constraints. The issue im having is that the IdListPanel is not resizing even though i tried setting the preferred size. I also tried revalidating the jscrollpane and that is not working. Anyone have any idea to update the jscrollpane viewport while it is visible??

答: So I figured out the issue, when you first create a Jbutton it takes sometime before the actual Height is set and computed,  so the getHeight method of the jbutton was returning 0 because it had not been set as it yet. So I fixed it by adding a constant of jbutton target height</p>

Body:
I'm having a issue resizing the jpanel in a jscrollpane while it is visible. Here is my code:

for (String Id : SearchResultsMap.keySet())
        {
            JButton IdPanelButton = CreateIdPanelButton(Id);

            IdListPanel.add(IdPanelButton);
            IdPanelButton.addActionListener(new ActionListener(){
                @Override

                public void actionPerformed(ActionEvent e)
                {
                    ClearRecordDetails();
                    setRecordDetails(SearchResultsMap.get(Id));
                }
            });
        }
        IdListPanel.setPreferredSize(new Dimension(IdListPanel.getWidth(), (int) (SearchResultsMap.size()* CreateIdPanelButton("").getHeight())));
        IdListPanel.validate();

What I'm basically doing is generating a list of buttons for the user to click on that will then display some information. The CreatIdPanelButton just create a new jbutton with visual constraints. The issue im having is that the IdListPanel is not resizing even though i tried setting the preferred size. I also tried revalidating the jscrollpane and that is not working. Anyone have any idea to update the jscrollpane viewport while it is visible??


问:
Replace a string in a list with a list of strings using a dictionary
I am attempting to replace the first string in the following list using the subsequent dictionary that is mapping to a list of strings.

```<code>id_list = ['40000', '58962', '85496']
id_dict = {'10000': ['10001','10002','10003'], '40000': ['40001','40002','40003']}
</code>```

Using a defined function such as this:

```<code>def find_replace_multi_ordered(string, dictionary):
    # sort keys by length, in reverse order
    for item in sorted(dictionary.keys(), key = len, reverse = True):
        string = re.sub(item, dictionary[item], string)
    return string

# Credit: http://pythoninthewyld.com/2018/03/12/dict-based-find-and-replace-deluxe/
</code>```

In the following for loop:

```<code>for i in id_list:

    if id_list[0][-4:] == '0000':
        id_list.replace(find_replace_multi_ordered(i, id_dict))

    else:
        pass

print(id_list)
</code>```

This works for string to string dictionary mapping but results in a TypeError for sting to list mapping.

Error:

```<code>TypeError: unhashable type: 'list'
</code>```

The desired output would be the following:

```<code>id_list = [['40001','40002','40003'], '58962', '85496']
</code>```

Thank you for any and all recommendations!

答:
There is much more easy, or each value of the list, if it's in the dict just replace by the pointed value, if it's absent keep the value

Detail of id_dict.get(item, item)

first item is the key to look at, to retrieve a value

second item is the default value, if the key has not been found

```<code>id_list = ['40000', '58962', '85496']
id_dict = {'10000': ['10001','10002','10003'], '40000': ['40001','40002','40003']}

id_list = [id_dict.get(item, item) for item in id_list]
print(id_list) # [['40001', '40002', '40003'], '58962', '85496']
</code>```

Body:
I am attempting to replace the first string in the following list using the subsequent dictionary that is mapping to a list of strings.

id_list = ['40000', '58962', '85496']
id_dict = {'10000': ['10001','10002','10003'], '40000': ['40001','40002','40003']}

Using a defined function such as this:

def find_replace_multi_ordered(string, dictionary):
    # sort keys by length, in reverse order
    for item in sorted(dictionary.keys(), key = len, reverse = True):
        string = re.sub(item, dictionary[item], string)
    return string

# Credit: http://pythoninthewyld.com/2018/03/12/dict-based-find-and-replace-deluxe/

In the following for loop:

for i in id_list:

    if id_list[0][-4:] == '0000':
        id_list.replace(find_replace_multi_ordered(i, id_dict))

    else:
        pass

print(id_list)

This works for string to string dictionary mapping but results in a TypeError for sting to list mapping.

Error:

TypeError: unhashable type: 'list'

The desired output would be the following:

id_list = [['40001','40002','40003'], '58962', '85496']

Thank you for any and all recommendations!

Body:
There is much more easy, or each value of the list, if it's in the dict just replace by the pointed value, if it's absent keep the value

Detail of id_dict.get(item, item)

first item is the key to look at, to retrieve a value

second item is the default value, if the key has not been found

id_list = ['40000', '58962', '85496']
id_dict = {'10000': ['10001','10002','10003'], '40000': ['40001','40002','40003']}

id_list = [id_dict.get(item, item) for item in id_list]
print(id_list) # [['40001', '40002', '40003'], '58962', '85496']


问:
What is the point of using types when declaring a variable in Typescript?
I'm newbie in Typescript, and I know its great benefits when working with big apps and teams : )

Let's suppose I have this TypeScript:

```<code>declare const num = 5: number;
</code>```

Why is that better than:

```<code>const num = 5
</code>```

Should I explicitly declare (with type) simple variables always in TypeScript?

Fortunately, the variable’s type is inferred from the data type of the value.
So can I use normal JS (like in the second example)?

答:
When declaring a variable, if the type of what you're assigning to it can be understood correctly by the TS compiler, then there's no need to define its type. In many cases, declaring an explicit type is not necessary, such as with const num = 5. But sometimes it is necessary, such as when declaring a variable which will be assigned to later, but not now:

```<code>let someData: MyData;
</code>```

Otherwise, someData will be typed as any, which isn't type-safe.

Another example for when it would be useful would be when creating an array which will later be pushed to:

```<code>const arr: number[] = [];
// later:
arr.push(5);
</code>```

The compiler can't infer at arr's declaration what values the array may contain, so number[] should be included when defining arr. (Otherwise, it'll be typed as any[], and any is not type-safe and should be avoided when possible)

Whenever TS can infer the type of a variable correctly and automatically - and most of the time, it can - then feel free to leave off the explicit note of the variable type, since it doesn't help.

Note that declare does something completely different - using that keyword tells TS that a variable with that name is defined in the current scope by other code, such as by a library. Variables which are declared will not exist in emitted code. Unless you have a library or something which defines a variable that Typescript doesn't understand exists, you almost certainly don't want to use declare.

Body:
I'm newbie in Typescript, and I know its great benefits when working with big apps and teams : )

Let's suppose I have this TypeScript:

declare const num = 5: number;

Why is that better than:

const num = 5

Should I explicitly declare (with type) simple variables always in TypeScript?

Fortunately, the variable’s type is inferred from the data type of the value.
So can I use normal JS (like in the second example)?

Body:
When declaring a variable, if the type of what you're assigning to it can be understood correctly by the TS compiler, then there's no need to define its type. In many cases, declaring an explicit type is not necessary, such as with const num = 5. But sometimes it is necessary, such as when declaring a variable which will be assigned to later, but not now:

let someData: MyData;

Otherwise, someData will be typed as any, which isn't type-safe.

Another example for when it would be useful would be when creating an array which will later be pushed to:

const arr: number[] = [];
// later:
arr.push(5);

The compiler can't infer at arr's declaration what values the array may contain, so number[] should be included when defining arr. (Otherwise, it'll be typed as any[], and any is not type-safe and should be avoided when possible)

Whenever TS can infer the type of a variable correctly and automatically - and most of the time, it can - then feel free to leave off the explicit note of the variable type, since it doesn't help.

Note that declare does something completely different - using that keyword tells TS that a variable with that name is defined in the current scope by other code, such as by a library. Variables which are declared will not exist in emitted code. Unless you have a library or something which defines a variable that Typescript doesn't understand exists, you almost certainly don't want to use declare.


问:
Why is my C++ program always throwing exception even if the user's input is ok?
What am I trying to achieve?

My goal is to make a program which will throw an exception and end the program everytime when input of type char is not either a, b or c and it should give following exception message: "You can't enter nothing else except a,b,c".

Where am I stuck at?

Even though user's input is a, b or c exception is being thrown.

Now my question is what should I do when if I enter a,b,c program keeps working and doesn't throw that exception?
Code:

```<code>int pitanjca()
  {
    cout<<endl;
    cout<<endl;
    cout<<endl;
    cout<<endl;
    cout<<endl;
    cout<<ime11<<" i  "<<ime22<<" sada započinjemo igru."<<endl;
    //Another question:
    cout<<"Pocinjemo sa pitanjima: "<<endl;
    cout<<"1.Kada je rođen Josip Broz Tito?";
    cout<<"a)7 maja 1892."<<endl;
    cout<<"b)25 maja 1892."<<endl;
    cout<<"c)25 maja 1900."<<endl;
    cout<<"Unesite odgovor: ";
    cin>>odgovor1;
    if(odgovor1!='a' || odgovor1!='b' || odgovor1!='c')
    {
      throw "Ne mozete unijeti nista osim a,b ili c";
    }
    cout<<endl;
    if(odgovor1=='a')
    {
      bodovi+=5;
    }
    else
    {
      bodovi+=0;
    }
</code>```

This is main function:

```<code> pitanja p(ime1,ime2);
  cout<<"Prvi igra: "<<ime1<<endl;
  try{
  player1bodovi=p.pitanjca();
  }catch (const char* msg) {
     cerr << msg << endl;
     goto tt;
  }
</code>```

And tt looks like this:

```<code>system("PAUSE")
return 0;
</code>```

答:
```<code>if (odgovor1 != 'a' || odgovor1 != 'b' || odgovor1 != 'c')
</code>```

Those should be && operators. Think of what happens when you enter a. You will get:

```<code>false || true || true
</code>```

which is true. In fact, you'll get true for every character since a single character cannot ever be all of a, b, and c at the same time.

However, there's probably little need to separate the scoring logic from the validation logic, you could combine the two with something like:

```<code>switch (odgovor1) {
    case 'a': bodovi += 5; break;
    case 'b':
    case 'c': break;
    default : throw "Ne mozete unijeti nista osim a, b ili c";
}
</code>```

Body:
What am I trying to achieve?

My goal is to make a program which will throw an exception and end the program everytime when input of type char is not either a, b or c and it should give following exception message: "You can't enter nothing else except a,b,c".

Where am I stuck at?

Even though user's input is a, b or c exception is being thrown.

Now my question is what should I do when if I enter a,b,c program keeps working and doesn't throw that exception?
Code:

int pitanjca()
  {
    cout<<endl;
    cout<<endl;
    cout<<endl;
    cout<<endl;
    cout<<endl;
    cout<<ime11<<" i  "<<ime22<<" sada započinjemo igru."<<endl;
    //Another question:
    cout<<"Pocinjemo sa pitanjima: "<<endl;
    cout<<"1.Kada je rođen Josip Broz Tito?";
    cout<<"a)7 maja 1892."<<endl;
    cout<<"b)25 maja 1892."<<endl;
    cout<<"c)25 maja 1900."<<endl;
    cout<<"Unesite odgovor: ";
    cin>>odgovor1;
    if(odgovor1!='a' || odgovor1!='b' || odgovor1!='c')
    {
      throw "Ne mozete unijeti nista osim a,b ili c";
    }
    cout<<endl;
    if(odgovor1=='a')
    {
      bodovi+=5;
    }
    else
    {
      bodovi+=0;
    }

This is main function:

 pitanja p(ime1,ime2);
  cout<<"Prvi igra: "<<ime1<<endl;
  try{
  player1bodovi=p.pitanjca();
  }catch (const char* msg) {
     cerr << msg << endl;
     goto tt;
  }

And tt looks like this:

system("PAUSE")
return 0;

Body:
if (odgovor1 != 'a' || odgovor1 != 'b' || odgovor1 != 'c')

Those should be && operators. Think of what happens when you enter a. You will get:

false || true || true

which is true. In fact, you'll get true for every character since a single character cannot ever be all of a, b, and c at the same time.

However, there's probably little need to separate the scoring logic from the validation logic, you could combine the two with something like:

switch (odgovor1) {
    case 'a': bodovi += 5; break;
    case 'b':
    case 'c': break;
    default : throw "Ne mozete unijeti nista osim a, b ili c";
}


问:
get query string in popup window
```<code><a href="tags.php" onclick="return popitup('tags.php')">tags</a>
</code>```

I have this line of code that runs the javascript to open new mini popup window,and it mostly works.

Now how could i add current query string attributes so that my popup window has url something like this "tags.php?variable1&variable2"

In few similar places I used this along with some other code to get the query attributes,the problem is that in this case page refreshes and contacts the sql without running javascript or opening window,when i try to make my code PHP using echo the quotation makrs f* everything up.

```<code>".$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']."
</code>```

答:
```<code>return popitup(this.href + window.location.search);
</code>```

would use the href belonging to the  that was clicked, so you don't have to retype it every time.

Title: get query string in popup window

Body:
tags

I have this line of code that runs the javascript to open new mini popup window,and it mostly works.

Now how could i add current query string attributes so that my popup window has url something like this "tags.php?variable1&variable2"

In few similar places I used this along with some other code to get the query attributes,the problem is that in this case page refreshes and contacts the sql without running javascript or opening window,when i try to make my code PHP using echo the quotation makrs f* everything up.

".$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']."

Body:
return popitup(this.href + window.location.search);

would use the href belonging to the <a> that was clicked, so you don't have to retype it every time.


问:
Database change log table not creating in Postgres environment for Liquibase
Maven Dependencies;

Spring Boot version: 2.2.3.RELEASE

Liquibase Core version: 3.8.5

Postgresql version: 42.2.9

I have a Spring Boot application that runs against a PostgreSQL 11 database which has presented with a new behavior not noticed before. When I run the update command a databasechangelog table is not getting created inside my active schema even though the databasechangeloglock table is being created. This is of course causing the run to fail for relation does not exist. However; I don't control the creation of this table and have never controlled it. The table used to create automagically just like the lock table but now it's not.

Here is how I set up my 2 primary objects for the Database and Liquibase for use by the update command.

```<code>private void setDatabase() {
    if (hasConn) {
        try {
            database = (Database) Class.forName("liquibase.database.core.PostgresDatabase").newInstance();
            database.setConnection(new JdbcConnection(getConnection()));
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            log.error("Could not return Liquibase Database Object");
            log.error(e.getMessage());
        }
    } else {
        log.warn("Connection Object not yet set!");
    }
}
</code>```

```<code>private void melt() {
        this.liquibase = new Liquibase(getDatabaseChangeLog(), new ClassLoaderResourceAccessor(), getDatabase());
}
</code>```

```<code>private void drinkUpdate() throws LiquibaseException {
        this.liquibase.update((String) null);
}
</code>```

I have recently changed this application to be part of a multi module Maven project which changed all the version references I'm using based on the new parent POM.

My question is, if anyone has seen this behavior before and if it's related to the versions of the jars being used while processing? Why would the databasechangeloglock table generate when update runs and not the databasechangelog table? Also; it appears that the databasechangelog tables generate in my public schema just fine for each of my databases that I generate... just not in my custom schema objects which hold the bulk of my database objects.

I've looked at the debug output and found that my liquibase.Liquibase object and the corresponding liquibase.database.Database object are complete and accurate with appropriately named databasechangelog and databasechangeloglock tables specified with the current schema set to my value but the change log table refuses to generate at the same time the lock table does. Unfortunately as soon as I create the databasechangelog table manually the rest of my objects specified in the database change log are created as expected.

答:
I believe you are not using the SpringBoot and Liquibase integration the way it was meant to be used.
You should not need to call liquibase directly. In fact, that may be the reason why the creation of databasechangelog table is not created.  If you configure you application:

make sure you fill out your application.properties with JDBC url and a pointer to your changelog

when you call Springboot:run the process will automatically see you have a db and changelog and will before startup run the migration.

If you don't want the DB migration to run at startup but instead manually, then I would use Liquibase CLI in a CICD pipeline (ex. A jenkins groovy pipeline script)

Here is a good primer on setup of Springboot with Liquibase:
https://docs.liquibase.com/tools-integrations/springboot/using-springboot-with-maven.html

I also played around with it to figure out using a SpringBoot initializr: https://start.spring.io/, adding Liquibase as a dependency

Hope that helps.

Body:
Maven Dependencies;

Spring Boot version: 2.2.3.RELEASE

Liquibase Core version: 3.8.5

Postgresql version: 42.2.9

I have a Spring Boot application that runs against a PostgreSQL 11 database which has presented with a new behavior not noticed before. When I run the update command a databasechangelog table is not getting created inside my active schema even though the databasechangeloglock table is being created. This is of course causing the run to fail for relation does not exist. However; I don't control the creation of this table and have never controlled it. The table used to create automagically just like the lock table but now it's not.

Here is how I set up my 2 primary objects for the Database and Liquibase for use by the update command.

private void setDatabase() {
    if (hasConn) {
        try {
            database = (Database) Class.forName("liquibase.database.core.PostgresDatabase").newInstance();
            database.setConnection(new JdbcConnection(getConnection()));
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            log.error("Could not return Liquibase Database Object");
            log.error(e.getMessage());
        }
    } else {
        log.warn("Connection Object not yet set!");
    }
}

private void melt() {
        this.liquibase = new Liquibase(getDatabaseChangeLog(), new ClassLoaderResourceAccessor(), getDatabase());
}

private void drinkUpdate() throws LiquibaseException {
        this.liquibase.update((String) null);
}

I have recently changed this application to be part of a multi module Maven project which changed all the version references I'm using based on the new parent POM.

My question is, if anyone has seen this behavior before and if it's related to the versions of the jars being used while processing? Why would the databasechangeloglock table generate when update runs and not the databasechangelog table? Also; it appears that the databasechangelog tables generate in my public schema just fine for each of my databases that I generate... just not in my custom schema objects which hold the bulk of my database objects.

I've looked at the debug output and found that my liquibase.Liquibase object and the corresponding liquibase.database.Database object are complete and accurate with appropriately named databasechangelog and databasechangeloglock tables specified with the current schema set to my value but the change log table refuses to generate at the same time the lock table does. Unfortunately as soon as I create the databasechangelog table manually the rest of my objects specified in the database change log are created as expected.


问:
how to remove duplicate char from ARGB
I am trying to get hex form rgb colors

```<code>public string GetCssValue(IWebElement iwe, string cssValue)
{
    var value = iwe.GetCssValue(cssValue);
    string[] numbers = value.Replace("rgba(", "").Replace(")", "").Split(",");

    int a = int.Parse(numbers[0]);
    int r = int.Parse(numbers[1]);
    int g = int.Parse(numbers[2]);
    int b = int.Parse(numbers[3]);

    Color myColor = Color.FromArgb(a, r, g, b);

    string hex = "#" + myColor.A.ToString("X2") + myColor.R.ToString("X2") +
        myColor.G.ToString("X2") + myColor.B.ToString("X2");
</code>```

here hex is gets the value #FFEEEE01 while my css on the page is #fee so that I can compare two strings (expected,actual)

how can I get the #fee as my hex value.
and what does this X2 represent here

答:
A quick way to change your code to return the value would be to only concatenate the first character from the RGB values:

```<code>string hex = "#" + myColor.R.ToString("X2")[0] + myColor.G.ToString("X2")[0] +
    myColor.B.ToString("X2")[0];
</code>```

But, since only a subset of 6-digit codes can be accurately converted to 3-digit codes (only those with repeating characters), it might be helpful to write a helper method to convert the values:

```<code>public string GetThreeDigitRGB(Color color)
{
    // Get the 2-character RGB color codes
    var r = color.R.ToString("X2");
    var g = color.G.ToString("X2");
    var b = color.B.ToString("X2");

    // Every color must have a repeating character for its code, otherwise we return null
    return r[0] == r[1] && g[0] == g[1] && b[0] == b[1]
        ? $"#{r[0]}{g[0]}{b[0]}"
        : null;
}
</code>```

Then your original code could be modified to create a Color object from the input and pass it to our helper method above to get the 3-digit code (also note the change where we get the color values in the order RGBA, which is how they're passed in):

```<code>public string GetCssValue(IWebElement iwe, string cssValue)
{
    var value = iwe.GetCssValue(cssValue);
    string[] numbers = value.Replace("rgba(", "").Replace(")", "").Split(",");

    // Note the change to get the colors in the correct order
    int r = int.Parse(numbers[0]);
    int g = int.Parse(numbers[1]);
    int b = int.Parse(numbers[2]);
    int a = int.Parse(numbers[3]);

    // Create a color from the values
    Color myColor = Color.FromArgb(a, r, g, b);

    // Call our helper method to get the three digit code from the color
    return GetThreeDigitRGB(myColor);
}
</code>```

Title: how to remove duplicate char from ARGB

Body:
I am trying to get hex form rgb colors

public string GetCssValue(IWebElement iwe, string cssValue)
{
    var value = iwe.GetCssValue(cssValue);
    string[] numbers = value.Replace("rgba(", "").Replace(")", "").Split(",");

    int a = int.Parse(numbers[0]);
    int r = int.Parse(numbers[1]);
    int g = int.Parse(numbers[2]);
    int b = int.Parse(numbers[3]);

    Color myColor = Color.FromArgb(a, r, g, b);

    string hex = "#" + myColor.A.ToString("X2") + myColor.R.ToString("X2") +
        myColor.G.ToString("X2") + myColor.B.ToString("X2");

here hex is gets the value #FFEEEE01 while my css on the page is #fee so that I can compare two strings (expected,actual)

how can I get the #fee as my hex value.
and what does this X2 represent here

Body:
A quick way to change your code to return the value would be to only concatenate the first character from the RGB values:

string hex = "#" + myColor.R.ToString("X2")[0] + myColor.G.ToString("X2")[0] +
    myColor.B.ToString("X2")[0];

But, since only a subset of 6-digit codes can be accurately converted to 3-digit codes (only those with repeating characters), it might be helpful to write a helper method to convert the values:

public string GetThreeDigitRGB(Color color)
{
    // Get the 2-character RGB color codes
    var r = color.R.ToString("X2");
    var g = color.G.ToString("X2");
    var b = color.B.ToString("X2");

    // Every color must have a repeating character for its code, otherwise we return null
    return r[0] == r[1] && g[0] == g[1] && b[0] == b[1]
        ? $"#{r[0]}{g[0]}{b[0]}"
        : null;
}

Then your original code could be modified to create a Color object from the input and pass it to our helper method above to get the 3-digit code (also note the change where we get the color values in the order RGBA, which is how they're passed in):

public string GetCssValue(IWebElement iwe, string cssValue)
{
    var value = iwe.GetCssValue(cssValue);
    string[] numbers = value.Replace("rgba(", "").Replace(")", "").Split(",");

    // Note the change to get the colors in the correct order
    int r = int.Parse(numbers[0]);
    int g = int.Parse(numbers[1]);
    int b = int.Parse(numbers[2]);
    int a = int.Parse(numbers[3]);

    // Create a color from the values
    Color myColor = Color.FromArgb(a, r, g, b);

    // Call our helper method to get the three digit code from the color
    return GetThreeDigitRGB(myColor);
}


问:
Is it possible to embed a .Net code in SSRS to remove CSV header from CSV file instead of changing report server configuration?
Is it possible to embed a .Net code in SSRS to remove CSV header from CSV file instead of changing report server configuration? As client is not ready to change rsreportconfiguration setting.</p>

答:
So you want to view a report from the report server and then export it as a CSV? These export functions are handled by the server and do not check or run any code from your .rdl file. So no, this is not possible.

One possible workaround might have been to rename the textboxes with the first row of data. But this doesn't work with numbers or blanks and it's not dynamic.

A better solution will probably end up being to ignore the headers wherever these are being consumed. If that's not possible, SSRS might not be the best tool for this job. Then you might look at generating the CSV with SSIS or some other ETL process.


问:
*args and **kwargs Python
I'm working on an exercise, I tried to solve it, but no result, I had to look at the solution, in order to have an idea and repeat it, the problem, I am stuck, a little lost.

```<code># Create an @authenticated decorator that only allows the function to run is user1 has 'valid' set to True:

 user1 = { 'name': 'Sorna',
           'valid': True }         #changing this will either run or not run the message_friends function.
</code>```

Solution :

```<code>def authenticated(fn):
  def wrapper(*args, **kwargs):
    if args[0]['valid']:
      return fn(*args, **kwargs)
  return wrapper

@authenticated
def message_friends(user):
    print('message has been sent')

message_friends(user1)
</code>```

I really don't get this part :

```<code>if args[0]['valid']:
</code>```

My question is if user1 = dict, why can't i just use **kwards so i can just check if the value is True by calling only [valid]:
where it comes from the args[0]?

Help, i'm really stuck with this..

答:
The @authenticated decorator does the following:

Ensure that the function is called with at least one positional argument (else, an exception is raised).

Ensure that this first argument is a dictionary, or at least supports item access by string subscripts (again, otherwise an exception is raised).

Ensure that the key 'valid' is found in the dictionary (else, exception).

If the key exists in the dictionary and has a True boolean value, then the original function is called and its return value returned by the decorated function. Else, no function is called, and no value returned.

It's not a very neat way of decorating functions, but if you can ensure that conditions 1 through 3 always hold, condition 4 can be useful in some scenarios.

Title: *args and **kwargs Python

Body:
I'm working on an exercise, I tried to solve it, but no result, I had to look at the solution, in order to have an idea and repeat it, the problem, I am stuck, a little lost.

# Create an @authenticated decorator that only allows the function to run is user1 has 'valid' set to True:

 user1 = { 'name': 'Sorna',
           'valid': True }         #changing this will either run or not run the message_friends function.

Solution :

def authenticated(fn):
  def wrapper(*args, **kwargs):
    if args[0]['valid']:
      return fn(*args, **kwargs)
  return wrapper

@authenticated
def message_friends(user):
    print('message has been sent')

message_friends(user1)

I really don't get this part :

if args[0]['valid']:

My question is if user1 = dict, why can't i just use **kwards so i can just check if the value is True by calling only [valid]:
where it comes from the args[0]?

Help, i'm really stuck with this..


问:
Azure Data Factory Lookup and For Each
I have a Data Factory Pipeline that I want to have iterate through the rows of a SQL Lookup activity. I have narrowed the query down to three columns and 500 rows.

I understand that to reference a value in the table I use:

```<code>@{activity('lookupActivity').output.value[row#].colname}
</code>```

However, the for each needs to have something to iterate over. My first guess is to set some array variable to the rows of the returned sql query. So what do I set that variable to?

```<code>@{activity('lookupActivity').output.value?
</code>```

Lastly, it looks like almost all data is represented as a json in ADF, is this true? And how could I view the output of this look up as a json so I can understand what my dynamic content needs to look like?

答: You can use the output value to for each activity and go through one at a time. You can do sequential or parallel depending on your needs.</p>

Title: Azure Data Factory Lookup and For Each

Body:
I have a Data Factory Pipeline that I want to have iterate through the rows of a SQL Lookup activity. I have narrowed the query down to three columns and 500 rows.

I understand that to reference a value in the table I use:

@{activity('lookupActivity').output.value[row#].colname}

However, the for each needs to have something to iterate over. My first guess is to set some array variable to the rows of the returned sql query. So what do I set that variable to?

@{activity('lookupActivity').output.value?

Lastly, it looks like almost all data is represented as a json in ADF, is this true? And how could I view the output of this look up as a json so I can understand what my dynamic content needs to look like?


问:
Functions In CoffeeScript
I'm trying to convert a function from Javascript to CoffeeScript. This is the code:

```<code>function convert(num1, num2, num3) {
    return num1 + num2 * num3;
}
</code>```

But how I can do that in CoffeeScript?

I'm trying to run the function from an HTML source like this:

```<code><script type="text/javascript" src="../coffee/convert.js"></script>

<script type="text/javascript">
    convert(6, 3, 10);
</script>
</code>```

But it won't work and I get an error saying: ReferenceError: Can't find variable: convert

How to correct this?

答:
You need to export the convert function to the global scope.

See How can Coffescript access functions from other assets?

```<code>window.convert = (num1, num2, num3) ->
  num1 + num2 * num3
</code>```

Title: Functions In CoffeeScript

Body:
I'm trying to convert a function from Javascript to CoffeeScript. This is the code:

function convert(num1, num2, num3) {
    return num1 + num2 * num3;
}

But how I can do that in CoffeeScript?

I'm trying to run the function from an HTML source like this:

But it won't work and I get an error saying: ReferenceError: Can't find variable: convert

How to correct this?

Body:
You need to export the convert function to the global scope.

See How can Coffescript access functions from other assets?

window.convert = (num1, num2, num3) ->
  num1 + num2 * num3


问:
No matching distribution found for tkinter
I am stuck with this issue since last two days and I have tried every possible solution on the stack and github. It will be really great if someone can recommend.

I am working with python 2.7 in a virtual environment on CentOS Linux release 7.3.1611.

I am running a script that uses matplotlib.pyplot and on run gives this error

```<code>import  matplotlib.pyplot as plt
 File "/usr/local/packages/Python-2.7/lib/python2.7/lib-tk/Tkinter.py", line 39, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ImportError: No module named _tkinter
</code>```

I tried to install tkinter using -

```<code> pip install tkinter and it gave this error
Could not find a version that satisfies the requirement tkinter (from versions: )
No matching distribution found for tkinter
</code>```

then I even installed -

```<code>sudo yum install tk
sudo yum install tk-devel
sudo yum install tc
</code>```

and it says packages are already installed and nothing to to

I have set up my virtual environment again to see if I missed something but I cannot get anywhere. Please help!

答:
```<code>sudo yum install python-tools -y
</code>```

This worked for me on Amazon Linux 2.

Body:
I am stuck with this issue since last two days and I have tried every possible solution on the stack and github. It will be really great if someone can recommend.

I am working with python 2.7 in a virtual environment on CentOS Linux release 7.3.1611.

I am running a script that uses matplotlib.pyplot and on run gives this error

import  matplotlib.pyplot as plt
 File "/usr/local/packages/Python-2.7/lib/python2.7/lib-tk/Tkinter.py", line 39, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ImportError: No module named _tkinter

I tried to install tkinter using -

 pip install tkinter and it gave this error
Could not find a version that satisfies the requirement tkinter (from versions: )
No matching distribution found for tkinter

then I even installed -

sudo yum install tk
sudo yum install tk-devel
sudo yum install tc

and it says packages are already installed and nothing to to

I have set up my virtual environment again to see if I missed something but I cannot get anywhere. Please help!

Body:
sudo yum install python-tools -y

This worked for me on Amazon Linux 2.


问:
Writing a new column if entries match on different data frames Python
I'm fairly new to Python and need some help with my data

Lets say my data 1 is

```<code>Year Population Country
1960            A
1998            A
1969 3          B
1999            B
..
2018 4          Z
</code>```

And data 2 is

```<code>Year A     B     C     D
1960 2     4     3     3
1961 3     4     2     1
...
2018 3     4     1     3
</code>```

Where [A, Z] are the countries

In data 1, the population is not filled for most countries and years, so I had to download the data for the population on a different set. Now I want to fill the entries in data 1 if the years and countries match on both data sets. I am struggling with this because the Columns in data 2 are each of the countries whereas in data 1, the countries are listed in only 1 column.

Any ideas? Thanks for the help!

答:
You can use lookup:

```<code>df2 = df2.set_index('Year')

df1['Population'] = df1['Population'].fillna(df2.lookup(df1['Year'], df1['Country']) )
</code>```

Body:
I'm fairly new to Python and need some help with my data

Lets say my data 1 is

Year Population Country
1960            A
1998            A
1969 3          B
1999            B
..
2018 4          Z

And data 2 is

Year A     B     C     D
1960 2     4     3     3
1961 3     4     2     1
...
2018 3     4     1     3

Where [A, Z] are the countries

In data 1, the population is not filled for most countries and years, so I had to download the data for the population on a different set. Now I want to fill the entries in data 1 if the years and countries match on both data sets. I am struggling with this because the Columns in data 2 are each of the countries whereas in data 1, the countries are listed in only 1 column.

Any ideas? Thanks for the help!

Body:
You can use lookup:

df2 = df2.set_index('Year')

df1['Population'] = df1['Population'].fillna(df2.lookup(df1['Year'], df1['Country']) )


问:
Cannot Receive JSON Response from Postman using Laravel API
I receive this error when I try to login with wrong credentials :

```<code><!doctype html>
<html class="theme-light">
<!--
TypeError: Argument 2 passed to Symfony\Component\HttpFoundation\JsonResponse::__construct() must be of the type integer, array given, called in /home/stylmyvz/cars.styleshopeg.com/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php on line 31 in file /home/stylmyvz/cars.styleshopeg.com/vendor/symfony/http-foundation/JsonResponse.php on line 42

#0 /home/stylmyvz/cars.styleshopeg.com/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php(31): Symfony\Component\HttpFoundation\JsonResponse->__construct(Array, Array, Array)
#1 /home/stylmyvz/cars.styleshopeg.com/vendor/laravel/framework/src/Illuminate/Routing/ResponseFactory.php(99): Illuminate\Http\JsonResponse->__construct(Array, Array, Array, 0)
#2 /home/stylmyvz/cars.styleshopeg.com/app/Http/Controllers/APILoginController.php(31): Illuminate\Routing\ResponseFactory->json(Array, Array)
#3 [internal function]: App\Http\Controllers\APILoginController->login(Object(Illuminate\Http\Request)
I want to receive JSON response like this in Postman :
{
  "error":"invalid username or password"
}
</code>```

Here is Login Controller and I instruct it to give me "invalid username or password"

Can anyone tell me what is wrong with it

```<code>class APILoginController extends Controller
{
    //
    public function login(Request $request){
        $validator = Validator::make($request -> all(),[
            'email' => 'required|string|email|max:255',
            'password' =>'required'
        ]);

        if($validator->fails()){
            return response()->json($validator->errors());
        }

        $credentials = $request->only('email', 'password');
        try {
            if(! $token = JWTAuth::attempt($credentials))
            {
                return response()->json(['error'=>'invalid username or password'], [401]);
            }
        } catch (JWTException $e) {
            //throw $th;
            return response()->json(['error'=>'could not create token'], [500]);
        }

        return response()->json(compact('token'));

    }
}
</code>```

Contents of api.php file:

```<code>Route::post('user/register','APIRegisterController@register');

Route::post('user/login','APILoginController@login');

Route::middleware('jwt.auth')->get('/users', function (Request $request) {
    return auth()->user();
});

Route::middleware('jwt.auth')->group( function(){
   Route::resource('/cars', 'API\CarController');
} );
</code>```

答:
I found the problem it was in the error message number I passed it as an array

```<code>return response()->json(['error'=>'invalid username or password'], [401]);
</code>```

and I should remove the brackets and pass it like int

```<code>return response()->json(['error'=>'invalid username or password'], 401);
</code>```

Body:
I receive this error when I try to login with wrong credentials :

<!doctype html>

Body:
I found the problem it was in the error message number I passed it as an array

return response()->json(['error'=>'invalid username or password'], [401]);

and I should remove the brackets and pass it like int

return response()->json(['error'=>'invalid username or password'], 401);


问:
MaterialComponents.DatePicker day selector circle off position and how to change colors?

This is my situation, as you can see I have a daterangepicker from the MaterialComponents.DatePicker library. The circle to select the day is off by a lot. Before any of you suggest, I have tried changing the date ranger picker to fullscreen instead of dialog and all the problems remained. This said, if any of you prefer to make the changes in the fullscreen mode, it is fine by me. By the way, the fragment in which the datepicker is called is centered.

The colors I have no idea where he got them from, so if anyone knows where or how  to change, please tell me. Plus, the purple color shown there is nowhere to be found in my colors.xml

Now, the code:
This is my Datepicker (called by a options menu button):

```<code>MaterialDatePicker.Builder dateBuilder = MaterialDatePicker.Builder.dateRangePicker();
                CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();
                dateBuilder.setCalendarConstraints(constraintsBuilder.build());
                dateBuilder.setTitleText("Select your Dates");
                dateBuilder.setTheme(R.style.DatePickerTheme);
                MaterialDatePicker<Pair<Long, Long>> datePicker = dateBuilder.build();
                datePicker.addOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        Log .d("DatePicker Activity", "Dialog was cancelled");
                    }
                });
                datePicker.addOnNegativeButtonClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.d("DatePicker Activity", "Dialog Negative Button was clicked");
                    }
                });
                datePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Pair<Long, Long>>() {
                    @Override
                    public void onPositiveButtonClick(Pair<Long, Long> selection) {
                        Log.d("DatePicker Activity", "Date String = ${picker.headerText}::  Date epoch values::${it.first}:: to :: ${it.second}");
                        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Settings", Context.MODE_PRIVATE);
                        SharedPreferences.Editor sEditor = sharedPreferences.edit();
                        sEditor.putLong("Start Date", selection.first);
                        sEditor.putLong("End Date", selection.second);
                        Toast.makeText(getActivity(), "Primeiro:" + selection.first.toString() + "SEgundo:" + selection.second.toString(), Toast.LENGTH_LONG).show();
                    }
                });
                assert getFragmentManager() != null;
                datePicker.show(getFragmentManager(), "RangePicker");
</code>```

And this is my styles.xml: (A lot of people suggest putting the style inside the AppTheme which I just couldn't do!)

```<code><resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <!-- Picker styles and themes. -->
    <style name="DatePickerTheme" parent="Theme.MaterialComponents.DayNight">
        <item name="materialCalendarStyle">@style/Widget.MaterialComponents.MaterialCalendar</item>
        <item name="materialCalendarFullscreenTheme">@style/ThemeOverlay.MaterialComponents.MaterialCalendar.Fullscreen</item>
        <item name="materialCalendarTheme">@style/ThemeOverlay.MaterialComponents.MaterialCalendar</item>
    </style>
</resources>
</code>```

答:
As described in the doc you have to use a Material Components Theme.

Just change your app theme to:

```<code><style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
   ....
</style>
</code>```

It is enough to fix the style and the position of the selector day in your picker.

The default style is based on the colorOnPrimary,colorPrimary and colorOnSurface defined in your app theme.

If you want to customize the color you can override these colors using:

```<code>builder.setTheme(R.style.MaterialCalendarTheme);
</code>```

with:

```<code>  <style name="MaterialCalendarTheme" parent="ThemeOverlay.MaterialComponents.MaterialCalendar">
    <item name="colorOnPrimary">@color/...</item>
    <item name="colorPrimary">@color/....</item>
  </style>
</code>```

Body:
This is my situation, as you can see I have a daterangepicker from the MaterialComponents.DatePicker library. The circle to select the day is off by a lot. Before any of you suggest, I have tried changing the date ranger picker to fullscreen instead of dialog and all the problems remained. This said, if any of you prefer to make the changes in the fullscreen mode, it is fine by me. By the way, the fragment in which the datepicker is called is centered.

The colors I have no idea where he got them from, so if anyone knows where or how  to change, please tell me. Plus, the purple color shown there is nowhere to be found in my colors.xml

Now, the code:
This is my Datepicker (called by a options menu button):

MaterialDatePicker.Builder dateBuilder = MaterialDatePicker.Builder.dateRangePicker();
                CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();
                dateBuilder.setCalendarConstraints(constraintsBuilder.build());
                dateBuilder.setTitleText("Select your Dates");
                dateBuilder.setTheme(R.style.DatePickerTheme);
                MaterialDatePicker<Pair<Long, Long>> datePicker = dateBuilder.build();
                datePicker.addOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        Log .d("DatePicker Activity", "Dialog was cancelled");
                    }
                });
                datePicker.addOnNegativeButtonClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.d("DatePicker Activity", "Dialog Negative Button was clicked");
                    }
                });
                datePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Pair<Long, Long>>() {
                    @Override
                    public void onPositiveButtonClick(Pair<Long, Long> selection) {
                        Log.d("DatePicker Activity", "Date String = ${picker.headerText}::  Date epoch values::${it.first}:: to :: ${it.second}");
                        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Settings", Context.MODE_PRIVATE);
                        SharedPreferences.Editor sEditor = sharedPreferences.edit();
                        sEditor.putLong("Start Date", selection.first);
                        sEditor.putLong("End Date", selection.second);
                        Toast.makeText(getActivity(), "Primeiro:" + selection.first.toString() + "SEgundo:" + selection.second.toString(), Toast.LENGTH_LONG).show();
                    }
                });
                assert getFragmentManager() != null;
                datePicker.show(getFragmentManager(), "RangePicker");

And this is my styles.xml: (A lot of people suggest putting the style inside the AppTheme which I just couldn't do!)

<resources>

</resources>

Body:
As described in the doc you have to use a Material Components Theme.

Just change your app theme to:

<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
   ....
</style>

It is enough to fix the style and the position of the selector day in your picker.

The default style is based on the colorOnPrimary,colorPrimary and colorOnSurface defined in your app theme.

If you want to customize the color you can override these colors using:

builder.setTheme(R.style.MaterialCalendarTheme);

with:

  <style name="MaterialCalendarTheme" parent="ThemeOverlay.MaterialComponents.MaterialCalendar">
    <item name="colorOnPrimary">@color/...</item>
    <item name="colorPrimary">@color/....</item>
  </style>


问:
iOS delegate is nil when trying to pass data back with Swift 5
I know this is a pretty common question but I've tried the various solutions offered here (that are not too old) and in numerous tutorials and I just can't seem to find out why it's still failing for me. Basically setting sendingViewController.delegate to self ends up being nil in sendingViewController. I understand this is very likely because the reference to the sendingViewController is being disposed of.  But here is why I'm asking this again.

First, almost every tutorial and every other StackOverflow post is wiring up the mainViewController and the sendingViewController differently. I'm trying to make this work through a Navigation Controller, what one would think is the most common pattern for this.

In the app I'm building (which is more complex than the sample I'm going to show), the mainViewController calls the Settings viewController through a right navbar button. Then the user can select items from a list, which opens a controller with a searchBar and a tableView of items to select from. I need that third view controller to return the selected item from the table view to the settings screen. I'm using storyboards as well. I'm fairly new to Swift and I'm not ready to do all this "programmatically". Any way in the sending view controller, my delegate which should have been set in the calling view controller is nil and I can't invoke the protocol function in the main view controller to pass the data back.

I did a tutorial directly (not using Nav controllers) and I got that to work, but the moment I deviate away, it starts failing. I then put together a streamlined project with two view controllers: ViewController and SendingViewController. ViewController was embedded in a navigation controller and a right bar button was added to go to the SendingViewController. The SendingViewController has a single UI Button that attempts to call the protocol function and dismiss the SendingViewController. I'm not using Seque's, just a simple buttons and protocol/delegate pattern as I can.

My question is what am I missing to actually set the SendingViewController.delegate correctly?

Here's some code:

```<code>//ViewController.swift
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var showDataLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func fetchDataButton(_ sender: UIBarButtonItem) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "SendingViewController") as! SendingViewController
        controller.delegate = self
        print("fetching data")
        present(controller, animated: true, completion: nil)
    }

}

extension ViewController: SendingViewControllerDelegate {
    func sendData(value: String) {
        print("got Data \(value)")
        self.showDataLabel.text = value
    }

}
</code>```

and

```<code>// SendingViewController.swift
import UIKit

protocol SendingViewControllerDelegate {
    func sendData(value: String)
}

class SendingViewController: UIViewController {

    var delegate: SendingViewControllerDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBAction func sendDataButton(_ sender: UIButton) {
        print("attempting to send data \(self)")
        print("to \(self.delegate)")
        self.delegate?.sendData(value: "Hello World")
        self.navigationController?.popViewController(animated: true)
    }
}
</code>```

Here is a screenshot of the Storyboard:

The ChildViewController does have a storyboard id name of "ChildViewController". All buttons and labels have their appropriate IBOutlet and IBAction's set up.

Help!

答:
I managed to get this working. In the receiving/parent view controller that needs the data:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let controller = segue.destination as! sendingViewController

    controller.cityDelegate = self
}
</code>```

Then in the sending view controller in my tableView did select row function:
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {

```<code>    let city = filtered[indexPath.row]

    searchBar.resignFirstResponder()

    self.navigationController?.popViewController(animated: true)
    self.cityDelegate?.addCity(city)
    self.dismiss(animated: true, completion: nil)
}
</code>```

I don't think I should be both popping the view controller and dismissing it, but it works. Also in the view controller I did this:

```<code>private var presentingController: UIViewController?

override func viewDidLoad() {
    super.viewDidLoad()

}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    presentingController = presentingViewController
}

override func didMove(toParent parent: UIViewController?) {
    super.didMove(toParent: parent)

    if parent == nil {
    }
}
</code>```

I don't know if I really need this didMove() or not since it doesn't really do anything.

But some combination of all this got it working.

In my other app I'm not using a navigation bar controller and the standard delegate/protocol method works like a charm.

Body:
I know this is a pretty common question but I've tried the various solutions offered here (that are not too old) and in numerous tutorials and I just can't seem to find out why it's still failing for me. Basically setting sendingViewController.delegate to self ends up being nil in sendingViewController. I understand this is very likely because the reference to the sendingViewController is being disposed of.  But here is why I'm asking this again.

First, almost every tutorial and every other StackOverflow post is wiring up the mainViewController and the sendingViewController differently. I'm trying to make this work through a Navigation Controller, what one would think is the most common pattern for this.

In the app I'm building (which is more complex than the sample I'm going to show), the mainViewController calls the Settings viewController through a right navbar button. Then the user can select items from a list, which opens a controller with a searchBar and a tableView of items to select from. I need that third view controller to return the selected item from the table view to the settings screen. I'm using storyboards as well. I'm fairly new to Swift and I'm not ready to do all this "programmatically". Any way in the sending view controller, my delegate which should have been set in the calling view controller is nil and I can't invoke the protocol function in the main view controller to pass the data back.

I did a tutorial directly (not using Nav controllers) and I got that to work, but the moment I deviate away, it starts failing. I then put together a streamlined project with two view controllers: ViewController and SendingViewController. ViewController was embedded in a navigation controller and a right bar button was added to go to the SendingViewController. The SendingViewController has a single UI Button that attempts to call the protocol function and dismiss the SendingViewController. I'm not using Seque's, just a simple buttons and protocol/delegate pattern as I can.

My question is what am I missing to actually set the SendingViewController.delegate correctly?

Here's some code:

//ViewController.swift
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var showDataLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func fetchDataButton(_ sender: UIBarButtonItem) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "SendingViewController") as! SendingViewController
        controller.delegate = self
        print("fetching data")
        present(controller, animated: true, completion: nil)
    }

}

extension ViewController: SendingViewControllerDelegate {
    func sendData(value: String) {
        print("got Data \(value)")
        self.showDataLabel.text = value
    }

}

and

// SendingViewController.swift
import UIKit

protocol SendingViewControllerDelegate {
    func sendData(value: String)
}

class SendingViewController: UIViewController {

    var delegate: SendingViewControllerDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    @IBAction func sendDataButton(_ sender: UIButton) {
        print("attempting to send data \(self)")
        print("to \(self.delegate)")
        self.delegate?.sendData(value: "Hello World")
        self.navigationController?.popViewController(animated: true)
    }
}

Here is a screenshot of the Storyboard:

The ChildViewController does have a storyboard id name of "ChildViewController". All buttons and labels have their appropriate IBOutlet and IBAction's set up.

Help!

Body:
I managed to get this working. In the receiving/parent view controller that needs the data:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let controller = segue.destination as! sendingViewController

    controller.cityDelegate = self
}

Then in the sending view controller in my tableView did select row function:
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {

    let city = filtered[indexPath.row]

    searchBar.resignFirstResponder()

    self.navigationController?.popViewController(animated: true)
    self.cityDelegate?.addCity(city)
    self.dismiss(animated: true, completion: nil)
}

I don't think I should be both popping the view controller and dismissing it, but it works. Also in the view controller I did this:

private var presentingController: UIViewController?

override func viewDidLoad() {
    super.viewDidLoad()

}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    presentingController = presentingViewController
}

override func didMove(toParent parent: UIViewController?) {
    super.didMove(toParent: parent)

    if parent == nil {
    }
}

I don't know if I really need this didMove() or not since it doesn't really do anything.

But some combination of all this got it working.

In my other app I'm not using a navigation bar controller and the standard delegate/protocol method works like a charm.


问:
Does MySQL stalls the whole cluster during DDL statements?
Recently, I read that Galera based MySQL cluster uses a concept called total order isolation (https://galeracluster.com/library/documentation/schema-upgrades.html#toi) for DDL's by default which stalls the writes on the whole cluster until it is commited on all the nodes.

How does MySQL handles DDL in native asynchronous replication ?
Does it stall writes for the other schemas as well?

答:
Native Replication sticks the DDL into the replication stream.  When the command pops up in the Slave, it executes the DDL before moving on to other queries in the replication stream.

Caveat:  The above statement assumes old flavor, without multi-master replication or multiple replication threads.  Regardless of this caveat the table being modified is blocked on the Slave just as it was on the Master.

Galera's TOI goes to some extra effort to make sure all the nodes are in sync, even accounting for the DDL versus ordinary writes.  Hnece the name "Total Order of Inserts".

Galera's RSU is, in many cases, a viable alternative.  It is not more invasive than a crash of each node, one at a time (hence "Rolling").  Assuming connections can failover to different nodes, RSU avoids other blockage.

Still, you should make a conscious choice between RSU and TOI; there are use cases for dictating one versus the other.

In a distributed system (multiple nodes, multiple clients, etc), pushing code gets tricky.  I like to take this approach, even though it leads to perhaps 3 times as many pushes:

Push application code to discover whether the database change has been pushed.  Have the code work either with the old schema or new.  Do this "push" in a "rolling" manor

Push the new schema (eg CREATE/ALTER TABLE).

Clean up the code.  (Again, "roll" it out to the many clients.)


问:
How can i remove different items on same page
how can i remove different items on same page without reloading page
like i want to remove some items and leave the rest </p>

```<code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").remove();
  });
});
</script>
</head>
<body>

<div>
<p>remove this paragraph</p><button>close</button>
<p>leave this paragraph</p><button>close</button>
<p>remove this paragraph</p><button>close</button>
<p>leave this paragraph</p><button>close</button>
</div>
</body>
</html>
</code>```

答:
well, you need to change the html to target the items for which you want to add a custom class for example:

```<code><p>remove this paragraph</p><button>close</button>
<p>leave this paragraph</p><button>close</button>
<p class="item-to-remove">remove this paragraph</p><button>close</button>
<p>leave this paragraph</p><button>close</button>
</code>```

so you need to change the CSS selector in the javascript as well:

```<code>$(document).ready(function(){
  $("button").click(function(){
    $(".item-to-remove").remove();
  });
});
</code>```

Body:
how can i remove different items on same page without reloading page
like i want to remove some items and leave the rest

<!DOCTYPE html>

remove this paragraph
<button>close</button>

leave this paragraph
<button>close</button>

remove this paragraph
<button>close</button>

leave this paragraph
<button>close</button>

Body:
well, you need to change the html to target the items for which you want to add a custom class for example:

<p>remove this paragraph</p><button>close</button>
<p>leave this paragraph</p><button>close</button>
<p class="item-to-remove">remove this paragraph</p><button>close</button>
<p>leave this paragraph</p><button>close</button>

so you need to change the CSS selector in the javascript as well:

$(document).ready(function(){
  $("button").click(function(){
    $(".item-to-remove").remove();
  });
});


问:
'NoneType' object is not subscriptable - Data generator
I created a list out of two other lists which looks like this:

```<code>samples = list(map(lambda x, y: [x,y], image_path, labels8))
[['s01_l01/1_1.png', '7C2 4698'],
 ['s01_l01/2_1.png', '7C2 4698'],
 ['s01_l01/2_2.png', '7C2 4698'],
 ['s01_l01/2_3.png', '7C2 4698'],
 ['s01_l01/2_4.png', '7C2 4698']]
</code>```

The first entry is the image_path, the second a label.

I also created this function:

```<code>def shuffle_data(data):
  data=random.shuffle(data)
  return data
</code>```

To get a data_generator, I modified the code I found in a video on YouTube (https://www.youtube.com/watch?v=EkzB6PJIcCA&t=530s):

```<code>def data_generator(samples, batch_size=32, shuffle_data = True, resize=224):
  num_samples = len(samples)
  while True:
    samples = random.shuffle(samples)

    for offset in range(0, num_samples, batch_size):
      batch_samples = samples[offset: offset + batch_size]

      X_train = []
      y_train = []

      for batch_sample in batch_samples:
        img_name = batch_sample[0]
        label = batch_sample[1]
        img = cv2.imread(os.path.join(root_dir, img_name))

        #img, label = preprocessing(img, label, new_height=224, new_width=224, num_classes=37)
        img = preprocessing(img, new_height=224, new_width=224)
        label = my_onehot_encoded(label)

        X_train.append(img)
        y_train.append(label)

      X_train = np.array(X_train)
      y_train = np.array(y_train)

      yield X_train, y_train
</code>```

When I now try to execute this code:

```<code>train_datagen = data_generator(samples, batch_size=32)

x, y = next(train_datagen)
print('x_shape: ', x.shape)
print('labels shape: ', y.shape)
print('labels: ', y)
</code>```

I got the following error code:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-6adc7f4509cd> in <module>()
      1 train_datagen = data_generator(samples, batch_size=32)
      2
----> 3 x, y = next(train_datagen)
      4 print('x_shape: ', x.shape)
      5 print('labels shape: ', y.shape)

<ipython-input-88-0f34e3e5c990> in data_generator(samples, batch_size, shuffle_data, resize)
      5
      6     for offset in range(0, num_samples, batch_size):
----> 7       batch_samples = samples[offset: offset + batch_size]
      8
      9       X_train = []

TypeError: 'NoneType' object is not subscriptable
</code>```

I don't get where the error is...

答:
random.shuffle is in-place and returns None.

So, write

```<code>random.shuffle(samples)
</code>```

instead of

```<code>samples = random.shuffle(samples)
</code>```

Body:
I created a list out of two other lists which looks like this:

samples = list(map(lambda x, y: [x,y], image_path, labels8))
[['s01_l01/1_1.png', '7C2 4698'],
 ['s01_l01/2_1.png', '7C2 4698'],
 ['s01_l01/2_2.png', '7C2 4698'],
 ['s01_l01/2_3.png', '7C2 4698'],
 ['s01_l01/2_4.png', '7C2 4698']]

The first entry is the image_path, the second a label.

I also created this function:

def shuffle_data(data):
  data=random.shuffle(data)
  return data

To get a data_generator, I modified the code I found in a video on YouTube (https://www.youtube.com/watch?v=EkzB6PJIcCA&t=530s):

def data_generator(samples, batch_size=32, shuffle_data = True, resize=224):
  num_samples = len(samples)
  while True:
    samples = random.shuffle(samples)

    for offset in range(0, num_samples, batch_size):
      batch_samples = samples[offset: offset + batch_size]

      X_train = []
      y_train = []

      for batch_sample in batch_samples:
        img_name = batch_sample[0]
        label = batch_sample[1]
        img = cv2.imread(os.path.join(root_dir, img_name))

        #img, label = preprocessing(img, label, new_height=224, new_width=224, num_classes=37)
        img = preprocessing(img, new_height=224, new_width=224)
        label = my_onehot_encoded(label)

        X_train.append(img)
        y_train.append(label)

      X_train = np.array(X_train)
      y_train = np.array(y_train)

      yield X_train, y_train

When I now try to execute this code:

train_datagen = data_generator(samples, batch_size=32)

x, y = next(train_datagen)
print('x_shape: ', x.shape)
print('labels shape: ', y.shape)
print('labels: ', y)

I got the following error code:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-6adc7f4509cd> in <module>()
      1 train_datagen = data_generator(samples, batch_size=32)
      2
----> 3 x, y = next(train_datagen)
      4 print('x_shape: ', x.shape)
      5 print('labels shape: ', y.shape)

<ipython-input-88-0f34e3e5c990> in data_generator(samples, batch_size, shuffle_data, resize)
      5
      6     for offset in range(0, num_samples, batch_size):
----> 7       batch_samples = samples[offset: offset + batch_size]
      8
      9       X_train = []

TypeError: 'NoneType' object is not subscriptable

I don't get where the error is...

Body:
random.shuffle is in-place and returns None.

So, write

random.shuffle(samples)

instead of

samples = random.shuffle(samples)


问:
How can I write to a file using C++ buider in an Android app?
I'm using the community version of C++ builder (10.3) under Windows 10 to develop an app to run on a Samsung Galaxy A40.

One thing I can't seem to get working is saving the contents of TListBox to a file.

Being a newbie to Android, I'm not sure about where this file should appear and what rights I need.

I've tried the following in a function to save the contents of a listbox to a file, but can't seem to open a file to write to. It always returns -1 :

```<code>int hFile;      // File Handle
int ByteCt=0;

hFile = FileOpen("Shopping.lst", fmOpenWrite);
if (hFile > 0)
{
    for (int i=0; i<ListBox1->Count; i++)
    {
        ByteCt+=FileWrite(hFile,ListBox1->Items[i].Text.c_str(),
                                ListBox1->Items->Strings[i].Length());
        ByteCt+=FileWrite(hFile,"\n\r",2);
    }
    FileClose(hFile);
}
</code>```

Is there something basic I've missed, or what ?

答:
Use the System::Ioutils::TPath class to determine various system paths that your app can access.  See Standard RTL Path Functions across the Supported Target Platforms for details.  For example:

String FileName = TPath::Combine(TPath::GetDocumentsPath(), _D("Shopping.lst"));
hFile = FileOpen(FileName, fmOpenWrite);
// or: hFile = FileCreate(FileName);
```

<p>But FYI, <code>ListBox1->Items</code> is a <code>TStrings</code>, which has its own <code>SaveToFile()</code> method, eg:</p>

<pre class="lang-cpp prettyprint-override"><code>ListBox1->Items->SaveToFile(FileName, TEncoding::UTF8);
</code>```

You are just duplicating what SaveToFile() already does for you.  So you don't need to write the strings manually - especially since you are not even writing them correctly to begin with!

String in C++Builder is an alias for UnicodeString, which is a UTF-16 encoded string. Its Length() specifies the number of WideChar (char16_t on Android) elements it contains, but FileWrite() deals in raw bytes only.  So you are writing only 1/2 of the bytes of each String since sizeof(WideChar)=2.  And also, "\n\r" is not a valid line break to use, either.  You would need to use "\r\n" or just "\n", or use the RTL's sLineBreak global constant.  But worse, you are trying to write the Strings in their original UTF-16 format but are writing the line breaks in an 8bit ANSI/UTF-8 format. So you end up with a mixed-encoding file, which many softwares won't be able to read correctly.

If you really want to write the Strings manually then it needs to look more like this instead:

int hFile;      // File Handle
int ByteCt=0, BytesWritten;

hFile = FileOpen(FileName, fmOpenWrite);
// or: hFile = FileCreate(FileName);
if (hFile > 0)
{
    for (int i=0; i < ListBox1->Count; i++)
    {
        String s = ListBox1->Items->Strings[i];
        BytesWritten = FileWrite(hFile, s.c_str(), s.Length() * sizeof(WideChar));
        if (BytesWritten < 0) break;
        ByteCt += BytesWritten;
        BytesWritten = FileWrite(hFile, _D("\r\n"), sizeof(WideChar) * 2);
        if (BytesWritten < 0) break;
        ByteCt += BytesWritten;

        /* alternatively:
        UTF8String s = ListBox1->Items->Strings[i];
        BytesWritten = FileWrite(hFile, s.c_str(), s.Length());
        if (BytesWritten < 0) break;
        ByteCt += BytesWritten;
        BytesWritten = FileWrite(hFile, "\r\n", 2);
        if (BytesWritten < 0) break;
        ByteCt += BytesWritten;
        */
    }
    FileClose(hFile);
}
```

<p>However, rather than using <code>FileWrite()</code> directly, consider using <code>TStreamWriter</code> instead, eg:</p>

<pre class="lang-cpp prettyprint-override"><code>int ByteCt=0;

std::unique_ptr<TStreamWriter> File(new TStreamWriter(FileName, TEncoding::UTF8));
// or: auto File = std::make_unique<TStreamWriter>(FileName, TEncoding::UTF8);

for (int i=0; i < ListBox1->Count; i++)
{
    String s = ListBox1->Items->Strings[i];
    File->WriteLine(s);
    ByteCt += (File->Encoding->GetByteCount(s) + File->Encoding->GetByteCount(File->NewLine));
}
</code>```

Body:
I'm using the community version of C++ builder (10.3) under Windows 10 to develop an app to run on a Samsung Galaxy A40.

One thing I can't seem to get working is saving the contents of TListBox to a file.

Being a newbie to Android, I'm not sure about where this file should appear and what rights I need.

I've tried the following in a function to save the contents of a listbox to a file, but can't seem to open a file to write to. It always returns -1 :

int hFile;      // File Handle
int ByteCt=0;

hFile = FileOpen("Shopping.lst", fmOpenWrite);
if (hFile > 0)
{
    for (int i=0; i<ListBox1->Count; i++)
    {
        ByteCt+=FileWrite(hFile,ListBox1->Items[i].Text.c_str(),
                                ListBox1->Items->Strings[i].Length());
        ByteCt+=FileWrite(hFile,"\n\r",2);
    }
    FileClose(hFile);
}

Is there something basic I've missed, or what ?

Body:
Use the System::Ioutils::TPath class to determine various system paths that your app can access.  See Standard RTL Path Functions across the Supported Target Platforms for details.  For example:

String FileName = TPath::Combine(TPath::GetDocumentsPath(), _D("Shopping.lst"));
hFile = FileOpen(FileName, fmOpenWrite);
// or: hFile = FileCreate(FileName);

But FYI, ListBox1->Items is a TStrings, which has its own SaveToFile() method, eg:

ListBox1->Items->SaveToFile(FileName, TEncoding::UTF8);

You are just duplicating what SaveToFile() already does for you.  So you don't need to write the strings manually - especially since you are not even writing them correctly to begin with!

String in C++Builder is an alias for UnicodeString, which is a UTF-16 encoded string. Its Length() specifies the number of WideChar (char16_t on Android) elements it contains, but FileWrite() deals in raw bytes only.  So you are writing only 1/2 of the bytes of each String since sizeof(WideChar)=2.  And also, "\n\r" is not a valid line break to use, either.  You would need to use "\r\n" or just "\n", or use the RTL's sLineBreak global constant.  But worse, you are trying to write the Strings in their original UTF-16 format but are writing the line breaks in an 8bit ANSI/UTF-8 format. So you end up with a mixed-encoding file, which many softwares won't be able to read correctly.

If you really want to write the Strings manually then it needs to look more like this instead:

int hFile;      // File Handle
int ByteCt=0, BytesWritten;

hFile = FileOpen(FileName, fmOpenWrite);
// or: hFile = FileCreate(FileName);
if (hFile > 0)
{
    for (int i=0; i < ListBox1->Count; i++)
    {
        String s = ListBox1->Items->Strings[i];
        BytesWritten = FileWrite(hFile, s.c_str(), s.Length() * sizeof(WideChar));
        if (BytesWritten < 0) break;
        ByteCt += BytesWritten;
        BytesWritten = FileWrite(hFile, _D("\r\n"), sizeof(WideChar) * 2);
        if (BytesWritten < 0) break;
        ByteCt += BytesWritten;

        /* alternatively:
        UTF8String s = ListBox1->Items->Strings[i];
        BytesWritten = FileWrite(hFile, s.c_str(), s.Length());
        if (BytesWritten < 0) break;
        ByteCt += BytesWritten;
        BytesWritten = FileWrite(hFile, "\r\n", 2);
        if (BytesWritten < 0) break;
        ByteCt += BytesWritten;
        */
    }
    FileClose(hFile);
}

However, rather than using FileWrite() directly, consider using TStreamWriter instead, eg:

int ByteCt=0;

std::unique_ptr<TStreamWriter> File(new TStreamWriter(FileName, TEncoding::UTF8));
// or: auto File = std::make_unique<TStreamWriter>(FileName, TEncoding::UTF8);

for (int i=0; i < ListBox1->Count; i++)
{
    String s = ListBox1->Items->Strings[i];
    File->WriteLine(s);
    ByteCt += (File->Encoding->GetByteCount(s) + File->Encoding->GetByteCount(File->NewLine));
}


问:
Is there a way to parallelize spark.read.load(string*) when reading many files?
I noticed that in spark-shell (spark 2.4.4), when I do a simple spark.read.format(xyz).load("a","b","c",...), it looks like spark uses a single ipc client (or "thread") to load the files a, b, c, ... sequentially (they are path to hdfs).

Is this expected?

The reason I am asking is, for my case, I am trying to load 50K files, and the sequential load takes a long time.

Thanks

PS, I am trying to see it in the source code, but not sure if this is the one:
https://github.com/apache/spark/blob/branch-2.4/sql/core/src/main/scala/org/apache/spark/sql/DataFrameReader.scala#L180

答: Might not be an exact "answer" to my original question, but I found out the reason for my particular case: from name node's audit log, it was found that there were some runaway jobs pegging name node, which greatly slowed down the rpc calls. After killing these bad jobs, the spark's load speed was greatly improved. </p>


问:
Replace a string in a list with a list of strings using a dictionary
I am attempting to replace the first string in the following list using the subsequent dictionary that is mapping to a list of strings.

```<code>id_list = ['40000', '58962', '85496']
id_dict = {'10000': ['10001','10002','10003'], '40000': ['40001','40002','40003']}
</code>```

Using a defined function such as this:

```<code>def find_replace_multi_ordered(string, dictionary):
    # sort keys by length, in reverse order
    for item in sorted(dictionary.keys(), key = len, reverse = True):
        string = re.sub(item, dictionary[item], string)
    return string

# Credit: http://pythoninthewyld.com/2018/03/12/dict-based-find-and-replace-deluxe/
</code>```

In the following for loop:

```<code>for i in id_list:

    if id_list[0][-4:] == '0000':
        id_list.replace(find_replace_multi_ordered(i, id_dict))

    else:
        pass

print(id_list)
</code>```

This works for string to string dictionary mapping but results in a TypeError for sting to list mapping.

Error:

```<code>TypeError: unhashable type: 'list'
</code>```

The desired output would be the following:

```<code>id_list = [['40001','40002','40003'], '58962', '85496']
</code>```

Thank you for any and all recommendations!

Body:
I am attempting to replace the first string in the following list using the subsequent dictionary that is mapping to a list of strings.

id_list = ['40000', '58962', '85496']
id_dict = {'10000': ['10001','10002','10003'], '40000': ['40001','40002','40003']}

Using a defined function such as this:

def find_replace_multi_ordered(string, dictionary):
    # sort keys by length, in reverse order
    for item in sorted(dictionary.keys(), key = len, reverse = True):
        string = re.sub(item, dictionary[item], string)
    return string

# Credit: http://pythoninthewyld.com/2018/03/12/dict-based-find-and-replace-deluxe/

In the following for loop:

for i in id_list:

    if id_list[0][-4:] == '0000':
        id_list.replace(find_replace_multi_ordered(i, id_dict))

    else:
        pass

print(id_list)

This works for string to string dictionary mapping but results in a TypeError for sting to list mapping.

Error:

TypeError: unhashable type: 'list'

The desired output would be the following:

id_list = [['40001','40002','40003'], '58962', '85496']

Thank you for any and all recommendations!

Body:
Does it do what you want?

id_list = ['40000', '58962', '85496']
id_dict = {'10000': ['10001','10002','10003'], '40000': ['40001','40002','40003']}

X = [
    item if item not in id_dict else id_dict[item] for item in id_list
]
print(X) # [['40001', '40002', '40003'], '58962', '85496']


问:
getting the output Optional("test")
I tried the following code

```<code>if let shortURL = shortURL {
     var url = "\(shortURL.absoluteString)"
     MUser.sharedInstance.setMobileReferralId(url)
     self.referralLink.text = url self.copyToClipboard()
}
</code>```

For the url variable, I get the output Optional("Test"). How do I remove the "Optional" part?

答:
The reason looks like absoluteString is optional so you can provide a default value or using if let to assign its value to url, like below

```<code>if let url = shortURL.absoluteString {
    print(url)
}
</code>```

or provide some default blank value like

```<code>var url = shortURL.absoluteString ?? ""
print(url)
</code>```

Title: getting the output Optional("test")

Body:
I tried the following code

if let shortURL = shortURL {
     var url = "\(shortURL.absoluteString)"
     MUser.sharedInstance.setMobileReferralId(url)
     self.referralLink.text = url self.copyToClipboard()
}

For the url variable, I get the output Optional("Test"). How do I remove the "Optional" part?

Body:
The reason looks like absoluteString is optional so you can provide a default value or using if let to assign its value to url, like below

if let url = shortURL.absoluteString {
    print(url)
}

or provide some default blank value like

var url = shortURL.absoluteString ?? ""
print(url)