问:
Vue select not highlight selected Item in Dropdown
I'm using vue-select. When I load the form, the item in the dropdown is not selected. When I open the dropdown, the first item is selected:

When i select an item, and the reopen the dropdown, the item is selected (as expected)

```<code>                    <div class="col-lg-6">
                        <div class="form-group row">
                            <label for="customer" class="col-sm-2 col-form-label">Kunde</label>
                            <div class="col-sm-10">
                                <v-select :options="customers" :reduce="name => name.id"  v-model="form.customer_id" id="customer" label="name" placeholder="Kunde" :class="$vSelectStyle($v.form.customer_id)"></v-select>

                                <template v-if="$v.form.customer_id.$error" >
                                    <p class="text-danger" v-if="!$v.form.customer_id.required">
                                        Name ist erforderlich!
                                    </p>
                                </template>
                            </div>
                        </div>
                    </div>
</code>```

What i have to do that the item is selected the first time?

答:
You can add a v-model="someVar" and set it to some default value of your choice if this is what you're looking for.
Check the link for reference.

Body:
I'm using vue-select. When I load the form, the item in the dropdown is not selected. When I open the dropdown, the first item is selected:

When i select an item, and the reopen the dropdown, the item is selected (as expected)

                            Kunde

                                <v-select :options="customers" :reduce="name => name.id"  v-model="form.customer_id" id="customer" label="name" placeholder="Kunde" :class="$vSelectStyle($v.form.customer_id)"></v-select>

                                <template v-if="$v.form.customer_id.$error" >

                                        Name ist erforderlich!

                                </template>

What i have to do that the item is selected the first time?


来源: stackexchange

问:
Call function from another file - Discord bot
I am not familiar with Discord bots or much of Python so here's a simple question I can't figure out the answer to.

I have two files; discord_bot.py and test.py
How do I forward a message from test.py to send it to a channel in Discord?

test.py

```<code>import discord_bot

discord_bot.signal(msg = "Hi")
</code>```

discord_bot.py

```<code>import discord
from discord.ext import commands

TOKEN = '1234567890'
bot = commands.Bot(command_prefix='!')

@bot.command()
async def signal(ctx, *, msg):
    await ctx.send(msg)
</code>```

The Discord bot works fine but calling the signal function from test is not the correct way to do it. Any help here please?

答:
This is a lot to unpack.

0. Never post your discord token online. Discord may automatically invalidate your token if it's posted online.

1. You are not running your bot at the moment, add bot.run(TOKEN) at the end

2. How the commands of the discord bot extension work

@bot.command() is a decorator, if you do not know how they work, read up on it. Overly simplified, they take your function and register in the bot.

The inner workings of the commands extension are basically:

Register all commands by loading the decorators

Whenever a message arrives, check if it contains a prefix and if so, check if it fits a command.

If both checks from 2 passed, construct a Context object, then pass that object to the function. Something like the following:

signal(ctx, *args)
```

<p>This is why the ctx object can't be positional, because the way the function is called in the inner workings of the bot as a normal argument.</p>

<p><strong>4. Do not try to mess with creating your own context object, unless you know what you're doing.</strong> You only need to create context objects if you're overriding the default message parser.</p>

<p><strong>5. Don't use commands for this.</strong></p>

<p>What you want to do, as far as I can tell:
Call a command yourself. This is easy enough:</p>

<p>file 1:</p>

<pre class="lang-py prettyprint-override"><code>@bot.command()
async def signal(ctx, *, msg):
    print(msg)
</code>```

file 2:

from file1 import signal
import asyncio # if you don't know asyncio, read up on it

asyncio.run(signal(None, 'This is an argument'))
```

<p>This works easily, it prints your stuff. But you don't want it to be printed, right? You want it to be <strong>sent</strong> in a <strong>channel</strong>. This is what you need the context object for, which I said before, to not construct yourself. So how do we actually do this?</p>

<p>The answer is: <strong>Don't use commands</strong>. They are used for <em>reacting</em> to messages, not to be called by themselves.</p>

<p><strong>6. The solution you (probably) want</strong></p>

<p>So the major changes here are:</p>

<ol>
<li><p>signal is now a normal async function with no decorator</p></li>
<li><p>We actually specify a channel where we want the stuff to be sent in as an argument of the function</p></li>
</ol>

<p>file 1:</p>

<pre class="lang-py prettyprint-override"><code>import discord
from discord.ext import commands

TOKEN = 'do not share your token online'
bot = commands.Bot(command_prefix='!')

# as the channel_id, pass the channel_id you want the message to be sent in
async def signal(msg, channel_id):
    global bot # getting our bot variable from the global context
    channel = bot.get_channel(channel_id)
    await channel.send(msg)

bot.run(TOKEN)
</code>```

Major changes here are:

We use asyncio.run to call the function. Async functions cannot be called with regular syntax.

You'll probably need to run file2.py to start the program. Running file1 will not load file2.

file 2

```<code>from file1 import signal
from time import sleep
import asyncio

sleep(5) # We need to give our bot time to log in, or it won't work
asyncio.run(signal('hi!', 123))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am not familiar with Discord bots or much of Python so here's a simple question I can't figure out the answer to.

I have two files; discord_bot.py and test.py
How do I forward a message from test.py to send it to a channel in Discord?

test.py

import discord_bot

discord_bot.signal(msg = "Hi")

discord_bot.py

import discord
from discord.ext import commands

TOKEN = '1234567890'
bot = commands.Bot(command_prefix='!')

@bot.command()
async def signal(ctx, *, msg):
    await ctx.send(msg)

The Discord bot works fine but calling the signal function from test is not the correct way to do it. Any help here please?

Body:
This is a lot to unpack.

0. Never post your discord token online. Discord may automatically invalidate your token if it's posted online.

1. You are not running your bot at the moment, add bot.run(TOKEN) at the end

2. How the commands of the discord bot extension work

@bot.command() is a decorator, if you do not know how they work, read up on it. Overly simplified, they take your function and register in the bot.

The inner workings of the commands extension are basically:

Register all commands by loading the decorators

Whenever a message arrives, check if it contains a prefix and if so, check if it fits a command.

If both checks from 2 passed, construct a Context object, then pass that object to the function. Something like the following:

signal(ctx, *args)

This is why the ctx object can't be positional, because the way the function is called in the inner workings of the bot as a normal argument.

4. Do not try to mess with creating your own context object, unless you know what you're doing. You only need to create context objects if you're overriding the default message parser.

5. Don't use commands for this.

What you want to do, as far as I can tell:
Call a command yourself. This is easy enough:

file 1:

@bot.command()
async def signal(ctx, *, msg):
    print(msg)

file 2:

from file1 import signal
import asyncio # if you don't know asyncio, read up on it

asyncio.run(signal(None, 'This is an argument'))

This works easily, it prints your stuff. But you don't want it to be printed, right? You want it to be sent in a channel. This is what you need the context object for, which I said before, to not construct yourself. So how do we actually do this?

The answer is: Don't use commands. They are used for reacting to messages, not to be called by themselves.

6. The solution you (probably) want

So the major changes here are:

signal is now a normal async function with no decorator

We actually specify a channel where we want the stuff to be sent in as an argument of the function

file 1:

import discord
from discord.ext import commands

TOKEN = 'do not share your token online'
bot = commands.Bot(command_prefix='!')

# as the channel_id, pass the channel_id you want the message to be sent in
async def signal(msg, channel_id):
    global bot # getting our bot variable from the global context
    channel = bot.get_channel(channel_id)
    await channel.send(msg)

bot.run(TOKEN)

Major changes here are:

We use asyncio.run to call the function. Async functions cannot be called with regular syntax.

You'll probably need to run file2.py to start the program. Running file1 will not load file2.

file 2

from file1 import signal
from time import sleep
import asyncio

sleep(5) # We need to give our bot time to log in, or it won't work
asyncio.run(signal('hi!', 123))


问:
Email notification when disk drive reaches a certain percentage? (Laravel)
I'd love to be able to monitor my disk drives automatically with email notifications. I'm using Laravel (and therefore it should be possible to schedule a task to check) this but I'm unsure how to go about checking the available disk size through Laravel/PHP code. Any ideas?

I did find this article (but it's not strictly what I want as it uses shell directly to send emails and I want a laravel scheduled task to send the emails whenever it finds the disk drive at a specified percentage): https://www.cyberciti.biz/tips/shell-script-to-watch-the-disk-space.html

答:
One good way I would do this is, at first, prepare a function to check for disk space.

```<code>function spaceLimit($limitPercent) {
    $drive = "/";
    $space = (disk_free_space($drive) / disk_total_space($drive)) * 100;
    return $limitPercent < $space;
}
</code>```

Then, send an email after checking at a specific internal (in file app/Console/Kernel.php).

```<code>protected function schedule(Schedule $schedule)
{
    // Ensure queue:work is running
    $schedule->call(function() {
        // 90% and more space used
        if (spaceLimit(90)) {
            Mail::to('admin@me.com')->send(/* Some Mailable Class here */);
        }
    })->everyFiveMinutes(); // Change interval here
}
</code>```

Of course, the spaceLimit function can be stored in the same file, or in another, or wherever you want.

Also, you can imagine having an Event class to easily handle other kinds of notifications later (such as SMS, Push Notification, whatever..).

Don't forget you will need to configure a cron to execute your tasks. Crontab :

```<code>* * * * * cd /var/www/html && php artisan schedule:run >> /dev/null 2>&1
</code>```

And, if your emails are in a queue, you will also need to start the queue :

```<code>php artisan queue:listen
</code>```

Body:
One good way I would do this is, at first, prepare a function to check for disk space.

function spaceLimit($limitPercent) {
    $drive = "/";
    $space = (disk_free_space($drive) / disk_total_space($drive)) * 100;
    return $limitPercent < $space;
}

Then, send an email after checking at a specific internal (in file app/Console/Kernel.php).

protected function schedule(Schedule $schedule)
{
    // Ensure queue:work is running
    $schedule->call(function() {
        // 90% and more space used
        if (spaceLimit(90)) {
            Mail::to('admin@me.com')->send(/* Some Mailable Class here */);
        }
    })->everyFiveMinutes(); // Change interval here
}

Of course, the spaceLimit function can be stored in the same file, or in another, or wherever you want.

Also, you can imagine having an Event class to easily handle other kinds of notifications later (such as SMS, Push Notification, whatever..).

Don't forget you will need to configure a cron to execute your tasks. Crontab :

* * * * * cd /var/www/html && php artisan schedule:run >> /dev/null 2>&1

And, if your emails are in a queue, you will also need to start the queue :

php artisan queue:listen


问:
Passing variable arguments conditionally
In one of my iPhone application, I need to send the variable arguments to the action sheet conditionally. i.e

```<code>if(condition1)
    otherButtonTitles = @"Button1", @"Button2", nil
else
    otherButtonTitles = @"Button3", @"Button4", nil

UIActionSheet *mediaActionsSheet = [[UIActionSheet alloc] initWithTitle: nil
                                                             delegate: self
                                                    cancelButtonTitle: @"Cancel"
                                               destructiveButtonTitle: nil
                                                    otherButtonTitles: otherButtonTitles];
</code>```

What is the syntax to do this? How should the data type for otherButtonTitles be defined?

答:
you can create 2 action sheets and can check in delegate right for suitable action..
why not 2 action sheets ?

something like :
- (void)actionSheetUIActionSheet *)modalView clickedButtonAtIndexNSInteger)buttonIndex
{
if( modalView==_firstActionSheetView )
{
}
else
{
}
}

Body:
In one of my iPhone application, I need to send the variable arguments to the action sheet conditionally. i.e

if(condition1)
    otherButtonTitles = @"Button1", @"Button2", nil
else
    otherButtonTitles = @"Button3", @"Button4", nil

UIActionSheet *mediaActionsSheet = [[UIActionSheet alloc] initWithTitle: nil
                                                             delegate: self
                                                    cancelButtonTitle: @"Cancel"
                                               destructiveButtonTitle: nil
                                                    otherButtonTitles: otherButtonTitles];

What is the syntax to do this? How should the data type for otherButtonTitles be defined?

ContentLicense: CC BY-SA 3.0


问:
BlueSky Statistics Issues about Blue Sky Open Source-x64
Good morning,
I downloaded the latest release of Blue Sky Open Source-x64 on my laptop (Windows 64 bit) but it's not able to open it.
I attach to you the screenshots about the writings on my desktop when I try to open Blue Sky.
I look forward your reply.
Thank you in advance.
Best Regards,
Luca</p>

答:
Please send us all the log files from the following location:

C:\Users\\AppData\Roaming\BlueSky\Log

 is your Windows username in the above path.

Perform Cleanup

After sending us the logs delete the "BlueSky" folder from following location:

C:\Users\\AppData

After deleting "BlueSky" folder from the above location, try to launch the BlueSky Statistics application.


问:
Which element should handle data in React?
For example, there are 2 components:

```<code>class App extends React.Component {
  state = {
    comments=[1, 2, 3, 4]
  }
  render() {
    return (
      <Comments />
    )
  }
}

class Comments extends React.Component {
  render() {
    return (
        /* show comments */
    )
  }
}
</code>```

and I want to show only even comments. Should I put sorting function into App and send prepared array to Comments or send entire array and let Comments sort it by itself?

答: That's a design decision. But usually the View should just display the Model without any logic. That means your parent component App should filter the comments.

Body:
For example, there are 2 components:

class App extends React.Component {
  state = {
    comments=[1, 2, 3, 4]
  }
  render() {
    return (
      <Comments />
    )
  }
}

class Comments extends React.Component {
  render() {
    return (
        /* show comments */
    )
  }
}

and I want to show only even comments. Should I put sorting function into App and send prepared array to Comments or send entire array and let Comments sort it by itself?


问:
Postgresql update with string_agg
I have two tables say table 1 and table 2. I need to match the two tables with Party ID. If the party id matched and domain which is also matched then no need to update anything in an invalid email column. In case if party id matched and the domain is not matched with table 1 then update all the domain with comma-separated in the invalid column

Anyone help me on this.....!!

答:
You can try this :</p>

```<code>update table2
  set invalid_email=array_to_string(t1.domaines,';')
  from (select party_id,array_agg(domaine) as domaines from table1 group by party_id) t1
 where table2.party_id=t1.party_id and table2.domaine not in (select unnest(domaines))
</code>```

Title: Postgresql update with string_agg

Body:
You can try this :

update table2
  set invalid_email=array_to_string(t1.domaines,';')
  from (select party_id,array_agg(domaine) as domaines from table1 group by party_id) t1
 where table2.party_id=t1.party_id and table2.domaine not in (select unnest(domaines))


Title: combine two column into one - Date and Time Column with changing their format

Body:
Structure of Data

str(noaaData)

'data.frame':   92 obs. of  3 variables:
 $ Date         : int  20121029 20121029 20121029 20121029 20121029 20121029 20121029 20121029 20121029 20121029 ...
 $ Time         : int  100 200 300 400 500 600 700 800 900 1000 ...
 $ AtmosPressure: num  999 999 998 998 997 ...

I need to combine Date & Time in one column with name "DateTime" by changing them into POSIXct format "%Y-%m-%d %H:%M:%OS"

It should look like this

2012-10-29 01:00:00

minimal reproducible

dput(noaaData)

structure(list(Date = c(20121029L, 20121029L, 20121029L, 20121029L,
20121029L, 20121029L, 20121029L, 20121029L, 20121029L, 20121029L,
20121029L, 20121029L, 20121029L, 20121029L, 20121029L, 20121029L,
20121029L, 20121029L, 20121029L, 20121029L, 20121029L, 20121029L,
20121029L, 20121030L, 20121030L, 20121030L, 20121030L, 20121030L,
20121030L, 20121030L, 20121030L, 20121030L, 20121030L, 20121030L,
20121030L, 20121030L, 20121030L, 20121030L, 20121030L, 20121030L,
20121030L, 20121030L, 20121030L, 20121030L, 20121031L, 20121031L,
20121031L, 20121031L, 20121031L, 20121031L, 20121031L, 20121031L,
20121031L, 20121031L, 20121031L, 20121031L, 20121031L, 20121031L,
20121031L, 20121031L, 20121031L, 20121031L, 20121031L, 20121031L,
20121031L, 20121031L, 20121031L, 20121031L, 20121101L, 20121101L,
20121101L, 20121101L, 20121101L, 20121101L, 20121101L, 20121101L,
20121101L, 20121101L, 20121101L, 20121101L, 20121101L, 20121101L,
20121101L, 20121101L, 20121101L, 20121101L, 20121101L, 20121101L,
20121101L, 20121101L, 20121101L, 20121101L), Time = structure(c(8640000,
17280000, 25920000, 34560000, 43200000, 51840000, 60480000, 69120000,
77760000, 86400000, 95040000, 103680000, 112320000, 120960000,
129600000, 138240000, 146880000, 155520000, 164160000, 172800000,
181440000, 190080000, 198720000, 25920000, 34560000, 43200000,
51840000, 60480000, 69120000, 77760000, 86400000, 95040000, 103680000,
112320000, 120960000, 129600000, 138240000, 146880000, 155520000,
164160000, 172800000, 181440000, 190080000, 198720000, 0, 8640000,
17280000, 25920000, 34560000, 43200000, 51840000, 60480000, 69120000,
77760000, 86400000, 95040000, 103680000, 112320000, 120960000,
129600000, 138240000, 146880000, 155520000, 164160000, 172800000,
181440000, 190080000, 198720000, 0, 8640000, 17280000, 25920000,
34560000, 43200000, 51840000, 60480000, 69120000, 77760000, 86400000,
95040000, 103680000, 112320000, 120960000, 129600000, 138240000,
146880000, 155520000, 164160000, 172800000, 181440000, 190080000,
198720000), class = c("POSIXct", "POSIXt")), AtmosPressure = c(999.2,
999.2, 998.3, 997.9, 996.7, 995.4, 994.4, 992, 990.2, 988.4,
987.1, 985.9, 984, 981.5, 978.8, 975.3, 971.4, 966.3, 961.9,
956.1, 951.4, 949.7, 946.3, 968, 972.9, 976.5, 979.4, 981.2,
982.5, 983.7, 985, 986.2, 987.5, 988.9, 990.1, 991, 992, 992.6,
993, 993.4, 994.1, 994.6, 995.4, 996, 996.6, 997, 997.1, 997.3,
997.3, 997.4, 997.2, 997.2, 997.5, 997.8, 998.3, 998.6, 999,
999.8, 1000, 1000.1, 1000.2, 999.7, 999.5, 999.1, 999.5, 1000,
1000.4, 1001.1, 1001.3, 1001.6, 1001.7, 1001.8, 1001.7, 1001.7,
1001.7, 1002, 1001.9, 1001.9, 1002.1, 1002, 1002.5, 1002.9, 1003.1,
1003, 1003.1, 1002.5, 1002.1, 1001.8, 1001.9, 1001.9, 1002.2,
1002.9)), row.names = c(NA, -92L), class = "data.frame")

I request someone to please help me in this.

Body:
Here is one way:

noaaData <- data.frame(
  Date = c(20121029,20121029, 20121029, 20121029, 20121029, 20121029, 20121029),
  Time = c(400, 500, 600, 700, 800, 900, 1000),
  stringsAsFactors = FALSE
)
strptime(
  paste(noaaData$Date, formatC(noaaData$Time, width = 4, format = "d", flag = "0")),
  format = "%Y%m%d %H%M"
)
[1] "2012-10-29 04:00:00 CET" "2012-10-29 05:00:00 CET" "2012-10-29 06:00:00 CET" "2012-10-29 07:00:00 CET" "2012-10-29 08:00:00 CET"
[6] "2012-10-29 09:00:00 CET" "2012-10-29 10:00:00 CET"

You might want to change timezone tz in strptime


问:
Integrating Apache Superset and Apache Drill
I installed Apache Drill through the link in the Drill Documentation. Apache Drill works fine. I also installed and got Apache Superset running using docker. Superset also works totally fine.

But my goal is to integrate Superset and Drill together. The only tutorial I was able to find was a tutorial from Dataist. When following this tutorial they ask us to add a database.

Since I am running both Drill and Superset in my local machine they ask us to type drill+sadrill://localhost:8047/dfs/test?use_ssl=False as the SQLAlchemy URI. They ask us to test the connection by pressing test connection.

When pressing test connection I get an error message as follows.

ERROR: {"error": "Connection failed!\n\nThe error message returned was:\nCan't load plugin: sqlalchemy.dialects:drill.sadrill", "stacktrace": "Traceback (most recent call last):\n  File \"/home/superset/superset/views/core.py\", line 1755, in testconn\n    engine = database.get_sqla_engine(user_name=username)\n  File \"/home/superset/superset/utils/core.py\", line 132, in __call__\n    value = self.func(*args, **kwargs)\n  File \"/home/superset/superset/models/core.py\", line 911, in get_sqla_engine\n    return create_engine(url, **params)\n  File \"/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/__init__.py\", line 435, in create_engine\n    return strategy.create(*args, **kwargs)\n  File \"/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/strategies.py\", line 61, in create\n    entrypoint = u._get_entrypoint()\n  File \"/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/url.py\", line 172, in _get_entrypoint\n    cls = registry.load(name)\n  File \"/usr/local/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py\", line 240, in load\n    \"Can't load plugin: %s:%s\" % (self.group, name)\nsqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:drill.sadrill\n"}

Can someone figure out why I am getting this error. And also if there are any other tutorials to follow which give a better idea on how to set up Drill and superset.

答:
I have encountered a similar issue while trying to connect elasticsearch. I guess the docker image you used was amancevice/superset. This issue cause because your image is not using the latest SQLAlchemy, SQLAlchemy-Utils packages. Upgrade or reinstall these packages to fix the issue.

To uninstall:

pip uninstall SQLAlchemy
pip uninstall SQLAlchemy-Utils

To install again (latest version):

pip install SQLAlchemy
pip install SQLAlchemy-Utils

I have reported this issue here https://github.com/amancevice/docker-superset/issues/158 maybe it get fixed with the upcoming images.


问:
(Excel) Is there a way to conditional format a cell from a range of cells based on the value of an another cell?
I have a cell with a text, which is the place of an another cell that I want to highlight. Lets say that it is the F6 cell, and in it, it says 'C6'. Is there a way to use conditional formatting to highlight the 'C6' cell ? Any other cell can be inputted into the F6 cell and the formatting will highlight it, if it is in the Data range.

答:
If you are happy to write $C$6 you could use CELL()

Define conditional formating on B4:D7 as =CELL("address",B4)=$F$6
=CELL("address",B4) will return the reference of that cell in the from of $COLUMN$ROW (e.g. $C$6 for the cell C6) and that you can then compare.


问:
configure: error: Please reinstall the BZip2 distribution
I am trying to compile php from source on mac with the bzip2 extension and I keep getting an error saying

checking for BZip2 in default path... not found

I've tried setting the LDFLAGS and CPPFLAGS but that doesn't seem to work.

The dylib is in /usr/local/opt/bzip2/lib and the header files are in usr/local/opt/bzip2/include.

答:
I had the exact same issue. I resolved it by installing bzip2 by using brew.

brew install bzip2


问:
Error class not found when I extends a class
I've two files in one directory named (classes )which contain classes, first one for main class (Database ) which build to connect to the database.
And the second one (Branch ) extends Database class which made to get data from the database.

When I try to run "getBranch" function I got an error says :

Uncaught Error: Class 'Database' not found in C:\xampp\htdocs\branches\classes\branch.php

Please find the codes below and advise what's required.

database.php:

```<code><?php

  class Database {
    private $host;
    private $user;
    private $pwd;
    private $dbName;
    public $conn;

    public function connect() {
      $this->host = "localhost";
      $this->user = "root";
      $this->pwd = "";
      $this->dbName = "branchs";
      //create connection
      $conn = new mysqli($this->host, $this->user, $this->pwd, $this->dbName);
      //chech connection
      if ($conn->connect_error) {
        die("Connection failed :" . $conn->connect_error);
      } else {
        echo "Success";
      }

      return $conn;

    }

  }

?>
</code>```

branch.php :

```<code><?php

    class Branch extends Database {

      public function getBranch() {

      $sql = "SELECT * FROM branches";
      $result = $this->connect()->query($sql);

      if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
          echo "Name :" . $row['brName'] . "City :" . $row['brCity'] . "<br>";
        }
      } else {
        echo "0 results";
      }

      }

    }

?>
</code>```

答:
You must include "database.php" file into top of "branch.php" file

```<code><?php include 'database.php'; ?>
</code>```

Also, take a look about autoload concept with php. https://www.php.net/manual/en/language.oop5.autoload.php

Body:
I've two files in one directory named (classes )which contain classes, first one for main class (Database ) which build to connect to the database.
And the second one (Branch ) extends Database class which made to get data from the database.

When I try to run "getBranch" function I got an error says :

Uncaught Error: Class 'Database' not found in C:\xampp\htdocs\branches\classes\branch.php

Please find the codes below and advise what's required.

database.php:

<?php

  class Database {
    private $host;
    private $user;
    private $pwd;
    private $dbName;
    public $conn;

    public function connect() {
      $this->host = "localhost";
      $this->user = "root";
      $this->pwd = "";
      $this->dbName = "branchs";
      //create connection
      $conn = new mysqli($this->host, $this->user, $this->pwd, $this->dbName);
      //chech connection
      if ($conn->connect_error) {
        die("Connection failed :" . $conn->connect_error);
      } else {
        echo "Success";
      }

      return $conn;

    }

  }

?>

branch.php :

<?php

    class Branch extends Database {

      public function getBranch() {

      $sql = "SELECT * FROM branches";
      $result = $this->connect()->query($sql);

      if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
          echo "Name :" . $row['brName'] . "City :" . $row['brCity'] . "
";
        }
      } else {
        echo "0 results";
      }

      }

    }

?>

Body:
You must include "database.php" file into top of "branch.php" file

<?php include 'database.php'; ?>

Also, take a look about autoload concept with php. https://www.php.net/manual/en/language.oop5.autoload.php


问:
XPath for table
I have such xml:

ID

NAME

City

id-10341

Anna

London

id-10249

Eva

Paris

```

I need to define xpath to a cell with class SelectBox in a line containing text id-10249

I tried to use this way, but it didn’t help.

//tbody//*[contains(text(),'id-10249')]//parent::tr//div[@class='SelectBox']

答:
Here is a variant of an XPath:

//tbody/tr[td/div[contains(text(),'id-10249')]]/td/div[@class='SelectBox']

You select tr elements which satisfy the condition for contaning text in div element and than search inside this tr element for div element with a specified class.

Title: XPath for table

Body:
I have such xml:

ID

NAME

City

id-10341

Anna

London

id-10249

Eva

Paris

I need to define xpath to a cell with class SelectBox in a line containing text id-10249

I tried to use this way, but it didn’t help.

//tbody//*[contains(text(),'id-10249')]//parent::tr//div[@class='SelectBox']


问:
Can I have both a code-behind Click event as well as a Command?
I'd like to know if I can have both a button click event in the code-behind, as well as a command in the viewmodel, and they both work? Like this:</p>

```<code><Button x:Name="CancelButton"
        Command="{Binding CancelCommand}"
        Content="Cancel" Click="CancelButton_Click" />
</code>```

答:
Sure you can. The Click event handler will be invoked and executed before the Execute method of the command.

Note that implementing any application logic in the Click event handler in the view effectively breaks the MVVM pattern though.

Body:
I'd like to know if I can have both a button click event in the code-behind, as well as a command in the viewmodel, and they both work? Like this:

<Button x:Name="CancelButton"
        Command="{Binding CancelCommand}"
        Content="Cancel" Click="CancelButton_Click" />


问:
Git init -q Permissions error while installing Homebrew
I'm attempting to install HomeBrew on OS X 10.12.6. When I use the autoinstall script from Homebrew's website:

```<code>/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
</code>```

Everything runs smoothly until it begins actually downloading and installing Homebrew, at which point it returns the following error:

```<code>==> Downloading and installing Homebrew...
/usr/local/homebrew/.git: Permission denied
Failed during: git init -q
</code>```

Any tips of how to resolve this? Any assistance would be greatly appreciated!

答:
Maybe git is missing:

apt install git

Body:
I'm attempting to install HomeBrew on OS X 10.12.6. When I use the autoinstall script from Homebrew's website:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Everything runs smoothly until it begins actually downloading and installing Homebrew, at which point it returns the following error:

==> Downloading and installing Homebrew...
/usr/local/homebrew/.git: Permission denied
Failed during: git init -q

Any tips of how to resolve this? Any assistance would be greatly appreciated!

Body:
Maybe git is missing:

apt install git


问:
How do I format a date in JavaScript?
How do I format a Date object to a string?

答:
This function was inspired by Java's SimpleDateFormat provides various formats such as:

```<code>dd-MMM-yyyy → 17-Jul-2018
yyyyMMdd'T'HHmmssXX → 20180717T120856+0900
yyyy-MM-dd'T'HH:mm:ssXXX → 2018-07-17T12:08:56+09:00
E, dd MMM yyyy HH:mm:ss Z → Tue, 17 Jul 2018 12:08:56 +0900
yyyy.MM.dd 'at' hh:mm:ss Z → 2018.07.17 at 12:08:56 +0900
EEE, MMM d, ''yy → Tue, Jul 17, '18
h:mm a → 12:08 PM
hh 'o''''clock' a, X → 12 o'clock PM, +09
</code>```

Code example:

function formatWith(formatStr, date, opts) {

    if (!date) {
        date = new Date();
    }

    opts = opts || {};

    let _days = opts.days;

    if (!_days) {
        _days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    }

    let _months = opts.months;

    if (!_months) {
        _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    }

    const pad = (number, strDigits, isUnpad) => {
        const strNum = number.toString();
        if (!isUnpad && strNum.length > strDigits.length) {
            return strNum;
        } else {
            return ('0000' + strNum).slice(-strDigits.length);
        }
    };

    const timezone = (date, letter) => {
        const chunk = [];
        const offset = -date.getTimezoneOffset();
        chunk.push(offset === 0 ? 'Z' : offset > 0 ? '+' : '-');//add Z or +,-
        if (offset === 0) return chunk;
        chunk.push(pad(Math.floor(offset / 60), '00'));//hour
        if (letter === 'X') return chunk.join('');
        if (letter === 'XXX') chunk.push(':');
        chunk.push(pad((offset % 60), '00'));//min
        return chunk.join('');
    };

    const ESCAPE_DELIM = '\0';
    const escapeStack = [];

    const escapedFmtStr = formatStr.replace(/'.*?'/g, m => {
        escapeStack.push(m.replace(/'/g, ''));
        return ESCAPE_DELIM + (escapeStack.length - 1) + ESCAPE_DELIM;
    });

    const formattedStr = escapedFmtStr
        .replace(/y{4}|y{2}/g, m => pad(date.getFullYear(), m, true))
        .replace(/M{3}/g, m => _months[date.getMonth()])
        .replace(/M{1,2}/g, m => pad(date.getMonth() + 1, m))
        .replace(/M{1,2}/g, m => pad(date.getMonth() + 1, m))
        .replace(/d{1,2}/g, m => pad(date.getDate(), m))
        .replace(/H{1,2}/g, m => pad(date.getHours(), m))
        .replace(/h{1,2}/g, m => {
            const hours = date.getHours();
            return pad(hours === 0 ? 12 : hours > 12 ? hours - 12 : hours, m);
        })
        .replace(/a{1,2}/g, m => date.getHours() >= 12 ? 'PM' : 'AM')
        .replace(/m{1,2}/g, m => pad(date.getMinutes(), m))
        .replace(/s{1,2}/g, m => pad(date.getSeconds(), m))
        .replace(/S{3}/g, m => pad(date.getMilliseconds(), m))
        .replace(/[E]+/g, m => _days[date.getDay()])
        .replace(/[Z]+/g, m => timezone(date, m))
        .replace(/X{1,3}/g, m => timezone(date, m))
    ;

    const unescapedStr = formattedStr.replace(/\0\d+\0/g, m => {
        const unescaped = escapeStack.shift();
        return unescaped.length > 0 ? unescaped : '\'';
    });

    return unescapedStr;
}

// Let's format with above function
const dateStr = '2018/07/17 12:08:56';
const date = new Date(dateStr);
const patterns = [
    "dd-MMM-yyyy",
    "yyyyMMdd'T'HHmmssXX",//ISO8601
    "yyyy-MM-dd'T'HH:mm:ssXXX",//ISO8601EX
    "E, dd MMM yyyy HH:mm:ss Z",//RFC1123(RFC822) like email
    "yyyy.MM.dd 'at' hh:mm:ss Z",//hh shows 1-12
    "EEE, MMM d, ''yy",
    "h:mm a",
    "hh 'o''''clock' a, X",
];

for (let pattern of patterns) {
    console.log(`${pattern} → ${formatWith(pattern, date)}`);
}```
</div>
</div>
</p>
<p><strong>And you can use this as a library</strong></p>
<p>It is also released as an NPM module. You can use this on Node.js or use this from a CDN for a browser.</p>
<p><strong>Node.js</strong></p>
```const {SimpleDateFormat} = require('@riversun/simple-date-format');
```
<p><strong>In the browser</strong></p>
```
```
<p>Write the code as follows.</p>
```const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat();
console.log(sdf.formatWith("yyyy-MM-dd'T'HH:mm:ssXXX", date));//to be "2018-07-17T12:08:56+09:00"
```

Source code here on GitHub:

https://github.com/riversun/simple-date-format

Title: How do I format a date in JavaScript?

Body:
This function was inspired by Java's SimpleDateFormat provides various formats such as:

dd-MMM-yyyy → 17-Jul-2018
yyyyMMdd'T'HHmmssXX → 20180717T120856+0900
yyyy-MM-dd'T'HH:mm:ssXXX → 2018-07-17T12:08:56+09:00
E, dd MMM yyyy HH:mm:ss Z → Tue, 17 Jul 2018 12:08:56 +0900
yyyy.MM.dd 'at' hh:mm:ss Z → 2018.07.17 at 12:08:56 +0900
EEE, MMM d, ''yy → Tue, Jul 17, '18
h:mm a → 12:08 PM
hh 'o''''clock' a, X → 12 o'clock PM, +09

Code example:

function formatWith(formatStr, date, opts) {

    if (!date) {
        date = new Date();
    }

    opts = opts || {};

    let _days = opts.days;

    if (!_days) {
        _days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    }

    let _months = opts.months;

    if (!_months) {
        _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    }

    const pad = (number, strDigits, isUnpad) => {
        const strNum = number.toString();
        if (!isUnpad && strNum.length > strDigits.length) {
            return strNum;
        } else {
            return ('0000' + strNum).slice(-strDigits.length);
        }
    };

    const timezone = (date, letter) => {
        const chunk = [];
        const offset = -date.getTimezoneOffset();
        chunk.push(offset === 0 ? 'Z' : offset > 0 ? '+' : '-');//add Z or +,-
        if (offset === 0) return chunk;
        chunk.push(pad(Math.floor(offset / 60), '00'));//hour
        if (letter === 'X') return chunk.join('');
        if (letter === 'XXX') chunk.push(':');
        chunk.push(pad((offset % 60), '00'));//min
        return chunk.join('');
    };

    const ESCAPE_DELIM = '\0';
    const escapeStack = [];

    const escapedFmtStr = formatStr.replace(/'.*?'/g, m => {
        escapeStack.push(m.replace(/'/g, ''));
        return ESCAPE_DELIM + (escapeStack.length - 1) + ESCAPE_DELIM;
    });

    const formattedStr = escapedFmtStr
        .replace(/y{4}|y{2}/g, m => pad(date.getFullYear(), m, true))
        .replace(/M{3}/g, m => _months[date.getMonth()])
        .replace(/M{1,2}/g, m => pad(date.getMonth() + 1, m))
        .replace(/M{1,2}/g, m => pad(date.getMonth() + 1, m))
        .replace(/d{1,2}/g, m => pad(date.getDate(), m))
        .replace(/H{1,2}/g, m => pad(date.getHours(), m))
        .replace(/h{1,2}/g, m => {
            const hours = date.getHours();
            return pad(hours === 0 ? 12 : hours > 12 ? hours - 12 : hours, m);
        })
        .replace(/a{1,2}/g, m => date.getHours() >= 12 ? 'PM' : 'AM')
        .replace(/m{1,2}/g, m => pad(date.getMinutes(), m))
        .replace(/s{1,2}/g, m => pad(date.getSeconds(), m))
        .replace(/S{3}/g, m => pad(date.getMilliseconds(), m))
        .replace(/[E]+/g, m => _days[date.getDay()])
        .replace(/[Z]+/g, m => timezone(date, m))
        .replace(/X{1,3}/g, m => timezone(date, m))
    ;

    const unescapedStr = formattedStr.replace(/\0\d+\0/g, m => {
        const unescaped = escapeStack.shift();
        return unescaped.length > 0 ? unescaped : '\'';
    });

    return unescapedStr;
}

// Let's format with above function
const dateStr = '2018/07/17 12:08:56';
const date = new Date(dateStr);
const patterns = [
    "dd-MMM-yyyy",
    "yyyyMMdd'T'HHmmssXX",//ISO8601
    "yyyy-MM-dd'T'HH:mm:ssXXX",//ISO8601EX
    "E, dd MMM yyyy HH:mm:ss Z",//RFC1123(RFC822) like email
    "yyyy.MM.dd 'at' hh:mm:ss Z",//hh shows 1-12
    "EEE, MMM d, ''yy",
    "h:mm a",
    "hh 'o''''clock' a, X",
];

for (let pattern of patterns) {
    console.log(`${pattern} → ${formatWith(pattern, date)}`);
}

And you can use this as a library

It is also released as an NPM module. You can use this on Node.js or use this from a CDN for a browser.

Node.js

const {SimpleDateFormat} = require('@riversun/simple-date-format');

In the browser

<script src="https://cdn.jsdelivr.net/npm/@riversun/simple-date-format@1.0.2/dist/simple-date-format.js"></script>

Write the code as follows.

const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat();
console.log(sdf.formatWith("yyyy-MM-dd'T'HH:mm:ssXXX", date));//to be "2018-07-17T12:08:56+09:00"

Source code here on GitHub:

https://github.com/riversun/simple-date-format


问:
Web scraping with R - html content
I am trying web scraping with R, but I am having problems pulling html content from the web.

Here is an exercise I'm doing on an example page from Amazon with some queries.

```<code>library(XML)

#> Warning message:
#> XML package is in R 3.5.3 version

my_url99 <- "https://www.amazon.com/s?k=Dell+laptop+windows+10&ref=nb_sb_noss_2"
html_page99 <- htmlTreeParse(my_url99, useInternalNode=TRUE)

#> Warning message:
#> XML content does not seem to be XML: 'https://www.amazon.com/s?k=Dell+laptop+windows+10&ref=nb_sb_noss_2'

head(html_page99)

#> Error in `[.XMLInternalDocument`(x, seq_len(n)) :
#>  No method for subsetting an XMLInternalDocument with integer

html_page99

#> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
#> <html><body><p>https://www.amazon.com/s?k=Dell+laptop+windows+10&ref=nb_sb_noss_2</p></body></html>
</code>```

But I need to scrape the above page with full content. I mean content with $ sign on the left (maybe that's not the best direct description) and all the tags.

答:
Without a lot of experience in scraping and manipulating strings, it is difficult to get at the data you want. As @ThomasL points out, using the XML library is not the best way forward. Here is how you could achieve the results you want using the rvest library:

library(rvest)
#> Loading required package: xml2
library(tibble)

my_url99 <- "https://www.amazon.com/s?k=Dell+laptop+windows+10&ref=nb_sb_noss_2"

read_html(my_url99)                                                       %>%
html_nodes(xpath = "//div[@class = 'sg-row']")                            %>%
html_text()                                                               %>%
{gsub("\n", " ", .)}                                                      %>%
{grep("5 stars", ., value = TRUE)}                                        %>%
{grep("Sponsored", ., invert = TRUE, value = TRUE)}                       %>%
{gsub("^ +", "", .)}                                                      %>%
{grep("[$]", ., value = TRUE)}                                            %>%
{gsub("[$][0123456789.]+[$]", "$", .)}                                    %>%
strsplit(" {2,50}")                                                       %>%
lapply(function(x) x[x != ""])                                            %>%
lapply(function(x) { grep("Buying Choices|Ships to|in stock|new offers",
                          x, invert = TRUE, value = TRUE)              }) %>%
lapply(function(x) if(length(x) < 4) NULL else x[c(1, 2, 4)])             %>%
{do.call(rbind, .)}                                                       %>%
`colnames<-`(c("Model", "Rating","Price"))                                %>%
as_tibble()                                                                ->
result
```

<p>Giving you a 3 column data frame (or tibble) with model, star rating and price:</p>

```result
#> # A tibble: 15 x 3
#>    Model                                                   Rating         Price
#>    <chr>                                                   <chr>          <chr>
#>  1 "Dell Latitude E6430 Laptop WEBCAM - HDMI - Intel Core~ 4.0 out of 5 ~ $201.~
#>  2 "New ! Dell Inspiron i3583 15.6\" HD Touch-Screen Lapt~ 4.3 out of 5 ~ $349.~
#>  3 "2019_Dell Inspiron 15.6\" HD High Performance Laptop,~ 3.9 out of 5 ~ $300.~
#>  4 "Dell Inspiron 15.6” Touch Screen Intel Core i3 128GB ~ 4.1 out of 5 ~ $365.~
#>  5 "Dell Inspiron 15.6 Inch HD Touchscreen Flagship High ~ 4.1 out of 5 ~ $443.~
#>  6 "Dell Latitude E5450 14in Laptop, Intel Core i5-5300U ~ 3.7 out of 5 ~ $225.~
#>  7 "New ! Dell Inspiron i3583 15.6\" HD Touch-Screen Lapt~ 4.5 out of 5 ~ $445.~
#>  8 "Dell 14inch High Performance Latitude 3340 Notebook, ~ 4.1 out of 5 ~ $199.~
#>  9 "2018 Dell Business Flagship Laptop Notebook 15.6\" HD~ 3.4 out of 5 ~ $567.~
#> 10 "Dell Latitude E6420 Laptop - HDMI - i5 2.5ghz - 4GB D~ 3.3 out of 5 ~ $178.~
#> 11 "Newest_Dell Vostro Real Business(Better Design Than I~ 3.6 out of 5 ~ $689.~
#> 12 "2019 Dell Inspiron 15 6\" HD Touchscreen Flagship Pre~ 4.0 out of 5 ~ $348.~
#> 13 "2019 Dell Inspiron 14\" Laptop Computer| 10th Gen Int~ 4.1 out of 5 ~ $328.~
#> 14 "2019 Dell Inspiron 15 6\" HD Touchscreen Flagship Pre~ 4.4 out of 5 ~ $442.~
#> 15 "Fast Dell Latitude E5470 HD Business Laptop Notebook ~ 4.5 out of 5 ~ $288.~
```

Created on 2020-02-17 by the reprex package (v0.3.0)

Title: Web scraping with R - html content

Body:
I am trying web scraping with R, but I am having problems pulling html content from the web.

Here is an exercise I'm doing on an example page from Amazon with some queries.

library(XML)

#> Warning message:
#> XML package is in R 3.5.3 version

my_url99 <- "https://www.amazon.com/s?k=Dell+laptop+windows+10&ref=nb_sb_noss_2"
html_page99 <- htmlTreeParse(my_url99, useInternalNode=TRUE)

#> Warning message:
#> XML content does not seem to be XML: 'https://www.amazon.com/s?k=Dell+laptop+windows+10&ref=nb_sb_noss_2'

head(html_page99)

#> Error in `[.XMLInternalDocument`(x, seq_len(n)) :
#>  No method for subsetting an XMLInternalDocument with integer

html_page99

#> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
#>
https://www.amazon.com/s?k=Dell+laptop+windows+10&ref=nb_sb_noss_2

But I need to scrape the above page with full content. I mean content with $ sign on the left (maybe that's not the best direct description) and all the tags.

Body:
Without a lot of experience in scraping and manipulating strings, it is difficult to get at the data you want. As @ThomasL points out, using the XML library is not the best way forward. Here is how you could achieve the results you want using the rvest library:

library(rvest)
#> Loading required package: xml2
library(tibble)

my_url99 <- "https://www.amazon.com/s?k=Dell+laptop+windows+10&ref=nb_sb_noss_2"

read_html(my_url99)                                                       %>%
html_nodes(xpath = "//div[@class = 'sg-row']")                            %>%
html_text()                                                               %>%
{gsub("\n", " ", .)}                                                      %>%
{grep("5 stars", ., value = TRUE)}                                        %>%
{grep("Sponsored", ., invert = TRUE, value = TRUE)}                       %>%
{gsub("^ +", "", .)}                                                      %>%
{grep("[$]", ., value = TRUE)}                                            %>%
{gsub("[$][0123456789.]+[$]", "$", .)}                                    %>%
strsplit(" {2,50}")                                                       %>%
lapply(function(x) x[x != ""])                                            %>%
lapply(function(x) { grep("Buying Choices|Ships to|in stock|new offers",
                          x, invert = TRUE, value = TRUE)              }) %>%
lapply(function(x) if(length(x) < 4) NULL else x[c(1, 2, 4)])             %>%
{do.call(rbind, .)}                                                       %>%
`colnames<-`(c("Model", "Rating","Price"))                                %>%
as_tibble()                                                                ->
result

Giving you a 3 column data frame (or tibble) with model, star rating and price:

result
#> # A tibble: 15 x 3
#>    Model                                                   Rating         Price
#>    <chr>                                                   <chr>          <chr>
#>  1 "Dell Latitude E6430 Laptop WEBCAM - HDMI - Intel Core~ 4.0 out of 5 ~ $201.~
#>  2 "New ! Dell Inspiron i3583 15.6\" HD Touch-Screen Lapt~ 4.3 out of 5 ~ $349.~
#>  3 "2019_Dell Inspiron 15.6\" HD High Performance Laptop,~ 3.9 out of 5 ~ $300.~
#>  4 "Dell Inspiron 15.6” Touch Screen Intel Core i3 128GB ~ 4.1 out of 5 ~ $365.~
#>  5 "Dell Inspiron 15.6 Inch HD Touchscreen Flagship High ~ 4.1 out of 5 ~ $443.~
#>  6 "Dell Latitude E5450 14in Laptop, Intel Core i5-5300U ~ 3.7 out of 5 ~ $225.~
#>  7 "New ! Dell Inspiron i3583 15.6\" HD Touch-Screen Lapt~ 4.5 out of 5 ~ $445.~
#>  8 "Dell 14inch High Performance Latitude 3340 Notebook, ~ 4.1 out of 5 ~ $199.~
#>  9 "2018 Dell Business Flagship Laptop Notebook 15.6\" HD~ 3.4 out of 5 ~ $567.~
#> 10 "Dell Latitude E6420 Laptop - HDMI - i5 2.5ghz - 4GB D~ 3.3 out of 5 ~ $178.~
#> 11 "Newest_Dell Vostro Real Business(Better Design Than I~ 3.6 out of 5 ~ $689.~
#> 12 "2019 Dell Inspiron 15 6\" HD Touchscreen Flagship Pre~ 4.0 out of 5 ~ $348.~
#> 13 "2019 Dell Inspiron 14\" Laptop Computer| 10th Gen Int~ 4.1 out of 5 ~ $328.~
#> 14 "2019 Dell Inspiron 15 6\" HD Touchscreen Flagship Pre~ 4.4 out of 5 ~ $442.~
#> 15 "Fast Dell Latitude E5470 HD Business Laptop Notebook ~ 4.5 out of 5 ~ $288.~

Created on 2020-02-17 by the reprex package (v0.3.0)


问:
Immutable classes and memory in C++
So, I'm getting deeper into C++ than I did in school as part of a personal project I'm working on. I'm a Java developer, so memory management is a little hard to get used to again, and now that I'm going out of my way to code a certain way, I have a quick question about immutable classes.

When I think about them as a concept, I of course compare them to Strings in Java. But now that I'm in C++, a reassignment operation can potentially create a memory leak (or at least, I think it can). So now if I do this:

```<code>  MyImmutableClass a ("blah");
  a = a.modifyInSomeWay();
</code>```

where modifyInSomeWay returns a new instance of MyImmutableClass, I haven't called the deconstructor. Is there something I'm missing here that would prevent the first assignment of 'a' from sticking around in memory?

答: The style of sharing immutable value objects which is found in lots of places in Java does not work very well in C++ due to its value semantics. Saying "the object should be immutable, but assignment should still work" is a contradiction. You could use variables of type shared_ptr<your_immutable_type>, but that clutters up the code, and hence very few people do it in practice.

Title: Immutable classes and memory in C++

Body:
So, I'm getting deeper into C++ than I did in school as part of a personal project I'm working on. I'm a Java developer, so memory management is a little hard to get used to again, and now that I'm going out of my way to code a certain way, I have a quick question about immutable classes.

When I think about them as a concept, I of course compare them to Strings in Java. But now that I'm in C++, a reassignment operation can potentially create a memory leak (or at least, I think it can). So now if I do this:

  MyImmutableClass a ("blah");
  a = a.modifyInSomeWay();

where modifyInSomeWay returns a new instance of MyImmutableClass, I haven't called the deconstructor. Is there something I'm missing here that would prevent the first assignment of 'a' from sticking around in memory?


问:
How to remove all formatting from the output of a console command written in PHP
I have some commands that format the output to the console.

Those commands are written using the Symfony Console component and formatted using its styles.

When run in the console, the formatting is good, but those commands are often also run from a queue system I wrote and so the logs are then shown on an HTML page.

The result is really hard to understand as it is filled with all the formatting "tag" that are useful on the console but are completely unuseful when the output is read on a web page.

Here an example of what I'm saying:

```<code>[32mStarting command[39m
[32m===========================[39m

[34m[>] Analyzing Entity [39m[32This is the entity[39m[34m.                                             [39m
[34m[>] Starting analyzing Entity [39m[32mThis is the entity[39m[34m.                                    [39m
[34m[>] Creating new Job for [39m[30;42This is the entity[39;49m[34m to analyze it in [39m[30;42m+1 week[39;49m[34m (Cause: The Entity is a clone of [39m[30;42Entity2[39;49m[34m).[39m
[34m[>] New Job for [39m[30;42mEntity[39;49m[34m created.                                         [39m
...
</code>```

As you can see the output is almost non readable.

How can I remove all the formatting from it before saving it to the database?

答: Another option is to call Symfony\Component\Console\Helper\Helper::removeDecoration()

Body:
I have some commands that format the output to the console.

Those commands are written using the Symfony Console component and formatted using its styles.

When run in the console, the formatting is good, but those commands are often also run from a queue system I wrote and so the logs are then shown on an HTML page.

The result is really hard to understand as it is filled with all the formatting "tag" that are useful on the console but are completely unuseful when the output is read on a web page.

Here an example of what I'm saying:

[32mStarting command[39m
[32m===========================[39m

[34m[>] Analyzing Entity [39m[32This is the entity[39m[34m.                                             [39m
[34m[>] Starting analyzing Entity [39m[32mThis is the entity[39m[34m.                                    [39m
[34m[>] Creating new Job for [39m[30;42This is the entity[39;49m[34m to analyze it in [39m[30;42m+1 week[39;49m[34m (Cause: The Entity is a clone of [39m[30;42Entity2[39;49m[34m).[39m
[34m[>] New Job for [39m[30;42mEntity[39;49m[34m created.                                         [39m
...

As you can see the output is almost non readable.

How can I remove all the formatting from it before saving it to the database?


问:
Location based AR with Three.js (+ React) - camera configuration?
I want to augment the image of a stationary webcam with location based markers. This is to be added to an existing React app that uses three.js (through react-three-fiber) in other parts already, so these technologies are to be reused.

While it is quite eays to calculate the position of the markers (locations known) relative to the camera (location known), I'm struggling with the configuration of the camera in order to get a good visual match between "real" object and AR marker.

I have created a codesandbox with an artificial example that illustrates the challenge.

Here's my attempt at configuring the camera:

const camera = {
    position: [0, 1.5, 0],
    fov: 85,
    near: 0.005,
    far: 1000
};

const bearing = 109;  // degrees

<Canvas camera={camera}>
    <Scene bearing={bearing}/>
</Canvas>
```

<p>Further down in the scene component I’m rotating the camera according to the bearing of the webcam like so:</p>

<pre class="lang-js prettyprint-override"><code>...

const rotation = { x: 0, y: bearing * -1, z: 0 };
camera.rotation.x = (rotation.x * Math.PI) / 180;
camera.rotation.y = (rotation.y * Math.PI) / 180;
camera.rotation.z = (rotation.z * Math.PI) / 180;

...
</code>```

Any tips/thoughts on how to get that camera configured for a good match of three.js boxes and real life objects?

答:
As a GIS-developer I can give a few hints to this issue:

Most 3D graphics API's (such as OpenGL / WebGL, for which Three.js is a wrapper) expect all coordinates to be in linear Cartesian space, but here the input data (the markers and camera locations) are given in Latitude and Longitude (degrees as floating point numbers). These are Spherical coordinates that need to be transformed first.

So to convert our spherical lat-lon coordinates to a linear space, we need to first decide which coordinate system we want to work in. Many Coordinate Reference Systems exist for various purposes, but for the sake of simplicity we will just use the so called Web Mercator Projection (defined by the identifier code EPSG:3857) as our target reference system. This will transform our values from degrees to meters.

There are a few ways to achieve this conversion, for example by using a JS library known as Proj4js or some helper functions of web mapping libraries such as Leaflet or OpenLayers.

Example: var xy = proj4( "EPSG:4326", "EPSG:3857", [ lon, lat ] );

Once we have the coordinates in meters it is important to put the marker locations in relation to the camera location. Otherwise we would get very large coordinate values. So my advise is to put the camera at the scene origin (0, 0, 0) and position the markers by their delta vector.

Example: var position = new THREE.Vector3( camXY[ 0 ] - markerXY[ 0 ], 0.0, markerXY[ 1 ] - camXY[ 1 ] );

You can then rotate the camera according to the given heading and pitch and it should more or less line up if the field-of-view is correct.

Body:
I want to augment the image of a stationary webcam with location based markers. This is to be added to an existing React app that uses three.js (through react-three-fiber) in other parts already, so these technologies are to be reused.

While it is quite eays to calculate the position of the markers (locations known) relative to the camera (location known), I'm struggling with the configuration of the camera in order to get a good visual match between "real" object and AR marker.

I have created a codesandbox with an artificial example that illustrates the challenge.

Here's my attempt at configuring the camera:

const camera = {
    position: [0, 1.5, 0],
    fov: 85,
    near: 0.005,
    far: 1000
};

const bearing = 109;  // degrees

<Canvas camera={camera}>
    <Scene bearing={bearing}/>
</Canvas>

Further down in the scene component I’m rotating the camera according to the bearing of the webcam like so:

...

const rotation = { x: 0, y: bearing * -1, z: 0 };
camera.rotation.x = (rotation.x * Math.PI) / 180;
camera.rotation.y = (rotation.y * Math.PI) / 180;
camera.rotation.z = (rotation.z * Math.PI) / 180;

...

Any tips/thoughts on how to get that camera configured for a good match of three.js boxes and real life objects?


问:
Python Paths - ImportError: cannot import name 'dataset_builder'
I am getting an error ImportError: cannot import name 'dataset_builder'. The import command is following:

from object_detection.builders import dataset_builder

The file tree looks following:

```<code>-ObjectDetection
   -train.py
   -models
     -research
       -object_detection
          -builders
             - __init__.py
             -dataset_builder.py
</code>```

I am running the train.py from the root directory (os.getcwd() returns following path C:\Users\horakm\PyCharmProjects\ObjectDetection) and I added in the train.py following code to add paths:

```<code>sys.path.append(r'C:\Users\horakm\PyCharmProjects\ObjectDetection\models')
sys.path.append(r'C:\Users\horakm\PyCharmProjects\ObjectDetection\models\research')
sys.path.append(r'C:\Users\horakm\PyCharmProjects\ObjectDetection\models\research\slim')
</code>```

When I print all paths using sys.path i get this:

```<code>   ['C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection',
'C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\python36.zip',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\DLLs',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env',
'C:\\Users\\horakm\\AppData\\Roaming\\Python\\Python36\\site-packages',
'C:\\Users\\horakm\\AppData\\Roaming\\Python\\Python36\\site-packages\\win32',
'C:\\Users\\horakm\\AppData\\Roaming\\Python\\Python36\\site-packages\\win32\\lib',
'C:\\Users\\horakm\\AppData\\Roaming\\Python\\Python36\\site-packages\\Pythonwin',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-packages',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-
packages\\object_detection-0.1-py3.6.egg',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-packages\\win32',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-
packages\\win32\\lib',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-packages\\Pythonwin',
'C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection\\models',
'C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection\\models\\research',
'C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection\\models\\research\\slim']
</code>```

How is it possible that the import statement doesn't work?

答:
Which object are you actually trying to import?

All that are defined in dataset_builder? In that case it should be from object_detection.builders.dataset_builder import *.

Or is the object also called dataset_builder? In that case it is from object_detection.builders.dataset_builder import dataset_builder.

Body:
I am getting an error ImportError: cannot import name 'dataset_builder'. The import command is following:

from object_detection.builders import dataset_builder

The file tree looks following:

-ObjectDetection
   -train.py
   -models
     -research
       -object_detection
          -builders
             - __init__.py
             -dataset_builder.py

I am running the train.py from the root directory (os.getcwd() returns following path C:\Users\horakm\PyCharmProjects\ObjectDetection) and I added in the train.py following code to add paths:

sys.path.append(r'C:\Users\horakm\PyCharmProjects\ObjectDetection\models')
sys.path.append(r'C:\Users\horakm\PyCharmProjects\ObjectDetection\models\research')
sys.path.append(r'C:\Users\horakm\PyCharmProjects\ObjectDetection\models\research\slim')

When I print all paths using sys.path i get this:

   ['C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection',
'C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\python36.zip',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\DLLs',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env',
'C:\\Users\\horakm\\AppData\\Roaming\\Python\\Python36\\site-packages',
'C:\\Users\\horakm\\AppData\\Roaming\\Python\\Python36\\site-packages\\win32',
'C:\\Users\\horakm\\AppData\\Roaming\\Python\\Python36\\site-packages\\win32\\lib',
'C:\\Users\\horakm\\AppData\\Roaming\\Python\\Python36\\site-packages\\Pythonwin',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-packages',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-
packages\\object_detection-0.1-py3.6.egg',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-packages\\win32',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-
packages\\win32\\lib',
'C:\\Users\\horakm\\AppData\\Local\\Continuum\\miniconda3\\envs\\tf1_env\\lib\\site-packages\\Pythonwin',
'C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection\\models',
'C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection\\models\\research',
'C:\\Users\\horakm\\PyCharmProjects\\ObjectDetection\\models\\research\\slim']

How is it possible that the import statement doesn't work?


答:
You could compare the address of the current cell to the contents of F6, either:

```<code>=ADDRESS(ROW(),COLUMN(),4)=$F$6
</code>```

or

```<code>=SUBSTITUTE(CELL("address",B4),"$","")=$F$6
</code>```

Title: (Excel) Is there a way to conditional format a cell from a range of cells based on the value of an another cell?

Body: I have a cell with a text, which is the place of an another cell that I want to highlight. Lets say that it is the F6 cell, and in it, it says 'C6'. Is there a way to use conditional formatting to highlight the 'C6' cell ? Any other cell can be inputted into the F6 cell and the formatting will highlight it, if it is in the Data range.

Body:
You could compare the address of the current cell to the contents of F6, either:

=ADDRESS(ROW(),COLUMN(),4)=$F$6

or

=SUBSTITUTE(CELL("address",B4),"$","")=$F$6


问:
Line break and inject span with javascript
I need help. I'm trying to achieve this effect with the headings of a site.

I tried by using background color and padding, but when the text grows in two or more lines it makes a big rectangle. I'm trying to figure out a way to break lines automatically into spans using javascript.

can anyone help me, please?

thanks a lot!

答:
If you want to achive this with CSS only then you need to set this element display attribute to inline like this:

```<code>display: inline;
</code>```

You can also use the line-height CSS attribute together with the font-size to style the height of this p element (if you're using p for this text).
Make sure that line-height value is significantly bigger than the font-size.

Body:
If you want to achive this with CSS only then you need to set this element display attribute to inline like this:

display: inline;

You can also use the line-height CSS attribute together with the font-size to style the height of this p element (if you're using p for this text).
Make sure that line-height value is significantly bigger than the font-size.


问:
Which is more better between basic auth and token auth as security perspective
I am currently developing a RESTful API server, and I am choosing between using ID and password or using a token to authenticate a user.

Let me, explain my situation first. I need to include static authentication information to my library to communicate between a client and my server or provide it to a partnership company to communicate between their server and my server. And when I was researching other services which are in a similar situation as us, they are using token now (for example, Bugfender is using a token to specify a user).

However, what I think is that using ID and PW and using the token are the same or using ID and PW is better because there are two factors to compare it is correct or incorrect.

Is there any reason why other services are using a token?

Which one is better as a security perspective or is there a better way to do this?

答:
I think, if you are going go use on your client fixed username/password, or some fixed token, then the level of the security is the same.

Username and password is not considered as multi-factor authentication. Multi factor means that you are authenticating someone by more than one of the factors:

What you know. This can be the combination of username and password, or some special token.

What you have. Might be some hardware that generates an additional one time password - Google authenticator app on your telephone, or SMS with OTP received with some time expiration.

What you are. This is for example your fingerprint or retina of the eye.

Where you are. This can be the IP address of the origin if it is applicable for your setup.

How you behave. What is your normal way of using the service.

etc.

Maybe not needed to mention that both - the token and the username/password combination have to be carried in an encrypted requests (I believe you are using HTTPS). Otherwise the client's identity can be stolen.

How are you going to provide the credentials to your client library? I thnk this is the most tricky part. If those credentials are saved as a configuration (or worse hard coded) on their server, is that storage secure enough? Who is going to have access to it. Can you avoid it?

What would happen if your partner company realize that the username/password is compromised? Can they change it easily themselves? Or how fast you can revoke the permissions of stolen credentials?

My advice is also to keep audit logs on your server, recording the activity of the client requests. Remember also the GDPR if you work with Europe servers, check for similar regulations in your country based on what you are going to audit log.


问:
Does it make sense to use sklearn GridSearchCV together with CalibratedClassifierCV?
What I want to do is to derive a classifier which is optimal in its parameters with respect to a given metric (for example the recall score) but also calibrated (in the sense that the output of the predict_proba method can be directly interpreted as a confidence level, see https://scikit-learn.org/stable/modules/calibration.html). Does it make sense to use sklearn GridSearchCV together with CalibratedClassifierCV, that is, to fit a classifier via GridSearchCV, and then pass the GridSearchCV output to the CalibratedClassifierCV object? If I'm correct, the CalibratedClassifierCV object would fit a given estimator cv times, and the probabilities for each of the folds are then averaged for prediction. However, the results of the GridSearchCV could be different for each of the folds. </p>

答:
Yes you can do this and it would work.  I don't know if it makes sense to do this, but the least I can do is explain what I believe would happen.

We can compare doing this to the alternative which is getting the best estimator from the grid search and feeding that to the calibration.

Simply getting the best estimator and feeding it to calibrationcv

```<code>from sklearn.model_selection import GridSearchCV
from sklearn import svm, datasets
from sklearn.calibration import CalibratedClassifierCV

iris = datasets.load_iris()
parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
svc = svm.SVC()
clf = GridSearchCV(svc, parameters)
clf.fit(iris.data, iris.target)
calibration_clf = CalibratedClassifierCV(clf.best_estimator_)
calibration_clf.fit(iris.data, iris.target)
calibration_clf.predict_proba(iris.data[0:10])

array([[0.91887427, 0.07441489, 0.00671085],
       [0.91907451, 0.07417992, 0.00674558],
       [0.91914982, 0.07412815, 0.00672202],
       [0.91939591, 0.0738401 , 0.00676399],
       [0.91894279, 0.07434967, 0.00670754],
       [0.91910347, 0.07414268, 0.00675385],
       [0.91944594, 0.07381277, 0.0067413 ],
       [0.91903299, 0.0742324 , 0.00673461],
       [0.91951618, 0.07371877, 0.00676505],
       [0.91899007, 0.07426733, 0.00674259]])

</code>```

Feeding grid search in the Calibration cv

```<code>
from sklearn.model_selection import GridSearchCV
from sklearn import svm, datasets
from sklearn.calibration import CalibratedClassifierCV

iris = datasets.load_iris()
parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
svc = svm.SVC()
clf = GridSearchCV(svc, parameters)
cal_clf = CalibratedClassifierCV(clf)
cal_clf.fit(iris.data, iris.target)
cal_clf.predict_proba(iris.data[0:10])

array([[0.900434  , 0.0906832 , 0.0088828 ],
       [0.90021418, 0.09086583, 0.00891999],
       [0.90206035, 0.08900572, 0.00893393],
       [0.9009212 , 0.09012478, 0.00895402],
       [0.90101953, 0.0900889 , 0.00889158],
       [0.89868497, 0.09242412, 0.00889091],
       [0.90214948, 0.08889812, 0.0089524 ],
       [0.8999936 , 0.09110965, 0.00889675],
       [0.90204193, 0.08896843, 0.00898964],
       [0.89985101, 0.09124147, 0.00890752]])

</code>```

Notice that the output of the probabilities are slightly different between the two.

The difference between each method is:

Using the best estimator is only doing the calibration across 5 splits (the default cv).  It uses the same estimator in all 5 splits.

Using grid search, is doing going to fit a grid search on each of the 5 CV splits from calibration 5 times.  You are essentially doing cross validation on 4/5 of the data each time choosing the best estimator for the 4/5 of the data and then doing the calibration with that best estimator on the last 5th.  You could have slightly different models running on each set of test data depending on what the grid search chooses.

I think the grid search and calibration are different goals so in my opinion I would probably work on each separately and go with the first way specified above get a model that works the best and then feed that in the calibration curve.

However, I don't know your specific goals so I can't say that the 2nd way described here is the WRONG way.  You can always try both ways and see what gives you better performance and go with the one that works best.

Body:
Yes you can do this and it would work.  I don't know if it makes sense to do this, but the least I can do is explain what I believe would happen.

We can compare doing this to the alternative which is getting the best estimator from the grid search and feeding that to the calibration.

Simply getting the best estimator and feeding it to calibrationcv

from sklearn.model_selection import GridSearchCV
from sklearn import svm, datasets
from sklearn.calibration import CalibratedClassifierCV

iris = datasets.load_iris()
parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
svc = svm.SVC()
clf = GridSearchCV(svc, parameters)
clf.fit(iris.data, iris.target)
calibration_clf = CalibratedClassifierCV(clf.best_estimator_)
calibration_clf.fit(iris.data, iris.target)
calibration_clf.predict_proba(iris.data[0:10])

array([[0.91887427, 0.07441489, 0.00671085],
       [0.91907451, 0.07417992, 0.00674558],
       [0.91914982, 0.07412815, 0.00672202],
       [0.91939591, 0.0738401 , 0.00676399],
       [0.91894279, 0.07434967, 0.00670754],
       [0.91910347, 0.07414268, 0.00675385],
       [0.91944594, 0.07381277, 0.0067413 ],
       [0.91903299, 0.0742324 , 0.00673461],
       [0.91951618, 0.07371877, 0.00676505],
       [0.91899007, 0.07426733, 0.00674259]])

Feeding grid search in the Calibration cv

from sklearn.model_selection import GridSearchCV
from sklearn import svm, datasets
from sklearn.calibration import CalibratedClassifierCV

iris = datasets.load_iris()
parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
svc = svm.SVC()
clf = GridSearchCV(svc, parameters)
cal_clf = CalibratedClassifierCV(clf)
cal_clf.fit(iris.data, iris.target)
cal_clf.predict_proba(iris.data[0:10])

array([[0.900434  , 0.0906832 , 0.0088828 ],
       [0.90021418, 0.09086583, 0.00891999],
       [0.90206035, 0.08900572, 0.00893393],
       [0.9009212 , 0.09012478, 0.00895402],
       [0.90101953, 0.0900889 , 0.00889158],
       [0.89868497, 0.09242412, 0.00889091],
       [0.90214948, 0.08889812, 0.0089524 ],
       [0.8999936 , 0.09110965, 0.00889675],
       [0.90204193, 0.08896843, 0.00898964],
       [0.89985101, 0.09124147, 0.00890752]])

Notice that the output of the probabilities are slightly different between the two.

The difference between each method is:

Using the best estimator is only doing the calibration across 5 splits (the default cv).  It uses the same estimator in all 5 splits.

Using grid search, is doing going to fit a grid search on each of the 5 CV splits from calibration 5 times.  You are essentially doing cross validation on 4/5 of the data each time choosing the best estimator for the 4/5 of the data and then doing the calibration with that best estimator on the last 5th.  You could have slightly different models running on each set of test data depending on what the grid search chooses.

I think the grid search and calibration are different goals so in my opinion I would probably work on each separately and go with the first way specified above get a model that works the best and then feed that in the calibration curve.

However, I don't know your specific goals so I can't say that the 2nd way described here is the WRONG way.  You can always try both ways and see what gives you better performance and go with the one that works best.


答:
You can achieve it by adding line-height css property.

Here is the sample to achieve

.hero-banner {
  background: url("https://www.tributemedia.com/hs-fs/hubfs/Images/Blog%20Images/shutterstock_252081805.jpg?width=2480&name=shutterstock_252081805.jpg");
  background-size: cover;
  width: 100%;
  height: 200px;
  padding: 20px;
}

.hero-banner span {
  background: #e7415e;
  color: #fff;
  font-size: 55px;
  line-height: 80px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div class="hero-banner">
      <span>Join our 2020 Welcome change tour</span>
  </div>

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

Title: Line break and inject span with javascript

Body:
I need help. I'm trying to achieve this effect with the headings of a site.

I tried by using background color and padding, but when the text grows in two or more lines it makes a big rectangle. I'm trying to figure out a way to break lines automatically into spans using javascript.

can anyone help me, please?

thanks a lot!

Body:
You can achieve it by adding line-height css property.

Here is the sample to achieve

.hero-banner {
  background: url("https://www.tributemedia.com/hs-fs/hubfs/Images/Blog%20Images/shutterstock_252081805.jpg?width=2480&name=shutterstock_252081805.jpg");
  background-size: cover;
  width: 100%;
  height: 200px;
  padding: 20px;
}

.hero-banner span {
  background: #e7415e;
  color: #fff;
  font-size: 55px;
  line-height: 80px;
}

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div class="hero-banner">
      <span>Join our 2020 Welcome change tour</span>
  </div>

  </body>
</html>


问:
Calculate diff in days between events for 1,000 columns
I'm trying to test where my real world data falls on a hypothetical probability distribution. I have created a DF of 1000 random Var and recoded it to match the probability of my real world events.

Next I want to calculate the "time between Events" (IE, the time between each 1 occurring), Then store the mean time between events for each random variable, so I can plot it. (End goal is 1 variable of 1000 means)

The code below I have created the random variables, recoded them, and added a date range.

```<code>dat <-as.data.frame( matrix (0, nr=1303, nc = 1000))
for (i in 1:1000){x<- runif(1303)
dat[,i] <-x}
#calculating values to 0,1.
dat[,] <- ifelse(dat[,] < "0.01611665", 1, ifelse(dat[,] > "0.01611665", 0, 1 ))
#creating date range
start_date <- as.Date("2016/10/10")
Date<- seq(start_date, by = "day", length.out = 1303)
#add date vector to a df
dat$date <- Date
</code>```

I'm not sure how to calculate the time between events for all variables. I have done it for my real world data (only 21 events in 1303 days) in the code below, but I'm not sure how to scale it to apply to all 1000 random variables, or how to extract 1000 mean "time between events" to a separate df.

```<code> events <- sort(sample(never1$date1, 21))
    d <- c(NA, diff(events))
</code>```

I know my solution involves lubridate and dplyr and rolling calculations. But my googleFU isn't helping too much.

Thanks!

答:
Resolved. </p>

```<code>dat <- as.data.frame( matrix(0, nr=1303, nc = 1000) )

  #Generate random numbers
  for (i in 1:1000){
    x<- runif(1303)
    dat[,i] <-x
  }

  #Split random numbers into zero and ones at the desired prevalence
  dat[,] <- ifelse(dat[,] < "0.01611665", 1, ifelse(dat[,] > "0.01611665", 0, 1 ) )

  length(dat[,1])

  plot.df <- as.data.frame(matrix(0, nr = 1000, nc = 3))
  colnames(plot.df) <- c("Mean","Sd","Median")

  #Check the run length encoding
  for (i in 1:1000){
  runs <- rle(dat[,i])
  #Check the length of runs
  runs$lengths
  #Remove the incident days and leave the length of 'no incident' runs
  noinc.days   <- runs$lengths[which(runs$lengths > 1)]
  plot.df[i,1] <- mean(noinc.days)
  plot.df[i,2] <- sd(noinc.days)
  plot.df[i,3] <- median(noinc.days)
</code>```

<p>Followed by the appropriate GGplots. </p>

Body:
I'm trying to test where my real world data falls on a hypothetical probability distribution. I have created a DF of 1000 random Var and recoded it to match the probability of my real world events.

Next I want to calculate the "time between Events" (IE, the time between each 1 occurring), Then store the mean time between events for each random variable, so I can plot it. (End goal is 1 variable of 1000 means)

The code below I have created the random variables, recoded them, and added a date range.

dat <-as.data.frame( matrix (0, nr=1303, nc = 1000))
for (i in 1:1000){x<- runif(1303)
dat[,i] <-x}
#calculating values to 0,1.
dat[,] <- ifelse(dat[,] < "0.01611665", 1, ifelse(dat[,] > "0.01611665", 0, 1 ))
#creating date range
start_date <- as.Date("2016/10/10")
Date<- seq(start_date, by = "day", length.out = 1303)
#add date vector to a df
dat$date <- Date

I'm not sure how to calculate the time between events for all variables. I have done it for my real world data (only 21 events in 1303 days) in the code below, but I'm not sure how to scale it to apply to all 1000 random variables, or how to extract 1000 mean "time between events" to a separate df.

 events <- sort(sample(never1$date1, 21))
    d <- c(NA, diff(events))

I know my solution involves lubridate and dplyr and rolling calculations. But my googleFU isn't helping too much.

Thanks!

Body:
Resolved.

dat <- as.data.frame( matrix(0, nr=1303, nc = 1000) )

  #Generate random numbers
  for (i in 1:1000){
    x<- runif(1303)
    dat[,i] <-x
  }

  #Split random numbers into zero and ones at the desired prevalence
  dat[,] <- ifelse(dat[,] < "0.01611665", 1, ifelse(dat[,] > "0.01611665", 0, 1 ) )

  length(dat[,1])

  plot.df <- as.data.frame(matrix(0, nr = 1000, nc = 3))
  colnames(plot.df) <- c("Mean","Sd","Median")

  #Check the run length encoding
  for (i in 1:1000){
  runs <- rle(dat[,i])
  #Check the length of runs
  runs$lengths
  #Remove the incident days and leave the length of 'no incident' runs
  noinc.days   <- runs$lengths[which(runs$lengths > 1)]
  plot.df[i,1] <- mean(noinc.days)
  plot.df[i,2] <- sd(noinc.days)
  plot.df[i,3] <- median(noinc.days)

Followed by the appropriate GGplots.


问:
Any good Resources for WCF Delegation?
I'm trying to setup WCF Delegation, without success (the scenario is Client > Frontend Server > Backend Server).

In theory, this should be straight forward using Kerberos (I do have a Windows Domain), but in practice I'm running into weird errors with things like SSPI or even basic message security.

I found countless shallow resources, and forum posts where people had problems and were essentially just guessing solutions through trial and error. I looked at the Table of Contents at some so-called "Pro" and "Expert" WCF Books, but Delegation seems to be something no one wants to cover (in fact, there is a typo in one of the Exceptions that .net throws that makes me feel not even Microsoft really bothers with it).

Anyway, is there any resource where someone that actually has a clue and the confidence to explain the whole process A-Z, using a methodological approach with actual explanations and not just meaningless code blocks that don't work and are never explained?

答:
The WCF code for this is actually fairly straight forward. Getting your service account configured and Kerberos behaving can be quite hard.

The reason why you are having such a hard time finding examples, is because very few people actually do it. The process that does the delegating must be running under an account that is "trusted for delegation" in Active Directory (on the domain controller). This ability is so powerful that many IT departments have an explicit policy against it.

There is a concept of "constrained delegation" that defines which resources can be accessed, but again this is defined in Active Directory and not your code. Before you continue your coding I suggest making sure you have the ability to make the needed changes to Active Directory. Enabling an account for delegation is a battle I lost at more than one company.

For references I suggest:

WCF Security Guide on Codeplex

How To: Use Protocol Transition and Constrained Delegation in ASP.NET 2.0

Yes both of these references are a little old, but they both apply. All of the constrained delegation steps listed in the "How To" are for Active Directory and not tied to ASP.

Title: Any good Resources for WCF Delegation?


问:
RxJS Change loading indication message depending on request time
I want to implement loading indication (spinner and the message below) using RxJS.

From 0 to 30sec the message would be 'Your request is being processed...'

after 30sec - the message would be 'Your request is being processed..., it usually takes less then minute'.

If data arrives successfully earlier than 30 seconds, the loader with message would disappear.

I am implementing this in Angular project.
The code below is kind of draft version, and it doesn't work as expected, because api data waits for timer to be completed

```<code>  public initializeDashboard() {
    const timerMessage$ = timer(30000, 1000).pipe(take(1));
    const dashboard$: Array<any> = this.headerService.getItems();

    this.progressMessage = 'Your request is being processed...';
    merge(timerMessage$, dashboard$).pipe(
      tap((item) => {
        if (isNumber(item)) {
          this.progressMessage = 'Usually it takes less then a minute';
        }
      }),
      filter(item => isArray(item)))
      .subscribe(
        (responseData) => {
            this.progressMessage = '';
             this.responseData = responseData,
          }
      );
  }
</code>```

答:
The trick here is that I'll merge two chains where the first one will only make a side-effect and update the message while the second one is the one that using take(1) can complete the chain. This is necessary because you obviously want to cancel the timer when
dashboard$ emits.

I think there's another variant without ignoreElements() but that would require also takeUntil() and share() and making two separate subscriptions so this is I think the easier one.

```<code>public initializeDashboard() {
  const dashboard$: Array<any> = this.headerService.getItems();
  const timerMessage$ = timer(30 * 1000) // This will emit just once after 30s
    .pipe(
      tap(() => this.progressMessage += 'Usually it takes less then a minute'),
      ignoreElements(), // all emission will be ignored so they won't reach `take(1)` and complete the chain
    );

  this.progressMessage = 'Your request is being processed...';

  merge(timerMessage$, dashboard$)
    .pipe(
      take(1), // This is required so when `dashboard$` emits it will unsubscribe from `timerMessage$` automatically
    )
    .subscribe((responseData) => {
      this.progressMessage = '';
      this.responseData = responseData,
    });
}
</code>```

Body:
I want to implement loading indication (spinner and the message below) using RxJS.

From 0 to 30sec the message would be 'Your request is being processed...'

after 30sec - the message would be 'Your request is being processed..., it usually takes less then minute'.

If data arrives successfully earlier than 30 seconds, the loader with message would disappear.

I am implementing this in Angular project.
The code below is kind of draft version, and it doesn't work as expected, because api data waits for timer to be completed

  public initializeDashboard() {
    const timerMessage$ = timer(30000, 1000).pipe(take(1));
    const dashboard$: Array<any> = this.headerService.getItems();

    this.progressMessage = 'Your request is being processed...';
    merge(timerMessage$, dashboard$).pipe(
      tap((item) => {
        if (isNumber(item)) {
          this.progressMessage = 'Usually it takes less then a minute';
        }
      }),
      filter(item => isArray(item)))
      .subscribe(
        (responseData) => {
            this.progressMessage = '';
             this.responseData = responseData,
          }
      );
  }

Body:
The trick here is that I'll merge two chains where the first one will only make a side-effect and update the message while the second one is the one that using take(1) can complete the chain. This is necessary because you obviously want to cancel the timer when
dashboard$ emits.

I think there's another variant without ignoreElements() but that would require also takeUntil() and share() and making two separate subscriptions so this is I think the easier one.

public initializeDashboard() {
  const dashboard$: Array<any> = this.headerService.getItems();
  const timerMessage$ = timer(30 * 1000) // This will emit just once after 30s
    .pipe(
      tap(() => this.progressMessage += 'Usually it takes less then a minute'),
      ignoreElements(), // all emission will be ignored so they won't reach `take(1)` and complete the chain
    );

  this.progressMessage = 'Your request is being processed...';

  merge(timerMessage$, dashboard$)
    .pipe(
      take(1), // This is required so when `dashboard$` emits it will unsubscribe from `timerMessage$` automatically
    )
    .subscribe((responseData) => {
      this.progressMessage = '';
      this.responseData = responseData,
    });
}


答:
You should do
require_once('database.php');to inherit the class entities from the parent class.

Title: Error class not found when I extends a class

Body:
I've two files in one directory named (classes )which contain classes, first one for main class (Database ) which build to connect to the database.
And the second one (Branch ) extends Database class which made to get data from the database.

When I try to run "getBranch" function I got an error says :

Uncaught Error: Class 'Database' not found in C:\xampp\htdocs\branches\classes\branch.php

Please find the codes below and advise what's required.

database.php:

<?php

  class Database {
    private $host;
    private $user;
    private $pwd;
    private $dbName;
    public $conn;

    public function connect() {
      $this->host = "localhost";
      $this->user = "root";
      $this->pwd = "";
      $this->dbName = "branchs";
      //create connection
      $conn = new mysqli($this->host, $this->user, $this->pwd, $this->dbName);
      //chech connection
      if ($conn->connect_error) {
        die("Connection failed :" . $conn->connect_error);
      } else {
        echo "Success";
      }

      return $conn;

    }

  }

?>

branch.php :

<?php

    class Branch extends Database {

      public function getBranch() {

      $sql = "SELECT * FROM branches";
      $result = $this->connect()->query($sql);

      if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
          echo "Name :" . $row['brName'] . "City :" . $row['brCity'] . "
";
        }
      } else {
        echo "0 results";
      }

      }

    }

?>