问:
Unable to import CSV data into MySQL database with Python
Next piece of Python source code I use to import data from CSV file into MySql.
The installed versions in use are: MySql 5.7 and Python2.7
Furthermore, the table has 3 columns. One ID column (auto increment) and two text columns: Firstname and lastname.

The matter seems to go wrong around the SQL statement. In particular the "%s" bit.

Literally, I have done everything with punctuates like: ",' and `. E.g 's', "s", ("s") etc.

Also I have searched and used various source code snippets. All of it failed. Even I doubted the quality of my CSV file. However, importing that via e.g. MySql workbench works fine.
Ploughing my way through I managed to get data in MySql when I add for instance some  plain example values in the source code. So technically everything seems to be fine. It is just parsing which fails...

Please help. Most probably I am overlooking something simple but it drives me utterly crazy...

```<code>import mysql.connector as mysql
import csv

db = mysql.connect(
    host = "xxxx",
    user = "xxxx",
    passwd = "xxxx",
    database = "abc"
)

cursor = db.cursor()

ifile  = open('/tmp/import.csv', "rb")
read = csv.reader(ifile)

for row in ifile:
    print row

    sql = "INSERT INTO Names(Firstname, Lastname) VALUES(%s, %s)"
    cursor.execute(sql, row)

    db.commit()

print(cursor.rowcount, "record inserted")
</code>```

What I would expect to happen is dat the data in the CSV is parsed into MySQL.
The error message I receive is:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s, %s, %s)' at line 1

Thanks for any hint, clue and/or solution!!

答:
Assuming you are reading the csv file correctly and you have same parameters required within the query try replacing this line

```<code>cursor.execute(sql, row)
</code>```

to

```<code>cursor.execute(sql, tuple(row))
</code>```

Body:
Next piece of Python source code I use to import data from CSV file into MySql.
The installed versions in use are: MySql 5.7 and Python2.7
Furthermore, the table has 3 columns. One ID column (auto increment) and two text columns: Firstname and lastname.

The matter seems to go wrong around the SQL statement. In particular the "%s" bit.

Literally, I have done everything with punctuates like: ",' and `. E.g 's', "s", ("s") etc.

Also I have searched and used various source code snippets. All of it failed. Even I doubted the quality of my CSV file. However, importing that via e.g. MySql workbench works fine.
Ploughing my way through I managed to get data in MySql when I add for instance some  plain example values in the source code. So technically everything seems to be fine. It is just parsing which fails...

Please help. Most probably I am overlooking something simple but it drives me utterly crazy...

import mysql.connector as mysql
import csv

db = mysql.connect(
    host = "xxxx",
    user = "xxxx",
    passwd = "xxxx",
    database = "abc"
)

cursor = db.cursor()

ifile  = open('/tmp/import.csv', "rb")
read = csv.reader(ifile)

for row in ifile:
    print row

    sql = "INSERT INTO Names(Firstname, Lastname) VALUES(%s, %s)"
    cursor.execute(sql, row)

    db.commit()

print(cursor.rowcount, "record inserted")

What I would expect to happen is dat the data in the CSV is parsed into MySQL.
The error message I receive is:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s, %s, %s)' at line 1

Thanks for any hint, clue and/or solution!!

Body:
Assuming you are reading the csv file correctly and you have same parameters required within the query try replacing this line

cursor.execute(sql, row)

to

cursor.execute(sql, tuple(row))


来源: stackexchange

问:
How does Jira link to git?
We are using Jira and have our code in a Git (1.7.4.1) repository.  I see that there is a Git plugin for Jira (4.0.1), but I'm not able to figure out from the web site how we can associate a branch or different revisions with Jira tasks.  Assuming we install the plugin into Jira, can someone provide some step-by-step instructions for a developer to answer

When we commit code, how do we associate that with a Jira task?

When we create a branch, how do we associate that with a Jira task?

答: For 1, you specify the JIRA issue# in the commit comment. </p>

ContentLicense: CC BY-SA 3.0

Title: How does Jira link to git?


问:
How do i render the json data on the canvas?
I just found a solution here about how to parse json data in flutter and everything is working well. Now how can i render them on my mobile screen?

I tried to make method after return statement and then call a list.builder inisde it but i couldn't made it.

```<code>import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(PostHome());

class PostHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("My Test"),),
      body: PostScreen(),

      ),
    );
  }
}

class PostScreen extends StatefulWidget {
  @override
  _PostScreenState createState() => _PostScreenState();
}

class _PostScreenState extends State<PostScreen> {

  List<Post> _postList =new List<Post>();

  Future<List<Post> > fetchPost() async {
    final response =
    await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

    if (response.statusCode == 200) {
      // If the call to the server was successful, parse the JSON
      List<dynamic> values=new List<dynamic>();
      values = json.decode(response.body);
      if(values.length>0){
        for(int i=0;i<values.length;i++){
          if(values[i]!=null){
            Map<String,dynamic> map=values[i];
            _postList.add(Post.fromJson(map));
            print('${map['link']}');
          }
        }
      }
      return _postList;

    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load post');
    }
  }
  @override
  Widget build(BuildContext context) {
    return Container(

    );
  }

      @override
      void initState() {
        fetchPost();
      }

}

class Post {

  final int id;
  String title;
  String link;
  String sourceurl;

  Post({this.id, this.title, this.link, this.sourceurl});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
        id: json['id'],
        title: json['title'].toString(),
        link: json['link'].toString(),
    );
  }
}
</code>```

the problem is that i don't know what i need to call inside my list.

Any help will be appreciated.

Thanks in advance.

答:
You should take a look at using the FutureBuilder widget.</p>

```<code>import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(PostHome());

class PostHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("My Test"),
        ),
        body: PostScreen(),
      ),
    );
  }
}

class PostScreen extends StatefulWidget {
  @override
  _PostScreenState createState() => _PostScreenState();
}

class _PostScreenState extends State<PostScreen> {
  List<Post> _postList = new List<Post>();

  Future<List<Post>> fetchPost() async {
    final response =
    await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

    if (response.statusCode == 200) {
      // If the call to the server was successful, parse the JSON
      List<dynamic> values = new List<dynamic>();
      values = json.decode(response.body);
      if (values.length > 0) {
        for (int i = 0; i < values.length; i++) {
          if (values[i] != null) {
            Map<String, dynamic> map = values[i];
            _postList.add(Post.fromJson(map));
            print('${map['link']}');
          }
        }
      }
      return _postList;
    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load post');
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Post>>(
      future: fetchPost(),
      builder: (_, AsyncSnapshot<List<Post>> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(child: CircularProgressIndicator());
        }

        return ListView.builder(
          itemCount: snapshot.data.length,
          itemBuilder: (_, index) {
            final post = snapshot.data[index];
            return ListTile(
              title: Text(post.title),
            );
          },
        );
      },
    );
  }

  @override
  void initState() {
    super.initState();
    fetchPost();
  }
}

class Post {
  final int id;
  String title;
  String link;
  String sourceurl;

  Post({this.id, this.title, this.link, this.sourceurl});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title']['rendered'].toString(),
      link: json['link'].toString(),
    );
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I just found a solution here about how to parse json data in flutter and everything is working well. Now how can i render them on my mobile screen?

I tried to make method after return statement and then call a list.builder inisde it but i couldn't made it.

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(PostHome());

class PostHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("My Test"),),
      body: PostScreen(),

      ),
    );
  }
}

class PostScreen extends StatefulWidget {
  @override
  _PostScreenState createState() => _PostScreenState();
}

class _PostScreenState extends State<PostScreen> {

  List<Post> _postList =new List<Post>();

  Future<List<Post> > fetchPost() async {
    final response =
    await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

    if (response.statusCode == 200) {
      // If the call to the server was successful, parse the JSON
      List<dynamic> values=new List<dynamic>();
      values = json.decode(response.body);
      if(values.length>0){
        for(int i=0;i<values.length;i++){
          if(values[i]!=null){
            Map<String,dynamic> map=values[i];
            _postList.add(Post.fromJson(map));
            print('${map['link']}');
          }
        }
      }
      return _postList;

    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load post');
    }
  }
  @override
  Widget build(BuildContext context) {
    return Container(

    );
  }

      @override
      void initState() {
        fetchPost();
      }

}

class Post {

  final int id;
  String title;
  String link;
  String sourceurl;

  Post({this.id, this.title, this.link, this.sourceurl});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
        id: json['id'],
        title: json['title'].toString(),
        link: json['link'].toString(),
    );
  }
}

the problem is that i don't know what i need to call inside my list.

Any help will be appreciated.

Thanks in advance.

Body:
You should take a look at using the FutureBuilder widget.

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(PostHome());

class PostHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("My Test"),
        ),
        body: PostScreen(),
      ),
    );
  }
}

class PostScreen extends StatefulWidget {
  @override
  _PostScreenState createState() => _PostScreenState();
}

class _PostScreenState extends State<PostScreen> {
  List<Post> _postList = new List<Post>();

  Future<List<Post>> fetchPost() async {
    final response =
    await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

    if (response.statusCode == 200) {
      // If the call to the server was successful, parse the JSON
      List<dynamic> values = new List<dynamic>();
      values = json.decode(response.body);
      if (values.length > 0) {
        for (int i = 0; i < values.length; i++) {
          if (values[i] != null) {
            Map<String, dynamic> map = values[i];
            _postList.add(Post.fromJson(map));
            print('${map['link']}');
          }
        }
      }
      return _postList;
    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load post');
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Post>>(
      future: fetchPost(),
      builder: (_, AsyncSnapshot<List<Post>> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(child: CircularProgressIndicator());
        }

        return ListView.builder(
          itemCount: snapshot.data.length,
          itemBuilder: (_, index) {
            final post = snapshot.data[index];
            return ListTile(
              title: Text(post.title),
            );
          },
        );
      },
    );
  }

  @override
  void initState() {
    super.initState();
    fetchPost();
  }
}

class Post {
  final int id;
  String title;
  String link;
  String sourceurl;

  Post({this.id, this.title, this.link, this.sourceurl});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title']['rendered'].toString(),
      link: json['link'].toString(),
    );
  }
}


问:
laravel, how to use controller store Action to save objects in cascade
I'm working on an app that requires multi-authentication, I used creative-tim preset for the dashboard (providing that creative-tim uses the "User" name for storing users in the dashboard) I created on top of that an Admin table that has a one-to-one relationship with the User table, and created the appropriate middleware to restrict access to my "Admin-only" views and used tinker to create an Admin and link it to a test everything.
the problem now is that I want to automate the creation of the admin relationship with the user through a registration form, only problem is, the creative-tim template I'm using doesn't follow the laravel docs so I couldn't understand it and I don't know how to link an "Admin" model to the created "User".

Here's a part of the database/model:
User(id,name,email,email_verified_at,password,rememberToken,timestamps)
Admin(id,user_id,role,timestamps)

the way they used is (obviously store) but they used a UserRequest and User Object, I tried doing this:

```<code>        $Admin = new Admin();
        $Admin->role="Admin";
        $Admin->user_id = $model->id;
        $Admin->save();
</code>```

here's the original function I found

```<code>    public function store(UserRequest $request, User $model)
    {
        $model->create($request->merge(['password' =>Hash::make($request->get('password'))])->all());
  return redirect()->route('user.index')->withStatus(__('User successfully created.'));
    }
</code>```

答:
I actually found a solution for the problem (that wasn't my preferred) so I created a user normally and got the id, used it to create an Admin, Works Perfectly after validation</p>

```<code>public function store(UserRequest $request, User $model)
    {
         //validation parameters

         $item = new User();
        $item->name = request('name');
        $item->email = request('email');
        $item->password = Hash::make(request('password'));
        $item->save();

        $admin = new Admin();
        $admin->user_id = $item->id;
        $admin->role ="SuperAdmin";
        $admin->save();
        return redirect()->route('user.index')->withStatus(__('User successfully created.'));
    }

</code>```

Body:
I'm working on an app that requires multi-authentication, I used creative-tim preset for the dashboard (providing that creative-tim uses the "User" name for storing users in the dashboard) I created on top of that an Admin table that has a one-to-one relationship with the User table, and created the appropriate middleware to restrict access to my "Admin-only" views and used tinker to create an Admin and link it to a test everything.
the problem now is that I want to automate the creation of the admin relationship with the user through a registration form, only problem is, the creative-tim template I'm using doesn't follow the laravel docs so I couldn't understand it and I don't know how to link an "Admin" model to the created "User".

Here's a part of the database/model:
User(id,name,email,email_verified_at,password,rememberToken,timestamps)
Admin(id,user_id,role,timestamps)

the way they used is (obviously store) but they used a UserRequest and User Object, I tried doing this:

        $Admin = new Admin();
        $Admin->role="Admin";
        $Admin->user_id = $model->id;
        $Admin->save();

here's the original function I found

    public function store(UserRequest $request, User $model)
    {
        $model->create($request->merge(['password' =>Hash::make($request->get('password'))])->all());
  return redirect()->route('user.index')->withStatus(__('User successfully created.'));
    }

Body:
I actually found a solution for the problem (that wasn't my preferred) so I created a user normally and got the id, used it to create an Admin, Works Perfectly after validation

public function store(UserRequest $request, User $model)
    {
         //validation parameters

         $item = new User();
        $item->name = request('name');
        $item->email = request('email');
        $item->password = Hash::make(request('password'));
        $item->save();

        $admin = new Admin();
        $admin->user_id = $item->id;
        $admin->role ="SuperAdmin";
        $admin->save();
        return redirect()->route('user.index')->withStatus(__('User successfully created.'));
    }


问:
Using Smart Pointers
I am working on a legacy C++ app which has the following function,

```<code>char* CreateNewString (const char* node)
{
   int len = (int) strlen(node) + 1;
   char * ptr = new char [len];
   strcpy_s(ptr, len, node);
   return ptr;
}
</code>```

This function is called from many classes in the app and here's an example use case.

```<code>char * nodeID = obj.CreateNewString(process->GetNodeID());
</code>```

The app calls a different process and get a node ID as char pointer and then passes it to CreateNewString function to dynamically allocate memory for a new string.

Nowhere in the app after the above call, it's deleting the memory. From what I observe, there's a definite memory leak here.

I think there're few ways of resolving this issue. But I want to explore using the smart pointers in C++11 first before trying anything else.

What I Tried:

So I came up with following function:

```<code>  char* CreateNewString (const char* node)
  {
       int len = (int) strlen(node) + 1;
       shared_ptr<char> ptr (new char [len](), [](char* p) {delete [] p;});
       strcpy_s(ptr.get(), len, node);
       return ptr.get();
    }
</code>```

The goal is to keep function signature the same, i.e. it returns a char pointer, so that I don't have to make changes at all calling places.

The above is not working as ptr is released as it's declared inside the scope of this function.

My goal is to:

Use C++ 11 smart pointers to achieve this with minimum code changes to the existing application.

An alternative way I am aware of is to dynamically initialize array in calling places itself and then delete it before end of that scope. But I want to explore new C++ features before going back to traditional C++ way. BTW, I am not interested in exploring std::string at this point.

答:
You could:

return the shared_ptr

return a std::string

leave everything as it is

Those are your options.

Title: Using Smart Pointers

Body:
I am working on a legacy C++ app which has the following function,

char* CreateNewString (const char* node)
{
   int len = (int) strlen(node) + 1;
   char * ptr = new char [len];
   strcpy_s(ptr, len, node);
   return ptr;
}

This function is called from many classes in the app and here's an example use case.

char * nodeID = obj.CreateNewString(process->GetNodeID());

The app calls a different process and get a node ID as char pointer and then passes it to CreateNewString function to dynamically allocate memory for a new string.

Nowhere in the app after the above call, it's deleting the memory. From what I observe, there's a definite memory leak here.

I think there're few ways of resolving this issue. But I want to explore using the smart pointers in C++11 first before trying anything else.

What I Tried:

So I came up with following function:

  char* CreateNewString (const char* node)
  {
       int len = (int) strlen(node) + 1;
       shared_ptr<char> ptr (new char [len](), [](char* p) {delete [] p;});
       strcpy_s(ptr.get(), len, node);
       return ptr.get();
    }

The goal is to keep function signature the same, i.e. it returns a char pointer, so that I don't have to make changes at all calling places.

The above is not working as ptr is released as it's declared inside the scope of this function.

My goal is to:

Use C++ 11 smart pointers to achieve this with minimum code changes to the existing application.

An alternative way I am aware of is to dynamically initialize array in calling places itself and then delete it before end of that scope. But I want to explore new C++ features before going back to traditional C++ way. BTW, I am not interested in exploring std::string at this point.


问:
How to play audio file in asp.net
i have a grid in my page...

grid consists of 2 columns like Songname and play(linkbutton column)

when i click play of the particular row, it should play that particular song in other web page

the song should play with the help of object tag(means it should have all options like next, prev,seek in the player)

i took a small above example to explain my problem overall the senario explained above matches in my project

Please help iam stuck up eith this problem from pat one week, i googled many times, iam not getting the exact answer

sorry for bad english

Thank you in advance

答:
function zvukkonj() {
    var audio = new Audio("konjz.mp3");
    audio.play();
}
function opiskonj() {
    alert("konj je to i to");
}```

Title: How to play audio file in asp.net


问:
How do I make the program do something when an object is destroyed?
I have plane(as in air plane) objects in my program, they get destroyed when bullets hit them but they also get destroyed after 5 seconds, when they exit the screen.

I also have a health script that resets the whole thing when it goes down to 0, and I want to remove a point every time the object is destroyed, but only when off screen. So I keep the scripts separate.

I use this in the ships spawn script to destroy them after 5 seconds, simple enough.

```<code>Destroy(spawnedPlane, 5f);
</code>```

It would be perfect if I could just have some code that does "Destroy this object after X seconds AND add this to this value". Because as I understand it, "destroy" only accepts 2 parameters and nothing else.

Surely it is possible but I am at a loss. Still very new to this. Sorry if this is very unclear but I barely know what I'm doing myself.

答:
If it was me I would surely go with events as suggested by CaTs.

Coroutine are another way to do that, but events are better <s>in general</s> at least in this case. Also using a Coroutine for just one Invoke is a bit an overkill (and unity Coroutines are a bit not performant.) Also the coroutine must be outside of the object you want to destroy because Unity Coroutines die when their MonoBehaviour is destroyed.

If you are still uncomfortable with events you...

<s>well you should overcome it and try them anyway.</s>

You could take a shortcut you can use More Effective Coroutine - Free.

And launch this code:

```<code>Timing.CallDelayed(5f, DestroyAndRemoveHP());
</code>```

Basically this will run your logic with the delay you want to apply.

DestroyAndRemoveHP will be your method to destroy the platform and do anything else you like.

Full method description.

On the plus side you will start using MEC that are better than unity coroutine, but learning events makes you also a better programmer. You might do both.

Body:
I have plane(as in air plane) objects in my program, they get destroyed when bullets hit them but they also get destroyed after 5 seconds, when they exit the screen.

I also have a health script that resets the whole thing when it goes down to 0, and I want to remove a point every time the object is destroyed, but only when off screen. So I keep the scripts separate.

I use this in the ships spawn script to destroy them after 5 seconds, simple enough.

Destroy(spawnedPlane, 5f);

It would be perfect if I could just have some code that does "Destroy this object after X seconds AND add this to this value". Because as I understand it, "destroy" only accepts 2 parameters and nothing else.

Surely it is possible but I am at a loss. Still very new to this. Sorry if this is very unclear but I barely know what I'm doing myself.

Body:
If it was me I would surely go with events as suggested by CaTs.

Coroutine are another way to do that, but events are better <s>in general</s> at least in this case. Also using a Coroutine for just one Invoke is a bit an overkill (and unity Coroutines are a bit not performant.) Also the coroutine must be outside of the object you want to destroy because Unity Coroutines die when their MonoBehaviour is destroyed.

If you are still uncomfortable with events you...

<s>well you should overcome it and try them anyway.</s>

You could take a shortcut you can use More Effective Coroutine - Free.

And launch this code:

Timing.CallDelayed(5f, DestroyAndRemoveHP());

Basically this will run your logic with the delay you want to apply.

DestroyAndRemoveHP will be your method to destroy the platform and do anything else you like.

Full method description.

On the plus side you will start using MEC that are better than unity coroutine, but learning events makes you also a better programmer. You might do both.


问:
Buffered files (for faster disk access)
I am working with large files and writing directly to disk is slow. Because the file is large I cannot load it in a TMemoryStream.

TFileStream is not buffered so I want to know if there is a custom library that can offer buffered streams or should I rely only on the buffering offered by OS. Is the OS buffering reliable? I mean if the cache is full an old file (mine) might be flushed from cache in order to make room for a new file.

My file is in the GB range. It contains millions of records. Unfortunately, the records are not of fix size. So, I have to do millions of readings (between 4 and 500 bytes). The reading (and the writing) is sequential. I don't jump up and down into the file (which I think is ideal for buffering).

In the end, I have to write such file back to disk (again millions of small writes).

David provided the his personal library that provides buffered disk access.

```<code>   Speed tests:
     Input file: 317MB.SFF
     Delphi stream: 9.84sec
     David's stream: 2.05sec
     ______________________________________

   More tests:
     Input file: input2_700MB.txt
     Lines: 19 millions
     Compiler optimization: ON
     I/O check: On
     FastMM: release mode
     **HDD**

     Reading: **linear** (ReadLine) (PS: multiply time with 10)
      We see clear performance drop at 8KB. Recommended 16 or 32KB
        Time: 618 ms  Cache size: 64KB.
        Time: 622 ms  Cache size: 128KB.
        Time: 622 ms  Cache size: 24KB.
        Time: 622 ms  Cache size: 32KB.
        Time: 622 ms  Cache size: 64KB.
        Time: 624 ms  Cache size: 256KB.
        Time: 625 ms  Cache size: 18KB.
        Time: 626 ms  Cache size: 26KB.
        Time: 626 ms  Cache size: 1024KB.
        Time: 626 ms  Cache size: 16KB.
        Time: 628 ms  Cache size: 42KB.
        Time: 644 ms  Cache size: 8KB.      <--- no difference until 8K
        Time: 664 ms  Cache size: 4KB.
        Time: 705 ms  Cache size: 2KB.
        Time: 791 ms  Cache size: 1KB.
        Time: 795 ms  Cache size: 1KB.

      **SSD**
      We see a small improvement as we go towards higher buffers. Recommended 16 or 32KB
        Time: 610 ms  Cache size: 128KB.
        Time: 611 ms  Cache size: 256KB.
        Time: 614 ms  Cache size: 32KB.
        Time: 623 ms  Cache size: 16KB.
        Time: 625 ms  Cache size: 66KB.
        Time: 639 ms  Cache size: 8KB.       <--- definitively not good with 8K
        Time: 660 ms  Cache size: 4KB.
     ______

     Reading: **Random** (ReadInteger) (100000 reads)
     SSD
       Time: 064 ms. Cache size: 1KB.   Count: 100000.  RAM: 13.27 MB         <-- probably the best buffer size for ReadInteger is 4bytes!
       Time: 067 ms. Cache size: 2KB.   Count: 100000.  RAM: 13.27 MB
       Time: 080 ms. Cache size: 4KB.   Count: 100000.  RAM: 13.27 MB
       Time: 098 ms. Cache size: 8KB.   Count: 100000.  RAM: 13.27 MB
       Time: 140 ms. Cache size: 16KB.  Count: 100000.  RAM: 13.27 MB
       Time: 213 ms. Cache size: 32KB.  Count: 100000.  RAM: 13.27 MB
       Time: 360 ms. Cache size: 64KB.  Count: 100000.  RAM: 13.27 MB
       Conclusion: don't use it for "random" reading
</code>```

Update 2020:

When reading sequentially, the new System.Classes.TBufferedFileStream seems to be 70% faster than the library presented above.

答:
The TFileStream class internally uses the CreateFile function which always uses a buffer to manage the file, unless which you specify the FILE_FLAG_NO_BUFFERING flag (be aware  which you can't specify this flag directly using the TFileStream). for
more information you can check these links

CreateFile Function

Windows File Buffering

also you can try the TGpHugeFileStream which is part of the GpHugeFile unit from Primoz Gabrijelcic.

Title: Buffered files (for faster disk access)

Body:
I am working with large files and writing directly to disk is slow. Because the file is large I cannot load it in a TMemoryStream.

TFileStream is not buffered so I want to know if there is a custom library that can offer buffered streams or should I rely only on the buffering offered by OS. Is the OS buffering reliable? I mean if the cache is full an old file (mine) might be flushed from cache in order to make room for a new file.

My file is in the GB range. It contains millions of records. Unfortunately, the records are not of fix size. So, I have to do millions of readings (between 4 and 500 bytes). The reading (and the writing) is sequential. I don't jump up and down into the file (which I think is ideal for buffering).

In the end, I have to write such file back to disk (again millions of small writes).

David provided the his personal library that provides buffered disk access.

   Speed tests:
     Input file: 317MB.SFF
     Delphi stream: 9.84sec
     David's stream: 2.05sec
     ______________________________________

   More tests:
     Input file: input2_700MB.txt
     Lines: 19 millions
     Compiler optimization: ON
     I/O check: On
     FastMM: release mode
     **HDD**

     Reading: **linear** (ReadLine) (PS: multiply time with 10)
      We see clear performance drop at 8KB. Recommended 16 or 32KB
        Time: 618 ms  Cache size: 64KB.
        Time: 622 ms  Cache size: 128KB.
        Time: 622 ms  Cache size: 24KB.
        Time: 622 ms  Cache size: 32KB.
        Time: 622 ms  Cache size: 64KB.
        Time: 624 ms  Cache size: 256KB.
        Time: 625 ms  Cache size: 18KB.
        Time: 626 ms  Cache size: 26KB.
        Time: 626 ms  Cache size: 1024KB.
        Time: 626 ms  Cache size: 16KB.
        Time: 628 ms  Cache size: 42KB.
        Time: 644 ms  Cache size: 8KB.      <--- no difference until 8K
        Time: 664 ms  Cache size: 4KB.
        Time: 705 ms  Cache size: 2KB.
        Time: 791 ms  Cache size: 1KB.
        Time: 795 ms  Cache size: 1KB.

      **SSD**
      We see a small improvement as we go towards higher buffers. Recommended 16 or 32KB
        Time: 610 ms  Cache size: 128KB.
        Time: 611 ms  Cache size: 256KB.
        Time: 614 ms  Cache size: 32KB.
        Time: 623 ms  Cache size: 16KB.
        Time: 625 ms  Cache size: 66KB.
        Time: 639 ms  Cache size: 8KB.       <--- definitively not good with 8K
        Time: 660 ms  Cache size: 4KB.
     ______

     Reading: **Random** (ReadInteger) (100000 reads)
     SSD
       Time: 064 ms. Cache size: 1KB.   Count: 100000.  RAM: 13.27 MB         <-- probably the best buffer size for ReadInteger is 4bytes!
       Time: 067 ms. Cache size: 2KB.   Count: 100000.  RAM: 13.27 MB
       Time: 080 ms. Cache size: 4KB.   Count: 100000.  RAM: 13.27 MB
       Time: 098 ms. Cache size: 8KB.   Count: 100000.  RAM: 13.27 MB
       Time: 140 ms. Cache size: 16KB.  Count: 100000.  RAM: 13.27 MB
       Time: 213 ms. Cache size: 32KB.  Count: 100000.  RAM: 13.27 MB
       Time: 360 ms. Cache size: 64KB.  Count: 100000.  RAM: 13.27 MB
       Conclusion: don't use it for "random" reading

Update 2020:

When reading sequentially, the new System.Classes.TBufferedFileStream seems to be 70% faster than the library presented above.


问:
How get properties from object in Laravel
I am beginner in Laravel. I use Laravel 5.8 in my project.

I have this object:

```<code>NominatimAddress {#1146 ▼
  -attribution: "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright"
  -category: "building"
  -displayName: "99, 9 Maja, Janowo, Olsztyn, powiat pomorski, pomorskie, "
  -osmType: "way"
  -osmId: 142789154
  -type: "yes"
  -coordinates: Coordinates {#1147 ▼
    -latitude: 51.51171143
    -longitude: 11.4023121
  }
  -bounds: Bounds {#1148 ▶}
  -adminLevels: AdminLevelCollection {#1149 ▶}
  -country: Country {#1152 ▶}
  -timezone: null
  -providedBy: "nominatim"
}
</code>```

How can I get latitude and longitude from this object?

答:
As I can see, you are using Geocoder library. So, NominatimAddress extends Address, which have following method:

```<code>public function getCoordinates()
{
    return $this->coordinates;
}
</code>```

And as Bogdan commented, coordinates are incapsulated into Coordinates class, which has accessors for latitude and longitude.

Then you can try:

```<code>$lat = $object->getCoordinates()->getLatitude();
$lon = $object->getCoordinates()->getLongitude();
</code>```

Body:
I am beginner in Laravel. I use Laravel 5.8 in my project.

I have this object:

NominatimAddress {#1146 ▼
  -attribution: "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright"
  -category: "building"
  -displayName: "99, 9 Maja, Janowo, Olsztyn, powiat pomorski, pomorskie, "
  -osmType: "way"
  -osmId: 142789154
  -type: "yes"
  -coordinates: Coordinates {#1147 ▼
    -latitude: 51.51171143
    -longitude: 11.4023121
  }
  -bounds: Bounds {#1148 ▶}
  -adminLevels: AdminLevelCollection {#1149 ▶}
  -country: Country {#1152 ▶}
  -timezone: null
  -providedBy: "nominatim"
}

How can I get latitude and longitude from this object?

Body:
As I can see, you are using Geocoder library. So, NominatimAddress extends Address, which have following method:

public function getCoordinates()
{
    return $this->coordinates;
}

And as Bogdan commented, coordinates are incapsulated into Coordinates class, which has accessors for latitude and longitude.

Then you can try:

$lat = $object->getCoordinates()->getLatitude();
$lon = $object->getCoordinates()->getLongitude();


问:
My JSP page is not fatching data from database. What should I do to Improve this?
I have a Spring application, in which CRUD operation is being performed. I am unable to fetch data from database using JSP ${tempClients.firstName} code. The browser keeps printing the same code as I have written in the JSP file. I have connectivity with Database. Which are of code should I consider to check? The console is not throwing any errors.

```<code><c:forEach var="tempClients" items="${clientsModel}">
   <tr>
       <td class="trtd">${tempClients.firstName}</td>
       <td class="trtd">${tempClients.lastName}</td>
       <td class="trtd">${tempClients.email}</td>
       <td class="trtd">${tempClients.mobileNumber}</td>
       <td class="trtd">${tempClients.city}</td>
       <td class="trtd">${tempClients.country}</td>
       <td class="trtd">${tempClients.domain}</td>
   </tr>
</c:forEach>
</code>```

Entity Class:

```<code>@Entity
@Table(name="clients")
public class Clients {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;

    @Column(name="email")
    private String email;

    @Column(name="mobilenumber")
    private String mobileNumber;

    @Column(name="city")
    private String city;

    @Column(name="country")
    private String country;

    @Column(name="domain")
    private String domain;

    @Column(name="requirments")
    private String requirments;

    @Column(name="startdate")
    private Date startDate;

    @Column(name="enddate")
    private Date endDate;

    // Getters and Setters
}
</code>```

Output in Web-Browser

Output:

答:
Does your JSP page prints the ${tempClients.firstName}?

which may mean your JSP page is ignoring the el expression.

try this <%@ page isELIgnored="false" %>

You can also add the following to your web.xml to enable it for all pages:

```<code><jsp-config>
  <jsp-property-group>
    <url-pattern>*.jsp</url-pattern>
    <el-enabled>true</el-enabled>
    <scripting-enabled>true</scripting-enabled>
  </jsp-property-group>
</jsp-config>
</code>```

Body:
I have a Spring application, in which CRUD operation is being performed. I am unable to fetch data from database using JSP ${tempClients.firstName} code. The browser keeps printing the same code as I have written in the JSP file. I have connectivity with Database. Which are of code should I consider to check? The console is not throwing any errors.

<c:forEach var="tempClients" items="${clientsModel}">

       ${tempClients.firstName}
       ${tempClients.lastName}
       ${tempClients.email}
       ${tempClients.mobileNumber}
       ${tempClients.city}
       ${tempClients.country}
       ${tempClients.domain}

</c:forEach>

Entity Class:

@Entity
@Table(name="clients")
public class Clients {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;

    @Column(name="email")
    private String email;

    @Column(name="mobilenumber")
    private String mobileNumber;

    @Column(name="city")
    private String city;

    @Column(name="country")
    private String country;

    @Column(name="domain")
    private String domain;

    @Column(name="requirments")
    private String requirments;

    @Column(name="startdate")
    private Date startDate;

    @Column(name="enddate")
    private Date endDate;

    // Getters and Setters
}

Output in Web-Browser

Output:

Body:
Does your JSP page prints the ${tempClients.firstName}?

which may mean your JSP page is ignoring the el expression.

try this <%@ page isELIgnored="false" %>

You can also add the following to your web.xml to enable it for all pages:

<jsp-config>
  <jsp-property-group>
    <url-pattern>*.jsp</url-pattern>
    <el-enabled>true</el-enabled>
    <scripting-enabled>true</scripting-enabled>
  </jsp-property-group>
</jsp-config>


问:
detect if H2O instance is already running in R
This relates to the h2o package in R. I'm working with multiple jobs running in parallel, some may come in later than others. Is it possible to detect whether a h2o instance already exists and make a connection to that instance.

I see that if I know an instance is already running, i just do h2o.init(startH2O=FALSE), but what if I don't know that?

答:
This is what you see if you try h2o.init(start_h2o=False) in Python.
"Warning: if you don't want to start local H2O server, then use of h2o.connect()
 is preferred."


问:
Laravel: Pass a variable to a tab without using Javascript
I am building an index page in whicgh I show the orders separated in three tables: "incoming", "in_progress", "ready"

Essencially is this same table shown three times (and separated into a different tab)

```<code><table class="table table-striped table-hover dataTables-example">
    <thead class="thead-dark">
        <tr>
            <th>Id</th>
            <th>Eingang</th>
            <th>Auftrag id</th>
            <th>Ort</th>
        </tr>
    </thead>
    <tbody>
        @foreach($all_ as $element)
        @if($element->status === 'in_progress')
        <tr>
            <td>{{$element->id}}</td>
            <td class="gradeX">{!! $element->created_at->format('D j M Y, G:i:s') !!}</td>
            <td><a href="{{route('orders.show', $element->title)}}">{!! $element->title !!}</a></td>
            <td>{!! $element->address->plz->locality !!}</td>
        </tr>
        @endif
        @endforeach
    </tbody>
</table>
</code>```

I saved the table in a different file and I called it like this:  @include('dashboard.orders.includes.table_orders')

```<code>....
<div class="tab-content py-3 px-3 px-sm-0" id="nav-tabContent">
    <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
        <!-- I need to call here the partial and pass status="incoming" -->
        @include('dashboard.orders.includes.table_orders')
    </div>

    <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">
        <!-- I need to call here the partial and pass status="in progress" -->
        @include('dashboard.orders.includes.table_orders')
    </div>

    <div class="tab-pane fade" id="nav-contact" role="tabpanel" aria-labelledby="nav-contact-tab">
        <!-- I need to call here the partial and pass status="ready" -->
        @include('dashboard.orders.includes.table_orders')
    </div>
</div>
</code>```

The model looks lilke this:

```<code>$element [
    "id" => 1
    "title" => "KFZ_0001_May_2019"
    "details" => "Lorem Ipsums dolor..."
    "status" => "in progress"    // <---or incoming or ready
    "created_at" => "2019-05-31 09:14:02"
    "updated_at" => "2019-05-31 11:16:55"
    "deleted_at" => null
  ]
</code>```

The question is:

How do I call the external partial and pass the "status" variable in order to show the orders separated each in its corresponding table?

All the three tables are show in the same page!

I would like to avoid using of javascript just for that.

答:
You can pass a variable to the blade file included just by passing an array as the second parameter:

```<code><div class="tab-content py-3 px-3 px-sm-0" id="nav-tabContent">
    <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
        @include('dashboard.orders.includes.table_orders', ['status' => 'incoming'])
    </div>

    <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">
        @include('dashboard.orders.includes.table_orders', ['status' => 'in_progress'])
    </div>

    <div class="tab-pane fade" id="nav-contact" role="tabpanel" aria-labelledby="nav-contact-tab">
        @include('dashboard.orders.includes.table_orders', ['status' => 'ready'])
    </div>
</div>
</code>```

and inside your table_orders template:

```<code>@foreach($all_ as $element)
    @if($element->status === $status)
    <tr>
        {{ .. your row format }}
    </tr>
    @endif
@endforeach
</code>```

If you want to further generalize your code, without the need to repeat 3 times the same inclusion and to easily add different statuses, you could pass to the view an object such as:

```<code>$tabs = [
  ['status' => 'incoming', 'id' => 'nav-home', 'label' => 'nav-home-tab'],
  ['status' => 'in_progress', 'id' => 'nav-profile', 'label' => 'nav-profile-tab'],
  ['status' => 'ready', 'id' => 'nav-contact', 'label' => 'nav-contact-tab'],
];
</code>```

and in your view:

```<code>@foreach($tabs as $tab)
    <div class="tab-pane fade show active" id="{{ $tab['id'] }}" role="tabpanel" aria-labelledby="{{ $tab['label'] }}">
        @include('dashboard.orders.includes.table_orders', ['status' => $tab['status']])
    </div>
@endforeach
</code>```

Body:
I am building an index page in whicgh I show the orders separated in three tables: "incoming", "in_progress", "ready"

Essencially is this same table shown three times (and separated into a different tab)

            Id
            Eingang
            Auftrag id
            Ort

        @foreach($all_ as $element)
        @if($element->status === 'in_progress')

            {{$element->id}}
            {!! $element->created_at->format('D j M Y, G:i:s') !!}
            title)}}">{!! $element->title !!}
            {!! $element->address->plz->locality !!}

        @endif
        @endforeach

I saved the table in a different file and I called it like this:  @include('dashboard.orders.includes.table_orders')

....

        @include('dashboard.orders.includes.table_orders')

        @include('dashboard.orders.includes.table_orders')

        @include('dashboard.orders.includes.table_orders')

The model looks lilke this:

$element [
    "id" => 1
    "title" => "KFZ_0001_May_2019"
    "details" => "Lorem Ipsums dolor..."
    "status" => "in progress"    // <---or incoming or ready
    "created_at" => "2019-05-31 09:14:02"
    "updated_at" => "2019-05-31 11:16:55"
    "deleted_at" => null
  ]

The question is:

How do I call the external partial and pass the "status" variable in order to show the orders separated each in its corresponding table?

All the three tables are show in the same page!

I would like to avoid using of javascript just for that.

Body:
You can pass a variable to the blade file included just by passing an array as the second parameter:

<div class="tab-content py-3 px-3 px-sm-0" id="nav-tabContent">
    <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
        @include('dashboard.orders.includes.table_orders', ['status' => 'incoming'])
    </div>

    <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">
        @include('dashboard.orders.includes.table_orders', ['status' => 'in_progress'])
    </div>

    <div class="tab-pane fade" id="nav-contact" role="tabpanel" aria-labelledby="nav-contact-tab">
        @include('dashboard.orders.includes.table_orders', ['status' => 'ready'])
    </div>
</div>

and inside your table_orders template:

@foreach($all_ as $element)
    @if($element->status === $status)
    <tr>
        {{ .. your row format }}
    </tr>
    @endif
@endforeach

If you want to further generalize your code, without the need to repeat 3 times the same inclusion and to easily add different statuses, you could pass to the view an object such as:

$tabs = [
  ['status' => 'incoming', 'id' => 'nav-home', 'label' => 'nav-home-tab'],
  ['status' => 'in_progress', 'id' => 'nav-profile', 'label' => 'nav-profile-tab'],
  ['status' => 'ready', 'id' => 'nav-contact', 'label' => 'nav-contact-tab'],
];

and in your view:

@foreach($tabs as $tab)
    <div class="tab-pane fade show active" id="{{ $tab['id'] }}" role="tabpanel" aria-labelledby="{{ $tab['label'] }}">
        @include('dashboard.orders.includes.table_orders', ['status' => $tab['status']])
    </div>
@endforeach


问:
Remove drag and drop for selected cells
I've created drag and drop for my recycler view, but I want disable drag and drop option on pull of cells (it's a headers in my view). How to make them not available for drag and drop function?

Drag And drop helper

```<code>class SimpleItemTouchHelperCallback(private val mAdapter: ItemTouchHelperAdapter) : ItemTouchHelper.Callback() {
    override fun isLongPressDragEnabled() = true

    override fun isItemViewSwipeEnabled() = true

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}

    override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
        val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
        val swipeFlags = ItemTouchHelper.START or ItemTouchHelper.END

        return ItemTouchHelper.Callback.makeMovementFlags(dragFlags, swipeFlags)
    }

    override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
        mAdapter.onItemMove(viewHolder.adapterPosition, target.adapterPosition)

        return true
    }
}
</code>```

Adapter for Recyclerview

```<code>interface ItemTouchHelperAdapter {
    fun onItemMove(fromPosition: Int, toPosition: Int): Boolean
}
</code>```

Code to pair adapter to rv

```<code>val drugAndDropHandler = SimpleItemTouchHelperCallback(adapter)
ItemTouchHelper(drugAndDropHandler).attachToRecyclerView(multiple_stores_list)
</code>```

答:
Just need to override getMovementFlags

```<code>override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
    if (viewHolder.adapterPosition in 0..NOT_DRAGABLE_ITEMS_MAX_POSITION) {
        return 0
    }
}
</code>```

Title: Remove drag and drop for selected cells

Body:
I've created drag and drop for my recycler view, but I want disable drag and drop option on pull of cells (it's a headers in my view). How to make them not available for drag and drop function?

Drag And drop helper

class SimpleItemTouchHelperCallback(private val mAdapter: ItemTouchHelperAdapter) : ItemTouchHelper.Callback() {
    override fun isLongPressDragEnabled() = true

    override fun isItemViewSwipeEnabled() = true

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}

    override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
        val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
        val swipeFlags = ItemTouchHelper.START or ItemTouchHelper.END

        return ItemTouchHelper.Callback.makeMovementFlags(dragFlags, swipeFlags)
    }

    override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
        mAdapter.onItemMove(viewHolder.adapterPosition, target.adapterPosition)

        return true
    }
}

Adapter for Recyclerview

interface ItemTouchHelperAdapter {
    fun onItemMove(fromPosition: Int, toPosition: Int): Boolean
}

Code to pair adapter to rv

val drugAndDropHandler = SimpleItemTouchHelperCallback(adapter)
ItemTouchHelper(drugAndDropHandler).attachToRecyclerView(multiple_stores_list)

Body:
Just need to override getMovementFlags

override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
    if (viewHolder.adapterPosition in 0..NOT_DRAGABLE_ITEMS_MAX_POSITION) {
        return 0
    }
}


问:
banner image loads with bigger size on mobile devices
I'm using: https://ready.mobi for testing my website for all devices. I'm interested in correctly set the image on the header for the index.
Right now the image is not looking great in all devices. Also the blue and orange buttons are too close to each other, and the
image appears too big (you have to scroll to see it).

Current result:

I've set media queries to handle this. Apparently they are not working well.

https://ready.mobi/#1164495-2wd6 (enter here to check the site on different devices online)

Desired result:

https://ready.mobi/#1164490-t8g2 (enter here to check the site on different devices online)

Codepen: https://codepen.io/anon/pen/EzOONJ

```<code>.my_header_bg_color {

    /*background-color: #4FB99F;*/
    /*background-color: #00ADB5;*/
    /*background-color: #6BB983;*/
    background-color: #00AD80;

}

/* Standard media queries breakpoints */

@media (min-width: 320px) and (max-width: 480px) {
    /* smartphones, iPhone, portrait 480x320 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .productos_finales_home img {

        padding-bottom: 15px;
    }

    .my_home_banner_image {

        bottom: 0;
        top: 0;
        position: relative;
        z-index: 0;
        width: 60%;
        display: block;
        margin-right: auto;
        margin-left: 165px;
    }

    /*.my_home_banner_image {*/
    /*display: none;*/
    /*}*/
    .my_home_banner_title {
        color: white;
        font-size: 36px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        text-decoration: none;
        background-color: #969696;
        display: inline-block;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        color: #fff;
        font-weight: 700;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        text-shadow: 0 -1px 0 rgba(0, 0, 0, .25);
        letter-spacing: 0;
        line-height: 1.2;
        -webkit-font-smoothing: antialiased;
        -webkit-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -ms-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -moz-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -o-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        background-image: linear-gradient(to bottom, rgba(255, 255, 255, .09) 0%, rgba(0, 0, 0, .09) 100%);
        font-size: 1.4rem;
        padding: 22px 30px;
        border-radius: 6px;
        border: none;
    }

.my_home_banner_left {
    margin-left: 10px;
    z-index: 100;
}

.stickers_referenciales {
    margin-bottom: 5px;
}

}

@media (min-width: 481px) {
    /* portrait e-readers (Nook/Kindle), smaller tablets @ 600 or @ 640 wide. */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 40%;
        display: block;
        margin-right: auto;
        margin-left: 185px;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

}

@media (min-width: 641px) {
    /* portrait tablets, portrait iPad, landscape e-readers, landscape 800x480 or 854x480 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 70%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .my_home_banner_lef_text {
        margin-left: 10px;
        z-index: 100;
    }

}

@media (min-width: 961px) {
    /* tablet, landscape iPad, lo-res laptops ands desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 60%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

}

@media (min-width: 1025px) {
    /* big landscape tablets, laptops, and desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 55%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .subscribe_field {
        width: 350px;
    }

}

@media (min-width: 1281px) {
    /* hi-res laptops and desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 50%;
    }

    /*.my_home_banner_image_left {*/
    /*display: none;*/
    /*}*/
    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .subscribe_field {
        width: 350px;
    }
}

.center-video {
    margin: 0 auto;
    width: 400px;
}
</code>```

答:
In the html, you can specify different images for different size devices:</p>

```<code><picture>
   <source media="(max-width: 480px)" srcset="yoursourceMobile.jpg">
   <source media="(max-width: 2056px)" srcset="yoursource.jpg">
   <img src="yoursource.jpg">
</picture>
</code>```

Body:
I'm using: https://ready.mobi for testing my website for all devices. I'm interested in correctly set the image on the header for the index.
Right now the image is not looking great in all devices. Also the blue and orange buttons are too close to each other, and the
image appears too big (you have to scroll to see it).

Current result:

I've set media queries to handle this. Apparently they are not working well.

https://ready.mobi/#1164495-2wd6 (enter here to check the site on different devices online)

Desired result:

https://ready.mobi/#1164490-t8g2 (enter here to check the site on different devices online)

Codepen: https://codepen.io/anon/pen/EzOONJ

.my_header_bg_color {

    /*background-color: #4FB99F;*/
    /*background-color: #00ADB5;*/
    /*background-color: #6BB983;*/
    background-color: #00AD80;

}

/* Standard media queries breakpoints */

@media (min-width: 320px) and (max-width: 480px) {
    /* smartphones, iPhone, portrait 480x320 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .productos_finales_home img {

        padding-bottom: 15px;
    }

    .my_home_banner_image {

        bottom: 0;
        top: 0;
        position: relative;
        z-index: 0;
        width: 60%;
        display: block;
        margin-right: auto;
        margin-left: 165px;
    }

    /*.my_home_banner_image {*/
    /*display: none;*/
    /*}*/
    .my_home_banner_title {
        color: white;
        font-size: 36px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        text-decoration: none;
        background-color: #969696;
        display: inline-block;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        color: #fff;
        font-weight: 700;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        text-shadow: 0 -1px 0 rgba(0, 0, 0, .25);
        letter-spacing: 0;
        line-height: 1.2;
        -webkit-font-smoothing: antialiased;
        -webkit-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -ms-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -moz-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -o-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        background-image: linear-gradient(to bottom, rgba(255, 255, 255, .09) 0%, rgba(0, 0, 0, .09) 100%);
        font-size: 1.4rem;
        padding: 22px 30px;
        border-radius: 6px;
        border: none;
    }

.my_home_banner_left {
    margin-left: 10px;
    z-index: 100;
}

.stickers_referenciales {
    margin-bottom: 5px;
}

}

@media (min-width: 481px) {
    /* portrait e-readers (Nook/Kindle), smaller tablets @ 600 or @ 640 wide. */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 40%;
        display: block;
        margin-right: auto;
        margin-left: 185px;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

}

@media (min-width: 641px) {
    /* portrait tablets, portrait iPad, landscape e-readers, landscape 800x480 or 854x480 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 70%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .my_home_banner_lef_text {
        margin-left: 10px;
        z-index: 100;
    }

}

@media (min-width: 961px) {
    /* tablet, landscape iPad, lo-res laptops ands desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 60%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

}

@media (min-width: 1025px) {
    /* big landscape tablets, laptops, and desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 55%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .subscribe_field {
        width: 350px;
    }

}

@media (min-width: 1281px) {
    /* hi-res laptops and desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 50%;
    }

    /*.my_home_banner_image_left {*/
    /*display: none;*/
    /*}*/
    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .subscribe_field {
        width: 350px;
    }
}

.center-video {
    margin: 0 auto;
    width: 400px;
}

Body:
In the html, you can specify different images for different size devices:

<picture>
   <source media="(max-width: 480px)" srcset="yoursourceMobile.jpg">
   <source media="(max-width: 2056px)" srcset="yoursource.jpg">
   <img src="yoursource.jpg">
</picture>


问:
how to close CrossApplicationNavigation pages from script with button
On the app i'm currently developping,
I have several hyperlink to standard sap backend transaction such as BP, PDL and so on.
i'm opening them by means of CrossApplicationNavigation.
they open new tab.

on my main app, I implemented a button to close every tab and returning to root view.

I tried the following :
Script to close other tabs or browser

here is my code :

```<code>            var oCrossAppNavigator = sap.ushell.Container.getService("CrossApplicationNavigation");
            var oExtUi = oEvent.getSource().getText();
            var hash = oCrossAppNavigator.hrefForExternal({
                target: {
                    semanticObject: "ZSIMM_PDL",
                    action: "display"
                },
                params: {
                    "UtilitiesPDL": oExtUi
                }
            });
            var url = window.location.href.split("#")[0] + hash;
            this._oComponent = sap.ui.component(sap.ui.core.Component.getOwnerIdFor(this.getView()));
            this._myModel = this._oComponent.getModel("oModelWindow");
            this._myModel.setProperty("/Window", window);
            sap.m.URLHelper.redirect(url, true);
        },
</code>```

this way, i open the new tab with my semanticObject. and I register it in my Model.

the next step is the method linked with my button :

```<code>            this._myModel = this._oComponent.getModel("oModelWindow");
            var aWindow = this._myModel.getData().Window;
            aWindow.close();
</code>```

I'm loading the window of the tab I opened.
the instruction close doesn't work it writes :
"Scripts may close only the windows that were opened by it."

what I understand in CrossApplicationNavigation is that it opened a new tab and redirect by use of sap.m.URLHelper.redirect(url, true);
does the current screen before calling the new one know which page it opens ?
and this way is there a method to close it manually ?

答:
I found a solution which is the following :
when opening the crossApplicationnavigation, I put on memory the tab opened :

```<code>            var oExtUi = oEvent.getSource().getText();
            var hash = oCrossAppNavigator.hrefForExternal({
                target: {
                    semanticObject: "ZSIMM_PDL",
                    action: "display"
                },
                params: {
                    "UtilitiesPDL": oExtUi
                }
            });
            var url = window.location.href.split("#")[0] + hash;
            this._oComponent = sap.ui.component(sap.ui.core.Component.getOwnerIdFor(this.getView()));
            this._myModel = this._oComponent.getModel("oModelWindow");
            var aWindow = this._myModel.getData().Windows;
            aWindow.push(window.open(url, "_blank"));
            this._myModel.setProperty("/Windows", aWindow);
</code>```

and in the button method, I recall all tab and close them all this way :

```<code>            this._oComponent = sap.ui.component(sap.ui.core.Component.getOwnerIdFor(this.getView()));
            this._myModel = this._oComponent.getModel("oModelWindow");
            //then you can iterate over them and close them all like this:
            var oWindow = this._myModel.getData().Windows;

            for (var i = 0; i < oWindow.length; i++) {
                oWindow[i].close();
            }
</code>```

that way when clicking the button all other tab are closed.

Body:
On the app i'm currently developping,
I have several hyperlink to standard sap backend transaction such as BP, PDL and so on.
i'm opening them by means of CrossApplicationNavigation.
they open new tab.

on my main app, I implemented a button to close every tab and returning to root view.

I tried the following :
Script to close other tabs or browser

here is my code :

            var oCrossAppNavigator = sap.ushell.Container.getService("CrossApplicationNavigation");
            var oExtUi = oEvent.getSource().getText();
            var hash = oCrossAppNavigator.hrefForExternal({
                target: {
                    semanticObject: "ZSIMM_PDL",
                    action: "display"
                },
                params: {
                    "UtilitiesPDL": oExtUi
                }
            });
            var url = window.location.href.split("#")[0] + hash;
            this._oComponent = sap.ui.component(sap.ui.core.Component.getOwnerIdFor(this.getView()));
            this._myModel = this._oComponent.getModel("oModelWindow");
            this._myModel.setProperty("/Window", window);
            sap.m.URLHelper.redirect(url, true);
        },

this way, i open the new tab with my semanticObject. and I register it in my Model.

the next step is the method linked with my button :

            this._myModel = this._oComponent.getModel("oModelWindow");
            var aWindow = this._myModel.getData().Window;
            aWindow.close();

I'm loading the window of the tab I opened.
the instruction close doesn't work it writes :
"Scripts may close only the windows that were opened by it."

what I understand in CrossApplicationNavigation is that it opened a new tab and redirect by use of sap.m.URLHelper.redirect(url, true);
does the current screen before calling the new one know which page it opens ?
and this way is there a method to close it manually ?

Body:
I found a solution which is the following :
when opening the crossApplicationnavigation, I put on memory the tab opened :

            var oExtUi = oEvent.getSource().getText();
            var hash = oCrossAppNavigator.hrefForExternal({
                target: {
                    semanticObject: "ZSIMM_PDL",
                    action: "display"
                },
                params: {
                    "UtilitiesPDL": oExtUi
                }
            });
            var url = window.location.href.split("#")[0] + hash;
            this._oComponent = sap.ui.component(sap.ui.core.Component.getOwnerIdFor(this.getView()));
            this._myModel = this._oComponent.getModel("oModelWindow");
            var aWindow = this._myModel.getData().Windows;
            aWindow.push(window.open(url, "_blank"));
            this._myModel.setProperty("/Windows", aWindow);

and in the button method, I recall all tab and close them all this way :

            this._oComponent = sap.ui.component(sap.ui.core.Component.getOwnerIdFor(this.getView()));
            this._myModel = this._oComponent.getModel("oModelWindow");
            //then you can iterate over them and close them all like this:
            var oWindow = this._myModel.getData().Windows;

            for (var i = 0; i < oWindow.length; i++) {
                oWindow[i].close();
            }

that way when clicking the button all other tab are closed.


问:
browser and web server comm
how does a web server identify that the request is from a specific client? i know the communication happens through http protocol but what is it that tells the server that, for a particular request, the response needs to be sent to this client?

(i am not sure if this is too simple a question but i just want to learn something here and may benefit others like me as well)

答:
Your question is almost an exact duplicate of this question, which has some good answers.

The response goes back over the same TCP/IP connection that the request came over.

The client initiated that connection with the server's IP address and port. The server does not need to know the IP address and port of the client, because the connection is already open and ready for use.

Most[citation needed] clients don't even have a publicly accessible IP address.

Title: browser and web server comm


问:
JS search in object values
I have an array of homogeneous objects like so;

```<code>[
  {
    "foo" : "bar",
    "bar" : "sit"
  },
  {
    "foo" : "lorem",
    "bar" : "ipsum"
  },
  {
    "foo" : "dolor",
    "bar" : "amet"
  }
]
</code>```

I'd like to search these objects' values (not keys) with a keyword, and return an array of objects that contain the keyword in any of the values.

So for example, with a keyword r, I would get all the objects ("baR" in object #1, "loRem" in object #2 and "doloR" in object #3). With a keyword lo, I would get objects 2 and 3 ("LOrem" and "doLOr"), with a, I'd get objects 1 and 3, ("bAr" and "Amet"). With the keyword foo however, I would get an empty array, since "foo" is a key, and isn't found in any of the values (unlike "bar")... you get the idea.

How would I go about doing this? Thanks a lot in advance!

答:
I needed to perform a search on a large object and return the addresses of the matches, not just the matched values themselves.

This function searches an object for a string (or alternatively, uses a callback function to perform custom logic) and keeps track of where the value was found within the object. It also avoids circular references.

//Search function
var locateInObject = function(obj, key, find, result, currentLocation){
  if(obj === null) return;
  result = result||{done:[],found:{}};
  if(typeof obj == 'object'){
    result.done.push(obj);
  }
  currentLocation = currentLocation||key;
  var keys = Object.keys(obj);
  for(var k=0; k<keys.length; ++k){
    var done = false;
    for(var d=0; d<result.done.length; ++d){
      if(result.done[d] === obj[keys[k]]){
        done = true;
        break;
      }
    }
    if(!done){
      var location = currentLocation+'.'+keys[k];
      if(typeof obj[keys[k]] == 'object'){
        locateInObject(obj[keys[k]], keys[k], find, result, location)
      }else if((typeof find == 'string' && obj[keys[k]].toString().indexOf(find) > -1) || (typeof find == 'function' && find(obj[keys[k]], keys[k]))){
        result.found[location] = obj[keys[k]];
      }
    }
  }
  return result.found;
}

//Test data
var test = {
  key1: {
    keyA: 123,
    keyB: "string"
  },
  key2: {
    keyC: [
      {
        keyI: "string123",
        keyII: 2.3
      },
      "string"
    ],
    keyD: null
  },
  key3: [
    1,
    2,
    123,
    "testString"
  ],
  key4: "123string"
}
//Add a circular reference
test.key5 = test;

//Tests
console.log(locateInObject(test, 'test', 'string'))
console.log(locateInObject(test, 'test', '123'))
console.log(locateInObject(test, 'test', function(val, key){ return key.match(/key\d/) && val.indexOf('string') > -1}))```

Title: JS search in object values

Body:
I have an array of homogeneous objects like so;

[
  {
    "foo" : "bar",
    "bar" : "sit"
  },
  {
    "foo" : "lorem",
    "bar" : "ipsum"
  },
  {
    "foo" : "dolor",
    "bar" : "amet"
  }
]

I'd like to search these objects' values (not keys) with a keyword, and return an array of objects that contain the keyword in any of the values.

So for example, with a keyword r, I would get all the objects ("baR" in object #1, "loRem" in object #2 and "doloR" in object #3). With a keyword lo, I would get objects 2 and 3 ("LOrem" and "doLOr"), with a, I'd get objects 1 and 3, ("bAr" and "Amet"). With the keyword foo however, I would get an empty array, since "foo" is a key, and isn't found in any of the values (unlike "bar")... you get the idea.

How would I go about doing this? Thanks a lot in advance!


问:
Scala Swing skips repaint of the Frame
I am currently working on an implementation of the game Othello in Scala and so far it's working pretty nicely. When implementing the GUI though (using Scala Swing) I've stumbled across an issue that I can't seem to fix.

When playing against the computer opponent the Frame seems to be repainted only when the bot is done making its move.

The game is also playable through the terminal and doing so updates the Frame properly every time regardless of the player configuration (Player vs Player or Player vs Computer). Also playing player vs player using the GUI exclusively presents no issues at all.

It might be an oversight on my behalf, but so far I am unable to find a solution and would greatly appreciate any help.

So far I have tried various combinations of revalidating and repainting the individual panels, adding and removing listeners, changing my implementation of the reactor pattern to the one provided by Scala Swing, adding Thread.sleep to see if there could be a scheduling conflict of sorts.

import java.awt.Color

import othello.controller.Controller
import javax.swing.ImageIcon
import javax.swing.border.LineBorder

import scala.swing.event.MouseClicked
import scala.swing.{BorderPanel, BoxPanel, Dimension, FlowPanel, GridPanel, Label, Orientation}

class TablePanel(controller: Controller) extends FlowPanel {

  val sides = 32
  val sidesColor: Color = Color.lightGray
  val squareSize = 52

  def tableSize: Int = controller.board.size

  def edgeLength: Int = tableSize * squareSize

  def rows: BoxPanel = new BoxPanel(Orientation.Vertical) {
    background = sidesColor
    preferredSize = new Dimension(sides, edgeLength)
    contents += new Label {
      preferredSize = new Dimension(sides, sides)
    }
    contents += new GridPanel(tableSize, 1) {
      background = sidesColor
      for { i <- 1 to rows } contents += new Label(s"$i")
    }
  }

  def columns: GridPanel = new GridPanel(1, tableSize) {
    background = sidesColor
    preferredSize = new Dimension(edgeLength, sides)
    for { i <- 0 until columns } contents += new Label(s"${(i + 65).toChar}")
  }

  def table: GridPanel = new GridPanel(tableSize, tableSize) {
    background = new Color(10, 90, 10)
    for {
      col <- 0 until columns
      row <- 0 until rows
    } contents += square(col, row)
  }

  def square(row: Int, col: Int): Label = new Label {
    border = new LineBorder(new Color(30, 30, 30, 140), 1)
    preferredSize = new Dimension(squareSize, squareSize)
    icon = controller.board.valueOf(col, row) match {
      case -1 => new ImageIcon("resources/big_dot.png")
      case 0  => new ImageIcon("resources/empty.png")
      case 1  => new ImageIcon("resources/black_shadow.png")
      case 2  => new ImageIcon("resources/white_shadow.png")
    }
    listenTo(mouse.clicks)
    reactions += {
      case _: MouseClicked =>
        if (controller.options.contains((col, row))) controller.set(col, row)
        else if (controller.board.gameOver) controller.newGame()
        else controller.highlight()
    }
  }

  def redraw(): Unit = {
    contents.clear
    contents += new BorderPanel {
      add(rows, BorderPanel.Position.West)
      add(new BoxPanel(Orientation.Vertical) {
        contents += columns
        contents += table
      }, BorderPanel.Position.East)
    }
    repaint
  }
}
```

<pre class="lang-scala prettyprint-override"><code>import scala.swing._
import othello.controller._
import othello.util.Observer

import scala.swing.event.Key

class SwingGui(controller: Controller) extends Frame with Observer {

  controller.add(this)

  lazy val tablePanel = new TablePanel(controller)

  lazy val mainFrame: MainFrame = new MainFrame {
    title = "Othello"
    menuBar = menus
    contents = tablePanel
    centerOnScreen
    // peer.setAlwaysOnTop(true)
    resizable = false
    visible = true
  }

  def menus: MenuBar = new MenuBar {
    contents += new Menu("File") {
      mnemonic = Key.F
      contents += new MenuItem(Action("New Game") {
        controller.newGame()
      })
      contents += new MenuItem(Action("Quit") {
        controller.exit()
      })
    }
    contents += new Menu("Edit") {
      mnemonic = Key.E
      contents += new MenuItem(Action("Undo") {
        controller.undo()
      })
      contents += new MenuItem(Action("Redo") {
        controller.redo()
      })
    }
    contents += new Menu("Options") {
      mnemonic = Key.O
      contents += new MenuItem(Action("Highlight possible moves") {
        controller.highlight()
      })
      contents += new MenuItem(Action("Reduce board size") {
        controller.resizeBoard("-")
      })
      contents += new MenuItem(Action("Increase board size") {
        controller.resizeBoard("+")
      })
      contents += new MenuItem(Action("Reset board size") {
        controller.resizeBoard(".")
      })
      contents += new Menu("Game mode") {
        contents += new MenuItem(Action("Player vs. Computer") {
          controller.setupPlayers("1")
        })
        contents += new MenuItem(Action("Player vs. Player") {
          controller.setupPlayers("2")
        })
      }
    }
  }

  def update: Boolean = {
    tablePanel.redraw()
    mainFrame.pack
    mainFrame.centerOnScreen
    mainFrame.repaint
    true
  }
}

</code>```

The expected behavior is a repainted Frame on every turn. The actual result is the Frame only being repainted after the opponent made a move. It only happens when playing player vs bot exclusively through clicking the UI.

答:
I don't think the problem is in the code you have shown, but I would bet that you are blocking the "event dispatch thread" (the UI thread) with your AI computation for the computer player.

In a Swing app, there is a special thread called the "event dispatch thread" that is responsible for handling messages from the O/S including dealing with repaint messages. All UI event handlers will be invoked on this thread. If you use that thread to do any computations which take a long time (such as a computer move in a game like this), any UI updates will be blocked until the thread becomes free.

This tutorial has more info: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html

You need to move the AI onto a background thread and release the event dispatch thread to deal with repaints. This might be tricky to implement if you are not familiar with multi-threaded programs! Good luck.

Title: Scala Swing skips repaint of the Frame

Body:
I am currently working on an implementation of the game Othello in Scala and so far it's working pretty nicely. When implementing the GUI though (using Scala Swing) I've stumbled across an issue that I can't seem to fix.

When playing against the computer opponent the Frame seems to be repainted only when the bot is done making its move.

The game is also playable through the terminal and doing so updates the Frame properly every time regardless of the player configuration (Player vs Player or Player vs Computer). Also playing player vs player using the GUI exclusively presents no issues at all.

It might be an oversight on my behalf, but so far I am unable to find a solution and would greatly appreciate any help.

So far I have tried various combinations of revalidating and repainting the individual panels, adding and removing listeners, changing my implementation of the reactor pattern to the one provided by Scala Swing, adding Thread.sleep to see if there could be a scheduling conflict of sorts.

import java.awt.Color

import othello.controller.Controller
import javax.swing.ImageIcon
import javax.swing.border.LineBorder

import scala.swing.event.MouseClicked
import scala.swing.{BorderPanel, BoxPanel, Dimension, FlowPanel, GridPanel, Label, Orientation}

class TablePanel(controller: Controller) extends FlowPanel {

  val sides = 32
  val sidesColor: Color = Color.lightGray
  val squareSize = 52

  def tableSize: Int = controller.board.size

  def edgeLength: Int = tableSize * squareSize

  def rows: BoxPanel = new BoxPanel(Orientation.Vertical) {
    background = sidesColor
    preferredSize = new Dimension(sides, edgeLength)
    contents += new Label {
      preferredSize = new Dimension(sides, sides)
    }
    contents += new GridPanel(tableSize, 1) {
      background = sidesColor
      for { i <- 1 to rows } contents += new Label(s"$i")
    }
  }

  def columns: GridPanel = new GridPanel(1, tableSize) {
    background = sidesColor
    preferredSize = new Dimension(edgeLength, sides)
    for { i <- 0 until columns } contents += new Label(s"${(i + 65).toChar}")
  }

  def table: GridPanel = new GridPanel(tableSize, tableSize) {
    background = new Color(10, 90, 10)
    for {
      col <- 0 until columns
      row <- 0 until rows
    } contents += square(col, row)
  }

  def square(row: Int, col: Int): Label = new Label {
    border = new LineBorder(new Color(30, 30, 30, 140), 1)
    preferredSize = new Dimension(squareSize, squareSize)
    icon = controller.board.valueOf(col, row) match {
      case -1 => new ImageIcon("resources/big_dot.png")
      case 0  => new ImageIcon("resources/empty.png")
      case 1  => new ImageIcon("resources/black_shadow.png")
      case 2  => new ImageIcon("resources/white_shadow.png")
    }
    listenTo(mouse.clicks)
    reactions += {
      case _: MouseClicked =>
        if (controller.options.contains((col, row))) controller.set(col, row)
        else if (controller.board.gameOver) controller.newGame()
        else controller.highlight()
    }
  }

  def redraw(): Unit = {
    contents.clear
    contents += new BorderPanel {
      add(rows, BorderPanel.Position.West)
      add(new BoxPanel(Orientation.Vertical) {
        contents += columns
        contents += table
      }, BorderPanel.Position.East)
    }
    repaint
  }
}

import scala.swing._
import othello.controller._
import othello.util.Observer

import scala.swing.event.Key

class SwingGui(controller: Controller) extends Frame with Observer {

  controller.add(this)

  lazy val tablePanel = new TablePanel(controller)

  lazy val mainFrame: MainFrame = new MainFrame {
    title = "Othello"
    menuBar = menus
    contents = tablePanel
    centerOnScreen
    // peer.setAlwaysOnTop(true)
    resizable = false
    visible = true
  }

  def menus: MenuBar = new MenuBar {
    contents += new Menu("File") {
      mnemonic = Key.F
      contents += new MenuItem(Action("New Game") {
        controller.newGame()
      })
      contents += new MenuItem(Action("Quit") {
        controller.exit()
      })
    }
    contents += new Menu("Edit") {
      mnemonic = Key.E
      contents += new MenuItem(Action("Undo") {
        controller.undo()
      })
      contents += new MenuItem(Action("Redo") {
        controller.redo()
      })
    }
    contents += new Menu("Options") {
      mnemonic = Key.O
      contents += new MenuItem(Action("Highlight possible moves") {
        controller.highlight()
      })
      contents += new MenuItem(Action("Reduce board size") {
        controller.resizeBoard("-")
      })
      contents += new MenuItem(Action("Increase board size") {
        controller.resizeBoard("+")
      })
      contents += new MenuItem(Action("Reset board size") {
        controller.resizeBoard(".")
      })
      contents += new Menu("Game mode") {
        contents += new MenuItem(Action("Player vs. Computer") {
          controller.setupPlayers("1")
        })
        contents += new MenuItem(Action("Player vs. Player") {
          controller.setupPlayers("2")
        })
      }
    }
  }

  def update: Boolean = {
    tablePanel.redraw()
    mainFrame.pack
    mainFrame.centerOnScreen
    mainFrame.repaint
    true
  }
}

The expected behavior is a repainted Frame on every turn. The actual result is the Frame only being repainted after the opponent made a move. It only happens when playing player vs bot exclusively through clicking the UI.


问:
Why was Swift designed to not allow generics for protocols?
Why didn't the designers of Swift not allow doing:

```<code>protocol Download<T> {
    var x: T
}
</code>```

and instead force us to do:

```<code>protocol Download {
    associatedtype: T
    var x: T
}
</code>```

I suppose it's because this way you can restrict/default the associatedtypes, something that isn't possible with generic parameters at the protocol level, but is that all?

答: This is because the type must be defined before it gets compiled. This is needed because Swift is a type-safe language.

Body:
Why didn't the designers of Swift not allow doing:

protocol Download<T> {
    var x: T
}

and instead force us to do:

protocol Download {
    associatedtype: T
    var x: T
}

I suppose it's because this way you can restrict/default the associatedtypes, something that isn't possible with generic parameters at the protocol level, but is that all?


问:
Installing OpenCV
I am on Mac OSX El Capitan and am trying to install opencv. I am using homebrew with this command.

```<code>Sumant:Sumant$ brew install opencv
</code>```

The result is Warning: homebrew/science/opencv 2.4.13.2_1 is already installed

Even though it says that opencv is already installed, I can't seem to use it with python. Importing cv2 on python gives the error

```<code>>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named cv2
</code>```

Is opencv different from cv2, if so how do I download cv2 (I already tried to look up questions on stackoverflow but none of those methods work).

答:
If you are using anaconda distribution your work will be very easy. Conda installer install most packages seamlessly. For opencv you can try following command after conda installation:</p>

```<code>conda install -c menpo opencv3
conda install -c menpo opencv
</code>```

Title: Installing OpenCV

Body:
I am on Mac OSX El Capitan and am trying to install opencv. I am using homebrew with this command.

Sumant:Sumant$ brew install opencv

The result is Warning: homebrew/science/opencv 2.4.13.2_1 is already installed

Even though it says that opencv is already installed, I can't seem to use it with python. Importing cv2 on python gives the error

>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named cv2

Is opencv different from cv2, if so how do I download cv2 (I already tried to look up questions on stackoverflow but none of those methods work).

Body:
If you are using anaconda distribution your work will be very easy. Conda installer install most packages seamlessly. For opencv you can try following command after conda installation:

conda install -c menpo opencv3
conda install -c menpo opencv


问:
How do I get the URL for an image stored in a subdirectory of a google-cloud-storage bucket
I have images storied in directories within a bucket in google-cloud-storage.
The images are not publicly viewable.
It's my understanding that I can 'sign' the image and the resulting URL will be publicly viewable for a specified time.
Nothing I've tried so far, however, seems to work.
Attempts to access the URL result in a NoSuchKey error.

Here's an example of the code I've tried.  Exactly what should the second parameter be that I pass to BlobInfo.newBuilder?  The documentation says it should be the object name.  Is that just the name of the file, i.e. myimage.jpg?

URL getSignedImageUrl(String uri) {
  // ImageUploadDetails contains metadata about the image
  ImageUploadDetails imageUploadDetails = ImageUploadDetails.findByUri(uri)
  if (imageUploadDetails) {
    BlobInfo blobInfo = BlobInfo.newBuilder(BlobId.of(bucket, imageUploadDetails.thumbnailPath)).build()
    URL url = storage.signUrl(blobInfo, 60, TimeUnit.MINUTES, Storage.SignUrlOption.withV4Signature())
    return url // this URL, when converted to a String, doesn't work
} else {
  throw new ImageNotFoundException("Cannot open file: ${imageUploadDetails.thumbnailPath}")}
}
```

<p>I expect the signed URL to be available to public users for the specified amount of time.  I would like to use it as the <code>src</code> value within an <code>image</code> tag.</p>

<p>Instead, what I'm getting is:</p>

<pre class="lang-xml prettyprint-override"><code><Error>
  <Code>NoSuchKey</Code>
  <Message>The specified key does not exist.</Message>
  <Details>
  obfuscated to protect the innocent
  </Details>
</Error>
</code>```

答:
By default, the url of an object would be https://storage.googleapis.com/${bucket.name}/${blob.name}

For example:

```<code>- bucket1
  - folder1
    - image1.jpg  https://storage.googleapis.com/bucket1/folder1/image1.jpg
    - image2.jpg  https://storage.googleapis.com/bucket1/folder1/image2.jpg
- bucket2
  - image3.jpg    https://storage.googleapis.com/bucket2/image3.jpg
</code>```

Body:
I have images storied in directories within a bucket in google-cloud-storage.
The images are not publicly viewable.
It's my understanding that I can 'sign' the image and the resulting URL will be publicly viewable for a specified time.
Nothing I've tried so far, however, seems to work.
Attempts to access the URL result in a NoSuchKey error.

Here's an example of the code I've tried.  Exactly what should the second parameter be that I pass to BlobInfo.newBuilder?  The documentation says it should be the object name.  Is that just the name of the file, i.e. myimage.jpg?

URL getSignedImageUrl(String uri) {
  // ImageUploadDetails contains metadata about the image
  ImageUploadDetails imageUploadDetails = ImageUploadDetails.findByUri(uri)
  if (imageUploadDetails) {
    BlobInfo blobInfo = BlobInfo.newBuilder(BlobId.of(bucket, imageUploadDetails.thumbnailPath)).build()
    URL url = storage.signUrl(blobInfo, 60, TimeUnit.MINUTES, Storage.SignUrlOption.withV4Signature())
    return url // this URL, when converted to a String, doesn't work
} else {
  throw new ImageNotFoundException("Cannot open file: ${imageUploadDetails.thumbnailPath}")}
}

I expect the signed URL to be available to public users for the specified amount of time.  I would like to use it as the src value within an image tag.

Instead, what I'm getting is:

<Error>
  NoSuchKey
  <Message>The specified key does not exist.</Message>

  obfuscated to protect the innocent

</Error>

Body:
By default, the url of an object would be https://storage.googleapis.com/${bucket.name}/${blob.name}

For example:

- bucket1
  - folder1
    - image1.jpg  https://storage.googleapis.com/bucket1/folder1/image1.jpg
    - image2.jpg  https://storage.googleapis.com/bucket1/folder1/image2.jpg
- bucket2
  - image3.jpg    https://storage.googleapis.com/bucket2/image3.jpg