问:
Spark Standalone: application gets 0 cores
I seem to be unable to assign cores to an application. This leads to the following (apparently common) error message:

```<code>Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
</code>```

I have one master and two slaves in a Spark cluster. All are 8-core i7s with 16GB of RAM.

I have left the spark-env.sh virtually virgin on all three, just specifying the master's IP address.

My spark-submit is the following:

```<code>nohup ./bin/spark-submit
  --jars ./ikoda/extrajars/ikoda_assembled_ml_nlp.jar,./ikoda/extrajars/stanford-corenlp-3.8.0.jar,./ikoda/extrajars/stanford-parser-3.8.0.jar \
  --packages datastax:spark-cassandra-connector:2.0.1-s_2.11 \
  --class ikoda.mlserver.Application \
  --conf spark.cassandra.connection.host=192.168.0.33 \
  --conf spark.cores.max=4 \
  --driver-memory 4g –num-executors 2 --executor-memory 2g --executor-cores 2 \
  --master spark://192.168.0.141:7077 ./ikoda/ikodaanalysis-mlserver-0.1.0.jar 1000 > ./logs/nohup.out &
</code>```

I suspect I am conflating the sparkConf initialization in my code with the spark-submit. I need this as the app involves SparkStreaming which can require reinitializing the SparkContext.

The sparkConf setup is as follows:

```<code>val conf = new SparkConf().setMaster(s"spark://$sparkmaster:7077").setAppName("MLPCURLModelGenerationDataStream")

conf.set("spark.streaming.stopGracefullyOnShutdown", "true")
conf.set("spark.cassandra.connection.host", sparkcassandraconnectionhost)
conf.set("spark.driver.maxResultSize", sparkdrivermaxResultSize)
conf.set("spark.network.timeout", sparknetworktimeout)
conf.set("spark.jars.packages", "datastax:spark-cassandra-connector:"+datastaxpackageversion)
 conf.set("spark.cores.max", sparkcoresmax)
</code>```

The Spark UI shows the following:

答:
It is because of the maximum of your physical memory.

your spark memory in spark UI 14.6GB So you must request memory for each executor below the volume
14.6GB, for this you can add config to your spark conf something like this:

```<code>conf.set("spark.executor.memory", "10gb")
</code>```

if you request more than your physical memory spark does't allocate cpu cores to your job and display 0 in Cores in spark UI and run NOTHING.

Body:
I seem to be unable to assign cores to an application. This leads to the following (apparently common) error message:

Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources

I have one master and two slaves in a Spark cluster. All are 8-core i7s with 16GB of RAM.

I have left the spark-env.sh virtually virgin on all three, just specifying the master's IP address.

My spark-submit is the following:

nohup ./bin/spark-submit
  --jars ./ikoda/extrajars/ikoda_assembled_ml_nlp.jar,./ikoda/extrajars/stanford-corenlp-3.8.0.jar,./ikoda/extrajars/stanford-parser-3.8.0.jar \
  --packages datastax:spark-cassandra-connector:2.0.1-s_2.11 \
  --class ikoda.mlserver.Application \
  --conf spark.cassandra.connection.host=192.168.0.33 \
  --conf spark.cores.max=4 \
  --driver-memory 4g –num-executors 2 --executor-memory 2g --executor-cores 2 \
  --master spark://192.168.0.141:7077 ./ikoda/ikodaanalysis-mlserver-0.1.0.jar 1000 > ./logs/nohup.out &

I suspect I am conflating the sparkConf initialization in my code with the spark-submit. I need this as the app involves SparkStreaming which can require reinitializing the SparkContext.

The sparkConf setup is as follows:

val conf = new SparkConf().setMaster(s"spark://$sparkmaster:7077").setAppName("MLPCURLModelGenerationDataStream")

conf.set("spark.streaming.stopGracefullyOnShutdown", "true")
conf.set("spark.cassandra.connection.host", sparkcassandraconnectionhost)
conf.set("spark.driver.maxResultSize", sparkdrivermaxResultSize)
conf.set("spark.network.timeout", sparknetworktimeout)
conf.set("spark.jars.packages", "datastax:spark-cassandra-connector:"+datastaxpackageversion)
 conf.set("spark.cores.max", sparkcoresmax)

The Spark UI shows the following:

Body:
It is because of the maximum of your physical memory.

your spark memory in spark UI 14.6GB So you must request memory for each executor below the volume
14.6GB, for this you can add config to your spark conf something like this:

conf.set("spark.executor.memory", "10gb")

if you request more than your physical memory spark does't allocate cpu cores to your job and display 0 in Cores in spark UI and run NOTHING.


来源: stackexchange

问:
Building array for chart with for loop and multiple orWhen
I'm building an array to show ratings in a chart for each day of the current week, using this loop

```<code>$ratings = collect([]);
$startOfWeek = Carbon::now()->startOfWeek();
for ($days_forwards = 0; $days_forwards <= 6; $days_forwards++) {
            $ratings->push(Rating::whereIn('song_id', $userSongs)
                    ->orWhere(function ($query) use ($userAlbums) {
                        $query->whereIn('album_id', $userAlbums);
                    })
                    ->orWhere(function ($query) use ($userArtists) {
                        $query->whereIn('artist_id', $userArtists);
                    })
                    ->whereDate('created_at', $startOfWeek->addDays($days_forwards))
                    ->count());
            $startOfWeek = Carbon::now()->startOfWeek();
        }
</code>```

This works fine with just the first whereIn, but when I add the other two orWhere filters, the chart flattens out to 2 results for every day. I can't work out why this is happening?

答:
So I figured this out in the end, nesting the orWhere() queries inside the first where(), like this;</p>

```<code>for ($days_forwards = 0; $days_forwards <= 6; $days_forwards++) {
            $ratings->push(Rating::where(function ($query) use ($userSongs, $userAlbums, $userArtists) {
                        $query->whereIn('song_id', $userSongs)
                        ->orWhere(function ($query) use ($userAlbums) {
                            $query->whereIn('album_id', $userAlbums);
                        })
                        ->orWhere(function ($query) use ($userArtists) {
                            $query->whereIn('artist_id', $userArtists);
                        });
                    })
                    ->whereDate('created_at', $startOfWeek->addDays($days_forwards))
                    ->count());
            $startOfWeek = Carbon::now()->startOfWeek();
        }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm building an array to show ratings in a chart for each day of the current week, using this loop

$ratings = collect([]);
$startOfWeek = Carbon::now()->startOfWeek();
for ($days_forwards = 0; $days_forwards <= 6; $days_forwards++) {
            $ratings->push(Rating::whereIn('song_id', $userSongs)
                    ->orWhere(function ($query) use ($userAlbums) {
                        $query->whereIn('album_id', $userAlbums);
                    })
                    ->orWhere(function ($query) use ($userArtists) {
                        $query->whereIn('artist_id', $userArtists);
                    })
                    ->whereDate('created_at', $startOfWeek->addDays($days_forwards))
                    ->count());
            $startOfWeek = Carbon::now()->startOfWeek();
        }

This works fine with just the first whereIn, but when I add the other two orWhere filters, the chart flattens out to 2 results for every day. I can't work out why this is happening?

Body:
So I figured this out in the end, nesting the orWhere() queries inside the first where(), like this;

for ($days_forwards = 0; $days_forwards <= 6; $days_forwards++) {
            $ratings->push(Rating::where(function ($query) use ($userSongs, $userAlbums, $userArtists) {
                        $query->whereIn('song_id', $userSongs)
                        ->orWhere(function ($query) use ($userAlbums) {
                            $query->whereIn('album_id', $userAlbums);
                        })
                        ->orWhere(function ($query) use ($userArtists) {
                            $query->whereIn('artist_id', $userArtists);
                        });
                    })
                    ->whereDate('created_at', $startOfWeek->addDays($days_forwards))
                    ->count());
            $startOfWeek = Carbon::now()->startOfWeek();
        }


问:
QueryDsl does not generate q-classes for @Entity classes of git submodules
I have a java project (spring boot) with git submodules. I've added QueryDsl to my project but it generates q-classes only for @Entity classes of main project, not for @Entity classes of submodules.

What should I do to fix it?

p.s. Spring Data works well, all @Entity classes are available to use.

答:
Add a package-info.java file to your own project, that references the classes from the child project in @QueryEntities:

@QueryEntities({
        BlobEntity.class
})
package com.pallasathenagroup.querydsl;

import com.blazebit.persistence.testsuite.entity.BlobEntity;
import com.querydsl.core.annotations.QueryEntities;
```


问:
TypeScript better way to define big models
So I am working on an application which has some large models used sometimes, an example is seen below:

```<code>import CapcodeModel from "./CapcodeModel";

export default class MeldingModel {
  hash: string;
  id: number;
  tijd: string;
  melding: string;
  adres: {
    straat: string;
    plaats: string;
    postcode: string;
    longitude: string;
    latitude: string;
  };
  discipline: string;
  disciplineId: number;
  disciplineVolledig: string;
  regioNaam: string;
  regioStream: string;
  cruciaal: boolean;
  proRail: boolean;
  capcodes: CapcodeModel[];

  constructor(
    {
      hash,
      id,
      tijd,
      melding,
      adres,
      discipline,
      disciplineId,
      disciplineVolledig,
      regioNaam,
      regioStream,
      cruciaal,
      proRail,
      capcodes
    }: MeldingModel = {
      hash: "",
      id: 0,
      tijd: "",
      melding: "",
      adres: {
        straat: "",
        plaats: "",
        postcode: "",
        longitude: "",
        latitude: ""
      },
      discipline: "",
      disciplineId: 0,
      disciplineVolledig: "",
      regioNaam: "",
      regioStream: "",
      cruciaal: false,
      proRail: false,
      capcodes: []
    }
  ) {
    this.hash = hash;
    this.id = id;
    this.tijd = tijd;
    this.melding = melding;
    this.adres = adres;
    this.discipline = discipline;
    this.disciplineId = disciplineId;
    this.disciplineVolledig = disciplineVolledig;
    this.regioNaam = regioNaam;
    this.regioStream = regioStream;
    this.cruciaal = cruciaal;
    this.proRail = proRail;
    this.capcodes = capcodes;
  }
}
</code>```

It has default values just so I can assign it as:

```<code>const _melding = new MeldingModel();
</code>```

aswell as

```<code>const _melding = new MeldingModel({ /* all props assigned here */ });
</code>```

Now, this big model looks absolutely hideous and hard to maintain in my opinion, is there a way to clean this up, while still being able to use it's default values?

答:
You can break it further to have the properties of address and disciple defined as interfaces respectively

```<code>  hash = "";
  id = 0;
  tijd = "";
  melding = "";
  adres: Address
  discipline: Discipline;
  regioNaam = "";
  regioStream = "";
  cruciaal = false;
  proRail = false;
  capcodes: CapcodeModel[] = [];
}
</code>```

Have your object initiated this way. It automatically gets all the properties in the class. You can also define your default values if you want

```<code>const _melding = new MeldingModel();
</code>```

Body:
So I am working on an application which has some large models used sometimes, an example is seen below:

import CapcodeModel from "./CapcodeModel";

export default class MeldingModel {
  hash: string;
  id: number;
  tijd: string;
  melding: string;
  adres: {
    straat: string;
    plaats: string;
    postcode: string;
    longitude: string;
    latitude: string;
  };
  discipline: string;
  disciplineId: number;
  disciplineVolledig: string;
  regioNaam: string;
  regioStream: string;
  cruciaal: boolean;
  proRail: boolean;
  capcodes: CapcodeModel[];

  constructor(
    {
      hash,
      id,
      tijd,
      melding,
      adres,
      discipline,
      disciplineId,
      disciplineVolledig,
      regioNaam,
      regioStream,
      cruciaal,
      proRail,
      capcodes
    }: MeldingModel = {
      hash: "",
      id: 0,
      tijd: "",
      melding: "",
      adres: {
        straat: "",
        plaats: "",
        postcode: "",
        longitude: "",
        latitude: ""
      },
      discipline: "",
      disciplineId: 0,
      disciplineVolledig: "",
      regioNaam: "",
      regioStream: "",
      cruciaal: false,
      proRail: false,
      capcodes: []
    }
  ) {
    this.hash = hash;
    this.id = id;
    this.tijd = tijd;
    this.melding = melding;
    this.adres = adres;
    this.discipline = discipline;
    this.disciplineId = disciplineId;
    this.disciplineVolledig = disciplineVolledig;
    this.regioNaam = regioNaam;
    this.regioStream = regioStream;
    this.cruciaal = cruciaal;
    this.proRail = proRail;
    this.capcodes = capcodes;
  }
}

It has default values just so I can assign it as:

const _melding = new MeldingModel();

aswell as

const _melding = new MeldingModel({ /* all props assigned here */ });

Now, this big model looks absolutely hideous and hard to maintain in my opinion, is there a way to clean this up, while still being able to use it's default values?

Body:
You can break it further to have the properties of address and disciple defined as interfaces respectively

  hash = "";
  id = 0;
  tijd = "";
  melding = "";
  adres: Address
  discipline: Discipline;
  regioNaam = "";
  regioStream = "";
  cruciaal = false;
  proRail = false;
  capcodes: CapcodeModel[] = [];
}

Have your object initiated this way. It automatically gets all the properties in the class. You can also define your default values if you want

const _melding = new MeldingModel();


问:
Append fields to PSQL jsonb array
I have a table called test_table that has the following structure:

```<code>id                       | 1
lookup                   | 166
arguments                | {"title": "Title", "name": "XYZ", "address": "1 main street"}
</code>```

I have a lot of entries into this table that follow a similar structure (I have simplified it for the purposes of this question.

I want to update certain rows (based on a list of IDs) so that there is an extra field within the arguments column that will result in this:

```<code>id                       | 1
lookup                   | 166
arguments                | {"title": "Title", "name": "XYZ", "address": "1 main street", "county": "County Name", "code": "4XC"}
</code>```

I have tried the following but cannot get it to work:

```<code>UPDATE test_table
SET arguments = arguments || '"county": "County Name", "code": "4XC"'::jsonb
WHERE id in (1,2,etc.);
</code>```

Can anyone advise as to what I am doing wrong?

This is the error I receive:

```<code>Expected end of input, but found ":"
</code>```

答:
That isn't valid JSON, you need {} around it.

```<code>UPDATE test_table
SET arguments = arguments || '{ "county": "County Name", "code": "4XC" }'::jsonb
WHERE id in (1,2,etc.);
</code>```

To avoid formatting problems, and to make using bind parameters easier, use jsonb_build_object.

```<code>UPDATE test_table
SET arguments = arguments || jsonb_build_object('county': ?, 'code': ?) )
WHERE id in (1,2,etc.);
</code>```

Title: Append fields to PSQL jsonb array

Body:
I have a table called test_table that has the following structure:

id                       | 1
lookup                   | 166
arguments                | {"title": "Title", "name": "XYZ", "address": "1 main street"}

I have a lot of entries into this table that follow a similar structure (I have simplified it for the purposes of this question.

I want to update certain rows (based on a list of IDs) so that there is an extra field within the arguments column that will result in this:

id                       | 1
lookup                   | 166
arguments                | {"title": "Title", "name": "XYZ", "address": "1 main street", "county": "County Name", "code": "4XC"}

I have tried the following but cannot get it to work:

UPDATE test_table
SET arguments = arguments || '"county": "County Name", "code": "4XC"'::jsonb
WHERE id in (1,2,etc.);

Can anyone advise as to what I am doing wrong?

This is the error I receive:

Expected end of input, but found ":"

Body:
That isn't valid JSON, you need {} around it.

UPDATE test_table
SET arguments = arguments || '{ "county": "County Name", "code": "4XC" }'::jsonb
WHERE id in (1,2,etc.);

To avoid formatting problems, and to make using bind parameters easier, use jsonb_build_object.

UPDATE test_table
SET arguments = arguments || jsonb_build_object('county': ?, 'code': ?) )
WHERE id in (1,2,etc.);


问:
Unknown module(s) in QT: charts - Error while building QGroundControl for Android
I am trying to build the QGroundControl for Android with the QT, but I am getting the below error:
error: Unknown module(s) in QT: charts

I can build the QGroundControl for Windows without any trouble.

I am using Windows 8.1 x64.

Error Message:

答:
you have to add

```<code>QT += charts
</code>```

in your .pro file.

If you want to use charts just in android use

```<code>android: QT += charts
</code>```

Body:
you have to add

QT += charts

in your .pro file.

If you want to use charts just in android use

android: QT += charts


问:
Why was my scroll bar enabled on my HTML site?
I am new in this field and now I am trying to improve myself by testing. I kept trying to figure out why I scroll bar vertically and horizontally, from what I noticed I think it's because of the tables. How can I solve this?
I know I didn't organize it very well, but I really want to solve that scroll bar, I also tried to hide it from the body, but if someone has a lower resolution, the total site will not be displayed. What do you think I could do to them?

body
{
 margin: 0;
 padding: 0;
 min-height: 100vh;
 background: #b3ccff;
 font-family: arcon;
  display: inline-block;
}
/* ------ [profesoreconomist.ro] ------ */
.link{
  left: 100px;
  top: 50px;
  position: absolute;
}
/* ------ [Imagine Banner] ------ */
.banner{
position: relative;
top: 0;
margin-top: 4.3%;
right: -80px;
max-width: 1750px;
}
/* ------ [Continut butoane] ------ */
.spoiler {
  display: none;
  bottom: 50%;
}
.show {
  display: none;
}
.hide:target + .show {
  display: inline;
}
.hide:target {
  display: none;
}
.hide:target ~ .spoiler {
  display: inline;
}
/* ------ [Buton Pagina Principala] ------ */
.btn {
  padding: 10px 30px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post1 {
  position: relative;
  padding: 20px;
  right: -58px;
}
/* ------ [Buton Curriculum] ------ */
.btn2 {
  position: relative;
  right: 0;
  top: 29%;
  padding: 10px 50px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post2 {
  position: relative;
  top: -42px;
  left: 270px;
}
/* ------ [Buton Standarde de pregatire...] ------ */
.btn3 {
  padding: 10px 12px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post3 {
  position: relative;
  padding: 20px;
  right: -435px;
  top: -84px;
}
/* ------ [Buton Prolectare didactica] ------ */
.btn4 {
  padding: 10px 30px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post4 {
  position: relative;
  padding: 20px;
  right: -723px;
  top: -146px;
}
/* ------ [Buton Evaluare] ------ */
.btn5 {
  padding: 10px 27px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post5 {
  position: relative;
  right: -963px;
  top: -188px;
}
/* ------ [Buton Resurse internationale] ------ */
.btn6 {
  padding: 10px 12px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post6 {
  position: relative;
  right: -1085px;
  top: -210px;
}
/* ------ [Buton Proiecte scolare] ------ */
.btn7 {
  padding: 10px 8px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post7 {
  position: relative;
  right: -1273px;
  top: -232px;
}
/* ------ [Buton Concursuri si olimpiade scolare] ------ */
.btn8 {
  padding: 10px 14px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post8 {
  position: relative;
  right: -1410px;
  top: -254px;
}
.spoiler-content {
 position: fixed;
 bottom: 40%;
 right: 45%;
}
/* ------ [Meniu Pagina autentificare] ------ */
input[type=text], input[type=password] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}
@-webkit-keyframes animatezoom {
  from {-webkit-transform: scale(0)}
  to {-webkit-transform: scale(1)}
}

@keyframes animatezoom {
  from {transform: scale(0)}
  to {transform: scale(1)}
}
@media screen and (max-width: 300px) {
  span.psw {
    display: block;
    float: none;
  }
  /* ------ [Pozitie buton cancel din meniul de autentificare] ------ */
  .cancelbtn {
    position: fixed;
    width: 100%;
    bottom: 100%;
  }
}
/* ------ [Buton Autentificare] ------ */
.login {
  padding: 13px 43px;
  margin-bottom: 0;
  *margin-left: .3em;
  cursor: pointer;
  background-color: #4d94ff;
  border: none;
   width: 200px;
 }
 /* ------ [Pozitie buton autentificare] ------ */
 .plogin {
  position: relative;
  top: -284px;
  right: -1669px;
 }
 /* ------ [Buton Login din meniul de autentificare] ------ */
 .login2 {
    padding: 12.5px 43px;
  margin-bottom: 0;
  *margin-left: .3em;
  cursor: pointer;
  background-color: #4d94ff;
  border: none;
   width: 100%;
 }
button:hover {
  opacity: 0.8;
}

/* ------ [Buton cancel din meniul de autentificare] ------ */
.cancelbtn {
 left: 0%;
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
  border: none;
}
/* ------ [Pozitie imagine din meniul de autentificare] ------ */
.imgcontainer {
  text-align: center;
  margin: 24px 0 12px 0;
  position: relative;
}

img.avatar {
  width: 20%;
  border-radius: 50%;
}

.container {
  padding: 16px;
}

span.psw {
  float: right;
  padding-top: 16px;
}

/* ------ [Background meniu de autentificare] ------ */
.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
  padding-top: 60px;
}

/* ------ [Continut meniu login] ------ */
.modal-content {
  background-color: #fefefe;
  margin: 5% auto 15% auto;
  border: 1px solid #888;
  width: 80%;
}

/* ------ [Buton X pentru inchidere meniu login] ------ */
.close {
  position: absolute;
  right: 25px;
  top: 0;
  color: #000;
  font-size: 35px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: red;
  cursor: pointer;
}

.animate {
  -webkit-animation: animatezoom 0.6s;
  animation: animatezoom 0.6s
}
/* ------ [Tabel Noutati] ------ */
.tabel-noutati {
  position: relative;
  left: 80px;
  top: -270px;
  border-collapse: collapse;
  width: 350px;
  background-color: #ffffff;
}
/* ------ [Background alb tabele] ------ */
td, th {
  border: 1px solid #dddddd;
  text-align: left;
  height: 550px;
  right: 10px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
/* ------ [Text noutati] ------ */
.news {
  position: absolute;
 top: -2.5%;
 left: 15px;
}
/* ------ [Text link-uri utile] ------ */
.links {
 position: absolute;
 top: -2.5%;
 left: 15px;
}
/* ------ [Tabel link-uri urile] ------ */
.tabel-links{
 position: relative;
  left: 1399px;
  bottom: 0;
  border-collapse: collapse;
  width: 350px;
  background-color: #ffffff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>xxxxxxx</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<div id="container">
<div id="header">

</div>
<body>
  <!------ Buton Pagina Principala ------>
<div class="forum-post1">
    Pagina principala
    Pagina principala
    <div class="spoiler">
      <p class="spoiler-content">Bine ai venit pe site-ul nostru!</p>
    </div>
</div>
  <!------ Buton Curriculum ------>
<div class="forum-post2">
    Curriculum
    Curriculum
    <div class="spoiler">
      <p class="spoiler-content">Continutul din Curriculum</p>
    </div>
</div>
  <!------ Buton Standarde de pregatire profesionala ------>
<div class="forum-post3">
    Standarde de pregatire profesionala
    Standarde de pregatire profesionala
    <div class="spoiler">
      <p class="spoiler-content">Standarde de pregatire profesionala</p>
    </div>
</div>
  <!------ Buton Prolectarea didactică ------>
<div class="forum-post4">
    Prolectarea didactică
    Prolectarea didactică
    <div class="spoiler">
      <p class="spoiler-content">Prolectarea didactică</p>
    </div>
</div>
  <!------ Buton Evaluare ------>
<div class="forum-post5">
    Evaluare
    Evaluare
    <div class="spoiler">
      <p class="spoiler-content">Continutul din Evaluare</p>
    </div>
</div>
  <!------ Buton Resurse internaționale ------>
<div class="forum-post6">
    Resurse internaționale
    Resurse internaționale
    <div class="spoiler">
      <p class="spoiler-content">Resurse internaționale</p>
    </div>
</div>
  <!------ Buton Proiecte școlare ------>
<div class="forum-post7">
    Proiecte școlare
    Proiecte școlare
    <div class="spoiler">
      <p class="spoiler-content">Continutul din Proiecte școlare</p>
    </div>
</div>
  <!------ Buton Concursuri si olimpiade scolare------>
<div class="forum-post8">
    Concursuri și olimpiade școlare
    Concursuri și olimpiade școlare
    <div class="spoiler">
      <p class="spoiler-content">Concursuri și olimpiade școlare</p>
    </div>
</div>
  <!------ Buton catre link-ul profesoreconomit.ro------>
profesoreconomist.ro
  <!------ Buton de Autentificare / Meniul de autentificare ------>
<div class="plogin">
<button class="login" onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Autentificare</button>
</div>
<div id="id01" class="modal">
  <form class="modal-content animate" action="#" method="post">
    <div class="imgcontainer">
      <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
      <img src="img\avatar.png" alt="Avatar" class="avatar">
    </div>
    <div class="container">
      <label for="uname"><b>Numele utilizatorului</b></label>
      <input type="text" placeholder="Introdu numele de utilizator" name="uname" required>

      <label for="psw"><b>Parola</b></label>
      <input type="password" placeholder="Introdu parola" name="psw" required>

      <button class="login2" type="submit">Login</button>
      <label>
        <input type="checkbox" checked="checked" name="remember"> Ține-mă minte
      </label>
    </div>

    <div class="container" style="background-color:#f1f1f1">
      <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
      <span class="psw">Ai uitat parola?</span>
    </div>
  </form>
</div>

<script>
var modal = document.getElementById('id01');
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>
  <!------ Tabelurile de noutati si link-uri utile ------>
<table class="tabel-noutati">
  <tr>
  <th>
  <h2 class="news">Noutăți</h2>

<table class="tabel-links">
  <tr>
  <th class="thh">
  <h2 class="links">Link-uri utile</h2>

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

答:
If you want to create a horizontal scroll bar, then wrap the contents in a div

        Home
        News
        Contact
        About
        ...

You can also customize it by using

div.scrollmenu {
        background-color: #ffff;
        overflow: auto;
        white-space: nowrap;
      }

```<code>div.scrollmenu a {
  display: inline-block;
  color: black;
  text-align: center;
  padding: 20px;
  text-decoration: none;
</code>```

}

```<code>div.scrollmenu a:hover {
  background-color: white;
}
</code>```

Body:
I am new in this field and now I am trying to improve myself by testing. I kept trying to figure out why I scroll bar vertically and horizontally, from what I noticed I think it's because of the tables. How can I solve this?
I know I didn't organize it very well, but I really want to solve that scroll bar, I also tried to hide it from the body, but if someone has a lower resolution, the total site will not be displayed. What do you think I could do to them?

body
{
 margin: 0;
 padding: 0;
 min-height: 100vh;
 background: #b3ccff;
 font-family: arcon;
  display: inline-block;
}
/* ------ [profesoreconomist.ro] ------ */
.link{
  left: 100px;
  top: 50px;
  position: absolute;
}
/* ------ [Imagine Banner] ------ */
.banner{
position: relative;
top: 0;
margin-top: 4.3%;
right: -80px;
max-width: 1750px;
}
/* ------ [Continut butoane] ------ */
.spoiler {
  display: none;
  bottom: 50%;
}
.show {
  display: none;
}
.hide:target + .show {
  display: inline;
}
.hide:target {
  display: none;
}
.hide:target ~ .spoiler {
  display: inline;
}
/* ------ [Buton Pagina Principala] ------ */
.btn {
  padding: 10px 30px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post1 {
  position: relative;
  padding: 20px;
  right: -58px;
}
/* ------ [Buton Curriculum] ------ */
.btn2 {
  position: relative;
  right: 0;
  top: 29%;
  padding: 10px 50px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post2 {
  position: relative;
  top: -42px;
  left: 270px;
}
/* ------ [Buton Standarde de pregatire...] ------ */
.btn3 {
  padding: 10px 12px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post3 {
  position: relative;
  padding: 20px;
  right: -435px;
  top: -84px;
}
/* ------ [Buton Prolectare didactica] ------ */
.btn4 {
  padding: 10px 30px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post4 {
  position: relative;
  padding: 20px;
  right: -723px;
  top: -146px;
}
/* ------ [Buton Evaluare] ------ */
.btn5 {
  padding: 10px 27px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post5 {
  position: relative;
  right: -963px;
  top: -188px;
}
/* ------ [Buton Resurse internationale] ------ */
.btn6 {
  padding: 10px 12px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post6 {
  position: relative;
  right: -1085px;
  top: -210px;
}
/* ------ [Buton Proiecte scolare] ------ */
.btn7 {
  padding: 10px 8px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post7 {
  position: relative;
  right: -1273px;
  top: -232px;
}
/* ------ [Buton Concursuri si olimpiade scolare] ------ */
.btn8 {
  padding: 10px 14px;
  margin-bottom: 0;
  *margin-left: .3em;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  vertical-align: middle;
  cursor: pointer;
  background-color: #f5f5f5;
  *background-color: #e6e6e6;
  border: 1px solid #bbbbbb;
  *border: 0;
  border-color: #e6e6e6 #e6e6e6 #bfbfbf;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  border-bottom-color: #a2a2a2;
  text-decoration: none;
}
.forum-post8 {
  position: relative;
  right: -1410px;
  top: -254px;
}
.spoiler-content {
 position: fixed;
 bottom: 40%;
 right: 45%;
}
/* ------ [Meniu Pagina autentificare] ------ */
input[type=text], input[type=password] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}
@-webkit-keyframes animatezoom {
  from {-webkit-transform: scale(0)}
  to {-webkit-transform: scale(1)}
}

@keyframes animatezoom {
  from {transform: scale(0)}
  to {transform: scale(1)}
}
@media screen and (max-width: 300px) {
  span.psw {
    display: block;
    float: none;
  }
  /* ------ [Pozitie buton cancel din meniul de autentificare] ------ */
  .cancelbtn {
    position: fixed;
    width: 100%;
    bottom: 100%;
  }
}
/* ------ [Buton Autentificare] ------ */
.login {
  padding: 13px 43px;
  margin-bottom: 0;
  *margin-left: .3em;
  cursor: pointer;
  background-color: #4d94ff;
  border: none;
   width: 200px;
 }
 /* ------ [Pozitie buton autentificare] ------ */
 .plogin {
  position: relative;
  top: -284px;
  right: -1669px;
 }
 /* ------ [Buton Login din meniul de autentificare] ------ */
 .login2 {
    padding: 12.5px 43px;
  margin-bottom: 0;
  *margin-left: .3em;
  cursor: pointer;
  background-color: #4d94ff;
  border: none;
   width: 100%;
 }
button:hover {
  opacity: 0.8;
}

/* ------ [Buton cancel din meniul de autentificare] ------ */
.cancelbtn {
 left: 0%;
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
  border: none;
}
/* ------ [Pozitie imagine din meniul de autentificare] ------ */
.imgcontainer {
  text-align: center;
  margin: 24px 0 12px 0;
  position: relative;
}

img.avatar {
  width: 20%;
  border-radius: 50%;
}

.container {
  padding: 16px;
}

span.psw {
  float: right;
  padding-top: 16px;
}

/* ------ [Background meniu de autentificare] ------ */
.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
  padding-top: 60px;
}

/* ------ [Continut meniu login] ------ */
.modal-content {
  background-color: #fefefe;
  margin: 5% auto 15% auto;
  border: 1px solid #888;
  width: 80%;
}

/* ------ [Buton X pentru inchidere meniu login] ------ */
.close {
  position: absolute;
  right: 25px;
  top: 0;
  color: #000;
  font-size: 35px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: red;
  cursor: pointer;
}

.animate {
  -webkit-animation: animatezoom 0.6s;
  animation: animatezoom 0.6s
}
/* ------ [Tabel Noutati] ------ */
.tabel-noutati {
  position: relative;
  left: 80px;
  top: -270px;
  border-collapse: collapse;
  width: 350px;
  background-color: #ffffff;
}
/* ------ [Background alb tabele] ------ */
td, th {
  border: 1px solid #dddddd;
  text-align: left;
  height: 550px;
  right: 10px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
/* ------ [Text noutati] ------ */
.news {
  position: absolute;
 top: -2.5%;
 left: 15px;
}
/* ------ [Text link-uri utile] ------ */
.links {
 position: absolute;
 top: -2.5%;
 left: 15px;
}
/* ------ [Tabel link-uri urile] ------ */
.tabel-links{
 position: relative;
  left: 1399px;
  bottom: 0;
  border-collapse: collapse;
  width: 350px;
  background-color: #ffffff;
}

<!DOCTYPE html>

<title>xxxxxxx</title>
  <link rel="stylesheet" type="text/css" href="style.css">

    Pagina principala
    Pagina principala

Bine ai venit pe site-ul nostru!

    Curriculum
    Curriculum

Continutul din Curriculum

    Standarde de pregatire profesionala
    Standarde de pregatire profesionala

Standarde de pregatire profesionala

    Prolectarea didactică
    Prolectarea didactică

Prolectarea didactică

    Evaluare
    Evaluare

Continutul din Evaluare

    Resurse internaționale
    Resurse internaționale

Resurse internaționale

    Proiecte școlare
    Proiecte școlare

Continutul din Proiecte școlare

    Concursuri și olimpiade școlare
    Concursuri și olimpiade școlare

Concursuri și olimpiade școlare

profesoreconomist.ro

<button class="login" onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Autentificare</button>

  <form class="modal-content animate" action="#" method="post">

      ×

      Numele utilizatorului
      <input type="text" placeholder="Introdu numele de utilizator" name="uname" required>

      Parola
      <input type="password" placeholder="Introdu parola" name="psw" required>

      <button class="login2" type="submit">Login</button>

        <input type="checkbox" checked="checked" name="remember"> Ține-mă minte

      <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
      Ai uitat parola?

  </form>

Noutăți

Link-uri utile

Body:
If you want to create a horizontal scroll bar, then wrap the contents in a div

        Home
        News
        Contact
        About
        ...

You can also customize it by using

div.scrollmenu {
        background-color: #ffff;
        overflow: auto;
        white-space: nowrap;
      }

div.scrollmenu a {
  display: inline-block;
  color: black;
  text-align: center;
  padding: 20px;
  text-decoration: none;

}

div.scrollmenu a:hover {
  background-color: white;
}


问:
How can I install pip when there is already python but pip is missed?
I'm using a remote server, which some others use together.

There are several versions of python installed.

I need python 3.6 version, and I can run it with  /bin/python3.6 command.

And I also want to make a virtualenv of the version, so I tried /bin/python3.6 -m pip --version

But it showed

/bin/python3.6: No module named pip
```

<p>When I checked the lib directory, <code>ll /usr/lib/python3.6/site-packages/</code></p>

<pre class="lang-none prettyprint-override"><code>total 0 drwxr-xr-x 2 root root 6 Dec 20  2017 __pycache__
</code>```

It seems that the server has python3.6, but misses pip for that, right?

How can I resolve this, with the minimum modification?

The server is centos7.

Any thought or comment appreciated :)

答:
In case you don't want to modify the system Python you can just use the zipapp version of virtualenv to create a virtual environment at some arbitrary location with latest pip included (see https://virtualenv.pypa.io/en/latest/installation.html#via-zipapp).

wget https://bootstrap.pypa.io/virtualenv/virtualenv.pyz
python3.6 /full/path/to/downloaded/virtualenv.pyz ~/virtualenv

~/virtualenv/bin/python -m pip list
```

That's probably the minimum harmful modification, and ensure that messing with the system python does not break your system python applications/environment.

Body:
I'm using a remote server, which some others use together.

There are several versions of python installed.

I need python 3.6 version, and I can run it with  /bin/python3.6 command.

And I also want to make a virtualenv of the version, so I tried /bin/python3.6 -m pip --version

But it showed

/bin/python3.6: No module named pip

When I checked the lib directory, ll /usr/lib/python3.6/site-packages/

total 0 drwxr-xr-x 2 root root 6 Dec 20  2017 __pycache__

It seems that the server has python3.6, but misses pip for that, right?

How can I resolve this, with the minimum modification?

The server is centos7.

Any thought or comment appreciated :)

Body:
In case you don't want to modify the system Python you can just use the zipapp version of virtualenv to create a virtual environment at some arbitrary location with latest pip included (see https://virtualenv.pypa.io/en/latest/installation.html#via-zipapp).

wget https://bootstrap.pypa.io/virtualenv/virtualenv.pyz
python3.6 /full/path/to/downloaded/virtualenv.pyz ~/virtualenv

~/virtualenv/bin/python -m pip list

That's probably the minimum harmful modification, and ensure that messing with the system python does not break your system python applications/environment.


问:
Problem solving - Coding Interview Question?
So I came along this mock interview question, I have to find a solution to this problem without using functions repelem or repmat.
Only 3 lines of code are allowed with the format: (only one  = operator per line)

p=... , q1=.... , q2=....,

So far I only got a solution using repelem, but when I try to change my code I always have to use more lines of code when indexing. Very thankful for any hints you got for me :)

```<code>p=[4 2 5 3 1]

q1 = repelem((1:length(p)),p)
q2 = repelem(p,p)
</code>```

Here is the question, if anyone wants to try by himself (designed for MATLAB, but can be done anywhere)

Let p be a vector with k different positive integer elements and s=sum(p). Two vectors q1 and q2 shall be determined such that:

• q1 is a vector of length s. The first p(1) elements of q1 are equal to 1, the next p(2) elements are equal to 2, . . . , the last p(k) elements are equal to k.

• q2 is a vector of length s. The first p(1) elements of q2 are equal to p(1), the next p(2) elements are equal to p(2), . . . , the last p(k) elements are equal to p(k).

答:
Here's a solution in Matlab.

Hints:

Use implicit expansion (or bsxfun) and nonzeros to build q1.

q2 is easily obtained from p and q1.

Code (give it a try yourself first!):

p = [4 2 5 3 1]; % example input

q1 = nonzeros(((1:max(p)).'<=p).*(1:numel(p))).';

q2 = p(q1);

Body:
So I came along this mock interview question, I have to find a solution to this problem without using functions repelem or repmat.
Only 3 lines of code are allowed with the format: (only one  = operator per line)

p=... , q1=.... , q2=....,

So far I only got a solution using repelem, but when I try to change my code I always have to use more lines of code when indexing. Very thankful for any hints you got for me :)

p=[4 2 5 3 1]

q1 = repelem((1:length(p)),p)
q2 = repelem(p,p)

Here is the question, if anyone wants to try by himself (designed for MATLAB, but can be done anywhere)

Let p be a vector with k different positive integer elements and s=sum(p). Two vectors q1 and q2 shall be determined such that:

• q1 is a vector of length s. The first p(1) elements of q1 are equal to 1, the next p(2) elements are equal to 2, . . . , the last p(k) elements are equal to k.

• q2 is a vector of length s. The first p(1) elements of q2 are equal to p(1), the next p(2) elements are equal to p(2), . . . , the last p(k) elements are equal to p(k).


问:
ie "webpage has expired" on back button PHP session problem
On IE when user hits back button they get the classic IE "webpage has expired" message.

I have found that setting the following in my php.ini has solved this.

```<code>'session.cache_limiter=private'
</code>```

However my problem now is when I send forms I include a PHP session value ($_SESSION['token']) in a hidden field. I then check this on the following page to see if token values match

```<code>echo "<form ......<input type='hidden' name='token' value='".$_SESSION['token']."' />";

/*on recieving page*/
if($_POST['token']==$_SESSION['token']){/*ok matched*/}
else{/*THIS IS WHERE THE ERROR OCCURS*/}
</code>```

My problem is since adding this setting to my php.ini file I noticed when sending forms I get my custom page error as for some reason the $_SESSION['token'] value appears to change on the page receiving the form data thus making the if() statement return false? It's happening in all browsers now?

Here is my $_SESSION['token'] code (NOTE when sending my form it lands in the else() but value changes of $_SESSION['token'] something to do with cache perhaps not retaining my $_SESSION values?

```<code>session_start()
if(!isset($_SESSION['token']))
{
            $token = md5(uniqid(rand(), TRUE));
            $_SESSION['token'] = $token; /*have to put current session token into this variable for hidden field in <form>*/
            $_SESSION['token_time'] = time();
}
else
{
            /*if token set ie user press back button on browser*/
            $token_age = time() - $_SESSION['token_time'];
            if ($token_age > 1200)
            {
                        /* More than 20 minutes has passed - regenerate. Do this so more likely wont timeout when user taking long time on <form> and token may not get refreshed before time limit*/
                        $token = md5(uniqid(rand(), TRUE));
                        $_SESSION['token'] = $token; /*have to put current session token into this variable for hidden field in <form>*/
                        $_SESSION['token_time'] = time();
            }

}
</code>```

If any use heres my other php.ini session settings

```<code>session.cache_limiter=private
session.cookie_secure=1 ;my wholes site is SSL
session.cookie_httponly=1
session.save_path = /tmp ;directory to store sessions
session.save_handler = files
session.cookie_lifetime = 0 ;persistence cookie dies after browser closed
session.use_trans_sid = 0
session.use_only_cookies=1
</code>```

Let me just clear something up guys, the reason this whole problem occurs is using the 'session.cache_limiter=private'. If I take this out theres no problem except I get a message in IE when hitting back button on a form page saying "Webpage expired". Is there any suggestions how to avoid that message occuring in IE when hitting the back button?

答:
Is that in HTML code?

```<code><input type='hidden' name='token' value='".$_SESSION['token']."' />
</code>```

If yes, try:

```<code><input type='hidden' name='token' value='<?PHP echo $_SESSION['token']; ?>' />
</code>```

:)

I never was too happy with the PHP built-in session functionality. Too many problems for me...

Are you initializing session handling with session_start()?

Are you sure that sessions are using cookies - not any Query-String / POST fields? (Check the generated HTML code in the browser).

ContentLicense: CC BY-SA 3.0

Body:
On IE when user hits back button they get the classic IE "webpage has expired" message.

I have found that setting the following in my php.ini has solved this.

'session.cache_limiter=private'

However my problem now is when I send forms I include a PHP session value ($_SESSION['token']) in a hidden field. I then check this on the following page to see if token values match

echo "<form ......<input type='hidden' name='token' value='".$_SESSION['token']."' />";

/*on recieving page*/
if($_POST['token']==$_SESSION['token']){/*ok matched*/}
else{/*THIS IS WHERE THE ERROR OCCURS*/}

My problem is since adding this setting to my php.ini file I noticed when sending forms I get my custom page error as for some reason the $_SESSION['token'] value appears to change on the page receiving the form data thus making the if() statement return false? It's happening in all browsers now?

Here is my $_SESSION['token'] code (NOTE when sending my form it lands in the else() but value changes of $_SESSION['token'] something to do with cache perhaps not retaining my $_SESSION values?

session_start()
if(!isset($_SESSION['token']))
{
            $token = md5(uniqid(rand(), TRUE));
            $_SESSION['token'] = $token; /*have to put current session token into this variable for hidden field in <form>*/
            $_SESSION['token_time'] = time();
}
else
{
            /*if token set ie user press back button on browser*/
            $token_age = time() - $_SESSION['token_time'];
            if ($token_age > 1200)
            {
                        /* More than 20 minutes has passed - regenerate. Do this so more likely wont timeout when user taking long time on <form> and token may not get refreshed before time limit*/
                        $token = md5(uniqid(rand(), TRUE));
                        $_SESSION['token'] = $token; /*have to put current session token into this variable for hidden field in <form>*/
                        $_SESSION['token_time'] = time();
            }

}

If any use heres my other php.ini session settings

session.cache_limiter=private
session.cookie_secure=1 ;my wholes site is SSL
session.cookie_httponly=1
session.save_path = /tmp ;directory to store sessions
session.save_handler = files
session.cookie_lifetime = 0 ;persistence cookie dies after browser closed
session.use_trans_sid = 0
session.use_only_cookies=1

Let me just clear something up guys, the reason this whole problem occurs is using the 'session.cache_limiter=private'. If I take this out theres no problem except I get a message in IE when hitting back button on a form page saying "Webpage expired". Is there any suggestions how to avoid that message occuring in IE when hitting the back button?

Body:
Is that in HTML code?

<input type='hidden' name='token' value='".$_SESSION['token']."' />

If yes, try:

<input type='hidden' name='token' value='<?PHP echo $_SESSION['token']; ?>' />

:)

I never was too happy with the PHP built-in session functionality. Too many problems for me...

Are you initializing session handling with session_start()?

Are you sure that sessions are using cookies - not any Query-String / POST fields? (Check the generated HTML code in the browser).


问:
Using a for loop to create a new list
I have a list of strings and would like to use a for loop to change the strings and create a new list.

```<code>oldList = ['AAA','BBB','CCC']

for i in range(len(oldList)):

    newList = []
    add1 = 'a_'
    add2 = '_z'

    newStr = add1 + oldList[i] + add2

    newList.append(newStr)
</code>```

The list 'newList' should contain all the strings on the old list plus the amendments (i.e. ['a_AAA_z', 'a_BBB_z', 'a_CCC_z']). However, it only contains the last string (i.e. ['a_CCC_z']).

What am I missig here? Many thanks in advance.

答:
You can use formatted strings and list comprehensions:

```<code>oldList = ['AAA','BBB','CCC']
newList = [f'a_{s}_z' for s in oldList]
print(newList)
</code>```

Output:

```<code>['a_AAA_z', 'a_BBB_z', 'a_CCC_z']
</code>```

Title: Using a for loop to create a new list

Body:
I have a list of strings and would like to use a for loop to change the strings and create a new list.

oldList = ['AAA','BBB','CCC']

for i in range(len(oldList)):

    newList = []
    add1 = 'a_'
    add2 = '_z'

    newStr = add1 + oldList[i] + add2

    newList.append(newStr)

The list 'newList' should contain all the strings on the old list plus the amendments (i.e. ['a_AAA_z', 'a_BBB_z', 'a_CCC_z']). However, it only contains the last string (i.e. ['a_CCC_z']).

What am I missig here? Many thanks in advance.

Body:
You can use formatted strings and list comprehensions:

oldList = ['AAA','BBB','CCC']
newList = [f'a_{s}_z' for s in oldList]
print(newList)

Output:

['a_AAA_z', 'a_BBB_z', 'a_CCC_z']


问:
Wordpress the_content is showing the custom post type, WHY? How can i remove it?
I'm having a problem with displaying the_content() of my custom post type. Apparently when I use the code in my single-project.php page, it outputs with a div showing the post title. Why does this happen  and how do I get rid of it?

```<code><?php if ( get_the_content() ) : ?>
<div class=" content post__text">
<?php the_content(); ?>
</div>
<?php
endif;?>
</code>```

output of above code:

```<code><p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed quis maximus urna. Vestibulum vel nisl fermentum, ultrices felis quis, euismod massa. Sed tristique enim ut mauris cursus, non placerat est luctus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. </p>

<div> Test Project Title</div>

</code>```

答:
By default the_content() will display tags. If you want to strip tags from the_content() you can use a function like so:

wp_strip_all_tags():

```<code>echo wp_strip_all_tags(the_content())
</code>```

if you wanted to strip certain HTML you could use something like:

```<code>function so_62136989( $content ) {
    return strip_tags( $content, '<p><div>' );
}
add_filter( 'the_content', 'so_62136989' );
</code>```

Body:
I'm having a problem with displaying the_content() of my custom post type. Apparently when I use the code in my single-project.php page, it outputs with a div showing the post title. Why does this happen  and how do I get rid of it?

<?php if ( get_the_content() ) : ?>

<?php the_content(); ?>

<?php
endif;?>

output of above code:

 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed quis maximus urna. Vestibulum vel nisl fermentum, ultrices felis quis, euismod massa. Sed tristique enim ut mauris cursus, non placerat est luctus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

 Test Project Title

Body:
By default the_content() will display tags. If you want to strip tags from the_content() you can use a function like so:

wp_strip_all_tags():

echo wp_strip_all_tags(the_content())

if you wanted to strip certain HTML you could use something like:

function so_62136989( $content ) {
    return strip_tags( $content, '<p><div>' );
}
add_filter( 'the_content', 'so_62136989' );


问:
Python checking if all item in nested list are the same
Simple question how would you find that all the elements in a nested list are equal to 0 or specific value
my code goes like this

```<code>a = [[0,0,0],[0,0,0]]
def checkall(a):
    zeros = 0
    for i in a:
        for b in i:
            if b==0:
                zeros+=1
            else:
                break
</code>```

is there any other better way to do this? without importing any libraries

答:
You can iterate through all sublists of a and check if the count of 0s is equal to the length of the sublist, meaning it contains only 0s, and then check if all of the resulting values are True:

```<code>a = [[0,0,0],[0,0,0]]
def checkall(a):
    return all(el.count(0) == len(el) for el in a)
</code>```

This results in

```<code>>>> checkall(a)
True
</code>```

Body:
Simple question how would you find that all the elements in a nested list are equal to 0 or specific value
my code goes like this

a = [[0,0,0],[0,0,0]]
def checkall(a):
    zeros = 0
    for i in a:
        for b in i:
            if b==0:
                zeros+=1
            else:
                break

is there any other better way to do this? without importing any libraries

Body:
You can iterate through all sublists of a and check if the count of 0s is equal to the length of the sublist, meaning it contains only 0s, and then check if all of the resulting values are True:

a = [[0,0,0],[0,0,0]]
def checkall(a):
    return all(el.count(0) == len(el) for el in a)

This results in

>>> checkall(a)
True


问:
Plotly zoomed marker area
I have multiple markers (expressed as latitude,longitude) on my map (I am using Scatter Geo), all of them with edge thourgh them.

I need to get a zoomed view for some marker and save that view to a .png file.

I could do this manually, zooming every intersted marker and taking the screenshot but I would like to do it via code.

How is it possible to create a loop for a markers list and take screenshot of the area around a specific marker?

A circle/area with marker in the center and a radius of 5km could be enough

答:
When using Scattergeo you can use center and projection_scale to home into an area.

projection_scale is similar to zoom level and not an obvious argument to use:

Zooms in or out on the map view. A scale of "1" corresponds to the
  largest zoom level that fits the map's lon and lat ranges.

Below is an example adapted from here.

import plotly.graph_objects as go

import pandas as pd

df = pd.read_csv('2011_february_us_airport_traffic.csv')
df['text'] = df['airport'] + '' + df['city'] + ', ' + df['state'] + '' + 'Arrivals: ' + df['cnt'].astype(str)

fig = go.Figure(data=go.Scattergeo(
        lon = df['long'], lat = df['lat'],
        text = df['text'],
        mode = 'markers',
        marker_color = df['cnt'],
        ))

fig.update_layout(
        title = 'Most trafficked US airports
(Hover for airport names)',
        geo = dict(
            scope='usa',
            projection_type='albers usa',
            showland = True
        ))

# focus point
lat_foc = 35.21401111
lon_foc = -80.94312583
fig.update_layout(
        geo = dict(
            projection_scale=10, #this is kind of like zoom
            center=dict(lat=lat_foc, lon=lon_foc), # this will center on the point
        ))

fig.show()
```

Title: Plotly zoomed marker area

Body:
When using Scattergeo you can use center and projection_scale to home into an area.

projection_scale is similar to zoom level and not an obvious argument to use:

Zooms in or out on the map view. A scale of "1" corresponds to the
  largest zoom level that fits the map's lon and lat ranges.

Below is an example adapted from here.

import plotly.graph_objects as go

import pandas as pd

df = pd.read_csv('2011_february_us_airport_traffic.csv')
df['text'] = df['airport'] + '' + df['city'] + ', ' + df['state'] + '' + 'Arrivals: ' + df['cnt'].astype(str)

fig = go.Figure(data=go.Scattergeo(
        lon = df['long'], lat = df['lat'],
        text = df['text'],
        mode = 'markers',
        marker_color = df['cnt'],
        ))

fig.update_layout(
        title = 'Most trafficked US airports<br>(Hover for airport names)',
        geo = dict(
            scope='usa',
            projection_type='albers usa',
            showland = True
        ))

# focus point
lat_foc = 35.21401111
lon_foc = -80.94312583
fig.update_layout(
        geo = dict(
            projection_scale=10, #this is kind of like zoom
            center=dict(lat=lat_foc, lon=lon_foc), # this will center on the point
        ))

fig.show()


问:
NodeJS Retriivng Record from DB 1 by 1 vs All
I have 2 Microservices

1 Auth Service : Store all the users Data

2 Club Service : Store userId Ref ( of a Auth Service User ) along with Service Specific Data

in the Club service i want to get all the users data but i only want the users subscribed to my Club Service (Not all users in Auth Service)
so i have 2 options
 2 functions in Club Service (Shared from Auth Service using RPC (MicroService))

1 - getUserById

2 - getAllUsers

should i make a for loop and supply the userId to getUserById Function to get all data related to Club Service only

or should i getAllUsers data from auth. Store them in an array and then loop through this array with the UserId to get the users data specific to my Club Service ?

Which is more Performant

It's all about which is more performant querying the data from DB one by one using getUserById method

or

getting all the Data from DB once. send them to Club Service. and on Club Service i loop through all the data to match the userId i have on Club Service and filter them?

答:
In microservice, this is one of the common tasks you will face. So, instead of doing a call to the user in the loop you just make use of aggregate match.

In user service, you just make a route as /read-many, here in the controller or repository you can write aggregate with a match query.

```<code>eg `aggregate[{$match: match}] // here match will be variable`
</code>```

So, from Club first, make all collect all the value into an array.eg
const users = ["id1", "id2"]
Now you just need to call to user service with userId variable this will return you all the Club subscribed result.
I hope it may help you solve your problem.

Body:
In microservice, this is one of the common tasks you will face. So, instead of doing a call to the user in the loop you just make use of aggregate match.

In user service, you just make a route as /read-many, here in the controller or repository you can write aggregate with a match query.

eg `aggregate[{$match: match}] // here match will be variable`

So, from Club first, make all collect all the value into an array.eg
const users = ["id1", "id2"]
Now you just need to call to user service with userId variable this will return you all the Club subscribed result.
I hope it may help you solve your problem.


问:
How to improve the behavior of ConnectionRequest?
I wrote this code:

```<code>public static Slider downloadStorageFile(String url, OnComplete<Integer> percentageCallback, OnComplete<String> filesavedCallback) {

        final String filename = getNewStorageFilename();

        ConnectionRequest cr = Rest.get(url).fetchAsBytes(response -> CN.callSerially(() -> filesavedCallback.completed(filename)));
        cr.setDestinationStorage(filename);

        Slider slider = new Slider();
        slider.addDataChangedListener((int type, int index) -> {
            CN.callSerially(() -> percentageCallback.completed(slider.getProgress()));
        });
        sliderBridgeMap.put(cr, slider);
        SliderBridge.bindProgress(cr, slider);

        return slider;
    }
</code>```

Basically, as you can guess, it asynchronously downloads a file, it offers two callbacks that will run on the EDT and it immediately returns a Slider that keep track of the download progress.

On Android, the download continues and ends even when the app is in background. On iOS, on the other hand, the app must remain active and foregrounded at all time.

Is it possible to complete the download even on iOS when the app goes to the background?

Alternatively, can I get ConnectionRequest.retry(), which is automatically invoked by my network error handler when the app returns to foreground on iOS, to restart where the download arrived at, rather than restart it from scratch?

Even better, can I get both points 1 and 2?

答:
I would like to design a system to download small and large files that is very robust, i.e. resistant to network errors and capable of resume the download as soon as network conditions allow and in a completely transparent way for the user.

However, this conflicts with certain limits imposed by a cross-platform approach. I'm not sure that background fetch is the most appropriate solution to download heavy multimedia content and I don't know if the network errors in the background fetch are captured by the general error handler. Maybe I'll look into it.

I've elaborated a solution that has pros and cons, and it circumvents the problem.

Pros: always allows you to complete downloads, even if very heavy (e.g. 100MB), even if the connection is unstable (network errors) and even if the app goes temporarily in the background

Cons: since my idea is based on splitting the download into small parts, this approach causes many GET requests that slightly slow down the download and cause more traffic than normally needed.

Prerequisite 1: in global network error handling, there must be an automatic .retry() as in this code: Distinguish between server-side errors and connection problems

Prerequisite 2: for the getFileSizeWithoutDownload(String url) implementation and the Wrapper implementation, see: https://stackoverflow.com/a/62130371/1277576

Explanation: the code should be self-explanatory. Basically it downloads 512kbytes at a time and then merges it with the output. If a network error happens (and if on iOS the app goes in the background) everything that has already been downloaded is not lost (at most only the last 512kbyte fragment is lost). As each fragment is downloaded, ConnectionRequest calls itself, changing the header for partial download. The filesavedCallback callback is only called when all the download is finished.

Code:

```<code>    public static void downloadToStorage(String url, OnComplete<Integer> percentageCallback, OnComplete<String> filesavedCallback) throws IOException {

        final String output = getNewStorageFilename(); // get a new random available Storage file name
        final long fileSize = getFileSizeWithoutDownload(url); // total expected download size
        final int splittingSize = 512 * 1024; // 512 kbyte, size of each small download
        Wrapper<Integer> downloadedTotalBytes = new Wrapper<>(0);
        OutputStream out = Storage.getInstance().createOutputStream(output); // leave it open to append partial downloads
        Wrapper<Integer> completedPartialDownload = new Wrapper<>(0);

        ConnectionRequest cr = new GZConnectionRequest();
        cr.setUrl(url);
        cr.setPost(false);
        if (fileSize > splittingSize) {
            // Which byte should the download start from?
            cr.addRequestHeader("Range", "bytes=0-"  + splittingSize);
            cr.setDestinationStorage("split-" + output);
        } else {
            Util.cleanup(out);
            cr.setDestinationStorage(output);
        }
        cr.addResponseListener(a -> {
            CN.callSerially(() -> {
                try {
                    // We append the just saved partial download to the output, if it exists
                    if (Storage.getInstance().exists("split-" + output)) {
                        InputStream in = Storage.getInstance().createInputStream("split-" + output);
                        Util.copyNoClose(in, out, 8192);
                        Util.cleanup(in);
                        Storage.getInstance().deleteStorageFile("split-" + output);
                        completedPartialDownload.set(completedPartialDownload.get() + 1);
                    }
                    // Is the download finished?
                    if (fileSize <= 0 || completedPartialDownload.get() * splittingSize >= fileSize || downloadedTotalBytes.get() >= fileSize) {
                        // yes, download finished
                        Util.cleanup(out);
                        filesavedCallback.completed(output);
                    } else {
                        // no, it's not finished, we repeat the request after updating the "Range" header
                        cr.addRequestHeader("Range", "bytes=" + downloadedTotalBytes.get() + "-" + (downloadedTotalBytes.get() + splittingSize));
                        NetworkManager.getInstance().addToQueue(cr);
                    }
                } catch (IOException ex) {
                    Log.p("Error in appending splitted file to output file", Log.ERROR);
                    Log.e(ex);
                    Server.sendLogAsync();
                }
            });
        });
        NetworkManager.getInstance().addToQueue(cr);
        NetworkManager.getInstance().addProgressListener((NetworkEvent evt) -> {
            if (cr == evt.getConnectionRequest() && fileSize > 0) {
                downloadedTotalBytes.set(completedPartialDownload.get() * splittingSize + evt.getSentReceived());
                // the following casting to long is necessary when the file is bigger than 21MB, otherwise the result of the calculation is wrong
                percentageCallback.completed((int) ((long) downloadedTotalBytes.get() * 100 / fileSize));
            }
        });
    }
</code>```

I tried this solution in the Simulator, on Android and iOS, in different network conditions, with a 100MB download and occasionally moving the app in the background (or letting it go automatically). In all cases the app succeeds in completing the download. However, the differences between Android and iOS remain when the app is in the background.

I hope this is useful. If someone wants to further improve this code, they can add another answer :)

Body:
I wrote this code:

public static Slider downloadStorageFile(String url, OnComplete<Integer> percentageCallback, OnComplete<String> filesavedCallback) {

        final String filename = getNewStorageFilename();

        ConnectionRequest cr = Rest.get(url).fetchAsBytes(response -> CN.callSerially(() -> filesavedCallback.completed(filename)));
        cr.setDestinationStorage(filename);

        Slider slider = new Slider();
        slider.addDataChangedListener((int type, int index) -> {
            CN.callSerially(() -> percentageCallback.completed(slider.getProgress()));
        });
        sliderBridgeMap.put(cr, slider);
        SliderBridge.bindProgress(cr, slider);

        return slider;
    }

Basically, as you can guess, it asynchronously downloads a file, it offers two callbacks that will run on the EDT and it immediately returns a Slider that keep track of the download progress.

On Android, the download continues and ends even when the app is in background. On iOS, on the other hand, the app must remain active and foregrounded at all time.

Is it possible to complete the download even on iOS when the app goes to the background?

Alternatively, can I get ConnectionRequest.retry(), which is automatically invoked by my network error handler when the app returns to foreground on iOS, to restart where the download arrived at, rather than restart it from scratch?

Even better, can I get both points 1 and 2?

Body:
I would like to design a system to download small and large files that is very robust, i.e. resistant to network errors and capable of resume the download as soon as network conditions allow and in a completely transparent way for the user.

However, this conflicts with certain limits imposed by a cross-platform approach. I'm not sure that background fetch is the most appropriate solution to download heavy multimedia content and I don't know if the network errors in the background fetch are captured by the general error handler. Maybe I'll look into it.

I've elaborated a solution that has pros and cons, and it circumvents the problem.

Pros: always allows you to complete downloads, even if very heavy (e.g. 100MB), even if the connection is unstable (network errors) and even if the app goes temporarily in the background

Cons: since my idea is based on splitting the download into small parts, this approach causes many GET requests that slightly slow down the download and cause more traffic than normally needed.

Prerequisite 1: in global network error handling, there must be an automatic .retry() as in this code: Distinguish between server-side errors and connection problems

Prerequisite 2: for the getFileSizeWithoutDownload(String url) implementation and the Wrapper implementation, see: https://stackoverflow.com/a/62130371/1277576

Explanation: the code should be self-explanatory. Basically it downloads 512kbytes at a time and then merges it with the output. If a network error happens (and if on iOS the app goes in the background) everything that has already been downloaded is not lost (at most only the last 512kbyte fragment is lost). As each fragment is downloaded, ConnectionRequest calls itself, changing the header for partial download. The filesavedCallback callback is only called when all the download is finished.

Code:

    public static void downloadToStorage(String url, OnComplete<Integer> percentageCallback, OnComplete<String> filesavedCallback) throws IOException {

        final String output = getNewStorageFilename(); // get a new random available Storage file name
        final long fileSize = getFileSizeWithoutDownload(url); // total expected download size
        final int splittingSize = 512 * 1024; // 512 kbyte, size of each small download
        Wrapper<Integer> downloadedTotalBytes = new Wrapper<>(0);
        OutputStream out = Storage.getInstance().createOutputStream(output); // leave it open to append partial downloads
        Wrapper<Integer> completedPartialDownload = new Wrapper<>(0);

        ConnectionRequest cr = new GZConnectionRequest();
        cr.setUrl(url);
        cr.setPost(false);
        if (fileSize > splittingSize) {
            // Which byte should the download start from?
            cr.addRequestHeader("Range", "bytes=0-"  + splittingSize);
            cr.setDestinationStorage("split-" + output);
        } else {
            Util.cleanup(out);
            cr.setDestinationStorage(output);
        }
        cr.addResponseListener(a -> {
            CN.callSerially(() -> {
                try {
                    // We append the just saved partial download to the output, if it exists
                    if (Storage.getInstance().exists("split-" + output)) {
                        InputStream in = Storage.getInstance().createInputStream("split-" + output);
                        Util.copyNoClose(in, out, 8192);
                        Util.cleanup(in);
                        Storage.getInstance().deleteStorageFile("split-" + output);
                        completedPartialDownload.set(completedPartialDownload.get() + 1);
                    }
                    // Is the download finished?
                    if (fileSize <= 0 || completedPartialDownload.get() * splittingSize >= fileSize || downloadedTotalBytes.get() >= fileSize) {
                        // yes, download finished
                        Util.cleanup(out);
                        filesavedCallback.completed(output);
                    } else {
                        // no, it's not finished, we repeat the request after updating the "Range" header
                        cr.addRequestHeader("Range", "bytes=" + downloadedTotalBytes.get() + "-" + (downloadedTotalBytes.get() + splittingSize));
                        NetworkManager.getInstance().addToQueue(cr);
                    }
                } catch (IOException ex) {
                    Log.p("Error in appending splitted file to output file", Log.ERROR);
                    Log.e(ex);
                    Server.sendLogAsync();
                }
            });
        });
        NetworkManager.getInstance().addToQueue(cr);
        NetworkManager.getInstance().addProgressListener((NetworkEvent evt) -> {
            if (cr == evt.getConnectionRequest() && fileSize > 0) {
                downloadedTotalBytes.set(completedPartialDownload.get() * splittingSize + evt.getSentReceived());
                // the following casting to long is necessary when the file is bigger than 21MB, otherwise the result of the calculation is wrong
                percentageCallback.completed((int) ((long) downloadedTotalBytes.get() * 100 / fileSize));
            }
        });
    }

I tried this solution in the Simulator, on Android and iOS, in different network conditions, with a 100MB download and occasionally moving the app in the background (or letting it go automatically). In all cases the app succeeds in completing the download. However, the differences between Android and iOS remain when the app is in the background.

I hope this is useful. If someone wants to further improve this code, they can add another answer :)


问:
How to achieve login authentication in Excel add-in using OfficeJS
We are using Excel add-in in OfficeJS and wanted to implement login authentication with below requirements.

we have own on-premise server (identity),

need to achieve access and refresh token.

Kindly suggest any examples for the same.

答: An add-in is just a web application embedded in Office. so you would implement login auth exactly the way you would for any web application. If you are using OAuth 2.0, then for resources and libraries about how to do this, see Authorize external services in your add-in. The one possible exception is that some identity providers (Secure Token Services) do not allow their login page to open in an iframe. If that is the case with the STS that you will be using, then you will need to open the service's login page in a special dialog. For more information, see Authorize with the Office Dialog API. </p>


问:
List insert replace all sublist with the latest insert sublist
```<code> y=[]
 x[0]=1
 x[1]=2
 y.insert(len(y),x)
 x[0]=3
 x[1]=4
 y.insert(len(y),x)
 y
 [[3,4],[3,4]]
</code>```

The above code is tested on python shell interpreter, my question, why does the line y.insert(len(y),x) replace all sublist of y witht he latest sublist x content ? it obviously not the correct way to insert sublist with changing content, what is the correct way then ?

答:
This is happening because y[0] and y[1] are referring to the same elements of x. Even though you change the content of x after y's first insert, still it ill be referring to the x. You can clearly understand, if you print the value of y right after the first insert. You can also print the ids of first and second element of y, the ids will be same. Use below:

print(id(y[0]), id(y[1]))
```

<p>To achieve what you require, you need to insert like below:</p>

<pre class="lang-py prettyprint-override"><code>y.insert(len(y),list(x))
</code>```

Using list(x) will create a new and fresh data.

Body:
 y=[]
 x[0]=1
 x[1]=2
 y.insert(len(y),x)
 x[0]=3
 x[1]=4
 y.insert(len(y),x)
 y
 [[3,4],[3,4]]

The above code is tested on python shell interpreter, my question, why does the line y.insert(len(y),x) replace all sublist of y witht he latest sublist x content ? it obviously not the correct way to insert sublist with changing content, what is the correct way then ?

Body:
This is happening because y[0] and y[1] are referring to the same elements of x. Even though you change the content of x after y's first insert, still it ill be referring to the x. You can clearly understand, if you print the value of y right after the first insert. You can also print the ids of first and second element of y, the ids will be same. Use below:

print(id(y[0]), id(y[1]))

To achieve what you require, you need to insert like below:

y.insert(len(y),list(x))

Using list(x) will create a new and fresh data.


问:
the first io.emit is never getting sent
```<code>io.on('connection',function(socket){
console.log('connected');
socket.on('disconnect',()=>{
    console.log('a user disconnected');
});
socket.on('sendMessage',function(data){
    const message = data.text;
    const cookieList = socket.handshake.headers.cookie;
    const parsedCookies = myModule.parseCookies(cookieList);
    if(parsedCookies.nickName!==undefined){
        socket.nickName = parsedCookies.nickName;
    }
    io.emit('showMessage',{
        'message':message,
        'nickName':socket.nickName
    });
});
});
</code>```

this is my server code

```<code>'use strict';
 let socket = io();
 window.addEventListener('load',function(){
const button = document.querySelector('.btn');
button.addEventListener('click',function(event){
    const inputText = document.getElementById('msg').value;
    try{
        event.preventDefault();
        if(inputText.length<2){
            throw "some error";
        }else{
            const errorMessage = document.querySelector('.row p');
            if(errorMessage){
                errorMessage.remove();
            }
            socket.emit('sendMessage',{
                'text':inputText
            });
            showMessage();
        }
    }catch(error){
        const div  = document.querySelector('.row');
        console.log('error');
        if(!div.querySelector('p')){
            const errorP = document.createElement('p');
            errorP.setAttribute('style','color:red;');
            const errorMessage = document.createTextNode(error);
            errorP.appendChild(errorMessage);
            div.appendChild(errorP);
        }
    }
});
});
function showMessage(){
socket.on('showMessage',function(data){
    console.log("nickname :"+data.nickName + " message :"+data.message);
});
}
</code>```

this is my client side code

Problem is the first message is never getting sent.
Tried it both on chrome and firefox

From second messages communication works fine.. I cannot understand why the first message is not working

答:
Well, that was a really simple mistake.
The problem was that I placed socket.on('showMessage') inside in a function and ran the  function in a try catch.
Removed function and it solved the problem.</p>

Title: the first io.emit is never getting sent

Body:
io.on('connection',function(socket){
console.log('connected');
socket.on('disconnect',()=>{
    console.log('a user disconnected');
});
socket.on('sendMessage',function(data){
    const message = data.text;
    const cookieList = socket.handshake.headers.cookie;
    const parsedCookies = myModule.parseCookies(cookieList);
    if(parsedCookies.nickName!==undefined){
        socket.nickName = parsedCookies.nickName;
    }
    io.emit('showMessage',{
        'message':message,
        'nickName':socket.nickName
    });
});
});

this is my server code

'use strict';
 let socket = io();
 window.addEventListener('load',function(){
const button = document.querySelector('.btn');
button.addEventListener('click',function(event){
    const inputText = document.getElementById('msg').value;
    try{
        event.preventDefault();
        if(inputText.length<2){
            throw "some error";
        }else{
            const errorMessage = document.querySelector('.row p');
            if(errorMessage){
                errorMessage.remove();
            }
            socket.emit('sendMessage',{
                'text':inputText
            });
            showMessage();
        }
    }catch(error){
        const div  = document.querySelector('.row');
        console.log('error');
        if(!div.querySelector('p')){
            const errorP = document.createElement('p');
            errorP.setAttribute('style','color:red;');
            const errorMessage = document.createTextNode(error);
            errorP.appendChild(errorMessage);
            div.appendChild(errorP);
        }
    }
});
});
function showMessage(){
socket.on('showMessage',function(data){
    console.log("nickname :"+data.nickName + " message :"+data.message);
});
}

this is my client side code

Problem is the first message is never getting sent.
Tried it both on chrome and firefox

From second messages communication works fine.. I cannot understand why the first message is not working