问:
Applying `const` CV-qualifier to decaying array-style `T arr[]` function parameter (intended to decay to `T * const arr`)
I'll start by pointing out that this question is purely out of curiosity, in so hoping to avoid discussions such as

"Consider staying away from new/dynamic arrays, and use fit-for-purpose stdlib containers instead, e.g. std::vector."

or

"Why would you want to use int arr[] parameter syntax on the first place? I always thought that it is considered to be one of the confusing abominations."

Decaying an array-style function parameter to T * const arr?

If I'm not wrong, the function signatures in the two following functions–intended to be called with a dynamically allocated C-style array–are equivalent due to decay, the first argument being (explicitly or by decay) a raw pointer to int.

```<code>// A) mutable raw ptr to mutable elements
void foo(int * arr, unsigned n)
{
  // ...
  arr = nullptr; // legal
}

// B) mutable raw ptr to mutable elements
void foo(int arr[], unsigned n)
      /* decays to int * arr */
{
  // ...
  arr = nullptr; // legal
}

// ... used e.g. as
int * arr = new int[3]{1, 2, 3}; // c++11
foo(arr, 3);
delete[] arr;
</code>```

Now, let's say for some reason we would like the raw pointer (which has been passed to the function as a copy by value) to be a const pointer (e.g. for correctness). For A), this is straight-forward:

```<code>// A') const raw ptr to mutable elements
void foo(int * const arr, unsigned n)
{
  arr = nullptr; // illegal, OK!
  // ...
}
</code>```

For B) however, I haven't been able to perform this modification.

Question:

Is it possible to specify an "array-type" function parameter (intended for a dynamic array argument) that decays into T * const arr?

(I'm naturally happy to receive a proper duplicate target that answers this; I wasn't able to find one myself. The closest one I found doesn't quite answer the above, as far as I can tell).

答:
First, you need to understand that arrays are pointers are not the same thing. The "decay" you're talking about is a transformation on the parameters:

After determining the type of each parameter, any parameter of type “array of T” or of function type T is adjusted to be “pointer to T”.
  After producing the list of parameter types, any top-level cv-qualifiers modifying a parameter type are deleted when forming the function type.

Notice the lack of "cv-qualifier-seq", which implies that it doesn't make sense to transform a const array to a const pointer (whatever that means).

Body:
I'll start by pointing out that this question is purely out of curiosity, in so hoping to avoid discussions such as

"Consider staying away from new/dynamic arrays, and use fit-for-purpose stdlib containers instead, e.g. std::vector."

or

"Why would you want to use int arr[] parameter syntax on the first place? I always thought that it is considered to be one of the confusing abominations."

Decaying an array-style function parameter to T * const arr?

If I'm not wrong, the function signatures in the two following functions–intended to be called with a dynamically allocated C-style array–are equivalent due to decay, the first argument being (explicitly or by decay) a raw pointer to int.

// A) mutable raw ptr to mutable elements
void foo(int * arr, unsigned n)
{
  // ...
  arr = nullptr; // legal
}

// B) mutable raw ptr to mutable elements
void foo(int arr[], unsigned n)
      /* decays to int * arr */
{
  // ...
  arr = nullptr; // legal
}

// ... used e.g. as
int * arr = new int[3]{1, 2, 3}; // c++11
foo(arr, 3);
delete[] arr;

Now, let's say for some reason we would like the raw pointer (which has been passed to the function as a copy by value) to be a const pointer (e.g. for correctness). For A), this is straight-forward:

// A') const raw ptr to mutable elements
void foo(int * const arr, unsigned n)
{
  arr = nullptr; // illegal, OK!
  // ...
}

For B) however, I haven't been able to perform this modification.

Question:

Is it possible to specify an "array-type" function parameter (intended for a dynamic array argument) that decays into T * const arr?

(I'm naturally happy to receive a proper duplicate target that answers this; I wasn't able to find one myself. The closest one I found doesn't quite answer the above, as far as I can tell).


来源: stackexchange

问:
Getting the user's browsing history's URLs
I was wondering if it is possible to get all the URL's from the history page of a person, perhaps with python (using selenium, or any other tool)?</p>

答:
No, that is not possible for two reasons:

Python is a server side language that is not executed in the user's browser

Even if you did use a client side language that runs in the user's browser (i.e. JavaScript), security restrictions prevent this

Think of the implications if this were possible: Would you want any company whose website you are accessing to be able to spy on you like that?

ContentLicense: CC BY-SA 3.0


问:
Code skipping run
```<code>public class A{
public static void main(String[] args) {
    int a;
    int b;int c=0;
    for(a=100;a<=999;a++){
        for(b=100;b<=999;b++){
            int n=a*b;
            int temp=n;
            while(n>0){
                int r=n%10;
                c=(c*10)+r;
                n=n/10;
            }
            if(temp==c){
                System.out.println(c);
            }
        }
    }
    }
}
</code>```

The code compiles well but while running it just skips off everything and exits. Help please.
P.S. Problem 4 ProjectEuler

答: It won't output anything because temp==cis false

Title: Code skipping run

Body:
public class A{
public static void main(String[] args) {
    int a;
    int b;int c=0;
    for(a=100;a<=999;a++){
        for(b=100;b<=999;b++){
            int n=a*b;
            int temp=n;
            while(n>0){
                int r=n%10;
                c=(c*10)+r;
                n=n/10;
            }
            if(temp==c){
                System.out.println(c);
            }
        }
    }
    }
}

The code compiles well but while running it just skips off everything and exits. Help please.
P.S. Problem 4 ProjectEuler


问:
optimistic and pessimistic locks
Working on my first php/Codeigniter project and I’ve scoured the ‘net for information on locking access to editing data and haven’t found very much information.

I expect it to be a fairly regular occurrence for 2 users to attempt to edit the same form simultaneously.

My experience (in the stateful world of BBx, filePro, and other RAD apps) is that the data being edited is locked using a pessimistic lock—one user has access to the edit form at the time. The second user basically has to wait for the first to finish.  I understand this can be done using Ajax sending XMLHttpRequests to maintain a ‘lock’ database.

The php world, lacking state, seems to prefer optimistic locking. If I understand it correctly it works like this:  both users get to access the data and they each record a ‘before changes’ version of the data.  Before saving their changes, the data is once again retrieved and compared the ‘before changes’ version. If the two versions are identical then the users changes are written.  If they are different; the user is shown what has changed since he/she started editing and some mechanism is added to resolve the differences—or the user is shown a ‘Sorry, try again’ message.

I’m interested in any experience people here have had with implementing both pessimistic and optimistic locking.  If there are any libraries, tools, or ‘how-to’s available I’m appreciate a link.

Thanks

答:
As far as I know, CodeIgniter has no support of locking rows.
If you want to implement optimistic locking, you should add a version column or timestamp column that is you must change on each update/insert. Put the version column into a hidden field in your forms. Then before each update, add a where  clause like :

```<code>$this->db->where('version',$editedVersion);
</code>```

or

```<code>$this->db->where('timestamp',$editedTimestamp);
</code>```

And then you should check that the update correctly updated 1 rows..

```<code>$this->db->where('id',$editedId);
$this->db->update('tablename',$data);
$rowsAffected = $this->db->affected_rows();
if ($rowsAffected == 0) {
    /* Data changed by other user, update failed */
} else {
   /* updated successfully */
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: optimistic and pessimistic locks

Body:
As far as I know, CodeIgniter has no support of locking rows.
If you want to implement optimistic locking, you should add a version column or timestamp column that is you must change on each update/insert. Put the version column into a hidden field in your forms. Then before each update, add a where  clause like :

$this->db->where('version',$editedVersion);

or

$this->db->where('timestamp',$editedTimestamp);

And then you should check that the update correctly updated 1 rows..

$this->db->where('id',$editedId);
$this->db->update('tablename',$data);
$rowsAffected = $this->db->affected_rows();
if ($rowsAffected == 0) {
    /* Data changed by other user, update failed */
} else {
   /* updated successfully */
}


问:
How can I view the metadata for a Microsoft Access 2013 table?
How can I view the metadata(data dictionary) for a Microsoft Access 2013 table?

答:
If you want to retrieve the access database metadata this may be helpful:

Every microsoft access database contains a system table named MSysObjects. This tables contains this database metadata. You can get all objects with there creation date and last update date.

You can list all Objects in an Access Database using the following query:

```<code>SELECT Name, DateCreate, DateUpdate,
 iif(LEFT(Name, 4) = 'MSys','System Table',
 iif(type = 2,'System Object',
 iif(type = 3,'System Object',
 iif(type = 8,'System Object',
 iif(type = 4,'Linked Table (ODBC)',
 iif(type = 1,'Table',
 iif(type = 6, 'Linked Table (MsAccess/MsExcel)',
 iif(type = 5,'Query',
 iif(type = -32768,'Form',
 iif(type = -32764,'Report',
 iif(type=-32766,'Macro',
 iif(type = -32761,'Module',
 iif(type = -32756,'Page',
 iif(type = -32758,'User','Unknown')))))))))))))) as ObjectType
  FROM MSysObjects WHERE LEFT(Name, 1) <> '~'
</code>```

If you don't want to show system objects you can add these conditions to the where clause:

```<code>AND LEFT(Name, 4) <> 'MSys' AND Type IN (1, 5, 4, 6,  -32768, -32764, -32766, -32761,-32756,-32758)
</code>```

Also i created an application that retrieve data from access database, Which i created a new Git-repository for it

Body:
If you want to retrieve the access database metadata this may be helpful:

Every microsoft access database contains a system table named MSysObjects. This tables contains this database metadata. You can get all objects with there creation date and last update date.

You can list all Objects in an Access Database using the following query:

SELECT Name, DateCreate, DateUpdate,
 iif(LEFT(Name, 4) = 'MSys','System Table',
 iif(type = 2,'System Object',
 iif(type = 3,'System Object',
 iif(type = 8,'System Object',
 iif(type = 4,'Linked Table (ODBC)',
 iif(type = 1,'Table',
 iif(type = 6, 'Linked Table (MsAccess/MsExcel)',
 iif(type = 5,'Query',
 iif(type = -32768,'Form',
 iif(type = -32764,'Report',
 iif(type=-32766,'Macro',
 iif(type = -32761,'Module',
 iif(type = -32756,'Page',
 iif(type = -32758,'User','Unknown')))))))))))))) as ObjectType
  FROM MSysObjects WHERE LEFT(Name, 1) <> '~'

If you don't want to show system objects you can add these conditions to the where clause:

AND LEFT(Name, 4) <> 'MSys' AND Type IN (1, 5, 4, 6,  -32768, -32764, -32766, -32761,-32756,-32758)

Also i created an application that retrieve data from access database, Which i created a new Git-repository for it


问:
Can I open 2 ports simultaneously with single websocket server
I am a newbie at websocket programming. Currently I am working on a simple websocket server,using c, that can respond to a websocket client. I managed to get that working with 1 client and  1 server on a single port. I want to know if I could open 2 ports, so different clients could connect to the the different ports.</p>

```<code>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>

int main(int argc, char *argv[])
{
  int listenfd = 0, connfd = 0;
  struct sockaddr_in serv_addr;

  char sendBuff[1025];

  listenfd = socket(AF_INET, SOCK_STREAM, 0);
  memset(&serv_addr, '0', sizeof(serv_addr));
  memset(sendBuff, '0', sizeof(sendBuff));

  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = htonl(INADDR_ANY );
  serv_addr.sin_port = htons(8000);

  bind(listenfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr));

  listen(listenfd, 10);

  while (1)
  {
    connfd = accept(listenfd, (struct sockaddr*) NULL, NULL );

    close(connfd);
    sleep(1);
  }
}
</code>```

答: Yes ,Try adding listeners to different ports on the same server script.</p>

Body:
I am a newbie at websocket programming. Currently I am working on a simple websocket server,using c, that can respond to a websocket client. I managed to get that working with 1 client and  1 server on a single port. I want to know if I could open 2 ports, so different clients could connect to the the different ports.

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>

int main(int argc, char *argv[])
{
  int listenfd = 0, connfd = 0;
  struct sockaddr_in serv_addr;

  char sendBuff[1025];

  listenfd = socket(AF_INET, SOCK_STREAM, 0);
  memset(&serv_addr, '0', sizeof(serv_addr));
  memset(sendBuff, '0', sizeof(sendBuff));

  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = htonl(INADDR_ANY );
  serv_addr.sin_port = htons(8000);

  bind(listenfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr));

  listen(listenfd, 10);

  while (1)
  {
    connfd = accept(listenfd, (struct sockaddr*) NULL, NULL );

    close(connfd);
    sleep(1);
  }
}


问:
expandable iOS tableViewCell
I have a custom tableViewControlelr that has rounded card view cells. The tableViewCells also have the ability to be clicked and when clicked, it expands.

```<code> func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectedIndex = indexPath
        self.didExpandCell()

    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if isExpanded && self.selectedIndex == indexPath{
            return 300
        }
        return 126
</code>```

within my tableviewcell, I have a custom view that is white, this is what allows for the card view appearance and it is also rounded. When the cell is not clicked, the cell is the standard height and looks like this:

And when the cell is clicked, it expands and looks like this:

As you can see when the cell is not clicked, the bottom part is straight and not rounded, I attempted to use this code to make it rounded but it did not work.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cells", for: indexPath) as! ProfileTableViewCell

if TableView.rowHeight == 126 {

            cell.CustomView = UIView(frame: CGRect(x: 7, y: 8, width: 359, height: 20))

            return cell
        }
        else{

        }
}
</code>```

答:
the problem can be resolve by just taking test label inside the view that make view round not cell when the cell expand remove radius from view.
    or you can set the particular corner radius eg top-left,top-right,.bottomLeft , .bottomRight.</p>

```<code>Use below example to set the corner radius

  let rectShape = CAShapeLayer()
    rectShape.bounds = self.myView.frame
    rectShape.position = self.myView.center
    rectShape.path = UIBezierPath(roundedRect: self.myView.bounds, byRoundingCorners: [.bottomLeft , .bottomRight , .topLeft], cornerRadii: CGSize(width: 20, height: 20)).cgPath

     self.myView.layer.backgroundColor = UIColor.green.cgColor
     self.myView.layer.mask = rectShape
</code>```

Title: expandable iOS tableViewCell

Body:
I have a custom tableViewControlelr that has rounded card view cells. The tableViewCells also have the ability to be clicked and when clicked, it expands.

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectedIndex = indexPath
        self.didExpandCell()

    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if isExpanded && self.selectedIndex == indexPath{
            return 300
        }
        return 126

within my tableviewcell, I have a custom view that is white, this is what allows for the card view appearance and it is also rounded. When the cell is not clicked, the cell is the standard height and looks like this:

And when the cell is clicked, it expands and looks like this:

As you can see when the cell is not clicked, the bottom part is straight and not rounded, I attempted to use this code to make it rounded but it did not work.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cells", for: indexPath) as! ProfileTableViewCell

if TableView.rowHeight == 126 {

            cell.CustomView = UIView(frame: CGRect(x: 7, y: 8, width: 359, height: 20))

            return cell
        }
        else{

        }
}

Body:
the problem can be resolve by just taking test label inside the view that make view round not cell when the cell expand remove radius from view.
    or you can set the particular corner radius eg top-left,top-right,.bottomLeft , .bottomRight.

Use below example to set the corner radius

  let rectShape = CAShapeLayer()
    rectShape.bounds = self.myView.frame
    rectShape.position = self.myView.center
    rectShape.path = UIBezierPath(roundedRect: self.myView.bounds, byRoundingCorners: [.bottomLeft , .bottomRight , .topLeft], cornerRadii: CGSize(width: 20, height: 20)).cgPath

     self.myView.layer.backgroundColor = UIColor.green.cgColor
     self.myView.layer.mask = rectShape


问:
SQL Server and asp.net application security models / best practice
For my asp.net web applications against sql server(at least the ones that require a logon to access) I generally implement security as follows:

I generally roll my own user signup, user login pages and keep a userid and an encrypted password in an sql server and validate the login against that table - I also provide for forgotten passwords, 'send me my password', email verification to activate accounts etc all thru custom code.

Once the user has been validated by the app (and lets assume that all users have the same privileges), I generally use a utility logonid to let asp.net talk to sql server, so in other words I only need to create a single logon id per application, and since 100% of all data access is done thru stored procedures, I need only grant access to a single user to execute stored procedures, and no other work is required on sql server. Each application has its own database, and the logon for that app can only access that database.

All this works perfectly well for me, the only negative of this is that it would be nice to be able to setup a trace in sql server and see the userid and the procs that are being called, but since all users are 'talking' to the database thru a single database logon, this can't happen.

So, two part question:

1) Are there security models are you folks using that I should consider? Its easy to always do the same thing over and over, - especially since it works - but are there other models that would work better or that I should consider? Is it recommended practice that all database access from an asp.net app would all share a single database login? or is this considered bad practice? and if so, why?

2) Assuming I stick with my model, is there a way to allow for the application login id to be seen in the sql trace window? It would be nice to see the sp's being called and the user id of the person logged into the system (not the database login).

答:
Is it recommended practice that all
  database access from an asp.net app
  would all share a single database
  login?

Yes, primarily for connection pooling.

In regards to 2), I normally do that by logging at the ASP.NET side.

OwnerDisplayName: E.J. Brennan


问:
How do Mobile Computer Barcode Scanners Integrate into a System?
Our company is considering using hand-held bar code scanners as a part of our inventory management process and I have some technical questions about how they actually integrate with an existing system. To clarify, I'm talking about the hand-held wireless bar code scanners with screens and keypads on them that are actually mini-computers. The ones that connect to a network over 802.11g and interact with a database in real time.

I know this is a broad question which is somewhat dependant on device, but the Internet seems to be lacking a good source of technically detailed information on the subject. The kind of information a software developer would want to know before buying one of these devices to be sure it will actually work in a specific situation.

I've found places selling them and basic sales sheets, but what I'm looking for is a detailed description of how these devices are actually programmed and how they talk to a back-end application.

Specifically, do you program them with a widely used language like C? Or do they use some obscure proprietary language? Is it scripted or compiled?

Do you need to install special software on a desktop PC to load your application onto the scanner?

A lot of them say they're running Windows Mobile or Windows CE. Does that mean you need a Windows desktop machine to program them? To interact with them? Or can they be programmed from a Linux desktop and interact with Linux servers?

How do they actually talk to the back-end application? Does it send XML over HTTP, for example?

Coming from a web development background, I'm imagining the gun running a "thin client" software sort of like javascript, which makes AJAX-like calls over http (through wifi) to the server. Do they or can they work like that?

What I'd really like is a guide called, "programming your first bar code scanner" that teaches you to create a "hello world" program step by step. Does such a thing exist?

Thanks in advance!

答:
All of the mobile computer barcode scanner devices that I have ever worked with have come pre-configured with an operating system.  And on all of them that I have worked with, that operating system has been Windows Mobile or Windows CE.  What you really have is a Windows Mobile PDA that happens to have specialized hardware for scanning barcodes.

So, the guide "programming your first bar code scanner" should really be called "programming for Windows Mobile."  There are all kinds of sites that can help you learn to program Windows Mobile, including Microsoft's own sites.  But, in general, you are locked into developing in the paradigms defined by Microsoft.  This pretty much comes down to writing C/C++ that uses the Windows CE Platform API, or writing .NET code that accesses the .NET Compact Framework.  That also means that you're probably going to end up using some flavor of Microsoft Visual Studio for development.  Fortunately, Visual Studio also comes with Windows Mobile emulation so you can do testing without actually having a physical device to play with.

Once you've got your basic application written, you can then add in the hardware vendor's specific library for accessing the barcode scanning hardware.  Testing this piece will require that you actually have a physical device.

As for communication techniques, protocols, etc., that is all going to be up to you.  If you're rolling everything from scratch, you will have to build the communications protocol from scratch as well.  Otherwise, you will have to do some research to find out if some kind of pre-built communications protocol components exist that you might be able to purchase/use.


问:
Adding Data to multiple tables with a single form Laravel
I am trying to insert a blog post on db, I do have two tables posts and tags tables. When I insert the create the post I want to be able to insert the data from the form in those two different tables.

create.blade.php;

```<code><div class="account_grid">

<div class="col-md-6 login-right wow fadeInRight col-md-offset-3" data-wow-delay="0.4s">
    <h3>CREATE A BLOG POST</h3>
    <p>Please fill out the required fields *</p>
    <form method="post" action="/posts"  enctype="multipart/form-data">
         {{csrf_field()}}
        <div>
            <span>Title:<label>*</label></span>
            <input type="text" id="title" name="title"  >
        </div>
        <div>
            <span>Body<label>*</label></span>
            <textarea id="body" name="body" rows="14"  ></textarea>
        </div>
        <div>
            <span>Tags:<label>*</label></span>
            <input type="text" id="tags" name="tags">
        </div>
        <div>
            <span>Image<label>*</label></span>
            <input type="file" name="image" id="image"  >
        </div>
        <input type="submit" value="Publish">

    </form>

@include('layouts.errors')
</div>
<div class="clearfix"> </div>
</div>
</code>```

On my route file I have the path that leads to PostsController.php which has a store method like below:

PostsController.php

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

        $this->validate($request, [

            'title' =>'required|max:48',
            'body'=>'required',
            'image'=>'required',
            'tags' =>'required|max:200'
        ]);

        $post = new Post;

        $destination ='uploads';
        $image = $request->file('image');
        $filename = $image->getClientOriginalName();
        $image->move($destination, $filename);
        $location=$destination.'/'.$filename;
        $tags = request('tags');

           Post::create([
            'title'=>request('title'),
            'body' =>request('body'),
            'user_id'=>auth()->id(),
            'image' =>$destination.'/'.$filename

        ]);

        $tag = new Tag;

        Tag::create([

            'name' => $tags
        ]);

        return redirect('/blog');
    }
}
</code>```

The thing is that when I call the method I want the form data to be saved on two different tables, I have tried like below but I am getting ERROR:

MassAssignmentException in Model.php line 232:
name

I did research the issue but no luck; and yes I do have the 'name' listed in the protected $fillable array. Any suggestion on how to store data in two different tables or what type of relationship should i use.

On post.php model i do have a relationship specified. Tags belongsToMany as well as on my tag.php model Post belongsToMany

p.s New to Laravel.

tag.php model:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    //

        public function posts(){

        return $this->belongsToMany(Post::class);
    }

    public function getRouteKeyName(){

        return 'name';

    }
}
</code>```

Post.php model:

```<code><?php

namespace App;
use Carbon\Carbon;
class Post extends Model
{

    public function comments(){

        return $this->hasMany(Comment::class);
    }

    public function addComment($body, $name, $email, $user_id){

        $this->comments()->create(compact('body','name','email', 'user_id'));
    }

    public function user(){ // $comment->user->name

        return $this->belongsTo(User::class);
    }

    public function scopeFilter($query, $filters){

        if($month =$filters['month']){
//
            $query->whereMonth('created_at', Carbon::parse($month)->month);
        }

        if($year = $filters['year']){

            $query->whereYear('created_at',$year );
        }
    }

    public static function archives(){
        return static:: selectRaw('year(created_at)year, monthname(created_at)month, count(*) published')
       ->groupBy('year','month')
       ->orderByRaw('min(created_at) desc')
       ->get()
       ->toArray();
    }

    public function tags(){

        return $this->belongsToMany(Tag::class);
    }

}
</code>```

答:
Just declare
Protected $fillable =['column 1','column 2'];

$fillable variable use for create method for insterting data.
If you are using create method to insert data then you must specify $fillable variable in model class

In $fillable variable, you specify specific column which you want to allow to insert data in table

I think your issue in

Either you are not declare $fillable variable or

You are not specify column in $fillable which you want to insert.

Body:
I am trying to insert a blog post on db, I do have two tables posts and tags tables. When I insert the create the post I want to be able to insert the data from the form in those two different tables.

create.blade.php;

CREATE A BLOG POST

Please fill out the required fields *

    <form method="post" action="/posts"  enctype="multipart/form-data">
         {{csrf_field()}}

            Title:*
            <input type="text" id="title" name="title"  >

            Body*
            <textarea id="body" name="body" rows="14"  ></textarea>

            Tags:*
            <input type="text" id="tags" name="tags">

            Image*
            <input type="file" name="image" id="image"  >

        <input type="submit" value="Publish">

    </form>

@include('layouts.errors')

On my route file I have the path that leads to PostsController.php which has a store method like below:

PostsController.php

    public function store(Request $request){

        $this->validate($request, [

            'title' =>'required|max:48',
            'body'=>'required',
            'image'=>'required',
            'tags' =>'required|max:200'
        ]);

        $post = new Post;

        $destination ='uploads';
        $image = $request->file('image');
        $filename = $image->getClientOriginalName();
        $image->move($destination, $filename);
        $location=$destination.'/'.$filename;
        $tags = request('tags');

           Post::create([
            'title'=>request('title'),
            'body' =>request('body'),
            'user_id'=>auth()->id(),
            'image' =>$destination.'/'.$filename

        ]);

        $tag = new Tag;

        Tag::create([

            'name' => $tags
        ]);

        return redirect('/blog');
    }
}

The thing is that when I call the method I want the form data to be saved on two different tables, I have tried like below but I am getting ERROR:

MassAssignmentException in Model.php line 232:
name

I did research the issue but no luck; and yes I do have the 'name' listed in the protected $fillable array. Any suggestion on how to store data in two different tables or what type of relationship should i use.

On post.php model i do have a relationship specified. Tags belongsToMany as well as on my tag.php model Post belongsToMany

p.s New to Laravel.

tag.php model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    //

        public function posts(){

        return $this->belongsToMany(Post::class);
    }

    public function getRouteKeyName(){

        return 'name';

    }
}

Post.php model:

<?php

namespace App;
use Carbon\Carbon;
class Post extends Model
{

    public function comments(){

        return $this->hasMany(Comment::class);
    }

    public function addComment($body, $name, $email, $user_id){

        $this->comments()->create(compact('body','name','email', 'user_id'));
    }

    public function user(){ // $comment->user->name

        return $this->belongsTo(User::class);
    }

    public function scopeFilter($query, $filters){

        if($month =$filters['month']){
//
            $query->whereMonth('created_at', Carbon::parse($month)->month);
        }

        if($year = $filters['year']){

            $query->whereYear('created_at',$year );
        }
    }

    public static function archives(){
        return static:: selectRaw('year(created_at)year, monthname(created_at)month, count(*) published')
       ->groupBy('year','month')
       ->orderByRaw('min(created_at) desc')
       ->get()
       ->toArray();
    }

    public function tags(){

        return $this->belongsToMany(Tag::class);
    }

}


答:
I don't think so, especially with python. The only thing that could potentially work is JavaScript. But a history is generally protected by the browser.

The only thing that comes close to this is Mozilla's History API. However, even this would work only in Firefox.

Hope it helps.

Title: Getting the user's browsing history's URLs

Body: I was wondering if it is possible to get all the URL's from the history page of a person, perhaps with python (using selenium, or any other tool)?


问:
Makefile always thinks project is up to date - but files don't even exist
I have the following makefile:

```CCC = g++
CCFLAGS = -ansi

driver: driver.o graph.o
        $(CCC) -o driver driver.o graph.o

graph.o: graph.h
driver.o: graph.h

adjl:
        rm -f graph.h graph.cc
        ln -s adjl/graph.cc .
        ln -s adjl/graph.h .
        touch graph.cc graph.h
adjm:
        rm -f graph.h graph.cc
        ln -s adjm/graph.cc .
        ln -s adjm/graph.h .
        touch graph.cc graph.h

clean:
        rm -f *.o
real_clean: clean
        rm -f graph.cc graph.h
        rm -f driver```

The idea is that I am trying to link two different .cc/.h files depending on which implementation I want to use.  If I make real_clean, none of the .cc/.h files exist, I merely have a driver.cc file and the makefile in the folder.  If I call make, it says they are up to date.  This happens even if I edit the files in adjl/adjm to make them "newer" versions.

``` [95]% ls
adjl/  adjm/  driver.cc  makefile
 [96]% make adjl
make: `adjl' is up to date.
 [97]% make adjm
make: `adjm' is up to date.```

I took the template makefile from another project I had done, and they are written the same way but I can repeatedly make the same commands with no "up to date" issues.

I have googled but have not found a problem similar to mine (they generally seem to involve users who aren't cleaning before making).

Thanks to anyone for reading.

答:
The problem is that you have directory named the same as your targets in Makefile.

When you issue make adjl make checks for file adjl which it finds and does nothing.
Rename targets to something else and try again.

Body:
I have the following makefile:

CCC = g++
CCFLAGS = -ansi

driver: driver.o graph.o
        $(CCC) -o driver driver.o graph.o

graph.o: graph.h
driver.o: graph.h

adjl:
        rm -f graph.h graph.cc
        ln -s adjl/graph.cc .
        ln -s adjl/graph.h .
        touch graph.cc graph.h
adjm:
        rm -f graph.h graph.cc
        ln -s adjm/graph.cc .
        ln -s adjm/graph.h .
        touch graph.cc graph.h

clean:
        rm -f *.o
real_clean: clean
        rm -f graph.cc graph.h
        rm -f driver

The idea is that I am trying to link two different .cc/.h files depending on which implementation I want to use.  If I make real_clean, none of the .cc/.h files exist, I merely have a driver.cc file and the makefile in the folder.  If I call make, it says they are up to date.  This happens even if I edit the files in adjl/adjm to make them "newer" versions.

 [95]% ls
adjl/  adjm/  driver.cc  makefile
 [96]% make adjl
make: `adjl' is up to date.
 [97]% make adjm
make: `adjm' is up to date.

I took the template makefile from another project I had done, and they are written the same way but I can repeatedly make the same commands with no "up to date" issues.

I have googled but have not found a problem similar to mine (they generally seem to involve users who aren't cleaning before making).

Thanks to anyone for reading.


问:
C# Coding a Tie in Tic Tac Toe
I've developed a game of tic tac toe in C# and set a function for the win conditions, but I can't seem to figure out how to set the condition for a tie when the grid is full. When I tried to input, the tie would occur randomly. I wonder if it's how I set the or and and operators.Here's what I tried. </p>

```<code>public bool Ended()
{
    if (grid[0, 0] == 'X' && grid[0, 1] == 'X' && grid[0, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[1, 0] == 'X' && grid[1, 1] == 'X' && grid[1, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[2, 0] == 'X' && grid[2, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 0] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 1] == 'X' && grid[1, 1] == 'X' && grid[2, 1] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 2] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 1] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[0, 1] == 'O' && grid[0, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[1, 0] == 'O' && grid[1, 1] == 'O' && grid[1, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[2, 0] == 'O' && grid[2, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 0] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 1] == 'O' && grid[1, 1] == 'O' && grid[2, 1] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 2] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 1] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    else if (grid[0, 0] == 'X' || grid[0, 0] == 'O' &&
        grid[0, 1] == 'X' || grid[0, 1] == 'O' &&
        grid[0, 2] == 'X' || grid[0, 2] == 'O' &&
        grid[1, 0] == 'X' || grid[1, 0] == 'O' &&
        grid[1, 1] == 'X' || grid[1, 1] == 'O' &&
        grid[1, 2] == 'X' || grid[1, 2] == 'O' &&
        grid[2, 0] == 'X' || grid[2, 0] == 'O' &&
        grid[2, 1] == 'X' || grid[2, 1] == 'O' &&
        grid[2, 2] == 'X' || grid[2, 2] == 'O')
    { Console.WriteLine("It's a Tie"); return true; }
    return false;
}
</code>```

答:
This solution works around your problem by removing the faulty code altogether and using a for-loop-based approach for the last check. It also avoids redundancy and makes it (imho) easier to follow:</p>

```<code>private const char PLAYER_1_SYMBOL = 'X';
private const char PLAYER_2_SYMBOL = 'O';

private readonly char[,] grid = new char[3,3];

public bool Ended()
{
    if (CheckPlayerVictory(PLAYER_1_SYMBOL))
    {
        Console.WriteLine("Player 1 Wins");
        return true;
    }
    else if (CheckPlayerVictory(PLAYER_2_SYMBOL))
    {
        Console.WriteLine("Player 2 Wins");
        return true;
    }
    else if (CheckNoMovesRemaining())
    {
        Console.WriteLine("It's a Tie");
        return true;
    }
    return false;
}

// true, if a match for the given symbol was found in the grid.
private bool CheckPlayerVictory(char symbol)
{
    return (grid[0, 0] == symbol && grid[0, 1] == symbol && grid[0, 2] == symbol)
        || (grid[1, 0] == symbol && grid[1, 1] == symbol && grid[1, 2] == symbol)
        || (grid[2, 0] == symbol && grid[2, 1] == symbol && grid[2, 2] == symbol)
        || (grid[0, 0] == symbol && grid[1, 0] == symbol && grid[2, 0] == symbol)
        || (grid[0, 1] == symbol && grid[1, 1] == symbol && grid[2, 1] == symbol)
        || (grid[0, 2] == symbol && grid[1, 2] == symbol && grid[2, 2] == symbol)
        || (grid[0, 0] == symbol && grid[1, 1] == symbol && grid[2, 2] == symbol)
        || (grid[0, 2] == symbol && grid[1, 1] == symbol && grid[2, 0] == symbol);
}

// true, if no free grid cell is left.
private bool CheckNoMovesRemaining()
{
    int numFreeSpaces = 9;
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            if (grid[i,j] == PLAYER_1_SYMBOL || grid[i,j] == PLAYER_2_SYMBOL)
            {
                numFreeSpaces--;
            }
        }
    }

    return numFreeSpaces <= 0;
}
</code>```

Title: C# Coding a Tie in Tic Tac Toe

Body:
I've developed a game of tic tac toe in C# and set a function for the win conditions, but I can't seem to figure out how to set the condition for a tie when the grid is full. When I tried to input, the tie would occur randomly. I wonder if it's how I set the or and and operators.Here's what I tried.

public bool Ended()
{
    if (grid[0, 0] == 'X' && grid[0, 1] == 'X' && grid[0, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[1, 0] == 'X' && grid[1, 1] == 'X' && grid[1, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[2, 0] == 'X' && grid[2, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 0] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 1] == 'X' && grid[1, 1] == 'X' && grid[2, 1] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 2] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 1] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[0, 1] == 'O' && grid[0, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[1, 0] == 'O' && grid[1, 1] == 'O' && grid[1, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[2, 0] == 'O' && grid[2, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 0] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 1] == 'O' && grid[1, 1] == 'O' && grid[2, 1] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 2] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 1] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    else if (grid[0, 0] == 'X' || grid[0, 0] == 'O' &&
        grid[0, 1] == 'X' || grid[0, 1] == 'O' &&
        grid[0, 2] == 'X' || grid[0, 2] == 'O' &&
        grid[1, 0] == 'X' || grid[1, 0] == 'O' &&
        grid[1, 1] == 'X' || grid[1, 1] == 'O' &&
        grid[1, 2] == 'X' || grid[1, 2] == 'O' &&
        grid[2, 0] == 'X' || grid[2, 0] == 'O' &&
        grid[2, 1] == 'X' || grid[2, 1] == 'O' &&
        grid[2, 2] == 'X' || grid[2, 2] == 'O')
    { Console.WriteLine("It's a Tie"); return true; }
    return false;
}

Body:
This solution works around your problem by removing the faulty code altogether and using a for-loop-based approach for the last check. It also avoids redundancy and makes it (imho) easier to follow:

private const char PLAYER_1_SYMBOL = 'X';
private const char PLAYER_2_SYMBOL = 'O';

private readonly char[,] grid = new char[3,3];

public bool Ended()
{
    if (CheckPlayerVictory(PLAYER_1_SYMBOL))
    {
        Console.WriteLine("Player 1 Wins");
        return true;
    }
    else if (CheckPlayerVictory(PLAYER_2_SYMBOL))
    {
        Console.WriteLine("Player 2 Wins");
        return true;
    }
    else if (CheckNoMovesRemaining())
    {
        Console.WriteLine("It's a Tie");
        return true;
    }
    return false;
}

// true, if a match for the given symbol was found in the grid.
private bool CheckPlayerVictory(char symbol)
{
    return (grid[0, 0] == symbol && grid[0, 1] == symbol && grid[0, 2] == symbol)
        || (grid[1, 0] == symbol && grid[1, 1] == symbol && grid[1, 2] == symbol)
        || (grid[2, 0] == symbol && grid[2, 1] == symbol && grid[2, 2] == symbol)
        || (grid[0, 0] == symbol && grid[1, 0] == symbol && grid[2, 0] == symbol)
        || (grid[0, 1] == symbol && grid[1, 1] == symbol && grid[2, 1] == symbol)
        || (grid[0, 2] == symbol && grid[1, 2] == symbol && grid[2, 2] == symbol)
        || (grid[0, 0] == symbol && grid[1, 1] == symbol && grid[2, 2] == symbol)
        || (grid[0, 2] == symbol && grid[1, 1] == symbol && grid[2, 0] == symbol);
}

// true, if no free grid cell is left.
private bool CheckNoMovesRemaining()
{
    int numFreeSpaces = 9;
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            if (grid[i,j] == PLAYER_1_SYMBOL || grid[i,j] == PLAYER_2_SYMBOL)
            {
                numFreeSpaces--;
            }
        }
    }

    return numFreeSpaces <= 0;
}


问:
JavaScript - compare two arrays with limited values/elements
I have an array of a few numbers or strings, eg.

```<code>[4.3, 1.2, 4.5, 3.9]

['I', 'the', 'sheriff', 'shot']
</code>```

The users re-arrange the elements in a specific order. For example, in an ascending order:

```<code>[1.2, 3.9, 4.3, 4.5]
</code>```

and to create a valid sentence:

```<code>['I', 'shot', 'the', 'sheriff']
</code>```

I have those predefined answers stored in an object. How do I compare the arrays with user generated order with the ones with correct order of elements. I have seen other answers on how to compare arrays but my question does not require a wide range of 'what if....' that other answers had. The elements are generated by the app so no unexpected input would be there, no undefined values, no empty elements, etc. Users do not input anything. They just rearrange tiles with those elements.

What's the best way to compare the arrays to determine if the users have rearranged the boxes in the right way.

My first attempt is incorrect as it always seems to be outputing 'BINGO' even if the order is incorrect:

```<code>if (this.props.squares === correctOrder) {
      console.log("BINGO");
    }
</code>```

答:
I would use every function which all arrays have.

```<code>const isCorrect = this.props.squares.every((square, index) =>
  correctOrder[index] === square);
</code>```

Body:
I have an array of a few numbers or strings, eg.

[4.3, 1.2, 4.5, 3.9]

['I', 'the', 'sheriff', 'shot']

The users re-arrange the elements in a specific order. For example, in an ascending order:

[1.2, 3.9, 4.3, 4.5]

and to create a valid sentence:

['I', 'shot', 'the', 'sheriff']

I have those predefined answers stored in an object. How do I compare the arrays with user generated order with the ones with correct order of elements. I have seen other answers on how to compare arrays but my question does not require a wide range of 'what if....' that other answers had. The elements are generated by the app so no unexpected input would be there, no undefined values, no empty elements, etc. Users do not input anything. They just rearrange tiles with those elements.

What's the best way to compare the arrays to determine if the users have rearranged the boxes in the right way.

My first attempt is incorrect as it always seems to be outputing 'BINGO' even if the order is incorrect:

if (this.props.squares === correctOrder) {
      console.log("BINGO");
    }

Body:
I would use every function which all arrays have.

const isCorrect = this.props.squares.every((square, index) =>
  correctOrder[index] === square);


问:
Symfony2, Doctrine2, findBy() order not working
I created a repository for my Articles entity and I'm trying to get all values ordered by ID DESC. But, I'll get everytime values ordered by id ASC. Here is my ArticleRepository.php:

```<code><?php

namespace Acme\BlogBundle\Entity;

use Doctrine\ORM\EntityRepository;

class ArticleRepository extends EntityRepository
{
    public function findAll()
    {
        return $this->findBy(array(), array('id' => 'DESC'));
    }

    public function findOneBySlug($slug)
    {
        $query = $this->getEntityManager()
                      ->createQuery('
                          SELECT p FROM AcmePagesBundle:Article a
                          WHERE a.slug = :slug
                      ')
                      ->setParameter('slug', $slug);

        try {
            return $query->getSingleResult();
        } catch (\Doctrine\ORM\NoResultException $e) {
            return false;
        }
    }
}
</code>```

Any ideas?

答:
Symfony 3.3 find by order working example.

From your controller:

```<code>public function indexAction(){
     $entityManager = $this->getDoctrine()->getManager();
     $categoryRepository = $entityManager->getRepository(ProductCategory::class);
     $items = $categoryRepository->findBy(array(), array('id' => 'DESC'));
     ....
}
</code>```

Body:
I created a repository for my Articles entity and I'm trying to get all values ordered by ID DESC. But, I'll get everytime values ordered by id ASC. Here is my ArticleRepository.php:

<?php

namespace Acme\BlogBundle\Entity;

use Doctrine\ORM\EntityRepository;

class ArticleRepository extends EntityRepository
{
    public function findAll()
    {
        return $this->findBy(array(), array('id' => 'DESC'));
    }

    public function findOneBySlug($slug)
    {
        $query = $this->getEntityManager()
                      ->createQuery('
                          SELECT p FROM AcmePagesBundle:Article a
                          WHERE a.slug = :slug
                      ')
                      ->setParameter('slug', $slug);

        try {
            return $query->getSingleResult();
        } catch (\Doctrine\ORM\NoResultException $e) {
            return false;
        }
    }
}

Any ideas?

Body:
Symfony 3.3 find by order working example.

From your controller:

public function indexAction(){
     $entityManager = $this->getDoctrine()->getManager();
     $categoryRepository = $entityManager->getRepository(ProductCategory::class);
     $items = $categoryRepository->findBy(array(), array('id' => 'DESC'));
     ....
}


问:
Script to Find Copies of Files in Powershell
I am trying to make a script in PowerShell that analyzes recursevily a directory and gets all hashes MD5 from all files and from all files inside any directories inside the 1st one given.

After that, I want to compare all the hashes between each other to see which one is a copy, and then give an option to delete these copies or not.

At the moment I have this:

```<code>$UserInput=Read-Host
Get-ChildItem -Path $UserInput -Recurse
$someFilePath = $UserInput
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))
$hash
</code>```

The main problem is in the hash part, that I get an error in calling the "ReadAllBytes".

I also am doubting if creating an array so when I compare the hashes, if they are equal, put the copies in an array, so then deleting them is "easier".

What do you think? (I am also not sure if I am using right the "SomeFilePath", MD5 nor Hash).

答:
Just do it

```<code>Get-ChildItem -Path $UserInput -Recurse -File | Get-FileHash | Group Hash | Where Count -gt 1
</code>```

Short version :

```<code>gci -Path $UserInput -R -File | Get-FileHash | Group Hash | ? Count -gt 1
</code>```

Body:
I am trying to make a script in PowerShell that analyzes recursevily a directory and gets all hashes MD5 from all files and from all files inside any directories inside the 1st one given.

After that, I want to compare all the hashes between each other to see which one is a copy, and then give an option to delete these copies or not.

At the moment I have this:

$UserInput=Read-Host
Get-ChildItem -Path $UserInput -Recurse
$someFilePath = $UserInput
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))
$hash

The main problem is in the hash part, that I get an error in calling the "ReadAllBytes".

I also am doubting if creating an array so when I compare the hashes, if they are equal, put the copies in an array, so then deleting them is "easier".

What do you think? (I am also not sure if I am using right the "SomeFilePath", MD5 nor Hash).

Body:
Just do it

Get-ChildItem -Path $UserInput -Recurse -File | Get-FileHash | Group Hash | Where Count -gt 1

Short version :

gci -Path $UserInput -R -File | Get-FileHash | Group Hash | ? Count -gt 1


问:
How to separate an array every x members?
I want to separate an array every 3 members and put them into different arrays

```<code>$array = array("hi", "hello", "sup", "example", "something", "ksikikikfr", "frefre");

$output1 = array("hi", "hello", "sup");
$output2 = array("example", "something", "ksikikikfr");
$output3 = array("frefre");
</code>```

This is what I want to get, thanks in advance

答:
Create chunks with a size of 3 with array_chunk:

```<code>$chunks = array_chunk($array, 3);
print_r($chunks);
</code>```

Body:
I want to separate an array every 3 members and put them into different arrays

$array = array("hi", "hello", "sup", "example", "something", "ksikikikfr", "frefre");

$output1 = array("hi", "hello", "sup");
$output2 = array("example", "something", "ksikikikfr");
$output3 = array("frefre");

This is what I want to get, thanks in advance

Body:
Create chunks with a size of 3 with array_chunk:

$chunks = array_chunk($array, 3);
print_r($chunks);


问:
Cant find phpmyadmin.conf for Allow IP to access
Im using
Server version: 5.7.18-0ubuntu0.16.04.1 - (Ubuntu)
Apache/2.4.18 (Ubuntu)

I try to connect db with

```<code>var mysql_crawl = mysql.createConnection({
    host: 'xx.xx.xx.xx',
    user: 'root',
    password: 'xxxx',
    database: 'db_xx'
});
</code>```

Im goint to allow ip to access but i cant find

```<code>/etc/apache2/conf.d/phpmyadmin.conf
</code>```

Its no conf.d folder

答: phpMyAdmin's configuration is not related to what you are attempting. If your MySQL server is running on the same machine as where you run your program, try 'localhost' for the 'host' parameter.</p>

Body:
Im using
Server version: 5.7.18-0ubuntu0.16.04.1 - (Ubuntu)
Apache/2.4.18 (Ubuntu)

I try to connect db with

var mysql_crawl = mysql.createConnection({
    host: 'xx.xx.xx.xx',
    user: 'root',
    password: 'xxxx',
    database: 'db_xx'
});

Im goint to allow ip to access but i cant find

/etc/apache2/conf.d/phpmyadmin.conf

Its no conf.d folder


问:
Get all class names starting with a specific prefix with JavaScript / jQuery
I want to extract classes based on specific prefix like "category-lifestyle" or "category-magazine".

The HTML markup looks like this:

```<code><article id="post-361" class="et_pb_post post-361 post type-post status-publish format-standard has-post-thumbnail hentry category-lifestyle category-magazine">

    Post content...

</article>
</code>```

答:
If you want to get a list of all the classes that start with, let's say, category-, you should first get all the elements that contain a matching class using an attribute contains selector:

```<code>document.querySelectorAll("*[class*='category-']")
</code>```

Then you should extract all the classes of those elements and filter out duplicates and those that do not start with the desired prefix.

Something like this:

const allCategoryClasses = [];

// Get all elements that have any class starting
// with 'category-':

const elementsWithCategoryClasses
  = document.querySelectorAll("*[class*='category-']");

const elementsCount = elementsWithCategoryClasses.length;

for (let i = 0; i < elementsCount; ++i) {
  // Append all the classes of the matching elements to
  // allCategoryClasses.

  // Note we are not filtering out the other classes that
  // do not start with 'category-' yet.

  Array.prototype.push.apply(
    allCategoryClasses,
    elementsWithCategoryClasses[i].classList
  );
}

// Now filter out the classes that do not start with
// 'category-' here, so we do it just one time, instead
// of doing it once for each single element.

// Also, use and object to remove duplicates.

const presentClasses = {};

console.log(allCategoryClasses
  .filter((classname) => {
    const present = presentClasses[classname];

    presentClasses[classname] = true;

    return classname.indexOf("category-") === 0 && !present;
  }));

// This will also filter out duplicates:

// const presentClasses = {};

// allCategoryClasses
//   .forEach((classname) => {
//     if (classname.indexOf("category-") === 0) {
//       presentClasses[classname] = true;
//     }
//   });

// console.log(Object.keys(presentClasses));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="category-a other-class"></div>
<div class="other-class category-b"></div>
<div class="category-c category-d other-class"></div>
<div class="category-e other-class category-f"></div>
<div class="other-class"></div>
<div class="category-e other-class category-f"></div></code>```

Body:
I want to extract classes based on specific prefix like "category-lifestyle" or "category-magazine".

The HTML markup looks like this:

    Post content...

Body:
If you want to get a list of all the classes that start with, let's say, category-, you should first get all the elements that contain a matching class using an attribute contains selector:

document.querySelectorAll("*[class*='category-']")

Then you should extract all the classes of those elements and filter out duplicates and those that do not start with the desired prefix.

Something like this:

const allCategoryClasses = [];

// Get all elements that have any class starting
// with 'category-':

const elementsWithCategoryClasses
  = document.querySelectorAll("*[class*='category-']");

const elementsCount = elementsWithCategoryClasses.length;

for (let i = 0; i < elementsCount; ++i) {
  // Append all the classes of the matching elements to
  // allCategoryClasses.

  // Note we are not filtering out the other classes that
  // do not start with 'category-' yet.

  Array.prototype.push.apply(
    allCategoryClasses,
    elementsWithCategoryClasses[i].classList
  );
}

// Now filter out the classes that do not start with
// 'category-' here, so we do it just one time, instead
// of doing it once for each single element.

// Also, use and object to remove duplicates.

const presentClasses = {};

console.log(allCategoryClasses
  .filter((classname) => {
    const present = presentClasses[classname];

    presentClasses[classname] = true;

    return classname.indexOf("category-") === 0 && !present;
  }));

// This will also filter out duplicates:

// const presentClasses = {};

// allCategoryClasses
//   .forEach((classname) => {
//     if (classname.indexOf("category-") === 0) {
//       presentClasses[classname] = true;
//     }
//   });

// console.log(Object.keys(presentClasses));

<div class="category-a other-class"></div>
<div class="other-class category-b"></div>
<div class="category-c category-d other-class"></div>
<div class="category-e other-class category-f"></div>
<div class="other-class"></div>
<div class="category-e other-class category-f"></div>


问:
Update TextBox while in Background Worker
Unable to update textbox value while in background worker,
value to be updated is sum of column("TaxableValue") of a datatable created inside background worker.
No Error message is prompted

On Button Click following event is raised

Private Sub btnCalcTax_Click(sender As Object, e As EventArgs) Handles btnCalcTax.Click
        BackgroundWorker1.RunWorkerAsync()
    End Sub
```

<p>I have created a function to calculate TAX.</p>

<pre class="lang-vb prettyprint-override"><code>Public Sub TAXCALC(itemname As String, rackrate As Double, discountedrate As Double, billdate As Date)
    Dim finalfdtaxcalcdt As New DataTable
    finalfdtaxcalcdt.Columns.Clear()
    finalfdtaxcalcdt.Rows.Clear()
    Dim outlettyp As String = "POS"
    Dim taxcount As New DataTable
    Dim tax As New DataTable
    If finalfdtaxcalcdt.Columns.Count = 0 Then
        finalfdtaxcalcdt.Columns.Add("TaxID")
        finalfdtaxcalcdt.Columns.Add("TaxName")
        finalfdtaxcalcdt.Columns.Add("TaxableValue")
        finalfdtaxcalcdt.Columns.Add("TaxRate")
        finalfdtaxcalcdt.Columns.Add("SalesAmount")
        finalfdtaxcalcdt.Columns.Add("TaxAmount")
        finalfdtaxcalcdt.Columns.Add("SalesID")
        finalfdtaxcalcdt.Columns.Add("PurchaseID")
        finalfdtaxcalcdt.Columns.Add("TaxClassID")
    End If

    For i = 0 To BodyGridView.RowCount - 1
        If IsDBNull(BodyGridView.GetRowCellValue(i, "Particulars")) Then
            Exit Sub
        End If
        If BodyGridView.GetRowCellValue(i, "Particulars") <> "# End of List" Then
            Dim tempdt As New DataTable

            If isinterstate Then
                GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select Distinct(TaxClassid) from mstitemTaxClass where ApplyFrom = (SELECT MAX(ApplyFrom) FROM dbo.MstItemTaxClass WHERE ApplyFrom <= '" + billdate.ToString("yyyy-MM-dd") + "' and ItemId = '" + GetDataFromSql("Select ITEM_ID from MStItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars") + "'", con) + "')) and IsInterState = 'TRUE'", tempdt)
                'GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select TaxClass_Id from MstItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars").ToString + "') and IsInterState = 'True'", tempdt)
            Else
                GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select Distinct(TaxClassid) from mstitemTaxClass where ApplyFrom = (SELECT MAX(ApplyFrom) FROM dbo.MstItemTaxClass WHERE ApplyFrom <= '" + billdate.ToString("yyyy-MM-dd") + "' and ItemId = '" + GetDataFromSql("Select ITEM_ID from MStItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars") + "'", con) + "')) and IsInterState = 'False'", tempdt)
                'GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select TaxClass_Id from MstItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars").ToString + "') and IsInterState = 'False'", tempdt)
            End If

            Dim sum As Double = tempdt.Compute("SUM(TaxRate)", String.Empty)

            For j = 0 To tempdt.Rows.Count - 1
                If finalfdtaxcalcdt.Select("TaxID = '" + tempdt.Rows(j).Item(0).ToString + "'").Count = 0 Then
                    finalfdtaxcalcdt.Rows.Add()
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxID") = tempdt.Rows(j).Item("Tax_ID").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxName") = tempdt.Rows(j).Item("TaxName").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxRate") = tempdt.Rows(j).Item("TaxRate").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount") = Double.Parse(BodyGridView.GetRowCellValue(i, "Amount"))
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxAmount") = Math.Round((Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount")) / (1 + (Double.Parse(sum) * 0.01))) * (Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxRate")) * 0.01), 2)
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxableValue") = Math.Round(Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount")) / (1 + (sum * 0.01)), 2)
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesID") = tempdt.Rows(j).Item("SalesAc_ID").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxClassID") = tempdt.Rows(j).Item("TaxClassId").ToString
                    'finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("PurchaseID") = tempdt.Rows(j).Item("TaxRate").ToString
                Else
                    Dim index As Integer = finalfdtaxcalcdt.Rows.IndexOf(finalfdtaxcalcdt.Select("TaxId = '" + tempdt.Rows(j).Item(0).ToString + "'").FirstOrDefault())
                    finalfdtaxcalcdt.Rows(index).Item("SalesAmount") = Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) + Double.Parse(BodyGridView.GetRowCellValue(i, "Amount"))
                    finalfdtaxcalcdt.Rows(index).Item("TaxAmount") = Math.Round((Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) / (1 + (Double.Parse(sum) * 0.01))) * (Double.Parse(finalfdtaxcalcdt.Rows(index).Item("TaxRate")) * 0.01), 2)
                    finalfdtaxcalcdt.Rows(index).Item("TaxableValue") = Math.Round(Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) / (1 + (sum * 0.01)), 2)
                End If
            Next
        End If
    Next
    '        MsgBox(finalfdtaxcalcdt.Compute("Sum(TaxAmount)", String.Empty).ToString + "1")
    '        TaxGridControl.DataSource = finalfdtaxcalcdt
    ''       TaxGridView.Columns("TaxID").Visible = False
    '     TaxGridView.Columns("SalesAmount").Visible = False
    '    TaxGridView.Columns("SalesID").Visible = False
    '   TaxGridView.Columns("PurchaseID").Visible = False
    '  TaxGridView.Columns("TaxClassID").Visible = False
    Dim k As String = finalfdtaxcalcdt.Compute("Sum(TaxAmount)", String.Empty)
    TextBox1.Invoke(DirectCast(Sub() TextBox1.Text = k.ToString, MethodInvoker))
End Sub
</code>```

I am unable to update sum of column("TaxableValue") to Textbox1.text

Code For BackgroundWorker_DoWork is

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            TAXCALC()
 End Sub
```

答:
You cannot access form objects in the context of a background worker thread as both objects run in the context of different threads (even though they might run in the context of the same process).

Data from the background worker needs to be buffered inside your class. The routine which fetches this data and passes it to the control must be run in the context of the process which created the form.

A fast and simple approach would be to create

A buffer variable containing result data from background worker

A boolean variable indicating that data is ready to be fetched (may be set on RunWorkerCompleted event)

An update routine on your form (e.g. timer) to check indicator variable and to update controls as necessary

A get routine to fetch buffered data, to reset indicator and to clear buffer

Note: The update routine should be kept as brief as possible, as it will run synchronously and thus block the form. For more complex control updates, consider researching on BeginUpdate, SuspendLayout, ResumeLayout, EndUpdate and common windows.forms.control update behavior.

Body:
Unable to update textbox value while in background worker,
value to be updated is sum of column("TaxableValue") of a datatable created inside background worker.
No Error message is prompted

On Button Click following event is raised

Private Sub btnCalcTax_Click(sender As Object, e As EventArgs) Handles btnCalcTax.Click
        BackgroundWorker1.RunWorkerAsync()
    End Sub

I have created a function to calculate TAX.

Public Sub TAXCALC(itemname As String, rackrate As Double, discountedrate As Double, billdate As Date)
    Dim finalfdtaxcalcdt As New DataTable
    finalfdtaxcalcdt.Columns.Clear()
    finalfdtaxcalcdt.Rows.Clear()
    Dim outlettyp As String = "POS"
    Dim taxcount As New DataTable
    Dim tax As New DataTable
    If finalfdtaxcalcdt.Columns.Count = 0 Then
        finalfdtaxcalcdt.Columns.Add("TaxID")
        finalfdtaxcalcdt.Columns.Add("TaxName")
        finalfdtaxcalcdt.Columns.Add("TaxableValue")
        finalfdtaxcalcdt.Columns.Add("TaxRate")
        finalfdtaxcalcdt.Columns.Add("SalesAmount")
        finalfdtaxcalcdt.Columns.Add("TaxAmount")
        finalfdtaxcalcdt.Columns.Add("SalesID")
        finalfdtaxcalcdt.Columns.Add("PurchaseID")
        finalfdtaxcalcdt.Columns.Add("TaxClassID")
    End If

    For i = 0 To BodyGridView.RowCount - 1
        If IsDBNull(BodyGridView.GetRowCellValue(i, "Particulars")) Then
            Exit Sub
        End If
        If BodyGridView.GetRowCellValue(i, "Particulars") <> "# End of List" Then
            Dim tempdt As New DataTable

            If isinterstate Then
                GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select Distinct(TaxClassid) from mstitemTaxClass where ApplyFrom = (SELECT MAX(ApplyFrom) FROM dbo.MstItemTaxClass WHERE ApplyFrom <= '" + billdate.ToString("yyyy-MM-dd") + "' and ItemId = '" + GetDataFromSql("Select ITEM_ID from MStItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars") + "'", con) + "')) and IsInterState = 'TRUE'", tempdt)
                'GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select TaxClass_Id from MstItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars").ToString + "') and IsInterState = 'True'", tempdt)
            Else
                GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select Distinct(TaxClassid) from mstitemTaxClass where ApplyFrom = (SELECT MAX(ApplyFrom) FROM dbo.MstItemTaxClass WHERE ApplyFrom <= '" + billdate.ToString("yyyy-MM-dd") + "' and ItemId = '" + GetDataFromSql("Select ITEM_ID from MStItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars") + "'", con) + "')) and IsInterState = 'False'", tempdt)
                'GetDataSetFromSqlToDataTable("Select * from MstTax where TaxClassId = (Select TaxClass_Id from MstItem where Item = '" + BodyGridView.GetRowCellValue(i, "Particulars").ToString + "') and IsInterState = 'False'", tempdt)
            End If

            Dim sum As Double = tempdt.Compute("SUM(TaxRate)", String.Empty)

            For j = 0 To tempdt.Rows.Count - 1
                If finalfdtaxcalcdt.Select("TaxID = '" + tempdt.Rows(j).Item(0).ToString + "'").Count = 0 Then
                    finalfdtaxcalcdt.Rows.Add()
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxID") = tempdt.Rows(j).Item("Tax_ID").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxName") = tempdt.Rows(j).Item("TaxName").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxRate") = tempdt.Rows(j).Item("TaxRate").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount") = Double.Parse(BodyGridView.GetRowCellValue(i, "Amount"))
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxAmount") = Math.Round((Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount")) / (1 + (Double.Parse(sum) * 0.01))) * (Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxRate")) * 0.01), 2)
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxableValue") = Math.Round(Double.Parse(finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesAmount")) / (1 + (sum * 0.01)), 2)
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("SalesID") = tempdt.Rows(j).Item("SalesAc_ID").ToString
                    finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("TaxClassID") = tempdt.Rows(j).Item("TaxClassId").ToString
                    'finalfdtaxcalcdt.Rows(finalfdtaxcalcdt.Rows.Count - 1).Item("PurchaseID") = tempdt.Rows(j).Item("TaxRate").ToString
                Else
                    Dim index As Integer = finalfdtaxcalcdt.Rows.IndexOf(finalfdtaxcalcdt.Select("TaxId = '" + tempdt.Rows(j).Item(0).ToString + "'").FirstOrDefault())
                    finalfdtaxcalcdt.Rows(index).Item("SalesAmount") = Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) + Double.Parse(BodyGridView.GetRowCellValue(i, "Amount"))
                    finalfdtaxcalcdt.Rows(index).Item("TaxAmount") = Math.Round((Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) / (1 + (Double.Parse(sum) * 0.01))) * (Double.Parse(finalfdtaxcalcdt.Rows(index).Item("TaxRate")) * 0.01), 2)
                    finalfdtaxcalcdt.Rows(index).Item("TaxableValue") = Math.Round(Double.Parse(finalfdtaxcalcdt.Rows(index).Item("SalesAmount")) / (1 + (sum * 0.01)), 2)
                End If
            Next
        End If
    Next
    '        MsgBox(finalfdtaxcalcdt.Compute("Sum(TaxAmount)", String.Empty).ToString + "1")
    '        TaxGridControl.DataSource = finalfdtaxcalcdt
    ''       TaxGridView.Columns("TaxID").Visible = False
    '     TaxGridView.Columns("SalesAmount").Visible = False
    '    TaxGridView.Columns("SalesID").Visible = False
    '   TaxGridView.Columns("PurchaseID").Visible = False
    '  TaxGridView.Columns("TaxClassID").Visible = False
    Dim k As String = finalfdtaxcalcdt.Compute("Sum(TaxAmount)", String.Empty)
    TextBox1.Invoke(DirectCast(Sub() TextBox1.Text = k.ToString, MethodInvoker))
End Sub

I am unable to update sum of column("TaxableValue") to Textbox1.text

Code For BackgroundWorker_DoWork is

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            TAXCALC()
 End Sub


问:
Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat
If I run gradle assembleDebug from the command line, I am suddenly getting this error:

```<code>UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dx.util.DexException: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl;
    at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:592)
    at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:550)
    at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:531)
    at com.android.dx.merge.DexMerger.mergeDexBuffers(DexMerger.java:168)
    at com.android.dx.merge.DexMerger.merge(DexMerger.java:186)
    at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:300)
    at com.android.dx.command.dexer.Main.run(Main.java:232)
    at com.android.dx.command.dexer.Main.main(Main.java:174)
    at com.android.dx.command.Main.main(Main.java:91)
</code>```

If I grep for v4 I see two files inside my build folder.

```<code>Binary file build/pre-dexed/debug/support-v4-19.0.0-2ba5fdd60a6c3836b3104a863fe42897da1fa9d1.jar matches
Binary file build/pre-dexed/debug/support-v4-r7-227d905d79b23b20866531d4f700446c040a2ccb.jar matches
</code>```

My gradle file includes only this support library:

```<code>compile 'com.android.support:support-v13:19.0.0'
</code>```

I am stumped as to how the r7 library is included somehow. I've run gradle clean and it always appears there when I rerun assembleDebug.

If I grep for r7 inside the build directory, I see it inside the file:

```<code>Binary file build/exploded-bundles/ComGoogleAndroidGmsPlayServices4030.aar/classes.jar matches
</code>```

If I don't include v13, then other things don't compile.

But doesn't v13 include v4 support library?

Is this an incompatibility between play services AAR bundle and the v13 library?

I grabbed the gradle file from gradleplease.appspot.com.

Removing play services does not fix it; same error.

My dependencies inside build.gradle:

```<code> dependencies {

 // Google Play Services
//compile 'com.google.android.gms:play-services:4.0.30'

// Support Libraries
//compile 'com.android.support:support-v4:19.0.0'
///compile 'com.android.support:appcompat-v7:19.0.0'
//compile 'com.android.support:gridlayout-v7:19.0.0'
compile 'com.android.support:support-v13:19.0.0'
compile 'org.eclipse.mylyn.github:org.eclipse.egit.github.core:2.1.5'
compile 'commons-codec:commons-codec:1.9'
compile 'com.madgag:markdownj-core:0.4.1'
compile 'com.wu-man:android-oauth-client:0.0.2'
compile 'com.google.http-client:google-http-client-jackson2:1.17.0-rc'
compile 'org.apache.commons:commons-lang3:3.2'
compile 'com.google.code.gson:gson:2.2.4'
}
</code>```

答:
I had the same problem when adding react-native-palette to my project, here is my dependencies tree:

```<code>./gradlew app:dependencies
+--- project :react-native-palette
|    +--- com.facebook.react:react-native:0.20.+ -> 0.44.2
|    |    +--- javax.inject:javax.inject:1
|    |    +--- com.android.support:appcompat-v7:23.0.1
|    |    |    \--- com.android.support:support-v4:23.0.1
|    |    |         \--- com.android.support:support-annotations:23.0.1 -> 24.2.1
...
|    \--- com.android.support:palette-v7:24.+ -> 24.2.1
|         +--- com.android.support:support-compat:24.2.1
|         |    \--- com.android.support:support-annotations:24.2.1
|         \--- com.android.support:support-core-utils:24.2.1
|              \--- com.android.support:support-compat:24.2.1 (*)
+--- com.android.support:appcompat-v7:23.0.1 (*)
\--- com.facebook.react:react-native:+ -> 0.44.2 (*)
</code>```

I tried many solutons and could not fix it, until changing the com.android.support:appcompat version in android/app/build.gradle, I wish this can help:

```<code>dependencies {
    compile project(':react-native-palette')
    compile project(':react-native-image-picker')
    compile project(':react-native-camera')
    compile fileTree(dir: "libs", include: ["*.jar"])
    // compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.android.support:appcompat-v7:24.2.1"
    compile "com.facebook.react:react-native:+"
}
</code>```

it seems that multiple entries is not a big problem, version mismatch is

Body:
If I run gradle assembleDebug from the command line, I am suddenly getting this error:

UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dx.util.DexException: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl;
    at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:592)
    at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:550)
    at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:531)
    at com.android.dx.merge.DexMerger.mergeDexBuffers(DexMerger.java:168)
    at com.android.dx.merge.DexMerger.merge(DexMerger.java:186)
    at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:300)
    at com.android.dx.command.dexer.Main.run(Main.java:232)
    at com.android.dx.command.dexer.Main.main(Main.java:174)
    at com.android.dx.command.Main.main(Main.java:91)

If I grep for v4 I see two files inside my build folder.

Binary file build/pre-dexed/debug/support-v4-19.0.0-2ba5fdd60a6c3836b3104a863fe42897da1fa9d1.jar matches
Binary file build/pre-dexed/debug/support-v4-r7-227d905d79b23b20866531d4f700446c040a2ccb.jar matches

My gradle file includes only this support library:

compile 'com.android.support:support-v13:19.0.0'

I am stumped as to how the r7 library is included somehow. I've run gradle clean and it always appears there when I rerun assembleDebug.

If I grep for r7 inside the build directory, I see it inside the file:

Binary file build/exploded-bundles/ComGoogleAndroidGmsPlayServices4030.aar/classes.jar matches

If I don't include v13, then other things don't compile.

But doesn't v13 include v4 support library?

Is this an incompatibility between play services AAR bundle and the v13 library?

I grabbed the gradle file from gradleplease.appspot.com.

Removing play services does not fix it; same error.

My dependencies inside build.gradle:

 dependencies {

 // Google Play Services
//compile 'com.google.android.gms:play-services:4.0.30'

// Support Libraries
//compile 'com.android.support:support-v4:19.0.0'
///compile 'com.android.support:appcompat-v7:19.0.0'
//compile 'com.android.support:gridlayout-v7:19.0.0'
compile 'com.android.support:support-v13:19.0.0'
compile 'org.eclipse.mylyn.github:org.eclipse.egit.github.core:2.1.5'
compile 'commons-codec:commons-codec:1.9'
compile 'com.madgag:markdownj-core:0.4.1'
compile 'com.wu-man:android-oauth-client:0.0.2'
compile 'com.google.http-client:google-http-client-jackson2:1.17.0-rc'
compile 'org.apache.commons:commons-lang3:3.2'
compile 'com.google.code.gson:gson:2.2.4'
}

Body:
I had the same problem when adding react-native-palette to my project, here is my dependencies tree:

./gradlew app:dependencies
+--- project :react-native-palette
|    +--- com.facebook.react:react-native:0.20.+ -> 0.44.2
|    |    +--- javax.inject:javax.inject:1
|    |    +--- com.android.support:appcompat-v7:23.0.1
|    |    |    \--- com.android.support:support-v4:23.0.1
|    |    |         \--- com.android.support:support-annotations:23.0.1 -> 24.2.1
...
|    \--- com.android.support:palette-v7:24.+ -> 24.2.1
|         +--- com.android.support:support-compat:24.2.1
|         |    \--- com.android.support:support-annotations:24.2.1
|         \--- com.android.support:support-core-utils:24.2.1
|              \--- com.android.support:support-compat:24.2.1 (*)
+--- com.android.support:appcompat-v7:23.0.1 (*)
\--- com.facebook.react:react-native:+ -> 0.44.2 (*)

I tried many solutons and could not fix it, until changing the com.android.support:appcompat version in android/app/build.gradle, I wish this can help:

dependencies {
    compile project(':react-native-palette')
    compile project(':react-native-image-picker')
    compile project(':react-native-camera')
    compile fileTree(dir: "libs", include: ["*.jar"])
    // compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.android.support:appcompat-v7:24.2.1"
    compile "com.facebook.react:react-native:+"
}

it seems that multiple entries is not a big problem, version mismatch is


问:
Overlay lines with a varying number of points from a list using ggplot2
I'd like to plot multiple lines with a varying number of points per line, with different colors using ggplot2. My MWE is given by

```<code>test <- list()
length(test) <- 10
for(i in 1:10){
  test[[i]] <- rnorm(100 - i) # Note - different number of points per line!!!!
}
</code>```

Note that The length for each vector in list are different. Then, is not possible to transform in data.frame.

答:
As already pointed out by Mike Wise in his accepted answer, gplot2 requires a data.frame as input, preferably in long format.

However, both question and accepted answer used for loops although R has neat functions. To create the test data set, the following "one-liner" can been
used:

```<code>set.seed(1234L)   # required to ensure reproducible data
test <- lapply(100L - 1:10, rnorm)
</code>```

instead of

```<code>test <- list()
length(test) <- 10
for(i in 1:10){
  test[[i]] <- rnorm(100 - i)
}
</code>```

Note the use of set.seed() to ensure reproducible random data.

To reshape test from wide to long form, the whole list is turned into a data.frame at once using unlist(), adding the additional columns as required:

```<code>df <- data.frame(
  id = rep(seq_along(test), lengths(test)),
  x = sequence(lengths(test)),
  y = unlist(test)
)
</code>```

instead of turning each list element into a separate small data.frame and incrementally appending the pieces to a target data.frame using a for loop.

The plot is then created by

```<code>library(ggplot2)
ggplot(df) + geom_line(aes(x = x, y = y, color = as.factor(id)))
</code>```

Alternatively, the melt() function has a method for lists:

```<code>library(data.table)
long <- melt(test, measure.vars = seq_along(test))
setDT(long)[, rn := rowid(L1)] # add row numbers for each group
ggplot(long) + aes(x = rn, y = value, color = as.factor(L1)) + geom_line()
</code>```

Body:
I'd like to plot multiple lines with a varying number of points per line, with different colors using ggplot2. My MWE is given by

test <- list()
length(test) <- 10
for(i in 1:10){
  test[[i]] <- rnorm(100 - i) # Note - different number of points per line!!!!
}

Note that The length for each vector in list are different. Then, is not possible to transform in data.frame.

Body:
As already pointed out by Mike Wise in his accepted answer, gplot2 requires a data.frame as input, preferably in long format.

However, both question and accepted answer used for loops although R has neat functions. To create the test data set, the following "one-liner" can been
used:

set.seed(1234L)   # required to ensure reproducible data
test <- lapply(100L - 1:10, rnorm)

instead of

test <- list()
length(test) <- 10
for(i in 1:10){
  test[[i]] <- rnorm(100 - i)
}

Note the use of set.seed() to ensure reproducible random data.

To reshape test from wide to long form, the whole list is turned into a data.frame at once using unlist(), adding the additional columns as required:

df <- data.frame(
  id = rep(seq_along(test), lengths(test)),
  x = sequence(lengths(test)),
  y = unlist(test)
)

instead of turning each list element into a separate small data.frame and incrementally appending the pieces to a target data.frame using a for loop.

The plot is then created by

library(ggplot2)
ggplot(df) + geom_line(aes(x = x, y = y, color = as.factor(id)))

Alternatively, the melt() function has a method for lists:

library(data.table)
long <- melt(test, measure.vars = seq_along(test))
setDT(long)[, rn := rowid(L1)] # add row numbers for each group
ggplot(long) + aes(x = rn, y = value, color = as.factor(L1)) + geom_line()


问:
Creating temp column upon logic
How can I create a temp (empty) column in which values will be inserted upon logic:

```<code>SELECT ..., *temp_col*

FROM *table*

IF *table.column_1* is not null, THEN *temp_col=table.column_1*

else temp_col=table.column_2
</code>```

Note: Colume_1 is a CLOB field which will be transformed to TEXT.
someone advised me to use the EXIST condition.

答:
In SQL, you use the CASE expression or the COALESCE() function:

```<code>SELECT ...,
       COALESCE(table.column_1, table.column_2) as temp_col
FROM table;
</code>```

Title: Creating temp column upon logic

Body:
How can I create a temp (empty) column in which values will be inserted upon logic:

SELECT ..., *temp_col*

FROM *table*

IF *table.column_1* is not null, THEN *temp_col=table.column_1*

else temp_col=table.column_2

Note: Colume_1 is a CLOB field which will be transformed to TEXT.
someone advised me to use the EXIST condition.

Body:
In SQL, you use the CASE expression or the COALESCE() function:

SELECT ...,
       COALESCE(table.column_1, table.column_2) as temp_col
FROM table;


问:
jQuery ajaxStart
I have the following in my code, but I'm not getting an alert message, even though I can see the $.ajax call is working correctly.

```<code>(function($)
 {
    $('.debug').ajaxStart(function() { alert('ajaxStart'); });
 }
)(jQuery);
</code>```

And of course, in the html, I have:

```<code><div class="debug">
     <h3>debug info:</h3>
</div>
</code>```

Maybe it's because I use:

```<code>google.load("jquery", "1");
google.setOnLoadCallback(OnLoad);
</code>```

答:
You made mistake in code ;)

```<code>(function($)
{
    $('.debug').ajaxStart(function()
    {
        alert('ajaxStart');
    });
}(jQuery));
</code>```

You closed the first bracket after anonymous function, but you had to do that after (jQuery).

For example:

( function($){ body }(jQuery) );

Title: jQuery ajaxStart

Body:
I have the following in my code, but I'm not getting an alert message, even though I can see the $.ajax call is working correctly.

(function($)
 {
    $('.debug').ajaxStart(function() { alert('ajaxStart'); });
 }
)(jQuery);

And of course, in the html, I have:

debug info:

Maybe it's because I use:

google.load("jquery", "1");
google.setOnLoadCallback(OnLoad);

Body:
You made mistake in code ;)

(function($)
{
    $('.debug').ajaxStart(function()
    {
        alert('ajaxStart');
    });
}(jQuery));

You closed the first bracket after anonymous function, but you had to do that after (jQuery).

For example:

( function($){ body }(jQuery) );


问:
How to create custom attribute that support all views in android?
In Android, XML is used for designing User Interface. Android provide set of attributes for each tag [ex: id,layout_width, layout_height].

But Is there any possibility to add a new attribute for all the tags commonly in Android.

```<code> <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/search_result"
    extra = "This is search field"
    useOfThisTag = "Search Operation"
    etc...
 />
</code>```

答:
It depends on what would you like to achieve. There are no global attributes in the official Android implementation. The ones you mentioned are of two kinds:

View attributes: id, tag, background, padding, etc. These are interpreted by View class and seem to be global, because almost everything you see in xml layout files extends View.

Layout attributes: width, height, margin, etc. This group is always interpreted by a parent layout. If you place a view inside LinearLayout, for that view you can use attributes declared by LinearLayout.LayoutParams.

If you wish to add a truly global attribute, you can try Calligraphy's approach. It's a library which adds support for custom fonts to all text views. Their author uses a custom ContextWrapper and a resource parser to intercept Calligraphy's attributes while parsing view tags.

This is very similiar to how include, fragment, layout and merge tags work but on attribute level. These tags are global and are parsed and handled inside LayoutInflater.

Body:
In Android, XML is used for designing User Interface. Android provide set of attributes for each tag [ex: id,layout_width, layout_height].

But Is there any possibility to add a new attribute for all the tags commonly in Android.

 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/search_result"
    extra = "This is search field"
    useOfThisTag = "Search Operation"
    etc...
 />


问:
What is the best case for a function: Database connection in function or pass it as argument?
I have a page where I establish a database connection at first. I use this for some queries and after that I also use some functions. And now I'm not sure whats the best practice for a function: pass database connection as argument or create a own database connection in the function?

Create database connection in function

```<code>function get_Number_of_Entries() {
  $mysqli = new mysqli(MYSQL_HOST,MYSQL_USER,MYSQL_PASSWORD,MYSQL_DATABASE);
  $stmt = $mysqli->prepare("SELECT * FROM users");
  $stmt->execute();
  $stmt->store_result();
  $count = $stmt->num_rows;
  $stmt->close();
  return $count;
}
</code>```

As argument "$stmt", no database connection created in function

```<code>function get_Number_of_Entries($mysqli) {
  $stmt = $mysqli->prepare("SELECT * FROM users");
  $stmt->execute();
  $stmt->store_result();
  $count = $stmt->num_rows;
  $stmt->close();
  return $count;
}
</code>```

答:
Usually, passing the connection as argument will be a better solution.
making connection it's an expensive action, and more than that, more than one connection can be make a real trouble. it can be lock the database and many more scenarios.

I would be recommending to read about Singleton pattern:
https://en.wikipedia.org/wiki/Singleton_pattern

or factory pattern:
https://www.tutorialspoint.com/design_pattern/factory_pattern.htm

Body:
I have a page where I establish a database connection at first. I use this for some queries and after that I also use some functions. And now I'm not sure whats the best practice for a function: pass database connection as argument or create a own database connection in the function?

Create database connection in function

function get_Number_of_Entries() {
  $mysqli = new mysqli(MYSQL_HOST,MYSQL_USER,MYSQL_PASSWORD,MYSQL_DATABASE);
  $stmt = $mysqli->prepare("SELECT * FROM users");
  $stmt->execute();
  $stmt->store_result();
  $count = $stmt->num_rows;
  $stmt->close();
  return $count;
}

As argument "$stmt", no database connection created in function

function get_Number_of_Entries($mysqli) {
  $stmt = $mysqli->prepare("SELECT * FROM users");
  $stmt->execute();
  $stmt->store_result();
  $count = $stmt->num_rows;
  $stmt->close();
  return $count;
}


问:
Accents, urls and Firefox
I'm having some problems and I was wondering if any of you could help me.

I have my site & DB set to utf8. I have a problem when I type in accents in the query strings section ã turns to %E3, but if i use links or forms within the page it gives %C3%A3 in the url.

What can I do?

EDIT: Let me try to clarify this a bit:

I'm trying to use accented characters in my URLs (query strings) but I'm having somewhat of a hard time getting this to work across multiple browsers. Some browsers like Firefox and IE output a different percent encoded string depending on whether I'm using a form within the page or typing the accented character in the address bar. Like I said in my original question, ã inputed in a form turns to %C3%A3 in the url but if I type ã in the address bar, the browser changes that to %E3 in the url.

This complicates things for me because if I get %E3, then in php/html I get an unknown character (that is the diamond question mark, correct?)

Hopefully this helps - let me know otherwise.

答:
ã inputed in a form turns to %C3%A3 in the url

Depends on the form encoding, which is usually taken from the encoding of the page that contains the form. %C3%A9 is the correct UTF-8 URL-encoded form of ã.

if I type ã in the address bar, the browser changes that to %E3 in the url.

This is browser-dependent. When you put non-ASCII characters in the a URL in location bar:

```<code>http://www.example.com/test.p/café?café
</code>```

WebKit browsers encode them all as UTF-8:

```<code>http://www.example.com/test.p/caf%C3%A9?caf%C3%A9
</code>```

which is IMO most correct, as per IRI. However, IE and Opera, for historical reasons, use the OS's default system encoding to encode text entered into the query string only. So on a Western European Windows installation (using code page 1252), you get:

```<code>http://www.example.com/test.p/caf%C3%A9?caf%E9
</code>```

For characters that aren't available in the system encoding, IE and Opera replaces them with a ?. Firefox will use the system encoding when all the characters in the query string, or UTF-8 otherwise.

Horrible and inconsistent, but then it's pretty rare for users to manually type out query strings.

Title: Accents, urls and Firefox

Body:
ã inputed in a form turns to %C3%A3 in the url

Depends on the form encoding, which is usually taken from the encoding of the page that contains the form. %C3%A9 is the correct UTF-8 URL-encoded form of ã.

if I type ã in the address bar, the browser changes that to %E3 in the url.

This is browser-dependent. When you put non-ASCII characters in the a URL in location bar:

http://www.example.com/test.p/café?café

WebKit browsers encode them all as UTF-8:

http://www.example.com/test.p/caf%C3%A9?caf%C3%A9

which is IMO most correct, as per IRI. However, IE and Opera, for historical reasons, use the OS's default system encoding to encode text entered into the query string only. So on a Western European Windows installation (using code page 1252), you get:

http://www.example.com/test.p/caf%C3%A9?caf%E9

For characters that aren't available in the system encoding, IE and Opera replaces them with a ?. Firefox will use the system encoding when all the characters in the query string, or UTF-8 otherwise.

Horrible and inconsistent, but then it's pretty rare for users to manually type out query strings.


问:
Python httplib.InvalidURL: nonnumeric port fail
I'm trying to open a URL in Python that needs username and password.  My specific implementation looks like this:

```<code>http://char_user:char_pwd@casfcddb.example.com/......
</code>```

I get the following error spit to the console:

```<code>httplib.InvalidURL: nonnumeric port: 'char_pwd@casfcddb.example.com'
</code>```

I'm using urllib2.urlopen, but the error is implying it doesn't understand the user credentials.  That it sees the ":" and expects a port number rather than the password and actual address.  Any ideas what I'm doing wrong here?

答:
I ran into a situation where I needed BasicAuth handling and only had urllib available (no urllib2 or requests). The answer from Uku mostly worked, but here are my mods:</p>

```<code>import urllib.request
url = 'https://your/url.xxx'
username = 'username'
password = 'password'
passman = urllib.request.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
auth_handler = urllib.request.HTTPBasicAuthHandler(passman)
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
resp = urllib.request.urlopen(url)
data = resp.read()
</code>```

Body:
I'm trying to open a URL in Python that needs username and password.  My specific implementation looks like this:

http://char_user:char_pwd@casfcddb.example.com/......

I get the following error spit to the console:

httplib.InvalidURL: nonnumeric port: 'char_pwd@casfcddb.example.com'

I'm using urllib2.urlopen, but the error is implying it doesn't understand the user credentials.  That it sees the ":" and expects a port number rather than the password and actual address.  Any ideas what I'm doing wrong here?

Body:
I ran into a situation where I needed BasicAuth handling and only had urllib available (no urllib2 or requests). The answer from Uku mostly worked, but here are my mods:

import urllib.request
url = 'https://your/url.xxx'
username = 'username'
password = 'password'
passman = urllib.request.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
auth_handler = urllib.request.HTTPBasicAuthHandler(passman)
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
resp = urllib.request.urlopen(url)
data = resp.read()