问:
Delay Javascript effect by 500 ms
I want to delay slideOutItem by 500 millisecond. Canno't get that working.</p>

```<code>if(current === idx) {
    slideOutItem($menuItems.eq(current), false, 250, 'easeOutQuint', true);
    current = -1;
}
</code>```

答:
Something like this</p>

```<code>if(current === idx) {
    setTimeout(function () {
        slideOutItem($menuItems.eq(current), false, 250, 'easeOutQuint', true);
    } , 500);
    current = -1;
}
</code>```

Title: Delay Javascript effect by 500 ms

Body:
I want to delay slideOutItem by 500 millisecond. Canno't get that working.

if(current === idx) {
    slideOutItem($menuItems.eq(current), false, 250, 'easeOutQuint', true);
    current = -1;
}

Body:
Something like this

if(current === idx) {
    setTimeout(function () {
        slideOutItem($menuItems.eq(current), false, 250, 'easeOutQuint', true);
    } , 500);
    current = -1;
}


来源: stackexchange

问:
Single query per pagination? datatable.js laravel
Currently I have a table called tblOrders

with the query like this

```<code> public function getIndex()
 {

    $cart = Cart::orderby('cart_date','DESC')
    ->orderby('cart_no','DESC')
    ->select('id','cart_no','client_id','cart_title')->limit(1000)->get();

    return View::make('_admin.orders.orders', compact('cart'));

 }
</code>```

on my blade file I have this datatable.js

```<code>  <table id="table-order" class="parennt-table uk-table-hover">
  <thead>
        <tr>
             <th>id</th>
             <th>cart_no</th>
             <th>cart_title</th>
             <th>cart_date</th>
        </tr>
  </thead>

  <tbody>
       @if(count($orderData))
       @foreach ($orderData as $field)
       <tr>
          <td>{{ $field->id }}</td>
          <td>{{ $field->cart_no }}</td>
          <td>{{ $field->cart_title }}</td>
          <td>{{ date('M j, Y',strtotime($field->cart_date)) }}</td>
       </tr>

       @endforeach
       @endif

  </tbody>
</code>```

and my js like this

```<code>  <script>
    oTable = $('#table-order').DataTable({
     "order": [[ 0, 'desc' ]]
   });
  </script>
</code>```

This datatable loads 8k rows. but needed to limit it by 1000 rows

How can I load only 20 rows per page? and query the next 1 when user tries to click specific pagination

答:
You should use pagination, the first parameter passed to the paginate() function is the number of results returned.

```<code> public function getIndex()
 {

    $cart = Cart::orderby('cart_date','DESC')
    ->orderby('cart_no','DESC')
    ->select('id','cart_no','client_id','cart_title')
    ->paginate(50);

    return View::make('_admin.orders.orders', compact('cart'));

 }
</code>```

However, I don't suggest you to use such a high number as 1000 but use more reasonable numbers to reduce the page loading and rendering time.

Anyway, using DataTables I suggest you to install this package yajra/laravel-datatables

ContentLicense: CC BY-SA 4.0

Body:
Currently I have a table called tblOrders

with the query like this

 public function getIndex()
 {

    $cart = Cart::orderby('cart_date','DESC')
    ->orderby('cart_no','DESC')
    ->select('id','cart_no','client_id','cart_title')->limit(1000)->get();

    return View::make('_admin.orders.orders', compact('cart'));

 }

on my blade file I have this datatable.js

             id
             cart_no
             cart_title
             cart_date

       @if(count($orderData))
       @foreach ($orderData as $field)

          {{ $field->id }}
          {{ $field->cart_no }}
          {{ $field->cart_title }}
          {{ date('M j, Y',strtotime($field->cart_date)) }}

       @endforeach
       @endif

and my js like this

This datatable loads 8k rows. but needed to limit it by 1000 rows

How can I load only 20 rows per page? and query the next 1 when user tries to click specific pagination

Body:
You should use pagination, the first parameter passed to the paginate() function is the number of results returned.

 public function getIndex()
 {

    $cart = Cart::orderby('cart_date','DESC')
    ->orderby('cart_no','DESC')
    ->select('id','cart_no','client_id','cart_title')
    ->paginate(50);

    return View::make('_admin.orders.orders', compact('cart'));

 }

However, I don't suggest you to use such a high number as 1000 but use more reasonable numbers to reduce the page loading and rendering time.

Anyway, using DataTables I suggest you to install this package yajra/laravel-datatables


问:
How to scrape url from a html table in python and BeautifulSoup
I want to scrape the urls from a html table of this website. I was able to gather LOCATION | DATE | SUMMARY | DEADLINE. But the SUMMARY field is having a url to another page. I want to scrape the entire table along with this url so my scraped data becomes LOCATION | DATE | SUMMARY | DEADLINE | URLS

```<code>import requests as rq
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://www.tendersinfo.com/global-information-technology-tenders-{}.php'

amount_of_pages = 4796 #5194
rows = []

for i in range(1,amount_of_pages):
    response = rq.get(url.format(i))

    if response.status_code == 200:
        soup = BeautifulSoup(response.text,'html.parser')
        table = soup.find('table',{'id':'datatable'})

        headers = []

        for th in table.find("tr").find_all("th"):
           headers.append(th.text.strip())

        for tr in table.find_all("tr")[1:]:
            cells = []
            tds = tr.find_all("td")

            if len(tds) == 0:
                ths = tr.find_all("th")

                for th in ths:
                    cells.append(th.text.strip())
                    links = [th.findAll('a')]
            else:
                for td in tds:
                    cells.append(td.text.strip())
                    links = [td.findAll('a')]

            rows.append(cells)
</code>```

答:
You'll need to get the '' tag under the  tag, and pull out the href attribute.

```<code>import requests as rq
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://www.tendersinfo.com/global-information-technology-tenders-{}.php'

amount_of_pages = 4796 #5194
rows = []
headers = []

for i in range(1,amount_of_pages+1):  #<-- if theres 4796 pages, your range needs to be to 4797. range goes from (start, end) but the is not inclusive of the end value
    response = rq.get(url.format(i))
    print (i)

    if response.status_code == 200:
        soup = BeautifulSoup(response.text,'html.parser')
        table = soup.find('table',{'id':'datatable'})

        if len(headers) == 0:
            for th in table.find("tr").find_all("th"):
               headers.append(th.text.strip())
            headers.append('URL')

        for tr in table.find_all("tr")[1:]:
            cells = []
            tds = tr.find_all("td")

            for td in tds:
                cells.append(td.text.strip())
                if td.find('a'):
                    link = td.find('a')['href']
            cells = cells + [link]

            rows.append(cells)

df = pd.DataFrame(rows,
               columns =headers)
</code>```

Body:
I want to scrape the urls from a html table of this website. I was able to gather LOCATION | DATE | SUMMARY | DEADLINE. But the SUMMARY field is having a url to another page. I want to scrape the entire table along with this url so my scraped data becomes LOCATION | DATE | SUMMARY | DEADLINE | URLS

import requests as rq
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://www.tendersinfo.com/global-information-technology-tenders-{}.php'

amount_of_pages = 4796 #5194
rows = []

for i in range(1,amount_of_pages):
    response = rq.get(url.format(i))

    if response.status_code == 200:
        soup = BeautifulSoup(response.text,'html.parser')
        table = soup.find('table',{'id':'datatable'})

        headers = []

        for th in table.find("tr").find_all("th"):
           headers.append(th.text.strip())

        for tr in table.find_all("tr")[1:]:
            cells = []
            tds = tr.find_all("td")

            if len(tds) == 0:
                ths = tr.find_all("th")

                for th in ths:
                    cells.append(th.text.strip())
                    links = [th.findAll('a')]
            else:
                for td in tds:
                    cells.append(td.text.strip())
                    links = [td.findAll('a')]

            rows.append(cells)

Body:
You'll need to get the '' tag under the <td> tag, and pull out the href attribute.

import requests as rq
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://www.tendersinfo.com/global-information-technology-tenders-{}.php'

amount_of_pages = 4796 #5194
rows = []
headers = []

for i in range(1,amount_of_pages+1):  #<-- if theres 4796 pages, your range needs to be to 4797. range goes from (start, end) but the is not inclusive of the end value
    response = rq.get(url.format(i))
    print (i)

    if response.status_code == 200:
        soup = BeautifulSoup(response.text,'html.parser')
        table = soup.find('table',{'id':'datatable'})

        if len(headers) == 0:
            for th in table.find("tr").find_all("th"):
               headers.append(th.text.strip())
            headers.append('URL')

        for tr in table.find_all("tr")[1:]:
            cells = []
            tds = tr.find_all("td")

            for td in tds:
                cells.append(td.text.strip())
                if td.find('a'):
                    link = td.find('a')['href']
            cells = cells + [link]

            rows.append(cells)

df = pd.DataFrame(rows,
               columns =headers)


问:
Ionic 5 / Angular 9 - Error importing componente to page
Im having troubles with the import and use a component in a page.

I have and component named prueba.component.ts that is exported by a module named prueba.module.ts

prueba.module.ts:

```<code>    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { PruebaComponent } from './prueba.component';

    @NgModule({
      declarations: [
        PruebaComponent
      ],
      imports: [
        CommonModule,
      ],
      exports: [
        PruebaComponent
      ]

    })
    export class PruebaModule { }
</code>```

And i have a page named home.page.ts than has a module home-routing.module.ts

home-routing.module.ts:

```<code>import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomePage } from './home.page';
import { PruebaModule } from 'src/app/componentes/prueba/prueba.module';
import { CommonModule } from '@angular/common';

const routes: Routes = [
  {
    path: '',
    component: HomePage
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(routes),
    CommonModule,
    PruebaModule
  ],
  exports: [RouterModule],
  declarations: [],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class HomePageRoutingModule {}
</code>```

I understood that this was enough to be able to use the component within the page, but it continues presenting the image error.

I appreciate any help you can give me.

答:
Here I guess you got confused between module and routing-module.
If you want to use your PruebaComponent in another module then you need to import the PruebaModule in that module. Let's suppose that your module name is home.module.ts then you need to add PruebaModule in home.module.ts and not in home-routing.module.ts

So basically your home.module.ts should look like this.

```<code>@NgModule({
imports: [
CommonModule,
PruebaModule]
})
export class HomeModule{ }
</code>```

and now simply you can use preubaComponent in your home-routing.module.ts
So home-routing.module.ts would look something like this.

```<code>    const routes: Routes = [{
             path: '',
             component: HomePage}
          ];
  @NgModule({
     imports: [
     RouterModule.forChild(routes)
    ],
     exports: [RouterModule]
     })
  export class HomePageRoutingModule {}
</code>```

And now you can use the component name in Homepage component.
So your homepage.component.html would simply have the below line.

```<code><app-prueba></app-prueba>
</code>```

Body:
Im having troubles with the import and use a component in a page.

I have and component named prueba.component.ts that is exported by a module named prueba.module.ts

prueba.module.ts:

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { PruebaComponent } from './prueba.component';

    @NgModule({
      declarations: [
        PruebaComponent
      ],
      imports: [
        CommonModule,
      ],
      exports: [
        PruebaComponent
      ]

    })
    export class PruebaModule { }

And i have a page named home.page.ts than has a module home-routing.module.ts

home-routing.module.ts:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomePage } from './home.page';
import { PruebaModule } from 'src/app/componentes/prueba/prueba.module';
import { CommonModule } from '@angular/common';

const routes: Routes = [
  {
    path: '',
    component: HomePage
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(routes),
    CommonModule,
    PruebaModule
  ],
  exports: [RouterModule],
  declarations: [],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class HomePageRoutingModule {}

I understood that this was enough to be able to use the component within the page, but it continues presenting the image error.

I appreciate any help you can give me.

Body:
Here I guess you got confused between module and routing-module.
If you want to use your PruebaComponent in another module then you need to import the PruebaModule in that module. Let's suppose that your module name is home.module.ts then you need to add PruebaModule in home.module.ts and not in home-routing.module.ts

So basically your home.module.ts should look like this.

@NgModule({
imports: [
CommonModule,
PruebaModule]
})
export class HomeModule{ }

and now simply you can use preubaComponent in your home-routing.module.ts
So home-routing.module.ts would look something like this.

    const routes: Routes = [{
             path: '',
             component: HomePage}
          ];
  @NgModule({
     imports: [
     RouterModule.forChild(routes)
    ],
     exports: [RouterModule]
     })
  export class HomePageRoutingModule {}

And now you can use the component name in Homepage component.
So your homepage.component.html would simply have the below line.

<app-prueba></app-prueba>


问:
Solr Index appears to be valid - but returns no results
Solr newbie here.

I have created a Solr index and write a whole bunch of docs into it. I can see
from the Solr admin page that the docs exist and the schema is fine as well.
But when I perform a search using a test keyword I do not get any results back.

On entering * : *

into the query (in Solr admin page) I get all the results.

However, when I enter any other query (e.g. a term or phrase) I get no results.
I have verified that the field being queried is Indexed and contains the values I am searching for.

So I am confused what I am doing wrong.

答:
I had the same issue with a new setup of Solr 8. The accepted answer is not valid anymore, because the <defaultSearchField> configuration will be deprecated.

As I found no answer to why Solr does not return results from any fields despite being indexed, I consulted the query documentation. What I found is the DisMax query parser:

The DisMax query parser is designed to process simple phrases (without complex syntax) entered by users and to search for individual terms across several fields using different weighting (boosts) based on the significance of each field. Additional options enable users to influence the score based on rules specific to each use case (independent of user input).

In contrast, the default Lucene parser only speaks about searching one field. So I gave DisMax a try and it worked very well!

Query example:

```<code>http://localhost:8983/solr/techproducts/select?defType=dismax&q=video
</code>```

You can also specify which fields to search exactly to prevent unwanted side effects. Multiple fields are separated by spaces which translate to + in URLs:

```<code>http://localhost:8983/solr/techproducts/select?defType=dismax&q=video&qf=features+text
</code>```

Last but not least, give the fields a weight:

```<code>http://localhost:8983/solr/techproducts/select?defType=dismax&q=video&qf=features^20.0+text^0.3
</code>```

If you are using pysolr like I do, you can add those parameters to your search request like this:

```<code>results = solr.search('search term', **{
    'defType': 'dismax',
    'qf': 'features text'
})
</code>```

Body:
I had the same issue with a new setup of Solr 8. The accepted answer is not valid anymore, because the <defaultSearchField> configuration will be deprecated.

As I found no answer to why Solr does not return results from any fields despite being indexed, I consulted the query documentation. What I found is the DisMax query parser:

The DisMax query parser is designed to process simple phrases (without complex syntax) entered by users and to search for individual terms across several fields using different weighting (boosts) based on the significance of each field. Additional options enable users to influence the score based on rules specific to each use case (independent of user input).

In contrast, the default Lucene parser only speaks about searching one field. So I gave DisMax a try and it worked very well!

Query example:

http://localhost:8983/solr/techproducts/select?defType=dismax&q=video

You can also specify which fields to search exactly to prevent unwanted side effects. Multiple fields are separated by spaces which translate to + in URLs:

http://localhost:8983/solr/techproducts/select?defType=dismax&q=video&qf=features+text

Last but not least, give the fields a weight:

http://localhost:8983/solr/techproducts/select?defType=dismax&q=video&qf=features^20.0+text^0.3

If you are using pysolr like I do, you can add those parameters to your search request like this:

results = solr.search('search term', **{
    'defType': 'dismax',
    'qf': 'features text'
})


问:
jquery $.each() for objects
```<code><script>
    $(document).ready(function() {
        var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };
        $.each(data.programs[0], function(key,val) {
            alert(key+val);
        });
    });
</script>
</code>```

This code retrieves the first data. name:zonealarm and price:500.

How can I retrieve all the data in the object?

I tried $.each(data.programs, function(key,val) but it didn't work.

Should I put it in a loop?

答:
You are indeed passing the first data item to the each function.

Pass data.programs to the each function instead.
Change the code to as below:

```<code><script>
    $(document).ready(function() {
        var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };
        $.each(data.programs, function(key,val) {
            alert(key+val);
        });
    });
</script>
</code>```

Title: jquery $.each() for objects

Body:
You are indeed passing the first data item to the each function.

Pass data.programs to the each function instead.
Change the code to as below:

<script>
    $(document).ready(function() {
        var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };
        $.each(data.programs, function(key,val) {
            alert(key+val);
        });
    });
</script>

ContentLicense: CC BY-SA 3.0


问:
not able to understand scope of variable in this code
In this code vid is initialized inside the function, so how can it be used outside the function
( i.e how could vid.play() know that vid is initialised using vid = document.querySelector("#myPlayer")).

```<code>window.onload = init;

let vid;
function init() {
  console.log('page loaded, DOM is ready');
  vid = document.querySelector('#myPlayer');
  vid.ontimeupdate = displayTimeWhileVideoIsPlaying();
}

function playVideo() {
  vid.play();
}
</code>```

答:
You have correctly identified that this is a question of "variable scope". I've added some comments to your code in the hope it clarifies things.

I suggest you look into: https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript

```<code>// This variable is defined globally. It does not yet have a value, but it is available to everyone at this root level or deeper. All share a reference to the same variable.
let vid;

function init() {
    console.log("Page loaded, DOM is ready!");

    // This function must run FIRST so we assign the value found here
    // but we store it in a variable defined at the root/global scope
    // so we are changing a variable that is defined outside this function
    vid = document.querySelector("#myPlayer");

    vid.ontimeupdate = displayTimeWhileVideoIsPlaying;
}

function playVideo() {
    // This will throw an error if the above function does not run first
    // Until that runs vid is `undefined`.
    // But since the variable that is defined is at the global scope this
    // function is able to read the same value that the above function writes.
    vid.play();
}
</code>```

Body:
In this code vid is initialized inside the function, so how can it be used outside the function
( i.e how could vid.play() know that vid is initialised using vid = document.querySelector("#myPlayer")).

window.onload = init;

let vid;
function init() {
  console.log('page loaded, DOM is ready');
  vid = document.querySelector('#myPlayer');
  vid.ontimeupdate = displayTimeWhileVideoIsPlaying();
}

function playVideo() {
  vid.play();
}

Body:
You have correctly identified that this is a question of "variable scope". I've added some comments to your code in the hope it clarifies things.

I suggest you look into: https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript

// This variable is defined globally. It does not yet have a value, but it is available to everyone at this root level or deeper. All share a reference to the same variable.
let vid;

function init() {
    console.log("Page loaded, DOM is ready!");

    // This function must run FIRST so we assign the value found here
    // but we store it in a variable defined at the root/global scope
    // so we are changing a variable that is defined outside this function
    vid = document.querySelector("#myPlayer");

    vid.ontimeupdate = displayTimeWhileVideoIsPlaying;
}

function playVideo() {
    // This will throw an error if the above function does not run first
    // Until that runs vid is `undefined`.
    // But since the variable that is defined is at the global scope this
    // function is able to read the same value that the above function writes.
    vid.play();
}


问:
Next.js with prettier formatting
I'm trying to format my next.js project with prettier. In my package.json I've defined this:

```<code>"scripts": {
"format": "prettier --write \"**/*.{js, jsx}\"",
},
</code>```

So my project has a lot of folders:

components

layouts

pages

.next

I obviously don't want to run prettier in my .next folder. How can I ignore some folders?

答:
You can add .prettierignore in the project root directory.

```<code>node_modules
.next
out
</code>```

It uses .gitignore syntax.

Title: Next.js with prettier formatting

Body:
I'm trying to format my next.js project with prettier. In my package.json I've defined this:

"scripts": {
"format": "prettier --write \"**/*.{js, jsx}\"",
},

So my project has a lot of folders:

components

layouts

pages

.next

I obviously don't want to run prettier in my .next folder. How can I ignore some folders?

Body:
You can add .prettierignore in the project root directory.

node_modules
.next
out

It uses .gitignore syntax.


问:
Generate Buttons inside Wrap from List<String> flutter
I have a List<String> and I want to generate, inside a Wrap widget, N Buttons (N string lenght).

I read about a List.generate, I'm trying to implement it, do you know how I can do that?

答:
```<code>Wrap(
    children:buttons.map((s)=>
                        MaterialButton(
                          //shape,color etc...
                        onPressed:(){
                          //todo
                        },
                          child:Text(s)
                        )).toList()
    )
</code>```


问:
Real-world use of Mercurial with a Team Foundation Server?
My shop uses TFS & is generally happy with it with the exception of the lack of local repository commits/reverts. I'm starting to use Mercurial locally myself to help manage smaller chunks of changes, then posting them to TFS. I see that Subversion has a 'bridge' component to automagically enable this if the central VCS is Subversion. I have not found one for Team System. This encourages me that other folks have gone down this path with integrating DVCS with CVCS systems.

(1) Does anyone know of one? I'm sort of doubting it (quick search didn't find anything).

(2) Is anyone using Mercurial/TFS in this manner? If so, can you share your experiences. I'm particularly looking for any insights into what issues might come up that aren't obvious regarding commits to TFS after significant activity via Mercurial.

It seems like a total win-win so far with just me using if for a few days--but I know enough then to think it's just that easy.

答:
@Eric, your post at lostechies was most helpful.  With VS2010 I had to add options /diff and /deletes to the tftp online command in the push script to get changed and deleted files to be checked in to TFS.  Initially I was getting an error from push when a file has been deleted (from -working) that hg update is

"unable to remove FileXyz : access  is denied".

I installed the MakeWritable.py extension but that only works when files are opened not deleted.  So I added a call to attrib to remove the READ-ONLY from all files in the project and then restore it afterwards (excluding the .hg folder)  I also added the /diff option so that differences are detected by MD5 checksum instead of depending on the READ-ONLY attribute.  Seems to be working fine now.

```<code>=====FILE: push.ps1=====
$projName = "TicTacToeCMMI"
$tftp = "C:\Program Files\Microsoft Team Foundation Server 2010 Power Tools\TFPT.exe"
$tf = "C:\Program Files\Microsoft Visual Studio 10.0\Common7\ide\tf.exe"

hg push
cd ..\$projName-tfs
"Syncing -tfs workspace with TFS server"
&$tftp scorch /noprompt /exclude:.hg',_Resharper*',*.user
"Making all files in -tfs writable"
attrib -R /S /D *
"Updating -tfs with latest push from Mercurial"
hg update -C -y
attrib +R /S /D *
attrib -R /S /D .hg\*
"Resyncing Mercurial changes with TFS Server"
&$tftp online /adds /deletes /diff /exclude:'.hgignore,.hg,bin,obj,*.ps1,_Resharper*,*.lnk,*.user,*.suo,*.vspscc'
"Checkin"
&$tf checkin
cd ..\$projName-working
cmd /c pause

====FILE: pull.ps1=====
$projName = "TicTacToeCMMI"
$tf = "C:\Program Files\Microsoft Visual Studio 10.0\Common7\ide\tf.exe"
$username = cmd /c set USERNAME
$username = $username.SubString($username.IndexOf("=")+1)

function pull {
    cd ..\$projName-tfs
    &$tf get
    hg commit -A -m "from tfs" --user $username
    cd ..\$projName-working
    hg pull --rebase
}
pull
cmd /c pause
</code>```

I had a bit of a learning curve with PowerShell scripts which I hadn't used before.  For others like me the scripts are run with a shortcut like this:

```<code>TARGET: C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe C:\dev\TicTacToeCMMI-working\push.ps1
START IN: C:\dev\TicTacToeCMMI-working
</code>```

I put push and pull shortcuts on my task bar so push/pull to/from TFS is a single click

Body:
@Eric, your post at lostechies was most helpful.  With VS2010 I had to add options /diff and /deletes to the tftp online command in the push script to get changed and deleted files to be checked in to TFS.  Initially I was getting an error from push when a file has been deleted (from -working) that hg update is

"unable to remove FileXyz : access  is denied".

I installed the MakeWritable.py extension but that only works when files are opened not deleted.  So I added a call to attrib to remove the READ-ONLY from all files in the project and then restore it afterwards (excluding the .hg folder)  I also added the /diff option so that differences are detected by MD5 checksum instead of depending on the READ-ONLY attribute.  Seems to be working fine now.

=====FILE: push.ps1=====
$projName = "TicTacToeCMMI"
$tftp = "C:\Program Files\Microsoft Team Foundation Server 2010 Power Tools\TFPT.exe"
$tf = "C:\Program Files\Microsoft Visual Studio 10.0\Common7\ide\tf.exe"

hg push
cd ..\$projName-tfs
"Syncing -tfs workspace with TFS server"
&$tftp scorch /noprompt /exclude:.hg',_Resharper*',*.user
"Making all files in -tfs writable"
attrib -R /S /D *
"Updating -tfs with latest push from Mercurial"
hg update -C -y
attrib +R /S /D *
attrib -R /S /D .hg\*
"Resyncing Mercurial changes with TFS Server"
&$tftp online /adds /deletes /diff /exclude:'.hgignore,.hg,bin,obj,*.ps1,_Resharper*,*.lnk,*.user,*.suo,*.vspscc'
"Checkin"
&$tf checkin
cd ..\$projName-working
cmd /c pause

====FILE: pull.ps1=====
$projName = "TicTacToeCMMI"
$tf = "C:\Program Files\Microsoft Visual Studio 10.0\Common7\ide\tf.exe"
$username = cmd /c set USERNAME
$username = $username.SubString($username.IndexOf("=")+1)

function pull {
    cd ..\$projName-tfs
    &$tf get
    hg commit -A -m "from tfs" --user $username
    cd ..\$projName-working
    hg pull --rebase
}
pull
cmd /c pause

I had a bit of a learning curve with PowerShell scripts which I hadn't used before.  For others like me the scripts are run with a shortcut like this:

TARGET: C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe C:\dev\TicTacToeCMMI-working\push.ps1
START IN: C:\dev\TicTacToeCMMI-working

I put push and pull shortcuts on my task bar so push/pull to/from TFS is a single click


问:
Script for automating online tool query
So I had a number of amino acid sequence strings that I wanted to use as input into a tool that studies its interactions with certain components of the human immune system (http://www.cbs.dtu.dk/services/NetMHCcons/).

I wanted to ask what, if any, would be a way of accessing, inputting data and getting the output, via a script (R or python preferably). My main issue was I had a lot of sequences that need to be queried separately so wanted to automate the whole thing. The website has one field that reads "Submission" which takes in the string input. There is another field "select species/loci" which gives a drop down menu from which an option needs to be selected. Lastly there's a "submit" button. The output simply loads on the page after hitting submit.

I've tentatively poked around with RSelenium and Rcurl but wanted to ask if there was a more efficient method.

答:
Try this :
Submitting to a web form using python
This link is an answer to how to send web forms in python, using urllib. Check your source code and extract the necessary data using re module from the source code of the link you have  put up, and send the request.
save the HTML source code of http://www.cbs.dtu.dk/services/NetMHCcons/ in the python file as

```<code>source_code = '''...'''
</code>```

The HTML can be found by using CTRL+U in firefox.

Title: Script for automating online tool query

Body:
Try this :
Submitting to a web form using python
This link is an answer to how to send web forms in python, using urllib. Check your source code and extract the necessary data using re module from the source code of the link you have  put up, and send the request.
save the HTML source code of http://www.cbs.dtu.dk/services/NetMHCcons/ in the python file as

source_code = '''...'''

The HTML can be found by using CTRL+U in firefox.


问:
.Net Core 3.1 - Mutiple hosted services with independent configurations
As far I know, it's possible to add multiple hosted services to run under the same 'host', like this example took from Microsoft page:

```<code>public IServiceProvider ConfigureServices(IServiceCollection services)
{
    //Other DI registrations;

    // Register Hosted Services
    services.AddHostedService<GracePeriodManagerService>();
    services.AddHostedService<MyHostedServiceB>();
    services.AddHostedService<MyHostedServiceC>();
    //...
}

</code>```

If instead of that I create three different projects, It would be possible to inject three different configurations for each one of them.

Is there any way to do that in same project? Maybe loading different configuration files(appsettings.json)?

Like:

For hosted service GracePeriodManagerService appsettings.graceperiod.json

For hosted service MyHostedServiceB appsettings.myHostedServiceB.json

Or separating it by folders:

For hosted service GracePeriodManagerService GracePeriodManagerService\appsettings.json

For hosted service MyHostedServiceB MyHostedServiceB\appsettings.json

答:
You can do it in many ways.

The best way would be to use IOptions pattern:
In your appsettings file you can add:

```<code>"Position": {
    "Title": "Editor",
    "Name": "Joe Smith"
  }
</code>```

You should have a class matching the json object above:

```<code>public class PositionOptions

{
    public const string Position = "Position";

    public string Title { get; set; }
    public string Name { get; set; }
}
</code>```

Finally you can inject it to the DI container by:

```<code>services.Configure<PositionOptions>(Configuration.GetSection(
                                        PositionOptions.Position));
</code>```

If you still want to use multiple appsetings files you could do the following.

In the Startup.cs:

```<code>        private readonly IConfiguration _configurationName1;
        private readonly IConfiguration _configurationName2;
        public Startup(IConfiguration configuration)
        {
            _configurationName1 = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettingsWorker1.json")
            .Build();

            _configurationName2 = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettingsWorker2.json")
            .Build();
         }
</code>```

Then you can use seperate configurations on demand.

Body:
As far I know, it's possible to add multiple hosted services to run under the same 'host', like this example took from Microsoft page:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    //Other DI registrations;

    // Register Hosted Services
    services.AddHostedService<GracePeriodManagerService>();
    services.AddHostedService<MyHostedServiceB>();
    services.AddHostedService<MyHostedServiceC>();
    //...
}

If instead of that I create three different projects, It would be possible to inject three different configurations for each one of them.

Is there any way to do that in same project? Maybe loading different configuration files(appsettings.json)?

Like:

For hosted service GracePeriodManagerService appsettings.graceperiod.json

For hosted service MyHostedServiceB appsettings.myHostedServiceB.json

Or separating it by folders:

For hosted service GracePeriodManagerService GracePeriodManagerService\appsettings.json

For hosted service MyHostedServiceB MyHostedServiceB\appsettings.json

Body:
You can do it in many ways.

The best way would be to use IOptions pattern:
In your appsettings file you can add:

"Position": {
    "Title": "Editor",
    "Name": "Joe Smith"
  }

You should have a class matching the json object above:

public class PositionOptions

{
    public const string Position = "Position";

    public string Title { get; set; }
    public string Name { get; set; }
}

Finally you can inject it to the DI container by:

services.Configure<PositionOptions>(Configuration.GetSection(
                                        PositionOptions.Position));

If you still want to use multiple appsetings files you could do the following.

In the Startup.cs:

        private readonly IConfiguration _configurationName1;
        private readonly IConfiguration _configurationName2;
        public Startup(IConfiguration configuration)
        {
            _configurationName1 = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettingsWorker1.json")
            .Build();

            _configurationName2 = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettingsWorker2.json")
            .Build();
         }

Then you can use seperate configurations on demand.


问:
JWT Encryption Error when using EncryptingCredentials in token generation method
I implemented JWT token in my ASP.net core 3.1 web api.
In the token generation method when I try to use EncryptingCredentials I got the below error :

IDX10662: The KeyWrap algorithm 'System.String' requires a key size of 'System.Int32' bits. Key '', is of size:'System.Int32'. (Parameter 'Length')

This is my Token generation method :

```<code>public async Task<string> GenerateAsync(User user)
    {
        var secretKey = Encoding.UTF8.GetBytes(_siteSetting.JwtSettings.SecretKey); //"SampleSecretKeyChange"
        var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(secretKey), SecurityAlgorithms.HmacSha256Signature);

        var encryptionkey = Encoding.UTF8.GetBytes(_siteSetting.JwtSettings.Encryptkey);  //"AbcdefgHijklmnopk123456"
        var encryptingCredentials = new EncryptingCredentials(new SymmetricSecurityKey(encryptionkey), SecurityAlgorithms.Aes128KW, SecurityAlgorithms.Aes128CbcHmacSha256);

        var descriptor = new SecurityTokenDescriptor
        {
            Issuer = _siteSetting.JwtSettings.Issuer,
            Audience = _siteSetting.JwtSettings.Audience,
            IssuedAt = DateTime.Now,
            NotBefore = DateTime.Now.AddMinutes(_siteSetting.JwtSettings.NotBeforeMinutes),
            Expires = DateTime.Now.AddMinutes(_siteSetting.JwtSettings.ExpirationMinutes),
            SigningCredentials = signingCredentials,
            EncryptingCredentials = encryptingCredentials,
            Subject = new ClaimsIdentity(_getClaims(user))
        };

        var tokenHandler = new JwtSecurityTokenHandler();
        var securityToken = tokenHandler.CreateToken(descriptor);
        var jwt = tokenHandler.WriteToken(securityToken);
        return await Task.FromResult(jwt);
    }
</code>```

答: After of all research that I did, I found the problem. When you want to use EncryptingCredentials with the conditions that I described the Encryptkey key length must be equal 16 characters.

Body:
I implemented JWT token in my ASP.net core 3.1 web api.
In the token generation method when I try to use EncryptingCredentials I got the below error :

IDX10662: The KeyWrap algorithm 'System.String' requires a key size of 'System.Int32' bits. Key '', is of size:'System.Int32'. (Parameter 'Length')

This is my Token generation method :

public async Task<string> GenerateAsync(User user)
    {
        var secretKey = Encoding.UTF8.GetBytes(_siteSetting.JwtSettings.SecretKey); //"SampleSecretKeyChange"
        var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(secretKey), SecurityAlgorithms.HmacSha256Signature);

        var encryptionkey = Encoding.UTF8.GetBytes(_siteSetting.JwtSettings.Encryptkey);  //"AbcdefgHijklmnopk123456"
        var encryptingCredentials = new EncryptingCredentials(new SymmetricSecurityKey(encryptionkey), SecurityAlgorithms.Aes128KW, SecurityAlgorithms.Aes128CbcHmacSha256);

        var descriptor = new SecurityTokenDescriptor
        {
            Issuer = _siteSetting.JwtSettings.Issuer,
            Audience = _siteSetting.JwtSettings.Audience,
            IssuedAt = DateTime.Now,
            NotBefore = DateTime.Now.AddMinutes(_siteSetting.JwtSettings.NotBeforeMinutes),
            Expires = DateTime.Now.AddMinutes(_siteSetting.JwtSettings.ExpirationMinutes),
            SigningCredentials = signingCredentials,
            EncryptingCredentials = encryptingCredentials,
            Subject = new ClaimsIdentity(_getClaims(user))
        };

        var tokenHandler = new JwtSecurityTokenHandler();
        var securityToken = tokenHandler.CreateToken(descriptor);
        var jwt = tokenHandler.WriteToken(securityToken);
        return await Task.FromResult(jwt);
    }


问:
PrestaShop 1.7 HTTP ERROR 500
I am trying to install PrestaShop 1.7 on my VPS and I am seeing a HTTP ERROR 500 when I navigate to my domain?

Has anyone had this problem?

答:
Rebuilding the .htaccess file helped me.
    You need to login in to your admin panel.
    Go to Shop Parameters -> Traffic & SEO.
    Set 'Friendly URL' No and Click on Save button.
    Now, Set 'Friendly URL' yes back and Click on Save Button.
    Now “. htaccess” regenerated Successfully on your server.</p>

Title: PrestaShop 1.7 HTTP ERROR 500


问:
Sending FormData not working in React-Native
I tried to communicate with an API to send a picture from an Iphone. I send form data by using Postman (key: mainPicture, value 'the file I choosed') and it's working well.

The problem come when I try to do it in js: the API don't find the file in my request.

Here is my code:

```<code>  const formData = new FormData();
  formData.append('mainPicture', {
    uri: mainPicture.uri,
    type: 'image/jpg',
    name: `${mainPicture.id}.jpg`,
  });
  // ...
  // api come from apisauce package
  api.post(API_RES_IMG, formData, { headers: { ['Content-Type']: 'multipart/form-data' } })
</code>```

Server say: "Error: Multipart: Boundary not found"

Without the content-type the server receive:

```<code>{"_parts":{"0":{"0":"mainPicture","1":{"uri":"assets-library://asset/asset.JPG?id=DE830A54-2526-44CB-81FE-00786D152080&ext=JPG","type":"image/jpg","name":"1e23519b-2006-4676-b63c-624e8198e17b.jpg"}}}}
</code>```

Too much struggle from a simple thing.

答:
you should add the content type </p>

<p>'Content-Type': type === 'form' ? 'multipart/form-data' : 'application/json',</p>

Body:
I tried to communicate with an API to send a picture from an Iphone. I send form data by using Postman (key: mainPicture, value 'the file I choosed') and it's working well.

The problem come when I try to do it in js: the API don't find the file in my request.

Here is my code:

  const formData = new FormData();
  formData.append('mainPicture', {
    uri: mainPicture.uri,
    type: 'image/jpg',
    name: `${mainPicture.id}.jpg`,
  });
  // ...
  // api come from apisauce package
  api.post(API_RES_IMG, formData, { headers: { ['Content-Type']: 'multipart/form-data' } })

Server say: "Error: Multipart: Boundary not found"

Without the content-type the server receive:

{"_parts":{"0":{"0":"mainPicture","1":{"uri":"assets-library://asset/asset.JPG?id=DE830A54-2526-44CB-81FE-00786D152080&ext=JPG","type":"image/jpg","name":"1e23519b-2006-4676-b63c-624e8198e17b.jpg"}}}}

Too much struggle from a simple thing.

Body:
you should add the content type

'Content-Type': type === 'form' ? 'multipart/form-data' : 'application/json',


问:
Install APC on Windows
How can I install APC on Windows? I am using PHP 5.3, Windows 7 x64.

I used

```<code>pecl install apc
</code>```

I got

```<code>C:\PHP>pecl install apc
downloading APC-3.0.19.tgz ...
Starting to download APC-3.0.19.tgz (115,735 bytes) ............
done: 115,735 bytes 47 source files, building
WARNING: php_bin c:\php\php.exe appears to have a suffix \php.exe, but config
    variable php_suffix does not match running: msdev APC.dsp /MAKE "APC - Release"
ERROR: Did not understand the completion status returned from msdev.exe.
</code>```

答:
Also, make sure that the compiled version from here http://downloads.php.net/pierre/
matches your php version, otherwise the extension will not load (php v. 5.2.17 requires php_apc.dll v 5.2.17.17 - which doesn't seem to be available as of this writing - I had to downgrade the php version to play with apc).

Another point, pierre's zip packages, at least the one I downloaded, did not include the management script. you can get it from here: http://pecl.php.net/package/APC - select the version you downloaded, then navigate to Browse Source, then find your version in the 'tags' folder. the apc.php script should be there.

ContentLicense: CC BY-SA 2.5

Title: Install APC on Windows

Body:
How can I install APC on Windows? I am using PHP 5.3, Windows 7 x64.

I used

pecl install apc

I got

C:\PHP>pecl install apc
downloading APC-3.0.19.tgz ...
Starting to download APC-3.0.19.tgz (115,735 bytes) ............
done: 115,735 bytes 47 source files, building
WARNING: php_bin c:\php\php.exe appears to have a suffix \php.exe, but config
    variable php_suffix does not match running: msdev APC.dsp /MAKE "APC - Release"
ERROR: Did not understand the completion status returned from msdev.exe.


问:
Why isn't text-justify: distribute working in Chrome?
In Firefox, the below CSS works:

.fill-space {
    text-align: justify;
    text-justify: distribute; /*This property is not working */
    text-align-last: center;
}
```

But it's not working in Chrome. How can I get it working in Chrome?

答:
was looking to do this also. Details here from W3 - basically its not been rolled out yet, looks to be behind experimental features and needs to be enabled on chrome.... but is available on IE!!!!?????

https://www.w3schools.com/cssref/css3_pr_text-justify.asp

*This feature is behind the Enable Experimental Web Platform Features preference (needs to be set to Enabled). To change preferences in Chrome: type in "chrome://flags" in the Chrome browser. To change preferences in Opera: type in "flags" in the Opera browser.

Body:
In Firefox, the below CSS works:

.fill-space {
    text-align: justify;
    text-justify: distribute; /*This property is not working */
    text-align-last: center;
}

But it's not working in Chrome. How can I get it working in Chrome?


问:
How ignore empty array elements for length calculation
JS:

```<code>var personnesAAjouter = [];

personnesAAjouter[idUtilisateur] = [];
personnesAAjouter[idUtilisateur]['nom'] = nomUtilisateur;
personnesAAjouter[idUtilisateur]['prenom'] = prenomUtilisateur;
personnesAAjouter[idUtilisateur]['email'] = emailUtilisateur;
</code>```

For exemple, if I add an user with idUtilisateur = 102, length of personneAAjouter is 102.

Maybe because keys are integer and that Javascript use keys to get the array length?

It exists a way to ignore each empty elements for length calculation?

Thank's for help!

答:
I ended up using arr.filter(x=>1).length instead of just arr.length

myArray = ["a","b"]
delete array[1] // deletes "b", but leaves an 'empty' slot 'existing'

console.log(myArray)
// ["a", empty]

myArray.length
// -> 2

// this is a filter that returns true for every item, but is only run for
// items that aren't empty. Note that it is non-mutating; it creates a
// new array in memory, measures its length, and then lets it disappear
// into the void.
myArray.filter(x=>1).length // -> 1
```

Body:
JS:

var personnesAAjouter = [];

personnesAAjouter[idUtilisateur] = [];
personnesAAjouter[idUtilisateur]['nom'] = nomUtilisateur;
personnesAAjouter[idUtilisateur]['prenom'] = prenomUtilisateur;
personnesAAjouter[idUtilisateur]['email'] = emailUtilisateur;

For exemple, if I add an user with idUtilisateur = 102, length of personneAAjouter is 102.

Maybe because keys are integer and that Javascript use keys to get the array length?

It exists a way to ignore each empty elements for length calculation?

Thank's for help!


问:
Install pip on mac failed
So I installed different versions of Pythons on my mac and it seems this is the root of all my problems at the moment. I want to import the module named pyperclip in Mueditor but it always says No module named 'pyperclip'

I read a lot of different other threads and tried to sudo /usr/bin/python get-pip.py
But I always get /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'get-pip.py': [Errno 2] No such file or directory
Which indicates that it is searching in the wrong directory (not sure with the correct terminology here).

I installed Python 3.8 with homebrew and everything is updated fine.

For context: I started programming with anaconda, deleted it downloaded Python from the official website and am using Mueditor right now while following the tasks in the book 'Automate the boring stuff with Python'.

I am even considering setting up my OSX again...
Help is much appreciated!

答:
I read a lot of different other threads and tried to sudo /usr/bin/python get-pip.py But I always get /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'get-pip.py': [Errno 2] No such file or directory Which indicates that it is searching in the wrong directory (not sure with the correct terminology here).

I installed Python 3.8 with homebrew and everything is updated fine.

You need to download the get-pip.py file and then execute that command referencing that file.

https://bootstrap.pypa.io/get-pip.py

Make sure you are selecting the right Python interpreter. You have multiple installed.  You can check their versions with /usr/bin/python -V. In your case /usr/bin/python/ is Python 2.7.

Python 3.8 comes with pip installed. Once you figured out the path of your Python3 interpreter you can do: /path/to/your/python3 -m pip install pyperclip.

Title: Install pip on mac failed


问:
main.xxxxxxxxxxxx.js in build file contains img src=x onerror=alert(1) which is related to XSS vulnerability. Is there a way to get rid of it?
While making a production build in Angular, the main.xxxxxxxx.js created contains the code

```<code><img src="</style><img src=x onerror=alert(1)"//>
</code>```

which we can find doing Ctrl + F. I have confirmed the behaviour in multiple projects including the boilerplate one. Since this particular line of code seems malicious due to its relation to XSS attacks, is there a way to get rid of it ? Also, can someone explain why this suspicious line exist if by any chance it serves a purpose or it is a bug on the part of Angular ?

答:
can someone explain why this suspicious line exist if by any chance

It looks like it's inserted as a sanitisation script, you can see it being added here

inertBodyElement.innerHTML = '<svg>
';
```

<p>and this class has the description</p>

<pre class="lang-js prettyprint-override"><code>/**
 * This helper class is used to get hold of an inert tree of DOM elements containing dirty HTML
 * that needs sanitizing.
 * Depending upon browser support we must use one of three strategies for doing this.
 * Support: Safari 10.x -> XHR strategy
 * Support: Firefox -> DomParser strategy
 * Default: InertDocument strategy
 */
</code>```

The spec file references a DOMPurify release which seems to be related to a Mozilla security bug. The DOMPurify release notes state:

Users who install this latest release are not affected by the bug
  anymore as DOMPurify fixes around the problem and mitigates the issue
  by not trusting Gecko's innerHTML implementation any much longer.
  Instead of the combination of document.implementation and
  doc.body.outerHTML, DOMPurify is now using the DOMParser feature
  available in all modern browsers.

So this piece of code is sanitising the DOM to prevent this XSS attack. It is not an exploit in itself.

is there a way to get rid of it?

You don't want to get rid of this, it's a good thing

Body:
While making a production build in Angular, the main.xxxxxxxx.js created contains the code

<img src="</style>

which we can find doing Ctrl + F. I have confirmed the behaviour in multiple projects including the boilerplate one. Since this particular line of code seems malicious due to its relation to XSS attacks, is there a way to get rid of it ? Also, can someone explain why this suspicious line exist if by any chance it serves a purpose or it is a bug on the part of Angular ?

Body:
can someone explain why this suspicious line exist if by any chance

It looks like it's inserted as a sanitisation script, you can see it being added here

inertBodyElement.innerHTML = '<svg><p><style><img src="</style><img src=x onerror=alert(1)//">';

and this class has the description

/**
 * This helper class is used to get hold of an inert tree of DOM elements containing dirty HTML
 * that needs sanitizing.
 * Depending upon browser support we must use one of three strategies for doing this.
 * Support: Safari 10.x -> XHR strategy
 * Support: Firefox -> DomParser strategy
 * Default: InertDocument strategy
 */

The spec file references a DOMPurify release which seems to be related to a Mozilla security bug. The DOMPurify release notes state:

Users who install this latest release are not affected by the bug
  anymore as DOMPurify fixes around the problem and mitigates the issue
  by not trusting Gecko's innerHTML implementation any much longer.
  Instead of the combination of document.implementation and
  doc.body.outerHTML, DOMPurify is now using the DOMParser feature
  available in all modern browsers.

So this piece of code is sanitising the DOM to prevent this XSS attack. It is not an exploit in itself.

is there a way to get rid of it?

You don't want to get rid of this, it's a good thing


问:
What is the best way to make clickable text in java?
This is for an application so I don't want a hyperlink. I first tried using a Jbutton without all of border/background stuff and then hooking up an actionListener to it but I couldn't get it to the point where I thought it looked nice.  I also tried using a JLabel and hooking up a mouse listener to that but I also couldn't get it to look right.

Basically I would like a way using swing to make a button exactly like a url link in an application.  What is the standard way of doing this?

答: It's you're trying to make a desktop application which looks like HTML inside a browser, you might try using some of the richer Swing text components in a read-only mode. You could use a mouse-listener to map X/Y clicks to a particular character of text, and then cause an action to occur on that basis.</p>


问:
Cloud Functions for Firebase - Billing account not configured
I just implemented the new Cloud Functions for Firebase, but there something in the log that bothers me:

Billing account not configured. External network is not accessible and
  quotas are severily limited. Configure billing account to remove these
  restrictions

I actually managed to access the function from the external network, so I'm wondering do I really have to give my billing account? There's nothing about this in the firebase documentation.

I'm using the Spark subscription plan for personal test purposes and I don't want to add billing info if I'm not going to pay for anything yet.

答:
Yes you need to upgrade to blaze plan from your existing free plan which is spark.
You wont be charged until you exceed the spark plan benefits.</p>


问:
Time Difference in Flutter (Dart)
I have an Api call. I  want to call the Api again when 24 hours passed from the previous Api call. How to find the time difference in flutter. please explain your answer in detail.</p>

答:
Support:

Official docs https://api.dart.dev/stable/2.8.3/dart-core/DateTime/difference.html

```<code>var berlinWallFell = new DateTime.utc(1989, DateTime.november, 9);
var dDay = new DateTime.utc(1944, DateTime.june, 6);

Duration difference = berlinWallFell.difference(dDay);
assert(difference.inDays == 16592);
</code>```

Duration has more properties and methods to check more details.
Duration docs https://api.dart.dev/stable/2.8.3/dart-core/Duration-class.html

Example: (Edit)

Save date time in SharedPreferences on API call

```<code>sharedPrefs.putInt('apiCallTime',DateTime.now().milliSecondsSinceEpoch);
</code>```

When you want to recall the API, get time and call

```<code>int lastCallTimeInSeconds = sharedPrefs.getInt('apiCallTime')??DateTime.now().milliSecondsSinceEpoch;
DateTime lastCallTime = DateTime.fromMilliSecondsSinceEpoch(lastCallTimeInSeconds);
if(DateTime.now().difference(lastCallTime).inHours>=24){
//Re call API here...
}
</code>```

Title: Time Difference in Flutter (Dart)

Body:
Support:

Official docs https://api.dart.dev/stable/2.8.3/dart-core/DateTime/difference.html

var berlinWallFell = new DateTime.utc(1989, DateTime.november, 9);
var dDay = new DateTime.utc(1944, DateTime.june, 6);

Duration difference = berlinWallFell.difference(dDay);
assert(difference.inDays == 16592);

Duration has more properties and methods to check more details.
Duration docs https://api.dart.dev/stable/2.8.3/dart-core/Duration-class.html

Example: (Edit)

Save date time in SharedPreferences on API call

sharedPrefs.putInt('apiCallTime',DateTime.now().milliSecondsSinceEpoch);

When you want to recall the API, get time and call

int lastCallTimeInSeconds = sharedPrefs.getInt('apiCallTime')??DateTime.now().milliSecondsSinceEpoch;
DateTime lastCallTime = DateTime.fromMilliSecondsSinceEpoch(lastCallTimeInSeconds);
if(DateTime.now().difference(lastCallTime).inHours>=24){
//Re call API here...
}


问:
Calculated query with parameters in HANA/CrystalReports
I'm having trouble trying to explain my necessity, so I'll describe the scenario.

Scenario:

Product A has a maximum production of 125KG at a time.

The operator received a production order of 1027,5KG of product A.

The operator have to calculate how many rounds he'll have to
manufacture and adjust the components quantity for each round.

We want to create a report where this calculations are already done and what we believe would be the first step, based on the values of this scenario, is to return something like this:

ROUND QUANTITY(KG)

1                 125

2                 125

3                 125

4                 125

5                 125

6                 125

7                 125

8                 125

9                 27,5

After that, the recalculation of the components could be done with simple operations.

The problem is that we couldn't think of a way to get the desired return and we also couldn't think of a different way of achieving the said report.

All we could do is get the integer part of the division

```<code>SELECT FLOOR(1027.5/125) AS "TEST" FROM DUMMY
</code>```

and the remainder

```<code>SELECT MOD(1027.5,125) AS "TEST" FROM DUMMY
</code>```

We are using:

SAP HANA SQL

Crystal Reports

SAP B1

Any help would be appreciated

Thanks in advance!

答:
There are several ways to achieve want you described.

One way is to translate the requirement into a function that takes the two input parameter values and returns the table of production rounds.

This can look like this:

```<code>create or replace  function production_rounds(
            IN max_production_volume_per_round decimal (10, 2)
          , IN production_order_volume         decimal (10, 2)
          )
returns table   (
          production_round integer
        , production_volume decimal (10, 2))
as
begin
declare rounds_to_produce integer;
declare remainder_production_volume decimal (10, 2);

    rounds_to_produce := floor( :production_order_volume / :max_production_volume_per_round);
    remainder_production_volume := mod(:production_order_volume, :max_production_volume_per_round);

    return
        select /* generate rows for all "max" rounds */
                 s.element_number                   as production_round
               , :max_production_volume_per_round   as production_volume
        from
            series_generate_integer
                (1, 1, :rounds_to_produce + 1) s
    UNION ALL
        select /* generate a row for the final row with the remainder */
                :rounds_to_produce + 1              as production_round
              , :remainder_production_volume        as production_volume
        from
            dummy
        where
            :remainder_production_volume > 0.0;

end;
</code>```

You can use this function just like any table - but with parameters:

```<code>select * from production_rounds (125 , 1027.5) ;

PRODUCTION_ROUND    PRODUCTION_VOLUME
1                   125
2                   125
3                   125
4                   125
5                   125
6                   125
7                   125
8                   125
9                   27.5
</code>```

The bit that probably needs explanation is SERIES_GENERATE_INTEGER. This is a HANA-specific built-in function that returns a number of records from a "series". Series here is a sequence of periods within a min and max limit and with a certain step-size between two adjacend periods.
More on how this works can be found in the HANA reference documentation, but for now just say, this is the fastest way to generate a result set with X rows.

This series-generator is used to create all "full" production rounds.
For the second part of the UNION ALL then creates just a single row by selecting from the built-in table DUMMY (DUAL in Oracle) which is guaranteed to only have a single record.
Finally, this second part needs to be "disabled" if there actually is no remainder, which is done by the WHERE clause.

Body:
I'm having trouble trying to explain my necessity, so I'll describe the scenario.

Scenario:

Product A has a maximum production of 125KG at a time.

The operator received a production order of 1027,5KG of product A.

The operator have to calculate how many rounds he'll have to
manufacture and adjust the components quantity for each round.

We want to create a report where this calculations are already done and what we believe would be the first step, based on the values of this scenario, is to return something like this:

ROUND QUANTITY(KG)

1                 125

2                 125

3                 125

4                 125

5                 125

6                 125

7                 125

8                 125

9                 27,5

After that, the recalculation of the components could be done with simple operations.

The problem is that we couldn't think of a way to get the desired return and we also couldn't think of a different way of achieving the said report.

All we could do is get the integer part of the division

SELECT FLOOR(1027.5/125) AS "TEST" FROM DUMMY

and the remainder

SELECT MOD(1027.5,125) AS "TEST" FROM DUMMY

We are using:

SAP HANA SQL

Crystal Reports

SAP B1

Any help would be appreciated

Thanks in advance!

Body:
There are several ways to achieve want you described.

One way is to translate the requirement into a function that takes the two input parameter values and returns the table of production rounds.

This can look like this:

create or replace  function production_rounds(
            IN max_production_volume_per_round decimal (10, 2)
          , IN production_order_volume         decimal (10, 2)
          )
returns table   (
          production_round integer
        , production_volume decimal (10, 2))
as
begin
declare rounds_to_produce integer;
declare remainder_production_volume decimal (10, 2);

    rounds_to_produce := floor( :production_order_volume / :max_production_volume_per_round);
    remainder_production_volume := mod(:production_order_volume, :max_production_volume_per_round);

    return
        select /* generate rows for all "max" rounds */
                 s.element_number                   as production_round
               , :max_production_volume_per_round   as production_volume
        from
            series_generate_integer
                (1, 1, :rounds_to_produce + 1) s
    UNION ALL
        select /* generate a row for the final row with the remainder */
                :rounds_to_produce + 1              as production_round
              , :remainder_production_volume        as production_volume
        from
            dummy
        where
            :remainder_production_volume > 0.0;

end;

You can use this function just like any table - but with parameters:

select * from production_rounds (125 , 1027.5) ;

PRODUCTION_ROUND    PRODUCTION_VOLUME
1                   125
2                   125
3                   125
4                   125
5                   125
6                   125
7                   125
8                   125
9                   27.5

The bit that probably needs explanation is SERIES_GENERATE_INTEGER. This is a HANA-specific built-in function that returns a number of records from a "series". Series here is a sequence of periods within a min and max limit and with a certain step-size between two adjacend periods.
More on how this works can be found in the HANA reference documentation, but for now just say, this is the fastest way to generate a result set with X rows.

This series-generator is used to create all "full" production rounds.
For the second part of the UNION ALL then creates just a single row by selecting from the built-in table DUMMY (DUAL in Oracle) which is guaranteed to only have a single record.
Finally, this second part needs to be "disabled" if there actually is no remainder, which is done by the WHERE clause.


问:
Top Down Approach for this dynamic programming problem
Here is the problem-

You are given array B of size n. You have to construct array A such that 1<=A[i]<=B[i] and sum of the absolute difference of consecutive pairs of A is maximized ,that is, summation of abs(A[i]-A[i-1]) is maximised.You have to return this cost.

Example B=[1,2,3] A can be [1,2,1],[1,1,3],[1,2,3] In all these cases cost is 2 which is the maximum.

Constraints n<=10^5 ,1<=B[i]<=100

Here is my approach -
Cost will be maximum when A[i]=1 or A[i]=B[i]

So I created dp[idx][flag][curr] of size [100002][2][102] where it calculates the cost till index idx. flag will be 0 or 1 representing if A[i] should be 1 or B[i] respectively. curr will be the value of A[i] depending upon flag

Here is my code

```<code>     #include<bits/stdc++.h>
using namespace std;
#define boost ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
typedef long long int ll;
#define mod 1000000007

 ll n;
ll dp[100002][2][101];
ll b[100005];
 ll solve(ll idx,ll flag,ll curr)
 {

     if(idx>=n)
         return 0;
     ll s1=0;
    if(dp[idx][flag][curr]!=-1)
        return dp[idx][flag][curr];
     if(idx==0)
     {
         int left=solve(idx+1,0,curr);
         int right=solve(idx+1,1,curr);
         return dp[idx][flag][curr]=max(left,right);
     }
     else
     {
         if(flag==0)
         {
             s1=abs(curr-1);
             return dp[idx][flag][curr]=s1+max(solve(idx+1,0,1),solve(idx+1,1,1));
         }
         else
         {
             s1=abs(b[idx]-curr);
        return dp[idx][flag][curr]=s1+max(solve(idx+1,0,b[idx]),solve(idx+1,1,b[idx]));
         }
     }
 }

int main()
{
    boost
ll t;
cin>>t;
while(t--)
{
cin>>n;
memset(dp,-1,sizeof(dp));
ll res=0;
for(int i=0;i<n;i++)
    cin>>b[i];
ll s1=solve(0,0,1);//Starting from idx 0 flag 0 and value as 1
ll s2=solve(0,1,b[0]);//Starting from idx 0 flag 1 and value as B[0]
cout<<max(s1,s2)<<"\n";
}
}'
</code>```

Is there any way to reduce states of dp or any other top down solution because my code fails if values of B[i] are large

答:
You implement a recursive approach. Here, a simple iterative implementation allows to get a time efficiency of O(n) and a space efficiency of O(1)
(not counting the space needed for the input array).

You correctly stated that at index i, we have two choices only, a[i]=1 (flag = 0) or a[i]=b[i] (flag = 1)

The basic idea is that, when studying what choice to make at index i, we only need to know what are the optimum sums ending at index i-1, for flag = 0 (sum0) or flag = 1 (sum1).

We don't need to explicitely calculate the array a[.].

Note: I kept long long int as in your code, but it seems that int is quite enough here.

```<code>#include    <iostream>
#include    <cstdio>
#include    <vector>
#include    <cstdlib>
#include    <algorithm>

#define mod 1000000007          // needed ???

long long int sum_diff (const std::vector<long long> &b) {
    int n = b.size();
    long long int sum0 = 0;
    long long int sum1 = 0;
    for (int i = 1; i < n; ++i) {
        long long int temp = std::max (sum0, sum1 + b[i-1] - 1);            // flag = 0: a[i] = 1
        sum1 = std::max (sum0 + b[i] - 1, sum1 + std::abs(b[i] - b[i-1]));  // flag = 1: a[i] = b[i]
        sum0 = temp;
    }
    return std::max (sum0, sum1);
 }

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    std::cout.tie(0);
    int t;
    std::cin >> t;
    while(t--) {
        int n;
        std::cin >> n;
        std::vector<long long int> b(n);
        for(int i = 0;i < n; i++) std::cin >> b[i];
        long long int s = sum_diff (b);
        std::cout << s << "\n";
    }
}
</code>```

As you insist to have a top-down (recursive) aproach, I have implement both approaches in the following code. But I insist that the iterative solution is better in this case.

```<code>#include    <iostream>
#include    <cstdio>
#include    <cstdlib>
#include    <vector>
#include    <algorithm>

int sum_diff (const std::vector<int> &b) {
    int n = b.size();
    int sum0 = 0;
    int sum1 = 0;
    for (int i = 1; i < n; ++i) {
        int temp = std::max (sum0, sum1 + b[i-1] - 1);                      // flag = 0: a[i] = 1
        sum1 = std::max (sum0 + b[i] - 1, sum1 + std::abs(b[i] - b[i-1]));  // flag = 1: a[i] = b[i]
        sum0 = temp;
    }
    return std::max (sum0, sum1);
 }

 void sum_diff_recurs (const std::vector<int> &b, int i, int&sum0, int &sum1) {
    if (i == 0) {
        sum0 = sum1 = 0;
        return;
    }
    sum_diff_recurs (b, i-1, sum0, sum1);
    int temp = std::max (sum0, sum1 + b[i-1] - 1);                      // flag = 0: a[i] = 1
    sum1 = std::max (sum0 + b[i] - 1, sum1 + std::abs(b[i] - b[i-1]));  // flag = 1: a[i] = b[i]
    sum0 = temp;
 }

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    std::cout.tie(0);
    int t;
    std::cin >> t;
    while(t--) {
        int n, sum0, sum1;
        std::cin >> n;
        std::vector<int> b(n);
        for(int i = 0; i < n; i++) std::cin >> b[i];
        int s = sum_diff (b);
        std::cout << s << "\n";
        sum_diff_recurs (b, n-1, sum0, sum1);
        std::cout << std::max(sum0, sum1) << "\n";
    }
}
</code>```

Body:
Here is the problem-

You are given array B of size n. You have to construct array A such that 1<=A[i]<=B[i] and sum of the absolute difference of consecutive pairs of A is maximized ,that is, summation of abs(A[i]-A[i-1]) is maximised.You have to return this cost.

Example B=[1,2,3] A can be [1,2,1],[1,1,3],[1,2,3] In all these cases cost is 2 which is the maximum.

Constraints n<=10^5 ,1<=B[i]<=100

Here is my approach -
Cost will be maximum when A[i]=1 or A[i]=B[i]

So I created dp[idx][flag][curr] of size [100002][2][102] where it calculates the cost till index idx. flag will be 0 or 1 representing if A[i] should be 1 or B[i] respectively. curr will be the value of A[i] depending upon flag

Here is my code

     #include<bits/stdc++.h>
using namespace std;
#define boost ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
typedef long long int ll;
#define mod 1000000007

 ll n;
ll dp[100002][2][101];
ll b[100005];
 ll solve(ll idx,ll flag,ll curr)
 {

     if(idx>=n)
         return 0;
     ll s1=0;
    if(dp[idx][flag][curr]!=-1)
        return dp[idx][flag][curr];
     if(idx==0)
     {
         int left=solve(idx+1,0,curr);
         int right=solve(idx+1,1,curr);
         return dp[idx][flag][curr]=max(left,right);
     }
     else
     {
         if(flag==0)
         {
             s1=abs(curr-1);
             return dp[idx][flag][curr]=s1+max(solve(idx+1,0,1),solve(idx+1,1,1));
         }
         else
         {
             s1=abs(b[idx]-curr);
        return dp[idx][flag][curr]=s1+max(solve(idx+1,0,b[idx]),solve(idx+1,1,b[idx]));
         }
     }
 }

int main()
{
    boost
ll t;
cin>>t;
while(t--)
{
cin>>n;
memset(dp,-1,sizeof(dp));
ll res=0;
for(int i=0;i<n;i++)
    cin>>b[i];
ll s1=solve(0,0,1);//Starting from idx 0 flag 0 and value as 1
ll s2=solve(0,1,b[0]);//Starting from idx 0 flag 1 and value as B[0]
cout<<max(s1,s2)<<"\n";
}
}'

Is there any way to reduce states of dp or any other top down solution because my code fails if values of B[i] are large

Body:
You implement a recursive approach. Here, a simple iterative implementation allows to get a time efficiency of O(n) and a space efficiency of O(1)
(not counting the space needed for the input array).

You correctly stated that at index i, we have two choices only, a[i]=1 (flag = 0) or a[i]=b[i] (flag = 1)

The basic idea is that, when studying what choice to make at index i, we only need to know what are the optimum sums ending at index i-1, for flag = 0 (sum0) or flag = 1 (sum1).

We don't need to explicitely calculate the array a[.].

Note: I kept long long int as in your code, but it seems that int is quite enough here.

#include    <iostream>
#include    <cstdio>
#include    <vector>
#include    <cstdlib>
#include    <algorithm>

#define mod 1000000007          // needed ???

long long int sum_diff (const std::vector<long long> &b) {
    int n = b.size();
    long long int sum0 = 0;
    long long int sum1 = 0;
    for (int i = 1; i < n; ++i) {
        long long int temp = std::max (sum0, sum1 + b[i-1] - 1);            // flag = 0: a[i] = 1
        sum1 = std::max (sum0 + b[i] - 1, sum1 + std::abs(b[i] - b[i-1]));  // flag = 1: a[i] = b[i]
        sum0 = temp;
    }
    return std::max (sum0, sum1);
 }

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    std::cout.tie(0);
    int t;
    std::cin >> t;
    while(t--) {
        int n;
        std::cin >> n;
        std::vector<long long int> b(n);
        for(int i = 0;i < n; i++) std::cin >> b[i];
        long long int s = sum_diff (b);
        std::cout << s << "\n";
    }
}

As you insist to have a top-down (recursive) aproach, I have implement both approaches in the following code. But I insist that the iterative solution is better in this case.

#include    <iostream>
#include    <cstdio>
#include    <cstdlib>
#include    <vector>
#include    <algorithm>

int sum_diff (const std::vector<int> &b) {
    int n = b.size();
    int sum0 = 0;
    int sum1 = 0;
    for (int i = 1; i < n; ++i) {
        int temp = std::max (sum0, sum1 + b[i-1] - 1);                      // flag = 0: a[i] = 1
        sum1 = std::max (sum0 + b[i] - 1, sum1 + std::abs(b[i] - b[i-1]));  // flag = 1: a[i] = b[i]
        sum0 = temp;
    }
    return std::max (sum0, sum1);
 }

 void sum_diff_recurs (const std::vector<int> &b, int i, int&sum0, int &sum1) {
    if (i == 0) {
        sum0 = sum1 = 0;
        return;
    }
    sum_diff_recurs (b, i-1, sum0, sum1);
    int temp = std::max (sum0, sum1 + b[i-1] - 1);                      // flag = 0: a[i] = 1
    sum1 = std::max (sum0 + b[i] - 1, sum1 + std::abs(b[i] - b[i-1]));  // flag = 1: a[i] = b[i]
    sum0 = temp;
 }

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    std::cout.tie(0);
    int t;
    std::cin >> t;
    while(t--) {
        int n, sum0, sum1;
        std::cin >> n;
        std::vector<int> b(n);
        for(int i = 0; i < n; i++) std::cin >> b[i];
        int s = sum_diff (b);
        std::cout << s << "\n";
        sum_diff_recurs (b, n-1, sum0, sum1);
        std::cout << std::max(sum0, sum1) << "\n";
    }
}


问:
How do I add sensitivity to Quaternion? C#
I have this script with a sensitivity variable but cannot figure out where do I add it in the code. Any experts able to help me out here?

I want to add this:

```<code>public float sensitivity = 5.0f;
</code>```

into this code for the Quaternion rotation:

```<code>switch (firstTouch.phase)
{
    case TouchPhase.Began:
        firstpoint = firstTouch.position;
        xAngTemp = xAngle;
        yAngTemp = yAngle;
        break;

    case TouchPhase.Moved:
        secondpoint = firstTouch.position;
        //Mainly, about rotate camera. For example, for Screen.width rotate on 180 degree
        xAngle = xAngTemp  + (secondpoint.x - firstpoint.x) * 180.0f / Screen.width;
        yAngle = yAngTemp  - (secondpoint.y - firstpoint.y) * 90.0f / Screen.height;
        //Rotate camera
        this.transform.rotation = Quaternion.Euler(yAngle, xAngle, 0.0f);
        character.transform.rotation = Quaternion.Euler(yAngle, xAngle, 0.0f);
        break;
}
</code>```

答:
Probably not an expert but what about simply multiplying it like

```<code>xAngle = xAngTemp  + (secondpoint.x - firstpoint.x) * 180f  * sensitivity / Screen.width;
yAngle = yAngTemp  - (secondpoint.y - firstpoint.y) * 90f * sensitiviy / Screen.height;
</code>```

Though I would recommend to rather use a Vector2 in order to be able to use individual sensitivties for x and y

```<code>public Vector2 sensitivtiy = Vector2.one * 5f;

...

xAngle = xAngTemp  + (secondpoint.x - firstpoint.x) * 180f  * sensitivity.x / Screen.width;
yAngle = yAngTemp  - (secondpoint.y - firstpoint.y) * 90f * sensitiviy.y / Screen.height;
</code>```

Body:
I have this script with a sensitivity variable but cannot figure out where do I add it in the code. Any experts able to help me out here?

I want to add this:

public float sensitivity = 5.0f;

into this code for the Quaternion rotation:

switch (firstTouch.phase)
{
    case TouchPhase.Began:
        firstpoint = firstTouch.position;
        xAngTemp = xAngle;
        yAngTemp = yAngle;
        break;

    case TouchPhase.Moved:
        secondpoint = firstTouch.position;
        //Mainly, about rotate camera. For example, for Screen.width rotate on 180 degree
        xAngle = xAngTemp  + (secondpoint.x - firstpoint.x) * 180.0f / Screen.width;
        yAngle = yAngTemp  - (secondpoint.y - firstpoint.y) * 90.0f / Screen.height;
        //Rotate camera
        this.transform.rotation = Quaternion.Euler(yAngle, xAngle, 0.0f);
        character.transform.rotation = Quaternion.Euler(yAngle, xAngle, 0.0f);
        break;
}

Body:
Probably not an expert but what about simply multiplying it like

xAngle = xAngTemp  + (secondpoint.x - firstpoint.x) * 180f  * sensitivity / Screen.width;
yAngle = yAngTemp  - (secondpoint.y - firstpoint.y) * 90f * sensitiviy / Screen.height;

Though I would recommend to rather use a Vector2 in order to be able to use individual sensitivties for x and y

public Vector2 sensitivtiy = Vector2.one * 5f;

...

xAngle = xAngTemp  + (secondpoint.x - firstpoint.x) * 180f  * sensitivity.x / Screen.width;
yAngle = yAngTemp  - (secondpoint.y - firstpoint.y) * 90f * sensitiviy.y / Screen.height;


问:
Is android:windowExitAnimation not working?
As mentioned by Google in this https://youtu.be/N_x7SV3I3P0

view.animation is still the way for Windows transition Animation.

Hence I use

```<code>    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:windowAnimationStyle">@style/WindowAnimations</item>
    </style>

    <style name="WindowAnimations">
        <item name="android:windowEnterAnimation">@anim/enter_activity</item>
        <item name="android:windowExitAnimation">@anim/exit_activity</item>
    </style>
</code>```

I only get the enter transition when I get from Activity1 (Hello World) to Activitity2 (Purple). Similar when getting back from Activity2 to Activitiy1, only the enter transition shown. The exit transition can never be triggered.

Shown below is the result.

Looks like android:windowExitAnimation is not working? (i.e. if I remove it, the effect is the same).

To workaround, in my Activity2, I use overridePendingTransition(R.anim.enter_activity, R.anim.exit_activity) instead like below.

```<code>class Main2Activity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        overridePendingTransition(R.anim.enter_activity, R.anim.exit_activity)
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(R.anim.enter_activity, R.anim.exit_activity)
    }
}
</code>```

Then I get the result as I wanted.

Is there a bug in android:windowExitAnimation? Or I miss something?

p/s: my transition animation XML as below

enter_activity.xml

```<code><set android:shareInterpolator="false"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:fromXScale="0.0"
        android:toXScale="1.0"
        android:fromYScale="0.0"
        android:toYScale="1.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:fillAfter="false"
        android:duration="2000" />
</set>
</code>```

exit_activity.xml

```<code><set android:shareInterpolator="false"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:fromXScale="1.0"
        android:toXScale="0.0"
        android:fromYScale="1.0"
        android:toYScale="0.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:fillAfter="false"
        android:duration="2000" />
</set>
</code>```

答:
Looks like I need to use the below instead

```<code><style name="WindowAnimations">
    <item name="android:activityOpenEnterAnimation">@anim/enter_activity</item>
    <item name="android:activityOpenExitAnimation">@anim/exit_activity</item>
    <item name="android:activityCloseEnterAnimation">@anim/enter_activity</item>
    <item name="android:activityCloseExitAnimation">@anim/exit_activity</item>
</style>
</code>```

The below is supposed to use for opening up the App or close the App (or background the App), and not for opening different Android Activities (although it is strange that android:windowEnterAnimation works for opening activity, and will interfere (mixed) with the android:activityOpenEnterAnimation and android:activityCloseEnterAnimation)

```<code><style name="WindowAnimations">
    <item name="android:windowEnterAnimation">@anim/enter_activity</item>
    <item name="android:windowExitAnimation">@anim/exit_activity</item>
</style>
</code>```

The windowEnterAnimation works but not windowExitAnimation though.

Body:
As mentioned by Google in this https://youtu.be/N_x7SV3I3P0

view.animation is still the way for Windows transition Animation.

Hence I use

I only get the enter transition when I get from Activity1 (Hello World) to Activitity2 (Purple). Similar when getting back from Activity2 to Activitiy1, only the enter transition shown. The exit transition can never be triggered.

Shown below is the result.

Looks like android:windowExitAnimation is not working? (i.e. if I remove it, the effect is the same).

To workaround, in my Activity2, I use overridePendingTransition(R.anim.enter_activity, R.anim.exit_activity) instead like below.

class Main2Activity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        overridePendingTransition(R.anim.enter_activity, R.anim.exit_activity)
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(R.anim.enter_activity, R.anim.exit_activity)
    }
}

Then I get the result as I wanted.

Is there a bug in android:windowExitAnimation? Or I miss something?

p/s: my transition animation XML as below

enter_activity.xml

<set android:shareInterpolator="false"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:fromXScale="0.0"
        android:toXScale="1.0"
        android:fromYScale="0.0"
        android:toYScale="1.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:fillAfter="false"
        android:duration="2000" />
</set>

exit_activity.xml

<set android:shareInterpolator="false"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:fromXScale="1.0"
        android:toXScale="0.0"
        android:fromYScale="1.0"
        android:toYScale="0.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:fillAfter="false"
        android:duration="2000" />
</set>

Body:
Looks like I need to use the below instead

<style name="WindowAnimations">
    <item name="android:activityOpenEnterAnimation">@anim/enter_activity</item>
    <item name="android:activityOpenExitAnimation">@anim/exit_activity</item>
    <item name="android:activityCloseEnterAnimation">@anim/enter_activity</item>
    <item name="android:activityCloseExitAnimation">@anim/exit_activity</item>
</style>

The below is supposed to use for opening up the App or close the App (or background the App), and not for opening different Android Activities (although it is strange that android:windowEnterAnimation works for opening activity, and will interfere (mixed) with the android:activityOpenEnterAnimation and android:activityCloseEnterAnimation)

<style name="WindowAnimations">
    <item name="android:windowEnterAnimation">@anim/enter_activity</item>
    <item name="android:windowExitAnimation">@anim/exit_activity</item>
</style>

The windowEnterAnimation works but not windowExitAnimation though.


问:
Inheriting from linked classes
This question is about OOP in any statically typed language.  Suppose I have two classes whose instances maintain pointers/references to each other.  In my case, one class is a container, and the other a wrapper around a contained object which maintains a pointer to the container in which it lives.

```<code>class Container {
  Element[] elements;
}
class Element {
  // ... data...
  Container holds_me;
}
</code>```

The constructor of Container creates an Element object to wrap each contained object, and sets their holds_me pointers to itself.

Now I want to inherit from these classes.  I want a DerivedContainer class, which inherits from Container and contains DerivedElement objects, where DerivedElement inherits from Element and refers to the containing DerivedContainer object.  What is the right way to do this (or is it the wrong thing to do)?

The most straightforward thing is for the constructor of DerivedContainer to create DerivedElements and store them in elements and set their holds_me pointer to itself.  Then all the methods of Container and Element will work, but any new methods defined in DerivedContainer and DerivedElement will have to downcast the objects held in elements and holds_me in order to invoke any new methods on them that weren't defined in the base classes.  This doesn't seem pretty; so I wonder, is there a better solution?

答: If your language supports it, you could use Generics/Templates. The Container class could have the Elements class as a parameterized type. That way, you can forget about downcasting the Elements.</p>

Title: Inheriting from linked classes

Body:
This question is about OOP in any statically typed language.  Suppose I have two classes whose instances maintain pointers/references to each other.  In my case, one class is a container, and the other a wrapper around a contained object which maintains a pointer to the container in which it lives.

class Container {
  Element[] elements;
}
class Element {
  // ... data...
  Container holds_me;
}

The constructor of Container creates an Element object to wrap each contained object, and sets their holds_me pointers to itself.

Now I want to inherit from these classes.  I want a DerivedContainer class, which inherits from Container and contains DerivedElement objects, where DerivedElement inherits from Element and refers to the containing DerivedContainer object.  What is the right way to do this (or is it the wrong thing to do)?

The most straightforward thing is for the constructor of DerivedContainer to create DerivedElements and store them in elements and set their holds_me pointer to itself.  Then all the methods of Container and Element will work, but any new methods defined in DerivedContainer and DerivedElement will have to downcast the objects held in elements and holds_me in order to invoke any new methods on them that weren't defined in the base classes.  This doesn't seem pretty; so I wonder, is there a better solution?


问:
Swift segue not doing what it is supposed to do
I am having a little problem with a segue in my application.
When I try to push a segue so that it has a navbar it shows up correctly in the storyboard but not when I try it on my iPhone.

This is an overview of a couple of view controllers where my problem lays.

This is supposed to be the segue, so you can see that it has a navigation bar and is correctly positioned on the storyboard.

This is the view on the iPhone. No navigation bar or nothing. I tried everything but can't seem to find a solution to this problem.

Does anyone what the problem could be?

A little extra side information:
I don't know if may have something to do with the problem but the navigation view controller is not always present only when the user is logged in the app. this is decided on a log in screen if the user is not logged in the user will see a normal login screen. Else it will go to navigation view controller with a view did appear function and self.present.

Here is the code that handles that action.

```<code> // Sees if the user is logged, If yes --> go to the account detail page else go to the account view.
    override func viewDidAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let data = UserDefaults.standard.data(forKey: "User") {
            do {
                // Create JSON Decoder
                let decoder = JSONDecoder()
                // Decode Note
                _ = try decoder.decode(User.self, from: data)
                guard let loginVC = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier:
                        "AccountDetailViewController") as? AccountDetailViewController else { return }
                loginVC.modalPresentationStyle = .overCurrentContext
                self.present(loginVC, animated: false, completion: {})
            } catch {
                print("Unable to Decode Note (\(error))")
            }
        }
    }
</code>```

答:
You should push view controller instead of present. Please check this article to know more about Pushing, Popping, Presenting, & Dismissing ViewControllers

You can push AccountDetailViewController without segues. And you don't need to call performSegue(withIdentifier:) into tableView's didSelect function.

Remove segue from Interface Builder

let navigator = UINavigationController()

guard let loginVC = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier:
                        "AccountDetailViewController") as? AccountDetailViewController else { return }
loginVC.modalPresentationStyle = .overCurrentContext

navigator.pushViewController(loginVC, animated: true)
```

Body:
I am having a little problem with a segue in my application.
When I try to push a segue so that it has a navbar it shows up correctly in the storyboard but not when I try it on my iPhone.

This is an overview of a couple of view controllers where my problem lays.

This is supposed to be the segue, so you can see that it has a navigation bar and is correctly positioned on the storyboard.

This is the view on the iPhone. No navigation bar or nothing. I tried everything but can't seem to find a solution to this problem.

Does anyone what the problem could be?

A little extra side information:
I don't know if may have something to do with the problem but the navigation view controller is not always present only when the user is logged in the app. this is decided on a log in screen if the user is not logged in the user will see a normal login screen. Else it will go to navigation view controller with a view did appear function and self.present.

Here is the code that handles that action.

 // Sees if the user is logged, If yes --> go to the account detail page else go to the account view.
    override func viewDidAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let data = UserDefaults.standard.data(forKey: "User") {
            do {
                // Create JSON Decoder
                let decoder = JSONDecoder()
                // Decode Note
                _ = try decoder.decode(User.self, from: data)
                guard let loginVC = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier:
                        "AccountDetailViewController") as? AccountDetailViewController else { return }
                loginVC.modalPresentationStyle = .overCurrentContext
                self.present(loginVC, animated: false, completion: {})
            } catch {
                print("Unable to Decode Note (\(error))")
            }
        }
    }


问:
Qt C++ SerialPort is not receiving data
I am trying hard to solve this problem. But could not figure out what the problem is!
In Qt, C++ I tried to implement serial port write and read. It can only send data over serial, but not receiving from other end. I searched on google and StackOverFlow but could not solve it.
I installed virtual com port pair COM1<-->COM2

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSerialPort>
#include <QDebug>

//QSerialPort *serial;

MainWindow::MainWindow(QWidget *parent)
 : QMainWindow(parent)
 , ui(new Ui::MainWindow)
{
 ui->setupUi(this);
 serial= new QSerialPort(this);
 serial->setPortName("COM1");
 serial->setBaudRate(QSerialPort::Baud9600);
 serial->setDataBits(QSerialPort::Data8);
 serial->setParity(QSerialPort::NoParity);
 serial->setStopBits(QSerialPort::OneStop);
 serial->setFlowControl(QSerialPort::NoFlowControl);
 //serial->clearError();
 //serial->setDataTerminalReady(false);
 //serial->clear();
// qDebug() << "serial->open(QIODevice::ReadWrite)";
 //serial->open(QIODevice::ReadWrite);
 if (serial->open(QIODevice::ReadWrite))
     {
          qDebug() << "Com port opened";
            // serial->setDataTerminalReady(false);
             serial->write("Hello");
     }
     else
     {
         qDebug() << "Not opened";
     }
  ui->label->setText("Waiting..");

 connect(serial,SIGNAL(readyRead()),this,SLOT(serialReceived()));
 connect(serial, SIGNAL(error(QSerialPort::SerialPortError)), this,SLOT(handleError(QSerialPort::SerialPortError)));
}

MainWindow::~MainWindow()
{
 delete ui;
 serial->close();
}

void MainWindow::serialReceived(){

//QString received = this->Read();
//qDebug() << "received data:" << received;

 QByteArray ba;
 ba=serial->readAll();
 ui->label->setText("Waiting..");
 ui->label->setText(serial->readAll());

 qDebug()<<ba;
 qDebug() << "bytes available:" << serial->bytesAvailable();

}

void MainWindow::handleError(QSerialPort::SerialPortError error)
{
qDebug()<<"Error:"<<error;//I added this line
if(error==QSerialPort::ResourceError)
{
qDebug()<<"serial->errorString())";
//closeSerialPort();
}
}
</code>```

COM1 is assigned in Qt code and COM2 is opened in a Serial Monitor.

To test, I wrote PythonQT code which is working fine but my requirement is c++

答: Even the Terminal example code supplied with Qt Creator is not sending or receiving data.  </p>

Title: Qt C++ SerialPort is not receiving data

Body:
I am trying hard to solve this problem. But could not figure out what the problem is!
In Qt, C++ I tried to implement serial port write and read. It can only send data over serial, but not receiving from other end. I searched on google and StackOverFlow but could not solve it.
I installed virtual com port pair COM1<-->COM2

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSerialPort>
#include <QDebug>

//QSerialPort *serial;

MainWindow::MainWindow(QWidget *parent)
 : QMainWindow(parent)
 , ui(new Ui::MainWindow)
{
 ui->setupUi(this);
 serial= new QSerialPort(this);
 serial->setPortName("COM1");
 serial->setBaudRate(QSerialPort::Baud9600);
 serial->setDataBits(QSerialPort::Data8);
 serial->setParity(QSerialPort::NoParity);
 serial->setStopBits(QSerialPort::OneStop);
 serial->setFlowControl(QSerialPort::NoFlowControl);
 //serial->clearError();
 //serial->setDataTerminalReady(false);
 //serial->clear();
// qDebug() << "serial->open(QIODevice::ReadWrite)";
 //serial->open(QIODevice::ReadWrite);
 if (serial->open(QIODevice::ReadWrite))
     {
          qDebug() << "Com port opened";
            // serial->setDataTerminalReady(false);
             serial->write("Hello");
     }
     else
     {
         qDebug() << "Not opened";
     }
  ui->label->setText("Waiting..");

 connect(serial,SIGNAL(readyRead()),this,SLOT(serialReceived()));
 connect(serial, SIGNAL(error(QSerialPort::SerialPortError)), this,SLOT(handleError(QSerialPort::SerialPortError)));
}

MainWindow::~MainWindow()
{
 delete ui;
 serial->close();
}

void MainWindow::serialReceived(){

//QString received = this->Read();
//qDebug() << "received data:" << received;

 QByteArray ba;
 ba=serial->readAll();
 ui->label->setText("Waiting..");
 ui->label->setText(serial->readAll());

 qDebug()<<ba;
 qDebug() << "bytes available:" << serial->bytesAvailable();

}

void MainWindow::handleError(QSerialPort::SerialPortError error)
{
qDebug()<<"Error:"<<error;//I added this line
if(error==QSerialPort::ResourceError)
{
qDebug()<<"serial->errorString())";
//closeSerialPort();
}
}

COM1 is assigned in Qt code and COM2 is opened in a Serial Monitor.

To test, I wrote PythonQT code which is working fine but my requirement is c++


问:
Error creating bean with name and Singleton bean creation not allowed
I am getting the following exception when I execute the code via JUnit Test Case

org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'somarFactory': Singleton bean creation not allowed while the singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)

Could someone advise what might be the issues?

答: You can also get this exception if you have a dependency that's in provided scope but it's not available at run time. </p>