问:
It takes a long time to loop over 1000 entries from my database in Laravel
I am setting up an api end point that is responsible for getting movies from my database. I have a many to many relationship with genre. They are connected with a pivot table. I am trying to group all the movies by their genre before I send it over the response. Chrome is showing that it is taking 7+s TTFB (Time To First Byte). I need to know where the slow down is happening. I have also tested the endpoint with Postman and showing the same results. I don't know if I'm doing something wrong with the relationships, looping over the database, getting the data.

I am using Laradock to provide my Mysql, PHP, NGINX. I have tried to break out of the loop so that each genre group only can have 10 movies with in them. Doing this sped up my time from 20+s -> 7+s.

There are:
11 genres
1300 movies
3205 genre_movie

Example of the database
movie:

```<code> |id|name|...|
 |1 |mov1|...|
 |2 |mov2|...|
 |3 |mov3|...|
 |4 |mov4|...|
</code>```

genre:

```<code>|id|genre   |...|
|1 |action  |...|
|2 |drama   |...|
|3 |thriller|...|
|4 |cartoon |...|
</code>```

pivot: genre_movie

```<code>|movie_id|genre_id|
|1       |1       |
|1       |2       |
|2       |2       |
|3       |4       |
</code>```

Here is my Relations
Genre:

```<code>    public function movie(){
        return $this->belongsToMany('App\Movie');
    }

</code>```

Movie:

```<code>    public function genre(){
        return $this->belongsToMany('App\Genre');
    }

</code>```

Here is my migrations
movies:

```<code>    public function up()
    {
        Schema::create('movies', function (Blueprint $table) {
            $table->bigIncrements('id')->unsigned();
            $table->string('title', 100);
            $table->text('synopsis');
            $table->integer('released_year');
            $table->string('imdb_url', 100);
            $table->string('s3_location', 100);
            $table->string('poster_location', 100);
            $table->boolean('isRestricted');
            $table->timestamps();
        });
    }

</code>```

genres:

```<code>    public function up()
    {
        Schema::create('genres', function (Blueprint $table) {
            $table->bigIncrements('id')->unsigned();
            $table->string('genre');
            $table->longText('description');
        });
    }

</code>```

genre_movie:

```<code>    public function up()
    {
        Schema::create('genre_movie', function (Blueprint $table) {
            $table->bigInteger('genre_id')->unsigned();
            $table->foreign('genre_id')->references('id')->on('genres');

            $table->bigInteger('movie_id')->unsigned();
            $table->foreign('movie_id')->references('id')->on('movies');
        });

</code>```

Here is how I'm seeding my Data:
Movie Factory

```<code>$factory->define(App\Movie::class, function (Faker $faker) {
    $faker->addProvider(new Image($faker));
    $faker->addProvider(new Base($faker));
    return [
        //
        'title' => $faker->name,
        'synopsis' => $faker->paragraph,
        'poster_location' => $faker->imageUrl($width=680, $height=680),
        'imdb_url' => 'https://www.imdb.com/title/tt5884052/',
        's3_location' => 'movie.mp4',
        'released_year' => $faker->numberBetween($min=1900, $max=1960),
        'isRestricted' => $faker->numberBetween($min=0, $max=1)
    ];
});

</code>```

GenreTable Seeder

```<code>    public function run()
    {
        //

        $genres = ['action', 'adventure', 'comedy', 'crime','drama','fantasy','historical','horror','romance','science fiction','thriller'];
        $seeds = [];
        foreach($genres as $genre){
            array_push($seeds,[
                'genre' => $genre,
                'description' => Str::random(150)
            ]);

        }
        DB::table('genres')->insert($seeds);

    }

</code>```

MovieTable Seeder

```<code>    public function run()
    {
        //
        $this->call([GenreSeeder::class]);
        factory(App\Movie::class, 1300)->create();

        $genres = App\Genre::all();

        App\Movie::all()->each(function ($movie) use ($genres) {
            $movie->genre()->attach(
                $genres->random(rand(1,4))->pluck('id')->toArray()
            );
        });

    }

</code>```

Api Route

```<code>    Route::get('movies/filteredByGenre', 'MovieController@filteredByGenre');

</code>```

MovieController@filteredByGenre

```<code>    public function filteredByGenre(Request $request){

        $movies = Movie::with('genre:genre')->get();
        $sizeofMovies = count($movies);
        $formatedMovie = [];

        $count = 0;
        for($x = 0; $x < $sizeofMovies; $x++){
            $sizeofGenre = count($movies[$x]->genre);
            for($y = 0; $y < $sizeofGenre; $y++){
                $genre = $movies[$x]->genre[$y];
                try{
                    if(isset($formatedMovie[$genre['genre']])){
                        if(sizeof($formatedMovie[$genre['genre']]) > 10){
                            break;
                        }
                        $formatedMovie[$genre['genre']][] = $movies[$x];
                    }else{
                        $formatedMovie[$genre['genre']][] = $movies[$x];
                    }
                } catch(ErrorException $e) {
                    $formatedMovie[$genre['genre']][] = $movies[$x];
                }

            }
        }
        $response = ['success' => true, 'data' => $formatedMovie ];
        return response()->json($response, 201);
    }

</code>```

How I'm receiving the data in the front-end

```<code>    componentDidMount() {
        var url = '/api/movies/filteredByGenre';
        axios
            .get(url)
            .then(response => {
                return response.data;
            })
            .then(json => {
                console.log(json);
                this.setState({ frontPageMovies: json.data });
            });
    }

</code>```

Commands to start my sever and seed the code

```<code>docker-compose up -d nginx mysql phpmyadmin workspace
php artisan db:seed --class=MoviesTableSeeder
</code>```

I expect movies sorted by their genre and the time it takes is no more than 1-3s to retrieve the data.

答:
The issues is how i retrieved the data from the database. The way i was using before was taking too long to retrieve the data. I switched the query to:

```<code>        $movies = DB::table('genre_movie')
        ->select('movies.*')
        ->addSelect('genres.genre')
        ->join('movies','genre_movie.movie_id','=','movies.id')
        ->join('genres','genre_movie.genre_id','=','genres.id')
        ->get();
</code>```

I am too new to understand why. I think it is how i set up my database, model, or relationship; I'm not sure.
Now my page loads in under 1 second.

If somebody can comment on why this is happening that would be helpful. I know that eloquent can handle this amount of data very easily.

Body:
I am setting up an api end point that is responsible for getting movies from my database. I have a many to many relationship with genre. They are connected with a pivot table. I am trying to group all the movies by their genre before I send it over the response. Chrome is showing that it is taking 7+s TTFB (Time To First Byte). I need to know where the slow down is happening. I have also tested the endpoint with Postman and showing the same results. I don't know if I'm doing something wrong with the relationships, looping over the database, getting the data.

I am using Laradock to provide my Mysql, PHP, NGINX. I have tried to break out of the loop so that each genre group only can have 10 movies with in them. Doing this sped up my time from 20+s -> 7+s.

There are:
11 genres
1300 movies
3205 genre_movie

Example of the database
movie:

 |id|name|...|
 |1 |mov1|...|
 |2 |mov2|...|
 |3 |mov3|...|
 |4 |mov4|...|

genre:

|id|genre   |...|
|1 |action  |...|
|2 |drama   |...|
|3 |thriller|...|
|4 |cartoon |...|

pivot: genre_movie

|movie_id|genre_id|
|1       |1       |
|1       |2       |
|2       |2       |
|3       |4       |

Here is my Relations
Genre:

    public function movie(){
        return $this->belongsToMany('App\Movie');
    }

Movie:

    public function genre(){
        return $this->belongsToMany('App\Genre');
    }

Here is my migrations
movies:

    public function up()
    {
        Schema::create('movies', function (Blueprint $table) {
            $table->bigIncrements('id')->unsigned();
            $table->string('title', 100);
            $table->text('synopsis');
            $table->integer('released_year');
            $table->string('imdb_url', 100);
            $table->string('s3_location', 100);
            $table->string('poster_location', 100);
            $table->boolean('isRestricted');
            $table->timestamps();
        });
    }

genres:

    public function up()
    {
        Schema::create('genres', function (Blueprint $table) {
            $table->bigIncrements('id')->unsigned();
            $table->string('genre');
            $table->longText('description');
        });
    }

genre_movie:

    public function up()
    {
        Schema::create('genre_movie', function (Blueprint $table) {
            $table->bigInteger('genre_id')->unsigned();
            $table->foreign('genre_id')->references('id')->on('genres');

            $table->bigInteger('movie_id')->unsigned();
            $table->foreign('movie_id')->references('id')->on('movies');
        });

Here is how I'm seeding my Data:
Movie Factory

$factory->define(App\Movie::class, function (Faker $faker) {
    $faker->addProvider(new Image($faker));
    $faker->addProvider(new Base($faker));
    return [
        //
        'title' => $faker->name,
        'synopsis' => $faker->paragraph,
        'poster_location' => $faker->imageUrl($width=680, $height=680),
        'imdb_url' => 'https://www.imdb.com/title/tt5884052/',
        's3_location' => 'movie.mp4',
        'released_year' => $faker->numberBetween($min=1900, $max=1960),
        'isRestricted' => $faker->numberBetween($min=0, $max=1)
    ];
});

GenreTable Seeder

    public function run()
    {
        //

        $genres = ['action', 'adventure', 'comedy', 'crime','drama','fantasy','historical','horror','romance','science fiction','thriller'];
        $seeds = [];
        foreach($genres as $genre){
            array_push($seeds,[
                'genre' => $genre,
                'description' => Str::random(150)
            ]);

        }
        DB::table('genres')->insert($seeds);

    }

MovieTable Seeder

    public function run()
    {
        //
        $this->call([GenreSeeder::class]);
        factory(App\Movie::class, 1300)->create();

        $genres = App\Genre::all();

        App\Movie::all()->each(function ($movie) use ($genres) {
            $movie->genre()->attach(
                $genres->random(rand(1,4))->pluck('id')->toArray()
            );
        });

    }

Api Route

    Route::get('movies/filteredByGenre', 'MovieController@filteredByGenre');

MovieController@filteredByGenre

    public function filteredByGenre(Request $request){

        $movies = Movie::with('genre:genre')->get();
        $sizeofMovies = count($movies);
        $formatedMovie = [];

        $count = 0;
        for($x = 0; $x < $sizeofMovies; $x++){
            $sizeofGenre = count($movies[$x]->genre);
            for($y = 0; $y < $sizeofGenre; $y++){
                $genre = $movies[$x]->genre[$y];
                try{
                    if(isset($formatedMovie[$genre['genre']])){
                        if(sizeof($formatedMovie[$genre['genre']]) > 10){
                            break;
                        }
                        $formatedMovie[$genre['genre']][] = $movies[$x];
                    }else{
                        $formatedMovie[$genre['genre']][] = $movies[$x];
                    }
                } catch(ErrorException $e) {
                    $formatedMovie[$genre['genre']][] = $movies[$x];
                }

            }
        }
        $response = ['success' => true, 'data' => $formatedMovie ];
        return response()->json($response, 201);
    }

How I'm receiving the data in the front-end

    componentDidMount() {
        var url = '/api/movies/filteredByGenre';
        axios
            .get(url)
            .then(response => {
                return response.data;
            })
            .then(json => {
                console.log(json);
                this.setState({ frontPageMovies: json.data });
            });
    }

Commands to start my sever and seed the code

docker-compose up -d nginx mysql phpmyadmin workspace
php artisan db:seed --class=MoviesTableSeeder

I expect movies sorted by their genre and the time it takes is no more than 1-3s to retrieve the data.

Body:
The issues is how i retrieved the data from the database. The way i was using before was taking too long to retrieve the data. I switched the query to:

        $movies = DB::table('genre_movie')
        ->select('movies.*')
        ->addSelect('genres.genre')
        ->join('movies','genre_movie.movie_id','=','movies.id')
        ->join('genres','genre_movie.genre_id','=','genres.id')
        ->get();

I am too new to understand why. I think it is how i set up my database, model, or relationship; I'm not sure.
Now my page loads in under 1 second.

If somebody can comment on why this is happening that would be helpful. I know that eloquent can handle this amount of data very easily.


来源: stackexchange

问:
Tkinter GUI freezes while running looping
I'm new to python coding and I have been working on a project which could click on an image based on a chosen color. I have been using a program which loops the search 50 times when I click the start button. However, I have been trying to implement a stop button, but the problem is that my code freezes when the loop is running. Any ideas?

I have heard to try threading but it seems very complicated and I have been unable to follow any tutorials properly in relation to my code. By the way, the image searched has been testing images I've been using stored inside the program files.

```<code>from imagesearch import *
import pyautogui
import tkinter as tk
from tkinter import *
from tkinter.ttk import *
import time
import threading

# ---Defined Programs---
def run():
    global enterColor
    enterColor = str(enterColorField.get())
    program(enterColor)

def program(color):
    whitePos = imagesearch_numLoop(str(color) + ".PNG", 0, 50)
    pyautogui.moveTo(whitePos[0] + 20, whitePos[1] + 10)
    pyautogui.click()

def stop():
    print("Placeholder")

# ---Main Runner---
window = tk.Tk()
window.geometry("250x250")
window.configure(background="#181b54")

app = tk.Frame(window)
app.grid()

enterColorLabel = tk.Label(window, text="Enter Color:", bg="#181b54", fg="white")
enterColorLabel.place(x=10, y=50)

enterColorField = Combobox(window)
enterColorField['values'] = ("Black", "White")
enterColorField.current("0")  # set the selected item
enterColorField.place(x=10, y=70)

submitButton = tk.Button(window, text="Start", bg="#66ff00", command=run)
submitButton.place(x=10, y=130)

stopButton = tk.Button(window, text="Stop", bg="red", command=stop)
stopButton.place(x=50, y=130)

window.mainloop()

#---New Python Script---
import cv2
import numpy as np
import pyautogui
import random
import time

def imagesearch_numLoop(image, timesample, maxSamples, precision=0.8):
    pos = imagesearch(image, precision)
    count = 0
    while pos[0] == -1:
        print(image+" not found, waiting")
        count = count + 1
        if count>maxSamples:
            break
        pos = imagesearch(image, precision)
    return pos
</code>```

Whenever clicking start, the whole code freezes. I can't even (x) out.

答:
A simple answer is you cannot use while loop in GUI design.

But you can use the method .after(delay, callback=None) instead.

Here is an example:

```<code>from tkinter import *

root = Tk()

def loop():
    print("Hi!")
    root.after(1000, loop) # 1000 is equal to 1 second.

root.after(1000, loop) # This line is to call loop() in 1 second.
root.mainloop()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to python coding and I have been working on a project which could click on an image based on a chosen color. I have been using a program which loops the search 50 times when I click the start button. However, I have been trying to implement a stop button, but the problem is that my code freezes when the loop is running. Any ideas?

I have heard to try threading but it seems very complicated and I have been unable to follow any tutorials properly in relation to my code. By the way, the image searched has been testing images I've been using stored inside the program files.

from imagesearch import *
import pyautogui
import tkinter as tk
from tkinter import *
from tkinter.ttk import *
import time
import threading

# ---Defined Programs---
def run():
    global enterColor
    enterColor = str(enterColorField.get())
    program(enterColor)

def program(color):
    whitePos = imagesearch_numLoop(str(color) + ".PNG", 0, 50)
    pyautogui.moveTo(whitePos[0] + 20, whitePos[1] + 10)
    pyautogui.click()

def stop():
    print("Placeholder")

# ---Main Runner---
window = tk.Tk()
window.geometry("250x250")
window.configure(background="#181b54")

app = tk.Frame(window)
app.grid()

enterColorLabel = tk.Label(window, text="Enter Color:", bg="#181b54", fg="white")
enterColorLabel.place(x=10, y=50)

enterColorField = Combobox(window)
enterColorField['values'] = ("Black", "White")
enterColorField.current("0")  # set the selected item
enterColorField.place(x=10, y=70)

submitButton = tk.Button(window, text="Start", bg="#66ff00", command=run)
submitButton.place(x=10, y=130)

stopButton = tk.Button(window, text="Stop", bg="red", command=stop)
stopButton.place(x=50, y=130)

window.mainloop()

#---New Python Script---
import cv2
import numpy as np
import pyautogui
import random
import time

def imagesearch_numLoop(image, timesample, maxSamples, precision=0.8):
    pos = imagesearch(image, precision)
    count = 0
    while pos[0] == -1:
        print(image+" not found, waiting")
        count = count + 1
        if count>maxSamples:
            break
        pos = imagesearch(image, precision)
    return pos

Whenever clicking start, the whole code freezes. I can't even (x) out.

Body:
A simple answer is you cannot use while loop in GUI design.

But you can use the method .after(delay, callback=None) instead.

Here is an example:

from tkinter import *

root = Tk()

def loop():
    print("Hi!")
    root.after(1000, loop) # 1000 is equal to 1 second.

root.after(1000, loop) # This line is to call loop() in 1 second.
root.mainloop()


问:
How to test the latest Knex migration by rolling back just that migration?
In Knex, every time we create a migration we want to test that migration by rolling forward/back.

However, if we have just rolled forward multiple migrations, there doesn't appear to be any way to test rolling back just one migration - all of them are rolled back with migrate:rollback.

How can we quickly test rolling back migrations one at a time to ensure the DB is in the desired state?  This seems like a very common use case so it seems possible we're overlooking something.

答:
It looks like the only way to do this is with knex-migrate.

Upgrade by a single migration via CLI:

knex-migrate up

Roll back a single migration via CLI:

knex-migrate down


问:
Drag and drop returns 'null' on item created by DOM
I'm currently working on a trello-like app, and have run into some issues with drag and drop events, and DOM. I basically have four lists, each containing a div with id "card-container". I'm able to move cards created in the source code as expected, however, when I add a card through DOM, and try to move it to another container, the container appends a child "null". Not sure what I am doing wrong.

When adding a new card, the function makeCard() is run by submitting a button.

draganddorp.js

```<code>const card = document.querySelector('.task-card');
const cards = document.querySelectorAll('.task-card')
const cardContainers = document.querySelectorAll('.card-container');

var draggingCard = null;

// card listeners
cards.forEach(addCardListeners);

// Loop through taskContainer boxes and add listeners
cardContainers.forEach(addContainerListeners);

// Drag Functions
function dragStart(event) {
    this.className += ' card-hold';
    setTimeout(() => (this.className = 'invisible'), 0); //set timeout so card wont dissapear
    draggingCard = event.target;
}

function dragEnd() {
    this.className = 'task-card';
    draggingCard = null;
}

function dragOver(e) {
    e.preventDefault();
}

function dragEnter(e) {
    e.preventDefault();
    this.className += ' card-container-hover';
}

function dragLeave() {
    this.className = 'card-container';
}

function dragDrop() {
    this.className = 'card-container';
    this.append(draggingCard);
}

function addCardListeners(card) {
    card.addEventListener('dragstart', dragStart);
    card.addEventListener('dragend', dragEnd);
}

function addContainerListeners(cardContainer) {
    cardContainer.addEventListener('dragover', dragOver);
    cardContainer.addEventListener('dragenter', dragEnter);
    cardContainer.addEventListener('dragleave', dragLeave);
    cardContainer.addEventListener('drop', dragDrop);
}
</code>```

makecard.js

```<code>function makeCard(destination) {
    //defining all variables needed for creating a card
    let getCardContainer = document.getElementById(destination);
    let createTaskCard = document.createElement("div");

    //varibles needed for task header
    let createTaskHeader = document.createElement("div");
    let createTags = document.createElement("div");
    let createTag = document.createElement("span");
    let createActionsBtn = document.createElement("div");

    //varibles needed for task body
    let createTaskBody = document.createElement("div");
    let createTaskTitle = document.createElement("p");

    //varibles needed for task footer
    let createTaskFooter = document.createElement("div");
    let createAsignee = document.createElement("div");
    let createAsigneeIcon = document.createElement("span");
    let createAsigneeMember = document.createElement("span");
    let createDueDate = document.createElement("div");
    let createDueDateDate = document.createElement("span");
    let createDueDateIcon = document.createElement("span");

    //creating card
    createTaskCard.className = "task-card";
    createTaskCard.setAttribute("draggable", true);

    //addding class/id and HTML to task header
    createTaskHeader.className = "task-card-header";
    createTags.className = "tags";
    createTag.className = "tag";
    createTag.id = "tag-";
    createTag.innerHTML = "someTags"
    createActionsBtn.className = "actions";
    //add action itself (svg)

    //addding class/id and HTML to task body
    createTaskBody.className = "task-card-body";
    createTaskTitle.innerHTML = "someTitle"

    //addding class/id and HTML to task footer
    createTaskFooter.className = "task-card-footer";
    createAsignee.className = "asignee";
    createAsigneeIcon.className = "icon";
    createAsigneeIcon.innerHTML = "I";
    createAsigneeMember.innerHTML = "Assignee name";
    createDueDate.className = "dueDate";
    createDueDateDate.innerHTML = "someDate"
    createDueDateIcon.className = "icon";
    createDueDateIcon.innerHTML = "I";

    //setting up structure
    createTaskHeader.appendChild(createTags);
    createTaskCard.appendChild(createTaskHeader);
    createTags.appendChild(createTag);
    createTaskHeader.appendChild(createActionsBtn);
    createTaskCard.appendChild(createTaskBody);
    createTaskBody.appendChild(createTaskTitle);
    createTaskCard.appendChild(createTaskFooter);
    createTaskFooter.appendChild(createAsignee);
    createAsignee.appendChild(createAsigneeIcon);
    createTaskFooter.appendChild(createDueDate);
    createAsignee.appendChild(createAsigneeMember)
    createDueDate.appendChild(createDueDateDate);
    createDueDate.appendChild(createDueDateIcon);

    //appending card to card container
    getCardContainer.appendChild(createTaskCard);
}
</code>```

html

```<code><div class="task-card" draggable="true">
    <div class="task-card-header">
        <div class="tags">
            <span class="tag">Priority</span>
            <span class="tag">Design</span>
        </div>
        <div class="actions">
            <a href="#">
               <!--icon-->
            </a>
        </div>
    </div>
    <div class="task-card-body">
        <p>Test</p>
    </div>
    <div class="task-card-footer">
        <div class="asignee">
            <span class="icon">
                <!--icon-->
            </span>
            <span>Daniel Kjellid</span>
        </div>
        <div class="dueDate">
            <span>23.05</span>
            <span class="icon">
                <!--icon-->
            </span>
        </div>
    </div>
</div>
</code>```

css

```<code>.card-container {
  background: white;
  height: auto;
  margin: 2px;
  min-height: 150px;
  width: 115%;
}

.card-container-hover {
  border: dashed 3px #F364A2 !important;
}

.card-dragging {
  display: absolute;
}

.card-hold {
  border: solid 5px #ccc;
}
.task-card {
  border-radius: 8px;
  box-shadow: 0 0 4px 0 rgba(0,0,0,0.50);
  color: #3E4C59;
  height: auto;
  margin-bottom: 13px;
  width: 100%;
}
</code>```

答:
It seems to me when you make a new card in the makeCard(destination) function, you do not add the dragstart snd dragend listeners to it. As such draggingCard is still null because it has not been set (which happens in the dragStart event listener).

Try adding this to the end of your makeCard function.

```<code>addCardListeners(createTaskCard);
</code>```

Ofcourse, it is a bit hard to help without a working example.

Body:
I'm currently working on a trello-like app, and have run into some issues with drag and drop events, and DOM. I basically have four lists, each containing a div with id "card-container". I'm able to move cards created in the source code as expected, however, when I add a card through DOM, and try to move it to another container, the container appends a child "null". Not sure what I am doing wrong.

When adding a new card, the function makeCard() is run by submitting a button.

draganddorp.js

const card = document.querySelector('.task-card');
const cards = document.querySelectorAll('.task-card')
const cardContainers = document.querySelectorAll('.card-container');

var draggingCard = null;

// card listeners
cards.forEach(addCardListeners);

// Loop through taskContainer boxes and add listeners
cardContainers.forEach(addContainerListeners);

// Drag Functions
function dragStart(event) {
    this.className += ' card-hold';
    setTimeout(() => (this.className = 'invisible'), 0); //set timeout so card wont dissapear
    draggingCard = event.target;
}

function dragEnd() {
    this.className = 'task-card';
    draggingCard = null;
}

function dragOver(e) {
    e.preventDefault();
}

function dragEnter(e) {
    e.preventDefault();
    this.className += ' card-container-hover';
}

function dragLeave() {
    this.className = 'card-container';
}

function dragDrop() {
    this.className = 'card-container';
    this.append(draggingCard);
}

function addCardListeners(card) {
    card.addEventListener('dragstart', dragStart);
    card.addEventListener('dragend', dragEnd);
}

function addContainerListeners(cardContainer) {
    cardContainer.addEventListener('dragover', dragOver);
    cardContainer.addEventListener('dragenter', dragEnter);
    cardContainer.addEventListener('dragleave', dragLeave);
    cardContainer.addEventListener('drop', dragDrop);
}

makecard.js

function makeCard(destination) {
    //defining all variables needed for creating a card
    let getCardContainer = document.getElementById(destination);
    let createTaskCard = document.createElement("div");

    //varibles needed for task header
    let createTaskHeader = document.createElement("div");
    let createTags = document.createElement("div");
    let createTag = document.createElement("span");
    let createActionsBtn = document.createElement("div");

    //varibles needed for task body
    let createTaskBody = document.createElement("div");
    let createTaskTitle = document.createElement("p");

    //varibles needed for task footer
    let createTaskFooter = document.createElement("div");
    let createAsignee = document.createElement("div");
    let createAsigneeIcon = document.createElement("span");
    let createAsigneeMember = document.createElement("span");
    let createDueDate = document.createElement("div");
    let createDueDateDate = document.createElement("span");
    let createDueDateIcon = document.createElement("span");

    //creating card
    createTaskCard.className = "task-card";
    createTaskCard.setAttribute("draggable", true);

    //addding class/id and HTML to task header
    createTaskHeader.className = "task-card-header";
    createTags.className = "tags";
    createTag.className = "tag";
    createTag.id = "tag-";
    createTag.innerHTML = "someTags"
    createActionsBtn.className = "actions";
    //add action itself (svg)

    //addding class/id and HTML to task body
    createTaskBody.className = "task-card-body";
    createTaskTitle.innerHTML = "someTitle"

    //addding class/id and HTML to task footer
    createTaskFooter.className = "task-card-footer";
    createAsignee.className = "asignee";
    createAsigneeIcon.className = "icon";
    createAsigneeIcon.innerHTML = "I";
    createAsigneeMember.innerHTML = "Assignee name";
    createDueDate.className = "dueDate";
    createDueDateDate.innerHTML = "someDate"
    createDueDateIcon.className = "icon";
    createDueDateIcon.innerHTML = "I";

    //setting up structure
    createTaskHeader.appendChild(createTags);
    createTaskCard.appendChild(createTaskHeader);
    createTags.appendChild(createTag);
    createTaskHeader.appendChild(createActionsBtn);
    createTaskCard.appendChild(createTaskBody);
    createTaskBody.appendChild(createTaskTitle);
    createTaskCard.appendChild(createTaskFooter);
    createTaskFooter.appendChild(createAsignee);
    createAsignee.appendChild(createAsigneeIcon);
    createTaskFooter.appendChild(createDueDate);
    createAsignee.appendChild(createAsigneeMember)
    createDueDate.appendChild(createDueDateDate);
    createDueDate.appendChild(createDueDateIcon);

    //appending card to card container
    getCardContainer.appendChild(createTaskCard);
}

html

            Priority
            Design

Test

            Daniel Kjellid

            23.05

css

.card-container {
  background: white;
  height: auto;
  margin: 2px;
  min-height: 150px;
  width: 115%;
}

.card-container-hover {
  border: dashed 3px #F364A2 !important;
}

.card-dragging {
  display: absolute;
}

.card-hold {
  border: solid 5px #ccc;
}
.task-card {
  border-radius: 8px;
  box-shadow: 0 0 4px 0 rgba(0,0,0,0.50);
  color: #3E4C59;
  height: auto;
  margin-bottom: 13px;
  width: 100%;
}

Body:
It seems to me when you make a new card in the makeCard(destination) function, you do not add the dragstart snd dragend listeners to it. As such draggingCard is still null because it has not been set (which happens in the dragStart event listener).

Try adding this to the end of your makeCard function.

addCardListeners(createTaskCard);

Ofcourse, it is a bit hard to help without a working example.


问:
How to clone/make another copy of an deployed bot on Azure?
I want to create a copy of an existing bot deployed on Azure. So, that the new copy can be used to create a new bot with minor changes.
Wanted to know if there is any direct option on Azure portal itself to create the clone of the existing bot</p>

答:
As the bot channels registration isn't currently supported for template export (as you have found), the best option might be to script something. You can build a bot and have it zipped up and then use cli/powershell to create the needed resources and have it deployed. You can script creating new apps and bot channel resources fairly easy.

See here for more info on how to generally go about that. Let me know if you want a sudo sample.


问:
How to emulate error in map pipe RXJS (Angular)?
I try return error in map function, if i get code "ERROR".

import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const request = req.clone();

    return next.handle(request).pipe(
      map((event: any) => {
        if (event instanceof HttpResponse) {
          if (event.body && event.body.code === 'ERROR') {
            throw new Error('Fatal Error');
          }
          const body = event.body ? event.body.body || event.body : null;

          if (body) {
            return event.clone({body});
          }
        }

        return event;
      })
    );
  }
}
```

But i catch error in console:

core.js:15724 ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
    at subscribeTo (subscribeTo.js:41)
    at subscribeToResult (subscribeToResult.js:11)

答:
```<code>import { throwError } from 'rxjs';

throwError('I made a boo boo')
</code>```

You cannot use it in a map so you would need to switchMap

```<code>return next.handle(request).pipe(
  switchMap((event: any) => {
    if (event instanceof HttpResponse) {
      if (event.body && event.body.code === 'ERROR') {
        return throwError('Fatal Error');
      }
      const body = event.body ? event.body.body || event.body : null;

      if (body) {
        return of(event.clone({body}));
      }
    }

    return of(event);
  })
);
</code>```

Body:
I try return error in map function, if i get code "ERROR".

import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const request = req.clone();

    return next.handle(request).pipe(
      map((event: any) => {
        if (event instanceof HttpResponse) {
          if (event.body && event.body.code === 'ERROR') {
            throw new Error('Fatal Error');
          }
          const body = event.body ? event.body.body || event.body : null;

          if (body) {
            return event.clone({body});
          }
        }

        return event;
      })
    );
  }
}

But i catch error in console:

core.js:15724 ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
    at subscribeTo (subscribeTo.js:41)
    at subscribeToResult (subscribeToResult.js:11)

Body:
import { throwError } from 'rxjs';

throwError('I made a boo boo')

You cannot use it in a map so you would need to switchMap

return next.handle(request).pipe(
  switchMap((event: any) => {
    if (event instanceof HttpResponse) {
      if (event.body && event.body.code === 'ERROR') {
        return throwError('Fatal Error');
      }
      const body = event.body ? event.body.body || event.body : null;

      if (body) {
        return of(event.clone({body}));
      }
    }

    return of(event);
  })
);


问:
How can I allow multiple activities to share the same inflated "included" view?
I see this question here, and it makes me wonder if what I'm asking isn't really possible:

How to share a view across various activities

Basically, I have a common footer view that I'm inflating (including) in all of my views. However, it uses the same repetitive code to do that. My thought was to create a parent activity class to do this, but it doesn't seem correct to have one activity render the view of another. So should I just create a utility class of some sort, or is there a better way?

答:
include is very useful while reusing View components.

But remember, if any problem occurs while using include tag, wrap the included view by an arbitrary layout.

ContentLicense: CC BY-SA 3.0


问:
Convert Multi Index back to columns after pivot a table in python
I want to pivot a table with multiple columns.

Dataframe

```<code> a       b       c      d

id_1   loc_1   sale_1  1
id_1   loc_1   sale_2  2
id_2   loc_2   sale_1  3
id_2   loc_2   sale_2  4
</code>```

I applied the following logic

```<code>pd.pivot_table(df,index=['a', 'b'], columns='c', values='d')
</code>```

I got the following output

```<code>                    sale_1  sale_2
('id_1', 'loc_1')      1      2
('id_2', 'loc_2')      3      4
</code>```

but i want it as

```<code> a       b     sale_1  sale_2
id_1   loc_1      1      2
id_2   loc_2      3      4
</code>```

I tried changing the logic to

```<code>pd.pivot_table(df,index=['a', 'b'], columns='c', values='d').reset_index()
</code>```

but i am facing an error of

```<code>TypeError: cannot insert an item into a CategoricalIndex that is not
           already an existing category
</code>```

I am not sure where i am doing wrong?

答:
Your problem is the pivoted dataframe has categorical columns. Reset that:

```<code>new_df = pd.pivot_table(df,index=['a', 'b'], columns='c', values='d')
new_df.columns = new_df.columns.categories

new_df.reset_index()
</code>```

Return:

```<code>    a       b       sale_1  sale_2
0   id_1    loc_1   1       2
1   id_2    loc_2   3       4
</code>```

Body:
I want to pivot a table with multiple columns.

Dataframe

 a       b       c      d

id_1   loc_1   sale_1  1
id_1   loc_1   sale_2  2
id_2   loc_2   sale_1  3
id_2   loc_2   sale_2  4

I applied the following logic

pd.pivot_table(df,index=['a', 'b'], columns='c', values='d')

I got the following output

                    sale_1  sale_2
('id_1', 'loc_1')      1      2
('id_2', 'loc_2')      3      4

but i want it as

 a       b     sale_1  sale_2
id_1   loc_1      1      2
id_2   loc_2      3      4

I tried changing the logic to

pd.pivot_table(df,index=['a', 'b'], columns='c', values='d').reset_index()

but i am facing an error of

TypeError: cannot insert an item into a CategoricalIndex that is not
           already an existing category

I am not sure where i am doing wrong?

Body:
Your problem is the pivoted dataframe has categorical columns. Reset that:

new_df = pd.pivot_table(df,index=['a', 'b'], columns='c', values='d')
new_df.columns = new_df.columns.categories

new_df.reset_index()

Return:

    a       b       sale_1  sale_2
0   id_1    loc_1   1       2
1   id_2    loc_2   3       4


问:
Loading lines from csv files into heatmap axes in Python
I am new to python and have a piece of coursework to generate a heatmap from data in a csv file. Across the top are performance indicators of cars, and down the side are names of cars. I have also sliced the headings of rows and columns into arrays. I am unsure as to how I can load these values into axes ticks.

I am using the code ax.set_xticks() and the same for y but unsure of what to put into the brackets. The ax.get_xticks() also doesn't work. I have tried multiple varieties of things and all of them throw an error, chiefly the name of the slice; see code below.

if __name__ == "__main__":
    # Load the data.
    fileObj = open("CARS.csv").readlines()
    lines = [line.strip().split(",") for line in fileObj]
    # Reads the data into a list,
    # then slicing to extract a list of cars, kpis and scoring.
    cars = [line[0] for line in lines[1:]]      #array storing car names
    kpis = lines[0][1:]                         #array storing kpis
    scoring = np.array([line[1:-1] for line in lines[1:]], dtype=float)
```

<pre class="lang-py prettyprint-override"><code>fig=plt.figure(figsize=(6,3))
    ax=fig.add_subplot(111)
    ax.set_xlim([0,9])
    ax.set_xticks(kpis[lines[0][1:]])
    ax.set_yticks(cars)
    ax.set_title('Sportscar KPI Data')
    ax.set_xlabel('KPI's')
    ax.set_ylabel('Sportscars')
    im = ax.imshow(scores, interpolation='nearest', aspect='auto')
    plt.show()
</code>```

I am hoping to have the sportscar names from the slice put into the ticks section, and an error brings up the list of names that could not be carried across. The same for kpi's.

答:
Short answer:

Use pandas and seaborn:

```<code>import pandas as pd
import seaborn as sns
df = pd.read_csv('CARS.csv', index_col=0)
sns.heatmap(df)
</code>```

Long answer:

You can get your code to run by correcting some mistakes...

```<code>fileObj = open("CARS.csv").readlines()
lines = [line.strip().split(",") for line in fileObj]
cars = [line[0] for line in lines[1:]]
kpis = lines[0][1:]
scoring = np.array([line[1:-1] for line in lines[1:]], dtype=float)

fig=plt.figure(figsize=(6,3))
ax=fig.add_subplot(111)
ax.set_title('Sportscar KPI Data')
ax.set_xlabel("KPI")
ax.set_ylabel('Sports car')
ax.set_xticks(range(len(kpis)))
ax.set_xticklabels(kpis)
ax.set_yticks(range(len(cars)))
ax.set_yticklabels(cars)
im = ax.imshow(scoring, interpolation='nearest', aspect='auto')
plt.show()
</code>```

However,

there are a lot of things which wouldn't be done like this in python (besides all the indentation errors and the fact, that you try to plot scores although your variable was introduced as scoring):

First of all, if opening a file, you would do this in a first line and then begin to access it:

```<code>fileObj = open("CARS.csv")
lines = [line.strip().split(",") for line in fileObj.readlines()]
</code>```

Then you can closr the file properly after reading it by

```<code>fileObj.close()
</code>```

because now fileObj really is a file object, fileObj.readlines() is not, it is a list of strings.

Anyway, it would be even better to use a with block for that file handling task, which does closing automatically for you:

```<code>with(open('CARS.csv')) as fileObj:
    lines = [line.strip().split(",") for line in fileObj.readlines()]
</code>```

(Note that here indentation is needed for everything which should be handled by the with block)

But still, even if this is already better, noone would do this step by step this way, reading the file line by line, extract labels by hand and convert a subsection to a numpy array.

Even if you for whatever reason cannot/do not want to use pandas and seaborn as suggested above, numpy has several well written importers itself like e.g. np.genfromtxt.

Body:
I am new to python and have a piece of coursework to generate a heatmap from data in a csv file. Across the top are performance indicators of cars, and down the side are names of cars. I have also sliced the headings of rows and columns into arrays. I am unsure as to how I can load these values into axes ticks.

I am using the code ax.set_xticks() and the same for y but unsure of what to put into the brackets. The ax.get_xticks() also doesn't work. I have tried multiple varieties of things and all of them throw an error, chiefly the name of the slice; see code below.

if __name__ == "__main__":
    # Load the data.
    fileObj = open("CARS.csv").readlines()
    lines = [line.strip().split(",") for line in fileObj]
    # Reads the data into a list,
    # then slicing to extract a list of cars, kpis and scoring.
    cars = [line[0] for line in lines[1:]]      #array storing car names
    kpis = lines[0][1:]                         #array storing kpis
    scoring = np.array([line[1:-1] for line in lines[1:]], dtype=float)

fig=plt.figure(figsize=(6,3))
    ax=fig.add_subplot(111)
    ax.set_xlim([0,9])
    ax.set_xticks(kpis[lines[0][1:]])
    ax.set_yticks(cars)
    ax.set_title('Sportscar KPI Data')
    ax.set_xlabel('KPI's')
    ax.set_ylabel('Sportscars')
    im = ax.imshow(scores, interpolation='nearest', aspect='auto')
    plt.show()

I am hoping to have the sportscar names from the slice put into the ticks section, and an error brings up the list of names that could not be carried across. The same for kpi's.

Body:
Short answer:

Use pandas and seaborn:

import pandas as pd
import seaborn as sns
df = pd.read_csv('CARS.csv', index_col=0)
sns.heatmap(df)

Long answer:

You can get your code to run by correcting some mistakes...

fileObj = open("CARS.csv").readlines()
lines = [line.strip().split(",") for line in fileObj]
cars = [line[0] for line in lines[1:]]
kpis = lines[0][1:]
scoring = np.array([line[1:-1] for line in lines[1:]], dtype=float)

fig=plt.figure(figsize=(6,3))
ax=fig.add_subplot(111)
ax.set_title('Sportscar KPI Data')
ax.set_xlabel("KPI")
ax.set_ylabel('Sports car')
ax.set_xticks(range(len(kpis)))
ax.set_xticklabels(kpis)
ax.set_yticks(range(len(cars)))
ax.set_yticklabels(cars)
im = ax.imshow(scoring, interpolation='nearest', aspect='auto')
plt.show()

However,

there are a lot of things which wouldn't be done like this in python (besides all the indentation errors and the fact, that you try to plot scores although your variable was introduced as scoring):

First of all, if opening a file, you would do this in a first line and then begin to access it:

fileObj = open("CARS.csv")
lines = [line.strip().split(",") for line in fileObj.readlines()]

Then you can closr the file properly after reading it by

fileObj.close()

because now fileObj really is a file object, fileObj.readlines() is not, it is a list of strings.

Anyway, it would be even better to use a with block for that file handling task, which does closing automatically for you:

with(open('CARS.csv')) as fileObj:
    lines = [line.strip().split(",") for line in fileObj.readlines()]

(Note that here indentation is needed for everything which should be handled by the with block)

But still, even if this is already better, noone would do this step by step this way, reading the file line by line, extract labels by hand and convert a subsection to a numpy array.

Even if you for whatever reason cannot/do not want to use pandas and seaborn as suggested above, numpy has several well written importers itself like e.g. np.genfromtxt.


问:
C# Multiply Each row of array by set of factors
I have a multidimensional array and I want to multiply each row of it by a single dimensional array containing factors to create a new multidimensional array. However, the number of rows in the multidimensional array will vary from one run to the next, so I'll need a way to loop the multiplication through each row of the multidimensional array until the last row is reached.

Here is a simple example, I have multidimensional array:
{ { 1, 2, 3, 4}, { 5, 6, 7, 8}, { 9, 10, 11, 12} }

and I want to multiply each row by:
{0.5, 0.4, 0, 0.8}

to get:
{ { 1*0.5, 2*0.4, 3*0, 4*0.8}, { 5*0.5, 6*0.4, 7*0, 8*0.8}, { 9*0.5, 10*0.4, 11*0, 12*0.8} }

I've tried to use .Length within a for loop using the example code.

```<code>double [] factors = {0.5, 0.4, 0, 0.8};

int [,] myarray = new int [3,4] {
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12}
};

double [] output = new double[myarray.Length];
for(int i = 0; i < myarray.Length; ++i)
    output[i] = myarray[i] * factors;
</code>```

I'm getting syntax errors that extension method 'Length' cannot be applied to type int, and also indexing with [] cannot be applied to type int.

答:
I'd suggest a ragged array. Multidimensional arrays exist, but are poorly supported and almost nobody uses them. If you use a jagged array, you can be more concise. More importantly, you can be more intentional about it:

```<code>double[][] myArray = getMeSomeData();
double[]   factors = getMeSomeRowFactors();

foreach (var row in myArray)
{
  MultiplyRow(row, factors)
}

. . .

void MultiplyRow( double[] row, double[] factors )
{
  for ( int col = 0 ; col < row.length ; ++col )
  {
    row[col] = row[col] * factors[col];
  }
}
</code>```

Or even better: use Linq:

```<code>double[][] myArray = getMeSomeData();
double[]   factors = getMeSomeRowFactors();

myArray = myArray
          .Select( row => row.Select( (cell, i) => cell * factors[i] ).ToArray() )
          .ToArray()
          ;
</code>```

Or even [arguably] better;

```<code>double[][] myArray = getMeSomeData();
double[]   factors = getMeSomeRowFactors();

myArray = myArray
          .Select( Multiply(factors) )
          .ToArray()
          ;

. . .
Func<double,int,double[]> Multiply( double[] factors )
{
  return (cell, i) => cell * factors[i];
}
</code>```

Body:
I have a multidimensional array and I want to multiply each row of it by a single dimensional array containing factors to create a new multidimensional array. However, the number of rows in the multidimensional array will vary from one run to the next, so I'll need a way to loop the multiplication through each row of the multidimensional array until the last row is reached.

Here is a simple example, I have multidimensional array:
{ { 1, 2, 3, 4}, { 5, 6, 7, 8}, { 9, 10, 11, 12} }

and I want to multiply each row by:
{0.5, 0.4, 0, 0.8}

to get:
{ { 1*0.5, 2*0.4, 3*0, 4*0.8}, { 5*0.5, 6*0.4, 7*0, 8*0.8}, { 9*0.5, 10*0.4, 11*0, 12*0.8} }

I've tried to use .Length within a for loop using the example code.

double [] factors = {0.5, 0.4, 0, 0.8};

int [,] myarray = new int [3,4] {
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12}
};

double [] output = new double[myarray.Length];
for(int i = 0; i < myarray.Length; ++i)
    output[i] = myarray[i] * factors;

I'm getting syntax errors that extension method 'Length' cannot be applied to type int, and also indexing with [] cannot be applied to type int.

Body:
I'd suggest a ragged array. Multidimensional arrays exist, but are poorly supported and almost nobody uses them. If you use a jagged array, you can be more concise. More importantly, you can be more intentional about it:

double[][] myArray = getMeSomeData();
double[]   factors = getMeSomeRowFactors();

foreach (var row in myArray)
{
  MultiplyRow(row, factors)
}

. . .

void MultiplyRow( double[] row, double[] factors )
{
  for ( int col = 0 ; col < row.length ; ++col )
  {
    row[col] = row[col] * factors[col];
  }
}

Or even better: use Linq:

double[][] myArray = getMeSomeData();
double[]   factors = getMeSomeRowFactors();

myArray = myArray
          .Select( row => row.Select( (cell, i) => cell * factors[i] ).ToArray() )
          .ToArray()
          ;

Or even [arguably] better;

double[][] myArray = getMeSomeData();
double[]   factors = getMeSomeRowFactors();

myArray = myArray
          .Select( Multiply(factors) )
          .ToArray()
          ;

. . .
Func<double,int,double[]> Multiply( double[] factors )
{
  return (cell, i) => cell * factors[i];
}


问:
webview turns black and application crashes
My android application has multiple webviews. After few minutes of running the webview turns black and crashes the application.

This is the webview xml

```<code><WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="63dp"
android:visibility="visible" />;
</code>```

Here is the code to initialize webview in my Activity.

```<code>mywebPage = (WebView) findViewById(R.id.webView);
mywebPage.getSettings().setJavaScriptEnabled(true);
mywebPage.getSettings().setDomStorageEnabled(true);
mywebPage.addJavascriptInterface(this, "Android");
mywebPage.setFocusable(true);
mywebPage.setFocusableInTouchMode(true);
mywebPage.setWebChromeClient(new WebChromeClient() {
    public boolean onConsoleMessage(ConsoleMessage cm) {
        LogUtil.writeLog(this.getClass(), "WebView " + cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId());
            return true;
    }
});
</code>```

Thanks in advance for your help!

答:
Your id in the XML with the id called in the Activity is not the same.
Try in the activity to define like this.
And as suggestion everytime when you define something you need to start with lowercase.
For example : myWebPage, android:id="@+id/tvInfo".

```<code>myWebPage = (WebView) findViewById(R.id.Info);
</code>```

Body:
My android application has multiple webviews. After few minutes of running the webview turns black and crashes the application.

This is the webview xml

<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="63dp"
android:visibility="visible" />;

Here is the code to initialize webview in my Activity.

mywebPage = (WebView) findViewById(R.id.webView);
mywebPage.getSettings().setJavaScriptEnabled(true);
mywebPage.getSettings().setDomStorageEnabled(true);
mywebPage.addJavascriptInterface(this, "Android");
mywebPage.setFocusable(true);
mywebPage.setFocusableInTouchMode(true);
mywebPage.setWebChromeClient(new WebChromeClient() {
    public boolean onConsoleMessage(ConsoleMessage cm) {
        LogUtil.writeLog(this.getClass(), "WebView " + cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId());
            return true;
    }
});

Thanks in advance for your help!

Body:
Your id in the XML with the id called in the Activity is not the same.
Try in the activity to define like this.
And as suggestion everytime when you define something you need to start with lowercase.
For example : myWebPage, android:id="@+id/tvInfo".

myWebPage = (WebView) findViewById(R.id.Info);


问:
Kendo MVC DropdownTree not displaying selected value
I have a Kendo MVC DropdownTree in may page. I am successfully saving the selected value from it into database. When I come to edit the data, the value is correctly returned from the model and set in the DropdownTree, however, no item is visually getting selected in the dropdown tree.

When I try to read the value of the dropdown tree from a button click, it correctly returns the value.

```<code>@(Html.Kendo().DropDownTree()
                .Name("VocationID")
                .DataTextField("Name")
                .DataValueField("Id")
                .ValuePrimitive(true)
                .Placeholder("--Select Vocation--")
                .Value(Model.VocationID.ToString())
                .DataSource(dataSource => dataSource
                    .Read(read => read
                    .Action("GetVocationTree", "ApplicationForm"))
                )
                .HtmlAttributes(new { style = "width: 250px;", required = "required", validationMessage = "Vocation is required" })
             )
</code>```

```<code>function TestValue() {
        var dropdowntree = $("#VocationID").data("kendoDropDownTree");
        alert(dropdowntree.value());
}
</code>```

The javascript alert above correctly returns the value but no item is displayed as selected in the DropdownTree. I also tried removing the ValuePrimitive attribute but nothing works.

Could someone please help to identify what is missing here?

答:
Found a way to handle this at last. Posting it if it helps someone someday.

This control behaves a little differently. You can read the selected item as ID but need to set its text instead of ID to set the selected item.

Getting the item value:

```<code>            var dropdowntree = $("#VocationID").data("kendoDropDownTree");
            var VocationID = dropdowntree.value().id;

</code>```

and to Set the default value:

```<code>            @(Html.Kendo().DropDownTree()
                            .Name("VocationID")
                            .DataTextField("Name")
                            .DataValueField("Id")
                            .Placeholder("--Select Vocation--")
                            .Value(Model.VocationName)

</code>```

Note the "VocationName" instead of ID.

Body:
I have a Kendo MVC DropdownTree in may page. I am successfully saving the selected value from it into database. When I come to edit the data, the value is correctly returned from the model and set in the DropdownTree, however, no item is visually getting selected in the dropdown tree.

When I try to read the value of the dropdown tree from a button click, it correctly returns the value.

@(Html.Kendo().DropDownTree()
                .Name("VocationID")
                .DataTextField("Name")
                .DataValueField("Id")
                .ValuePrimitive(true)
                .Placeholder("--Select Vocation--")
                .Value(Model.VocationID.ToString())
                .DataSource(dataSource => dataSource
                    .Read(read => read
                    .Action("GetVocationTree", "ApplicationForm"))
                )
                .HtmlAttributes(new { style = "width: 250px;", required = "required", validationMessage = "Vocation is required" })
             )

function TestValue() {
        var dropdowntree = $("#VocationID").data("kendoDropDownTree");
        alert(dropdowntree.value());
}

The javascript alert above correctly returns the value but no item is displayed as selected in the DropdownTree. I also tried removing the ValuePrimitive attribute but nothing works.

Could someone please help to identify what is missing here?

Body:
Found a way to handle this at last. Posting it if it helps someone someday.

This control behaves a little differently. You can read the selected item as ID but need to set its text instead of ID to set the selected item.

Getting the item value:

            var dropdowntree = $("#VocationID").data("kendoDropDownTree");
            var VocationID = dropdowntree.value().id;

and to Set the default value:

            @(Html.Kendo().DropDownTree()
                            .Name("VocationID")
                            .DataTextField("Name")
                            .DataValueField("Id")
                            .Placeholder("--Select Vocation--")
                            .Value(Model.VocationName)

Note the "VocationName" instead of ID.


问:
SortableJS Drag into empty Vuetify v-data-table not working
I'm trying to create a drag-drop between two v-data-tables in Vuetify using SortableJS.
Here is an example with 3 tables: https://codepen.io/arno-van-oordt/pen/MdqrgK

It works fine if both tables start with at least one item (between table 1 and 3 for example). But when a table starts of empty I can't seem to drop items onto it.

What would be the best solution to this issue?

```<code>new Vue({
  el: "#app",
  data() {
    return {
      headers: [
        {
          text: "Title",
          value: "name"
        }
      ],
      list1: [
        {
          name: "Item1-1"
        },
        {
          name: "Item1-2"
        }
      ],
      list2: [],
      list3: [
        {
          name: "Item3-1"
        },
        {
          name: "Item3-2"
        }
      ]
    };
  },
  mounted: function() {
    new Sortable(this.$refs.table1.$el.getElementsByTagName("tbody")[0], {
      group: "test",
      draggable: ".sortableRow"
    });

    new Sortable(this.$refs.table2.$el.getElementsByTagName("tbody")[0], {
      group: "test",
      draggable: ".sortableRow"
    });

    new Sortable(this.$refs.table3.$el.getElementsByTagName("tbody")[0], {
      group: "test",
      draggable: ".sortableRow"
    });
  },
  methods: {}
});
</code>```

答:
This was a flaw in SortableJS which is now solved in the next-version branch.
This branch is still in development but is backwards compatible and will be merged to the master branch soon.

Edit: It is now in the master branch

Body:
I'm trying to create a drag-drop between two v-data-tables in Vuetify using SortableJS.
Here is an example with 3 tables: https://codepen.io/arno-van-oordt/pen/MdqrgK

It works fine if both tables start with at least one item (between table 1 and 3 for example). But when a table starts of empty I can't seem to drop items onto it.

What would be the best solution to this issue?

new Vue({
  el: "#app",
  data() {
    return {
      headers: [
        {
          text: "Title",
          value: "name"
        }
      ],
      list1: [
        {
          name: "Item1-1"
        },
        {
          name: "Item1-2"
        }
      ],
      list2: [],
      list3: [
        {
          name: "Item3-1"
        },
        {
          name: "Item3-2"
        }
      ]
    };
  },
  mounted: function() {
    new Sortable(this.$refs.table1.$el.getElementsByTagName("tbody")[0], {
      group: "test",
      draggable: ".sortableRow"
    });

    new Sortable(this.$refs.table2.$el.getElementsByTagName("tbody")[0], {
      group: "test",
      draggable: ".sortableRow"
    });

    new Sortable(this.$refs.table3.$el.getElementsByTagName("tbody")[0], {
      group: "test",
      draggable: ".sortableRow"
    });
  },
  methods: {}
});


问:
Unable to start Oracle Virtual Box
overflow community,

I need a help on virtual machine issue.

I was working on Oracle VM Virtual Box.it was all working fine.i save state and close it

After some days when i try to access it.
it restore it states but giving an error  as i attached screenshot. and i m unable to access it.

how can i solve this error.what are possible reasons for this

Plz help as i have so  much data and installations on this VM

Thanks in advance
Nisha

答: Right button on your virtual machine, Discard Saved State should fix the VM with no data loss</p>

Title: Unable to start Oracle Virtual Box


问:
How do I resolve "git pull" merge conflicts onto one of my previous commits?
This is what my git tree looks like:

```<code>A   B   C   D   E
o---o---o---o---o master
         \
          o---o---o---o my_branch
          C1  C2  C3  C4
</code>```

I am trying to rebase my_branch with master, and for my tree to look like this in the end, however, I have merge conflicts, which I want to be resolved as part of my commit C2 (or earlier commit) instead of top of head (C4).

```<code>A   B   C   D   E
o---o---o---o---o master
                 \
                  o---o---o---o my_branch
                  C1  C2* C3  C4
                       |
                      includes merge conflict resolution with master
</code>```

Tried: Git rebase & resolve conflict + commit
git pull --rebase master This causes merge conflict.

I can resolve the conflict and do git commit, but, I do not wish to create a new commit, C5. I would rather the conflict changes be made as part of an older commit, say, C2.

Alternatively, I tried git rebase to C2 followed by git pull
git rebase -i C1 Mark C2 as "edit". I hoped to do git pull --rebase master on this, and resolve conflicts + commit + git rebase --continue so the conflict resolution becomes part of C2, but this did not work.

Can you suggest a way I can do this? Anything short of reverting my changes and re-applying them after git rebase?

答:
You're already replacing all of your commits

Commit C1 says that its parent commit is C.  You need a new and different commit—you might call it E1, for instance—that says that its parent is E.

This new and different commit will have a new and different hash ID.  In the end, though, you'll still have four commits—they will just be E1 through E4.  Your name my_branch will identify new commit E4; commit C4 will be forgotten, and will eventually go away, unless someone or something else has hold of it and won't let go:

```<code>                  E1  E2  E3  E4
                  o---o---o---o   <-- my_branch
A   B   C   D   E/
o---o---o---o---o   <-- master
         \
          o---o---o---o   [abandoned]
          C1  C2  C3  C4
</code>```

When git rebase hits a conflict, it stops in the middle of the rebase

Rebase works by copying each commit, one at a time, turning the snapshot in C1 into a change-set against commit C—its parent—and applying that change-set to commit E.  Git does this using Git's internal merge engine, i.e., Git also compares C vs E to determine how to apply C vs C1.

In this case, that comparison and copy went well, and Git built commit E1 successfully.  Then Git went on to attempt to build E2 by comparing C2 to C1, to turn it into a change-set, then merging that with the changes from C1 to E1.  This is where the conflict occurred.  So at this point, you have:

```<code>                  E1
                  o   <-- HEAD
A   B   C   D   E/
o---o---o---o---o   <-- master
         \
          o---o---o---o   <-- my_branch
          C1  C2  C3  C4
</code>```

Commit E2 is in progress, but does not exist yet.  You must resolve the conflict, git add the resolved files, and run git rebase --continue to cause Git to make new commit E2:

```<code>                  E1  E2
                  o---o   <-- HEAD
A   B   C   D   E/
o---o---o---o---o   <-- master
         \
          o---o---o---o   <-- my_branch
          C1  C2  C3  C4
</code>```

At this point Git will be able to attempt to copy C3.  If that goes well, Git will make E3 on its own.  Otherwise it will stop to get your help again, and you go through the same process and eventually use git rebase --continue to make Git go on to copy C4 to E4.

Once E4 is successfully made, there are no copies left to perform, and git rebase does its last trick: it moves the name my_branch so that it points to E4 instead of C4, re-attaching the special name HEAD to the name my_branch.

Body:
This is what my git tree looks like:

A   B   C   D   E
o---o---o---o---o master
         \
          o---o---o---o my_branch
          C1  C2  C3  C4

I am trying to rebase my_branch with master, and for my tree to look like this in the end, however, I have merge conflicts, which I want to be resolved as part of my commit C2 (or earlier commit) instead of top of head (C4).

A   B   C   D   E
o---o---o---o---o master
                 \
                  o---o---o---o my_branch
                  C1  C2* C3  C4
                       |
                      includes merge conflict resolution with master

Tried: Git rebase & resolve conflict + commit
git pull --rebase master This causes merge conflict.

I can resolve the conflict and do git commit, but, I do not wish to create a new commit, C5. I would rather the conflict changes be made as part of an older commit, say, C2.

Alternatively, I tried git rebase to C2 followed by git pull
git rebase -i C1 Mark C2 as "edit". I hoped to do git pull --rebase master on this, and resolve conflicts + commit + git rebase --continue so the conflict resolution becomes part of C2, but this did not work.

Can you suggest a way I can do this? Anything short of reverting my changes and re-applying them after git rebase?

Body:
You're already replacing all of your commits

Commit C1 says that its parent commit is C.  You need a new and different commit—you might call it E1, for instance—that says that its parent is E.

This new and different commit will have a new and different hash ID.  In the end, though, you'll still have four commits—they will just be E1 through E4.  Your name my_branch will identify new commit E4; commit C4 will be forgotten, and will eventually go away, unless someone or something else has hold of it and won't let go:

                  E1  E2  E3  E4
                  o---o---o---o   <-- my_branch
A   B   C   D   E/
o---o---o---o---o   <-- master
         \
          o---o---o---o   [abandoned]
          C1  C2  C3  C4

When git rebase hits a conflict, it stops in the middle of the rebase

Rebase works by copying each commit, one at a time, turning the snapshot in C1 into a change-set against commit C—its parent—and applying that change-set to commit E.  Git does this using Git's internal merge engine, i.e., Git also compares C vs E to determine how to apply C vs C1.

In this case, that comparison and copy went well, and Git built commit E1 successfully.  Then Git went on to attempt to build E2 by comparing C2 to C1, to turn it into a change-set, then merging that with the changes from C1 to E1.  This is where the conflict occurred.  So at this point, you have:

                  E1
                  o   <-- HEAD
A   B   C   D   E/
o---o---o---o---o   <-- master
         \
          o---o---o---o   <-- my_branch
          C1  C2  C3  C4

Commit E2 is in progress, but does not exist yet.  You must resolve the conflict, git add the resolved files, and run git rebase --continue to cause Git to make new commit E2:

                  E1  E2
                  o---o   <-- HEAD
A   B   C   D   E/
o---o---o---o---o   <-- master
         \
          o---o---o---o   <-- my_branch
          C1  C2  C3  C4

At this point Git will be able to attempt to copy C3.  If that goes well, Git will make E3 on its own.  Otherwise it will stop to get your help again, and you go through the same process and eventually use git rebase --continue to make Git go on to copy C4 to E4.

Once E4 is successfully made, there are no copies left to perform, and git rebase does its last trick: it moves the name my_branch so that it points to E4 instead of C4, re-attaching the special name HEAD to the name my_branch.


问:
Map an array into another array
I have an array of dict like:

```<code>[{'id': 1, 'tags': ['tag_a', 'tag_b']}, {'id': 2, 'tags': ['tag_c', 'tag_b']}]
</code>```

and I would like to convert this array into a new array based on ticket_id and each tag value should be an object in the array.

I almost did it using the following function:

```<code>raw = [{'id': 1, 'tags': ['tag_a', 'tag_b']}, {'id': 2, 'tags': ['tag_c', 'tag_b']}]

def transform(ticket):
    result = []
    for tag in ticket.get('tags', []):
        result.append({'ticket_id': ticket.get('id'), 'tag': tag, 'sync': '123'})
    return result

print(list(map(transform, raw)))
</code>```

But it's returning something like [[{...}], [{...}]] and the syntax looks strange.

What is the right approach to return something like:

```<code>[{'ticket_id': 1, 'tag': 'tag_a', 'sync': '123'}, {'ticket_id': 1, 'tag': 'tag_b', 'sync': '123'}, ...]
</code>```

答:
You just need to flatten your results. Essentially, you used a map operation when you wanted a flat-map operation.

You can do this in one go by using a nested list comprehension:

```<code>[x for ticket in raw for x in transform(ticket)]
</code>```

Of course, you could have done something like:

```<code>[x for xs in map(transform, raw) for x in xs]
</code>```

Or just a regular nested loop would work.

Title: Map an array into another array

Body:
I have an array of dict like:

[{'id': 1, 'tags': ['tag_a', 'tag_b']}, {'id': 2, 'tags': ['tag_c', 'tag_b']}]

and I would like to convert this array into a new array based on ticket_id and each tag value should be an object in the array.

I almost did it using the following function:

raw = [{'id': 1, 'tags': ['tag_a', 'tag_b']}, {'id': 2, 'tags': ['tag_c', 'tag_b']}]

def transform(ticket):
    result = []
    for tag in ticket.get('tags', []):
        result.append({'ticket_id': ticket.get('id'), 'tag': tag, 'sync': '123'})
    return result

print(list(map(transform, raw)))

But it's returning something like [[{...}], [{...}]] and the syntax looks strange.

What is the right approach to return something like:

[{'ticket_id': 1, 'tag': 'tag_a', 'sync': '123'}, {'ticket_id': 1, 'tag': 'tag_b', 'sync': '123'}, ...]

Body:
You just need to flatten your results. Essentially, you used a map operation when you wanted a flat-map operation.

You can do this in one go by using a nested list comprehension:

[x for ticket in raw for x in transform(ticket)]

Of course, you could have done something like:

[x for xs in map(transform, raw) for x in xs]

Or just a regular nested loop would work.


问:
Is it possible to copy/paste/type (eg. a password) from an app into the Oculus Quest headset?
Currently there doesn't seem to be an easy way to copy/paste text in the Oculus Quest, nor to 'type' into a companion app and have it sent into the headset (at least that I have seen). This makes it extremely challenging to enter complex passwords from password managers, etc.

I have read some articles that say it might be possible to pair a bluetooth keyboard with the headset, which would be slightly better, but still doesn't allow me to copy/paste from my password manager.

Does anyone know of a way to achieve this?

答:
After some Googling/SO'ing, it seems like this might be possible using the Android Debug Bridge (adb) (Oculus has their own help page for it as well)

Your device needs to be in developer mode for this to work:

Create/join an organisation in the Oculus Dashboard

Open the Oculus app on your mobile phone.

In the Settings menu, select the Oculus Quest headset that you’re using for development.

Select More Settings.

Toggle Developer Mode on.

If you're using homebrew on macOS, you can install adb with:

```<code>brew cask install android-platform-tools
</code>```

Next, plug your headset into your computer with the USB-C cable. You then should be able to list connected devices:

```<code>adb devices
</code>```

If it says 'unauthorized', check in the headset for a dialog box asking for permission to connect. Ticking 'always allow' will make this easier in future.

At this point, we should be good to send text to the device. In the headset, focus a field that you want to 'type' into, then use adb shell input to 'type' your text:

```<code>adb shell input text "sometext"
</code>```

It seems it is also possible to send a 'paste' command using adb shell input keyevent:

```<code>adb shell input keyevent 279
</code>```

In older Android devices, you could send a 'copy' command in a similar way, but this has since been deprecated:

```<code>service call clipboard 2 i32 1 i32 0 s16 "text"
</code>```

It seems that on newer devices, you need to leverage an external service (eg. Clipper) to 'copy to clipboard'. Using Clipper, you can send a command in adb shell such as:

```<code>am broadcast -a clipper.set -e text "text"
</code>```

There are many different inputs we can send using these methods. You can find a full list of KeyEvent's in the Android Developer Documentation.

Using one (or more) of these methods, it should be possibly to 'copy'/'paste'/'type' passwords stored in a password manager on your computer 'into' the Oculus Quest headset.

Body:
After some Googling/SO'ing, it seems like this might be possible using the Android Debug Bridge (adb) (Oculus has their own help page for it as well)

Your device needs to be in developer mode for this to work:

Create/join an organisation in the Oculus Dashboard

Open the Oculus app on your mobile phone.

In the Settings menu, select the Oculus Quest headset that you’re using for development.

Select More Settings.

Toggle Developer Mode on.

If you're using homebrew on macOS, you can install adb with:

brew cask install android-platform-tools

Next, plug your headset into your computer with the USB-C cable. You then should be able to list connected devices:

adb devices

If it says 'unauthorized', check in the headset for a dialog box asking for permission to connect. Ticking 'always allow' will make this easier in future.

At this point, we should be good to send text to the device. In the headset, focus a field that you want to 'type' into, then use adb shell input to 'type' your text:

adb shell input text "sometext"

It seems it is also possible to send a 'paste' command using adb shell input keyevent:

adb shell input keyevent 279

In older Android devices, you could send a 'copy' command in a similar way, but this has since been deprecated:

service call clipboard 2 i32 1 i32 0 s16 "text"

It seems that on newer devices, you need to leverage an external service (eg. Clipper) to 'copy to clipboard'. Using Clipper, you can send a command in adb shell such as:

am broadcast -a clipper.set -e text "text"

There are many different inputs we can send using these methods. You can find a full list of KeyEvent's in the Android Developer Documentation.

Using one (or more) of these methods, it should be possibly to 'copy'/'paste'/'type' passwords stored in a password manager on your computer 'into' the Oculus Quest headset.


问:
Convert ISO string to specific date format
I need to display date in a certain format in application. I have input of '2009-04-01' as string and I want this format April 1, 2009 using Javascript.</p>

答:
Just create a new Date object and then use that to format the output:</p>

```<code>d = new Date("2009-04-01")
</code>```

Body:
Just create a new Date object and then use that to format the output:

d = new Date("2009-04-01")


问:
Display Blobs/Photos stored in Azure-storage in Xamarin Mobile Application
Trying to develop a Xamarin Forms mobile application which displays blobs stored in Azure-Storage container through the api.

Current process goes like this
API > Azure-Storage Blob > Displayed in Xamarin mobile application.

Connecting to azure storage using Storage Account Key.

Problem is, blobs are not displaying in the mobile application when public access setting on the container is set to 'private'.
If the container public access setting is set to 'blob' then the photos display in the xamarin Mobile app.

Photo For illustration purposes.Photo of issue

Code is below.

```<code>string storageConnectionString
Environment.GetEnvironmentVariable("storageconnectionstring");

CloudStorageAccount storageAccount;
if (CloudStorageAccount.TryParse(storageConnectionString, out
storageAccount))
{
// If the connection string is valid, proceed with operations against
Blob storage here.
...
}
else
{
//Error
}
[enter image description here][1]CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
</code>```

How can i make the container private whilst still displaying the blobs in the mobile application?

答:
Many thanks for your help @justjoshin.

SAS is the answer. From there you can generate a SAS token which you append after the blob url to display it even if the container is private.

Hope this helps anyone else.

Best

Body:
Trying to develop a Xamarin Forms mobile application which displays blobs stored in Azure-Storage container through the api.

Current process goes like this
API > Azure-Storage Blob > Displayed in Xamarin mobile application.

Connecting to azure storage using Storage Account Key.

Problem is, blobs are not displaying in the mobile application when public access setting on the container is set to 'private'.
If the container public access setting is set to 'blob' then the photos display in the xamarin Mobile app.

Photo For illustration purposes.Photo of issue

Code is below.

string storageConnectionString
Environment.GetEnvironmentVariable("storageconnectionstring");

CloudStorageAccount storageAccount;
if (CloudStorageAccount.TryParse(storageConnectionString, out
storageAccount))
{
// If the connection string is valid, proceed with operations against
Blob storage here.
...
}
else
{
//Error
}
[enter image description here][1]CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

How can i make the container private whilst still displaying the blobs in the mobile application?


问:
Dagger @ContributesAndroidInjector ComponentProcessor was unable to process this interface
I was testing new feature of dagger: Android module. And I am not able to compile the code when I use @ContributesAndroidInjector
I am always getting following error:

Error:(12, 8) error: dagger.internal.codegen.ComponentProcessor was unable to process this interface because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.

I tried to implement my components like here, but still I got the error.

Here is the smallest example:

```<code>@PerApplication
@Component(modules = {AndroidInjectionModule.class, LoginBindingModule.class})
public interface ApplicationComponent {
    void inject(ExampleApplication application);
}

@Module
public abstract class LoginBindingModule {
    @ContributesAndroidInjector
    abstract LoginActivity contributeYourActivityInjector();
}

public class LoginActivity extends Activity {

    @Inject
    LoginPresenter loginPresenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
    }
}

public class LoginPresenter {

    @Inject
    public LoginPresenter() {

    }
}
</code>```

If I remove LoginBindingModule from ApplicationComponent the app would be build, but would fail with runtime exception:

java.lang.IllegalArgumentException: No injector factory bound for Class

project setup:

```<code>gradle 3.3
buildToolsVersion "25.0.2"
dagger 2.11
</code>```

答:
I had the same error but the problem was with the module (project) where I declared the Dagger module.
Make sure you add the kotlin-kapt plugin otherwise Dagger won't be able to generate any class.

```<code>// declare it at the top of your build.gradle file
apply plugin: 'kotlin-kapt'
</code>```

Body:
I was testing new feature of dagger: Android module. And I am not able to compile the code when I use @ContributesAndroidInjector
I am always getting following error:

Error:(12, 8) error: dagger.internal.codegen.ComponentProcessor was unable to process this interface because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.

I tried to implement my components like here, but still I got the error.

Here is the smallest example:

@PerApplication
@Component(modules = {AndroidInjectionModule.class, LoginBindingModule.class})
public interface ApplicationComponent {
    void inject(ExampleApplication application);
}

@Module
public abstract class LoginBindingModule {
    @ContributesAndroidInjector
    abstract LoginActivity contributeYourActivityInjector();
}

public class LoginActivity extends Activity {

    @Inject
    LoginPresenter loginPresenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
    }
}

public class LoginPresenter {

    @Inject
    public LoginPresenter() {

    }
}

If I remove LoginBindingModule from ApplicationComponent the app would be build, but would fail with runtime exception:

java.lang.IllegalArgumentException: No injector factory bound for Class

project setup:

gradle 3.3
buildToolsVersion "25.0.2"
dagger 2.11

Body:
I had the same error but the problem was with the module (project) where I declared the Dagger module.
Make sure you add the kotlin-kapt plugin otherwise Dagger won't be able to generate any class.

// declare it at the top of your build.gradle file
apply plugin: 'kotlin-kapt'


问:
WPF How to get window reference that is loaded from a page that is into it?
I have a page that is into a window similiar to MDI. I want to get the reference of the window in what the page is placed into. The window is loaded.

Thanks.

答:
I ran into a similar problem and I started with Richard's solution (+1 vote from me!), but I found I had to cast the type to my specific window type to do anything useful.</p>

```<code>MainWindow w = (MainWindow)Window.GetWindow(this);
w.method_to_run();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I ran into a similar problem and I started with Richard's solution (+1 vote from me!), but I found I had to cast the type to my specific window type to do anything useful.

MainWindow w = (MainWindow)Window.GetWindow(this);
w.method_to_run();


答:
This is one way to do it using nested for loops. Moreover, you don't need to map your function. You can just pass the list to the function and print. The problem with your code was that you were using a single for loop whereas, the depth (length) of your tags was more than one

```<code>raw = [{'id': 1, 'tags': ['tag_a', 'tag_b']}, {'id': 2, 'tags': ['tag_c', 'tag_b']}]

def transform(ticket):
    result = []
    for dic in raw:
        for tag in dic['tags']:
            result.append({'ticket_id': dic['id'], 'tag': tag, 'sync': '123'})
    return result

print(transform(raw))
# [{'ticket_id': 1, 'tag': 'tag_a', 'sync': '123'}, {'ticket_id': 1, 'tag': 'tag_b', 'sync': '123'},
#  {'ticket_id': 2, 'tag': 'tag_c', 'sync': '123'}, {'ticket_id': 2, 'tag': 'tag_b', 'sync': '123'}]
</code>```

Title: Map an array into another array

Body:
This is one way to do it using nested for loops. Moreover, you don't need to map your function. You can just pass the list to the function and print. The problem with your code was that you were using a single for loop whereas, the depth (length) of your tags was more than one

raw = [{'id': 1, 'tags': ['tag_a', 'tag_b']}, {'id': 2, 'tags': ['tag_c', 'tag_b']}]

def transform(ticket):
    result = []
    for dic in raw:
        for tag in dic['tags']:
            result.append({'ticket_id': dic['id'], 'tag': tag, 'sync': '123'})
    return result

print(transform(raw))
# [{'ticket_id': 1, 'tag': 'tag_a', 'sync': '123'}, {'ticket_id': 1, 'tag': 'tag_b', 'sync': '123'},
#  {'ticket_id': 2, 'tag': 'tag_c', 'sync': '123'}, {'ticket_id': 2, 'tag': 'tag_b', 'sync': '123'}]


问:
How to print the integer 00 instead of java printing 0
I have a variable saying private int minutes = 00.

If I do System.out.println(minutes), Java will print 0 instead of 00, which is the value. It is removing the last zero, but in this particular example, I want it to print 00. How to do that?

I also tried making minutes a string, and do: Integer.parseInt(minutes) and then print that. But the result is the same.

答:
you can try this method, i've learned it in the college</p>

```<code>private static String formate(int valor) {
    return (valor < 10 ? "0" : "") + valor;
}
</code>```

Body:
you can try this method, i've learned it in the college

private static String formate(int valor) {
    return (valor < 10 ? "0" : "") + valor;
}


问:
How to structure my API call, and where to put the key and query?
I am trying to structure my API call to the openweatherapi properly, just trying to create a simple weather app, where upon the user entering a city the forecast is rendered to the page. This is what I have so far, also trying to prevent the default action where the page refreshes when the button is pressed. I am using react.

```<code>class App extends Component {
  getWeatherData = (userInput, event) => {
    event.preventDefault();
    axios({
      url: "http://openweathermap.org/data/2.5/weather/",
      method: "GET",
      dataType: "json",
      data: {
        q: userInput,
        API_KEY: "d108038ec889cfe762230283abaa7c7b"
      }
    }).then(res => {
      console.log(res);
      this.setState({});
    });
  };
</code>```

./Form. js is as follows

```<code>class Form extends Component {
  render() {
    return (
      <div>
        <form onSubmit={(this.props.getWeather, e)}>
          <input type="text" name="city" placeholder="City..." />
          <input type="text" name="country" placeholder="Country" />
          <button>Get Weather</button>

        </form>
      </div>
    );
  }
}
</code>```

Error:

```<code>./src/Form.js
  Line 7:  'e' is not defined  no-undef
</code>```

答:
Using class components, I would do something like this :

(each class/function should be split in a different file)

```<code>/**
 * This is just a helper to encapsulate the weather fetching logic
 */
function getWeatherFromInput({ city, country }) {
    const query = `${city},${country}`;

    return axios({
        method: 'GET',
        url: `http://openweathermap.org/data/2.5/weather?${query}`,
        responseType: 'json'
    });
}

/**
 * Here is the specific form
 */
export class WeatherForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            city: '',
            country: ''
        };
    }

    handleSubmit = (event) => {
        event.preventDefault();
        this.props.onSubmit(this.state);
    };

    handleInputChange = (event) => {
        const { name, value } = event.target;
        this.setState({ [name]: value });
    };

    render() {
        const { city, country } = this.state;
        return (
            <form onSubmit={this.handleSubmit}>
                <input
                    type='text'
                    name='city'
                    value={city}
                    onChange={this.handleInputChange}
                    placeholder='City...'
                />
                <input
                    type='text'
                    name='country'
                    value={country}
                    onChange={this.handleInputChange}
                    placeholder='Country'
                />
                <button type='submit'>Get weather</button>
            </form>
        );
    }
}

/**
 * And how you use it in your App
 */
export class App extends React.Component {
    constructor() {
        this.state = {
            weather: {}
        };
    }

    /**
     * The userInput is provided by the WeatherForm
     */
    handleSubmit = (userInput) => {
        getWeatherFromInput(userInput).then((response) => {
            this.setState({ weather: response.data });
        });
    };

    render() {
        return <WeatherForm onSubmit={handleSubmit} />;
    }
}
</code>```

Body:
I am trying to structure my API call to the openweatherapi properly, just trying to create a simple weather app, where upon the user entering a city the forecast is rendered to the page. This is what I have so far, also trying to prevent the default action where the page refreshes when the button is pressed. I am using react.

class App extends Component {
  getWeatherData = (userInput, event) => {
    event.preventDefault();
    axios({
      url: "http://openweathermap.org/data/2.5/weather/",
      method: "GET",
      dataType: "json",
      data: {
        q: userInput,
        API_KEY: "d108038ec889cfe762230283abaa7c7b"
      }
    }).then(res => {
      console.log(res);
      this.setState({});
    });
  };

./Form. js is as follows

class Form extends Component {
  render() {
    return (

        <form onSubmit={(this.props.getWeather, e)}>
          <input type="text" name="city" placeholder="City..." />
          <input type="text" name="country" placeholder="Country" />
          <button>Get Weather</button>

        </form>

    );
  }
}

Error:

./src/Form.js
  Line 7:  'e' is not defined  no-undef

Body:
Using class components, I would do something like this :

(each class/function should be split in a different file)

/**
 * This is just a helper to encapsulate the weather fetching logic
 */
function getWeatherFromInput({ city, country }) {
    const query = `${city},${country}`;

    return axios({
        method: 'GET',
        url: `http://openweathermap.org/data/2.5/weather?${query}`,
        responseType: 'json'
    });
}

/**
 * Here is the specific form
 */
export class WeatherForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            city: '',
            country: ''
        };
    }

    handleSubmit = (event) => {
        event.preventDefault();
        this.props.onSubmit(this.state);
    };

    handleInputChange = (event) => {
        const { name, value } = event.target;
        this.setState({ [name]: value });
    };

    render() {
        const { city, country } = this.state;
        return (
            <form onSubmit={this.handleSubmit}>
                <input
                    type='text'
                    name='city'
                    value={city}
                    onChange={this.handleInputChange}
                    placeholder='City...'
                />
                <input
                    type='text'
                    name='country'
                    value={country}
                    onChange={this.handleInputChange}
                    placeholder='Country'
                />
                <button type='submit'>Get weather</button>
            </form>
        );
    }
}

/**
 * And how you use it in your App
 */
export class App extends React.Component {
    constructor() {
        this.state = {
            weather: {}
        };
    }

    /**
     * The userInput is provided by the WeatherForm
     */
    handleSubmit = (userInput) => {
        getWeatherFromInput(userInput).then((response) => {
            this.setState({ weather: response.data });
        });
    };

    render() {
        return <WeatherForm onSubmit={handleSubmit} />;
    }
}


问:
getElementById is returning null when trying to access an SVG element
I am trying to write a script that will dynamically create an SVG element and display it. However, when I set the ID of the SVG element and then try to access it with Document.getElementById(), it returns null. I am using window.onload to make sure that the document will have loaded before calling the script.

```<code><body>
  <script>
  function buildSVG(color) {
  const shape = `<rect x="0" y="0" width="90" height="90" stroke="black" fill="${color}"/>`;
  return shape;
}

function addSVG(color) {
  let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  svg.id = "svgID";
  let elem = document.getElementById("svgID");
  elem.setAttribute('width', '600');
  svg.setAttribute('height', '250');
  svg.innerHTML = buildSVG(color);
  svg.setAttribute('style', 'border: 1px solid black');
  document.body.appendChild(svg);
}
  window.onload = addSVG("cyan");
  </script>
</body>
</code>```

I would expect a cyan square to be displayed. However, I get the error "cannot read property setAttribute of null".

What can I do to fix this?

答:
When you create your svg-element you already have a reference to it in the variable you assigned. No need to get it again from the document. That would even not be possible, since it is not yet added to the document. Here is the corrected code:

function buildSVG(color) {
  const shape = `<rect x="0" y="0" width="90" height="90" stroke="black" fill="${color}"/>`;
  return shape;
}

function addSVG(color) {
  let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  svg.id = "svgID";
  svg.setAttribute('width', '600');
  svg.setAttribute('height', '250');
  svg.innerHTML = buildSVG(color);
  svg.setAttribute('style', 'border: 1px solid black');
  document.body.appendChild(svg);
}
window.onload = addSVG("cyan");

// after 1 second: get the svgID-element and change the border.
setTimeout(function(){
  document.getElementById('svgID').setAttribute('style', 'border: 1px dashed red');
}, 1000);```

Body:
I am trying to write a script that will dynamically create an SVG element and display it. However, when I set the ID of the SVG element and then try to access it with Document.getElementById(), it returns null. I am using window.onload to make sure that the document will have loaded before calling the script.

I would expect a cyan square to be displayed. However, I get the error "cannot read property setAttribute of null".

What can I do to fix this?


问:
How do you in SAS return the list of all columns in all tables in a library that contain a target value?
I am trying to map out fields I see in an application to columns in the source database using SAS EG.

If I search for 'SomeString' or someNumericValue in Library = SomeLibrary
I want the code to output a table that lists the tableName ColumnName that contains the value searched.

Proc SQL:
Select * columns C from all tables in Library L that contain the value or string = 'SomeValue'

答:
It is a nice question, i myself wanted to develop the code for me .. you can try following code to find the table names from a library, exact variable names which has the required value

Modified Code

```<code>libname temp "Y:\temp\t";
data temp.aa;
a=0;
b=0;
test="String";
run;

data temp.bb;
a=1;
c=0;
d=1;
run;

data temp.cc;
a=0;
b=1;
e=1;
run;

proc sql;
create table info
as
select memname as table, name as column from dictionary.columns
where upcase(type)="NUM" /*upcase(type)="CHAR"*/
and libname='TEMP'
order by memname;
quit;

options merror mprint nosymbolgen nomlogic;
data info1;
length coltab $1000.;
 set info;
 newtab=catx("_","TEMPT",_n_);
 condition=column||"=1"; /*Set Desired value here*/
 tab=("'"||table||"' as tab_name");
 var=("'"||column||"' as var_name");
 coltab="create table "||newtab||" as Select "||column||","||tab||","||var||" from temp."||table|| "where "||condition||";";
run;

proc sql noprint;
select count(*) into: nobs from info1;
quit;

%macro process;
%do i=1 %to &nobs;
    Data _null_;
        Set info1(firstobs=&i obs=&i);
        call symput('query',coltab);
    run;
    proc sql noprint;
        &Query;
    quit;
%end;
%mend;

%process;

proc sql noprint;
select distinct memname into :gt separated by " " from dictionary.columns where memname like '%TEMPT%';
quit;

%macro split(var);
%let var_c=%sysfunc(countw(&var));
%do i=1 %to &var_c;
    %let var_t=%sysfunc(scan(&var,&i));

    proc sql noprint;
    select count(*) into :cnt from &var_t;
    quit;

    %if &cnt=0 %then
    %do;
        proc datasets lib=work nolist;
        delete &var_t;
        quit;
        run;
    %end;
%end;
%mend split;

%split(&gt);

proc sql noprint;
select distinct memname into :gt0 separated by " " from dictionary.columns where memname like '%TEMPT%';
quit;

data all;
 set &gt0;
 keep tab_name var_name;
run;

proc sort data=all; by tab_name; run;

data final;
length vars $100.;
 set all;
  by tab_name;
  retain vars '';
  if first.tab_name then vars=var_name;
  else vars=catx(",",vars,var_name);
  if last.tab_name;
  drop var_name;
run;

proc print data=final; run;
</code>```

Body:
It is a nice question, i myself wanted to develop the code for me .. you can try following code to find the table names from a library, exact variable names which has the required value

Modified Code

libname temp "Y:\temp\t";
data temp.aa;
a=0;
b=0;
test="String";
run;

data temp.bb;
a=1;
c=0;
d=1;
run;

data temp.cc;
a=0;
b=1;
e=1;
run;

proc sql;
create table info
as
select memname as table, name as column from dictionary.columns
where upcase(type)="NUM" /*upcase(type)="CHAR"*/
and libname='TEMP'
order by memname;
quit;

options merror mprint nosymbolgen nomlogic;
data info1;
length coltab $1000.;
 set info;
 newtab=catx("_","TEMPT",_n_);
 condition=column||"=1"; /*Set Desired value here*/
 tab=("'"||table||"' as tab_name");
 var=("'"||column||"' as var_name");
 coltab="create table "||newtab||" as Select "||column||","||tab||","||var||" from temp."||table|| "where "||condition||";";
run;

proc sql noprint;
select count(*) into: nobs from info1;
quit;

%macro process;
%do i=1 %to &nobs;
    Data _null_;
        Set info1(firstobs=&i obs=&i);
        call symput('query',coltab);
    run;
    proc sql noprint;
        &Query;
    quit;
%end;
%mend;

%process;

proc sql noprint;
select distinct memname into :gt separated by " " from dictionary.columns where memname like '%TEMPT%';
quit;

%macro split(var);
%let var_c=%sysfunc(countw(&var));
%do i=1 %to &var_c;
    %let var_t=%sysfunc(scan(&var,&i));

    proc sql noprint;
    select count(*) into :cnt from &var_t;
    quit;

    %if &cnt=0 %then
    %do;
        proc datasets lib=work nolist;
        delete &var_t;
        quit;
        run;
    %end;
%end;
%mend split;

%split(&gt);

proc sql noprint;
select distinct memname into :gt0 separated by " " from dictionary.columns where memname like '%TEMPT%';
quit;

data all;
 set &gt0;
 keep tab_name var_name;
run;

proc sort data=all; by tab_name; run;

data final;
length vars $100.;
 set all;
  by tab_name;
  retain vars '';
  if first.tab_name then vars=var_name;
  else vars=catx(",",vars,var_name);
  if last.tab_name;
  drop var_name;
run;

proc print data=final; run;