问:
Specify alternatives in java validation annotations
I'm looking for a way to specify validation constraint that allows alternatives, for example:

```<code>@Documented
@Constraint(validatedBy = {})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Pattern(regexp = "^(\\s|\\d|[-+:()])*$")
@Or( // I'm looking for something like this
    @Size(min = 6, max = 20),
    @Size(min = 0, max = 0)
)
public @interface Phone {
    String message() default "Not a valid phone number";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}
</code>```

Is it possible using java validator tools?

答:
I found a solution involving creating several intermediate annotations and using @ConstraintComposition(CompositionType.OR), but maybe someone will propose better solution.

So, first, create Annotation for single branch of alternative:

```<code>@Documented
@Constraint(validatedBy = {})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Size(max = 0)
public @interface Empty {
    String message() default "Should be empty string";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}
</code>```

Secondly, create another annotation, that combines your custom annotation with another branch:

```<code>@Documented
@Constraint(validatedBy = {})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@ConstraintComposition(CompositionType.OR)
@Size
@Empty
public @interface SizeOrEmpty {
    String message() default "Should be empty or have defined size";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    @OverridesAttribute(constraint = Size.class, name = "min") int min();

    @OverridesAttribute(constraint = Size.class, name = "max") int max();
}
</code>```

Unfortunately, you cannot use two @Size annotations, as it is not a @Repeatable annotation, and, secondly, you cannot override attributes from only one of them with @OverridesAttribute.

Body:
I'm looking for a way to specify validation constraint that allows alternatives, for example:

@Documented
@Constraint(validatedBy = {})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Pattern(regexp = "^(\\s|\\d|[-+:()])*$")
@Or( // I'm looking for something like this
    @Size(min = 6, max = 20),
    @Size(min = 0, max = 0)
)
public @interface Phone {
    String message() default "Not a valid phone number";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Is it possible using java validator tools?

Body:
I found a solution involving creating several intermediate annotations and using @ConstraintComposition(CompositionType.OR), but maybe someone will propose better solution.

So, first, create Annotation for single branch of alternative:

@Documented
@Constraint(validatedBy = {})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Size(max = 0)
public @interface Empty {
    String message() default "Should be empty string";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Secondly, create another annotation, that combines your custom annotation with another branch:

@Documented
@Constraint(validatedBy = {})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@ConstraintComposition(CompositionType.OR)
@Size
@Empty
public @interface SizeOrEmpty {
    String message() default "Should be empty or have defined size";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    @OverridesAttribute(constraint = Size.class, name = "min") int min();

    @OverridesAttribute(constraint = Size.class, name = "max") int max();
}

Unfortunately, you cannot use two @Size annotations, as it is not a @Repeatable annotation, and, secondly, you cannot override attributes from only one of them with @OverridesAttribute.


来源: stackexchange

问:
Google Cloud BigQuery is not refreshing?
Excuse me for maybe a not very precise question, but I just need to check if I am missing something or it really is some kind of problem with Google Cloud (GC) BigQuery.

I've got this Java program that reads from a website and publish the data into a GC Pub/Sub Topic; a pipeline is conveniently up, pulling the message from Pub/Sub and sending it to BigQuery via the template job offered in GC Dataflow. In the end, a DataStudio dashboard is getting the data from the BigQuery table and building up its charts and all...

The thing is, all the process is working fine: I can see the resulting dashboard being populated correctly, BUT I cannot see the data in the table in BigQuery, even after refreshing the whole page. Sometimes the results show on the following day (!).

Is it me forgetting something, or is it GC BigQuery in a beta release being incomplete?

答: As @Pentium10 said, the GUI is just for quick previews. It does take some time to update itself. If you want to check if the data is in the table do a query.</p>

ContentLicense: CC BY-SA 3.0


问:
htaccess does not understand ^www\. rule , if paramters are appended to url
.htaccess does not understand ^www\. rule

```<code>#do not use this, because i want to redirect from https://www.somedomain.com
#RewriteCond %{HTTPS} off

RewriteCond %{HTTP:X-Forwarded-Proto} !https [OR]
RewriteCond %{HTTP_HOST} ^somedomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.somedomain\.com$
RewriteRule ^/?$ "https\:\/\/somedomain\.com" [L,R=301]
#[NE,L,R=301] - NE|noescape
</code>```

This gives the following redirections, though very slow:

somedomain.com  -->  https://somedomain.com

www.somedomain.com  -->  https://www.somedomain.com

somedomain.com/folder/file  -->  https://somedomain.com/folder/file

www.somedomain.com/folder/file  -->  http://www.somedomain.com/folder/file

the last url www.somedomain.com/folder/file is not redirected to https. WHY?

答:
This works will all urls with parameters and without.
And it is true, it is very important to clear cache and try to relaod page several times, in several different browsers. Otherwise, some old rules may apply.

```<code>RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^somedomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.somedomain\.com$ [NC]
RewriteRule ^(.*)$ https://somedomain.com%{REQUEST_URI} [L,NE,R=301]
</code>```

Results are :

somedomain.com --> https://somedomain.com

www.somedomain.com --> https://www.somedomain.com

somedomain.com/folder/file --> https://somedomain.com/folder/file

www.somedomain.com/folder/file --> https://www.somedomain.com/folder/file

TO make things faster:

```<code>DirectoryIndex /index.php
RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^typejoy\.biz$
#RewriteCond %{HTTP_HOST} ^typejoy\.biz$ [OR]
#RewriteCond %{HTTP_HOST} ^www\.typejoy\.biz$ [NC]
RewriteRule ^(.*)$ https://typejoy.biz%{REQUEST_URI} [L,NE,R=301]

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.typejoy\.biz$ [NC]
RewriteRule ^(.*)$ https://typejoy.biz%{REQUEST_URI} [L,NE,R=301]

RewriteCond %{HTTP_HOST} ^www\.typejoy\.biz$ [NC]
RewriteRule ^(.*)$ https://typejoy.biz%{REQUEST_URI} [L, NE,R=301]
</code>```

i believe you should not not put L if there are more rules

Body:
.htaccess does not understand ^www\. rule

#do not use this, because i want to redirect from https://www.somedomain.com
#RewriteCond %{HTTPS} off

RewriteCond %{HTTP:X-Forwarded-Proto} !https [OR]
RewriteCond %{HTTP_HOST} ^somedomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.somedomain\.com$
RewriteRule ^/?$ "https\:\/\/somedomain\.com" [L,R=301]
#[NE,L,R=301] - NE|noescape

This gives the following redirections, though very slow:

somedomain.com  -->  https://somedomain.com

www.somedomain.com  -->  https://www.somedomain.com

somedomain.com/folder/file  -->  https://somedomain.com/folder/file

www.somedomain.com/folder/file  -->  http://www.somedomain.com/folder/file

the last url www.somedomain.com/folder/file is not redirected to https. WHY?

Body:
This works will all urls with parameters and without.
And it is true, it is very important to clear cache and try to relaod page several times, in several different browsers. Otherwise, some old rules may apply.

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^somedomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.somedomain\.com$ [NC]
RewriteRule ^(.*)$ https://somedomain.com%{REQUEST_URI} [L,NE,R=301]

Results are :

somedomain.com --> https://somedomain.com

www.somedomain.com --> https://www.somedomain.com

somedomain.com/folder/file --> https://somedomain.com/folder/file

www.somedomain.com/folder/file --> https://www.somedomain.com/folder/file

TO make things faster:

DirectoryIndex /index.php
RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^typejoy\.biz$
#RewriteCond %{HTTP_HOST} ^typejoy\.biz$ [OR]
#RewriteCond %{HTTP_HOST} ^www\.typejoy\.biz$ [NC]
RewriteRule ^(.*)$ https://typejoy.biz%{REQUEST_URI} [L,NE,R=301]

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.typejoy\.biz$ [NC]
RewriteRule ^(.*)$ https://typejoy.biz%{REQUEST_URI} [L,NE,R=301]

RewriteCond %{HTTP_HOST} ^www\.typejoy\.biz$ [NC]
RewriteRule ^(.*)$ https://typejoy.biz%{REQUEST_URI} [L, NE,R=301]

i believe you should not not put L if there are more rules


问:
Is std::string thead-safe with gcc 4.3?
I'm developing a multithreaded program running on Linux (compiled with G++ 4.3) and if you search around for a bit you find a lot of scary stories about std::string not being thread-safe with GCC. This is supposedly due to the fact that internally it uses copy-on-write which wreaks havoc with tools like Helgrind.

I've made a small program that copies one string to another string and if you inspect both strings they both share the same internal _M_p pointer. When one string is modified the pointer changes so the copy-on-write stuff is working fine.

What I'm worried about though is what happens if I share a string between two threads (for instance passing it as an object in a threadsafe dataqueue between two threads). I've already tried compiling with the '-pthread' option but that does not seem to make much difference. So my question:

Is there any way to force std::string to be threadsafe? I would not mind if the copy-on-write behaviour was disabled to achieve this.

How have other people solved this? Or am I being paranoid?

I can't seem to find a definitive answer so I hope you guys can help me..

Edit:

Wow, that's a whole lot of answers in such a short time. Thank you! I will definitely use Jack's solution when I want to disable COW. But now the main question becomes: do I really have to disable COW? Or is the 'bookkeeping' done for COW thread safe? I'm currently browsing the libstdc++ sources but that's going to take quite some time to figure out...

Edit 2

OK browsed the libstdc++ source code and I find something like this in libstd++-v3/include/bits/basic_string.h:

```<code>  _CharT*
   _M_refcopy() throw()
   {
#ifndef _GLIBCXX_FULLY_DYNAMIC_STRING
     if (__builtin_expect(this != &_S_empty_rep(), false))
#endif
            __gnu_cxx::__atomic_add_dispatch(&this->_M_refcount, 1);
     return _M_refdata();
   }  // XXX MT
</code>```

So there is definitely something there about atomic changes to the reference counter...

Conclusion

I'm marking sellibitze's comment as answer here because I think we've reached the conclusion that this area is still unresolved for now. To circumvent the COW behaviour I'd suggest Jack Lloyd's answer. Thank you everybody for an interesting discussion!

答:
This section of the libstdc++ internals states:

The C++ library string functionality
  requires a couple of atomic operations
  to provide thread-safety. If you don't
  take any special action, the library
  will use stub versions of these
  functions that are not thread-safe.
  They will work fine, unless your
  applications are multi-threaded.

The reference counting should work in a multi-threaded environment. (unless your system doesn't provide the necessary atomics)

ContentLicense: CC BY-SA 2.5

Title: Is std::string thead-safe with gcc 4.3?

Body:
I'm developing a multithreaded program running on Linux (compiled with G++ 4.3) and if you search around for a bit you find a lot of scary stories about std::string not being thread-safe with GCC. This is supposedly due to the fact that internally it uses copy-on-write which wreaks havoc with tools like Helgrind.

I've made a small program that copies one string to another string and if you inspect both strings they both share the same internal _M_p pointer. When one string is modified the pointer changes so the copy-on-write stuff is working fine.

What I'm worried about though is what happens if I share a string between two threads (for instance passing it as an object in a threadsafe dataqueue between two threads). I've already tried compiling with the '-pthread' option but that does not seem to make much difference. So my question:

Is there any way to force std::string to be threadsafe? I would not mind if the copy-on-write behaviour was disabled to achieve this.

How have other people solved this? Or am I being paranoid?

I can't seem to find a definitive answer so I hope you guys can help me..

Edit:

Wow, that's a whole lot of answers in such a short time. Thank you! I will definitely use Jack's solution when I want to disable COW. But now the main question becomes: do I really have to disable COW? Or is the 'bookkeeping' done for COW thread safe? I'm currently browsing the libstdc++ sources but that's going to take quite some time to figure out...

Edit 2

OK browsed the libstdc++ source code and I find something like this in libstd++-v3/include/bits/basic_string.h:

  _CharT*
   _M_refcopy() throw()
   {
#ifndef _GLIBCXX_FULLY_DYNAMIC_STRING
     if (__builtin_expect(this != &_S_empty_rep(), false))
#endif
            __gnu_cxx::__atomic_add_dispatch(&this->_M_refcount, 1);
     return _M_refdata();
   }  // XXX MT

So there is definitely something there about atomic changes to the reference counter...

Conclusion

I'm marking sellibitze's comment as answer here because I think we've reached the conclusion that this area is still unresolved for now. To circumvent the COW behaviour I'd suggest Jack Lloyd's answer. Thank you everybody for an interesting discussion!


问:
How can i send daily mail with my application using azure pass
I want to send daily email with my application.

Background
My application has web.api which created .net core & published on Azure app api (Paas).
API has it's own authentication mechanism(JWT token) & it's used dependancy injection. It read configuration value ex. Database, Redis cache, bob storage connection string from Azure key vault

Solution
1)If i create new console application and set in web job. I have to do lot of coding for dependnecy injection and have to integrate azure valut.
2)Can i create web api in current api project but how to ensure security only azure web job can call api.

same question ::Securely calling a WebSite hosted Web API from an Azure WebJob

答:
As you mentioned that we could use the Azure scheduled WebJob to send daily mail. Send mail demo code please refer to another SO thread.

Can i create web api in current api project but how to ensure security only azure web job can call api.

We need to use our authentication way to security our WebApi. And Azure also supply multiple ways to help us protect our WebApp. We can get more info about
Authentication and authorization for API Apps in Azure App Service  from document.


问:
Querying in Firebase for Android isn't working
```<code>reference = database.getReferenceFromUrl("https://...........firebaseio.com/General/Dish");
dishName.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        searchString = editable.toString();
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.d("firebase",dataSnapshot.getKey());
                for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                    s.setText(snapshot.getValue(String.class));
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };
        reference.startAt(searchString).addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Log.d("Firebase",dataSnapshot.getKey()+">>>>"+dataSnapshot.getValue()+">>>"+s);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        s1.setText(searchString);
</code>```

Why isn't Im not getting any query back from Firebase? I've used both addValueEventListner and addListnerForSingleValueEvent. Nothing is happening. "......" in Url represent my firebase database url. Since this is my mvp for my startup i dont want to share. And also I know getInstances().child("..") is also an alternative.

答:
Distilling your code down, it becomes:

```<code>reference = database.getReferenceFromUrl("https://...........firebaseio.com/General/Dish");
reference.startAt(searchString).addChildEventListener(...
</code>```

Since you don't specify what to order on, Firebase will search the key in this case.

You probably want:

```<code>reference.orderByChild("name").startAt(searchString).addChildEventListener(...
</code>```

Body:
reference = database.getReferenceFromUrl("https://...........firebaseio.com/General/Dish");
dishName.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        searchString = editable.toString();
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.d("firebase",dataSnapshot.getKey());
                for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                    s.setText(snapshot.getValue(String.class));
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };
        reference.startAt(searchString).addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Log.d("Firebase",dataSnapshot.getKey()+">>>>"+dataSnapshot.getValue()+">>>"+s);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        s1.setText(searchString);

Why isn't Im not getting any query back from Firebase? I've used both addValueEventListner and addListnerForSingleValueEvent. Nothing is happening. "......" in Url represent my firebase database url. Since this is my mvp for my startup i dont want to share. And also I know getInstances().child("..") is also an alternative.

Body:
Distilling your code down, it becomes:

reference = database.getReferenceFromUrl("https://...........firebaseio.com/General/Dish");
reference.startAt(searchString).addChildEventListener(...

Since you don't specify what to order on, Firebase will search the key in this case.

You probably want:

reference.orderByChild("name").startAt(searchString).addChildEventListener(...


问:
ignored setbounds
I simply would like to place my JButton by the setBounds method. But whatever the parameters of this method, the button is on the middle at the top.

This is my code :

```<code>import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

class Panneau_fenetre1A extends JPanel
{
    JButton boutonOK = new JButton ("OK");

    public Panneau_fenetre1A(int Na)
    {
        boutonOK.setBounds(300,300,30,30);
        add(boutonOK);

    }

}
</code>```

答:
You are extending JPanel so the default constructor of JPanel is used and the default LayoutManager is, for whatever reason, the FlowLayout !
So if you really want to use NullLayout you could add this to your class:

```<code>  public Panneau_fenetre1A()
  {
    super(null);
  }
</code>```

But seriously consider other Layout managers, for example the BorderLayoutManager (super(new BorderLayout())) is a good start.

When designing your dialog, remember that you can and should nest your layouts: one JPanel inside another JPanel (e.g. a GridLayout inside a BorderLayout). Please note: a 'good' dialog should resize properly, so that if the user resizes your Frame, you want to automatically extend your information objects such as your table, and not show large areas of JPanel background. That's something you cannot achieve with a NullLayout.

Title: ignored setbounds

Body:
I simply would like to place my JButton by the setBounds method. But whatever the parameters of this method, the button is on the middle at the top.

This is my code :

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

class Panneau_fenetre1A extends JPanel
{
    JButton boutonOK = new JButton ("OK");

    public Panneau_fenetre1A(int Na)
    {
        boutonOK.setBounds(300,300,30,30);
        add(boutonOK);

    }

}

Body:
You are extending JPanel so the default constructor of JPanel is used and the default LayoutManager is, for whatever reason, the FlowLayout !
So if you really want to use NullLayout you could add this to your class:

  public Panneau_fenetre1A()
  {
    super(null);
  }

But seriously consider other Layout managers, for example the BorderLayoutManager (super(new BorderLayout())) is a good start.

When designing your dialog, remember that you can and should nest your layouts: one JPanel inside another JPanel (e.g. a GridLayout inside a BorderLayout). Please note: a 'good' dialog should resize properly, so that if the user resizes your Frame, you want to automatically extend your information objects such as your table, and not show large areas of JPanel background. That's something you cannot achieve with a NullLayout.


问:
Change recursive .then to async/await
I have js recursive fn like this

```<code>const recur = () => {
  fetchSomething().then( res => {
    if(typeof res.data == 'undefined'){ recur() }
    else { console.log(res.data) }
  })
}
recur()
</code>```

Can I apply above code to Async/Await style?

答:
torazaburo and robertklep both rightfully recommend using a while instead to achieve this. Ill add the comments here so they dont get missed as they make good points.

IMHO the non-recursive solution should be the preferred one. The nature of promises and then sort of requires the pseudo-recursive solution, but one of the great advantages of await is that it allows us to write asynchronous code in synchronous-like fashion.

```<code>const recur = async () => {
    const res = await fetchSomething();

    if (!res.data)
        recur();
    else
        console.log(res.data);
}
</code>```

Something like that should do the trick.

Demo

Title: Change recursive .then to async/await

Body:
I have js recursive fn like this

const recur = () => {
  fetchSomething().then( res => {
    if(typeof res.data == 'undefined'){ recur() }
    else { console.log(res.data) }
  })
}
recur()

Can I apply above code to Async/Await style?

Body:
torazaburo and robertklep both rightfully recommend using a while instead to achieve this. Ill add the comments here so they dont get missed as they make good points.

IMHO the non-recursive solution should be the preferred one. The nature of promises and then sort of requires the pseudo-recursive solution, but one of the great advantages of await is that it allows us to write asynchronous code in synchronous-like fashion.

const recur = async () => {
    const res = await fetchSomething();

    if (!res.data)
        recur();
    else
        console.log(res.data);
}

Something like that should do the trick.

Demo


问:
npm "failed to parse json"
When I'm trying to install express with npm I always get the following error:

```<code>Failed to parse json
No data, empty input at 1:1
File: /root/.npm/inherits/2.0.1/package/package.json
Failed to parse package.json data.
package.json must be actual JSON, not just JavaScript.

This is not a bug in npm.
Tell the package author to fix their package.json file. JSON.parse
</code>```

What am I doing wrong?

```<code> sudo npm install -g express
</code>```

OS is Ubuntu 12.04 (precise) armhf

答:
I had the same problem but "npm cache clean" didnt resolve it for me. I had to go back to my package.json and realize i had comma where it shouldn't i suppose as shown below:

```<code>},
  "devDependencies": {
    "axios": "^0.15.3",
    "bootstrap-sass": "^3.3.7",
    "cross-env": "^3.2.4",
    "jquery": "^3.1.1",
    "laravel-mix": "0.*",
    "lodash": "^4.17.4",
    "vue": "^2.1.10",
  }
</code>```

after  the "vue..." so I deleted that and every went back to normal. So it is worth checking the package.json file first before running npm cache clean

Title: npm "failed to parse json"

Body:
When I'm trying to install express with npm I always get the following error:

Failed to parse json
No data, empty input at 1:1
File: /root/.npm/inherits/2.0.1/package/package.json
Failed to parse package.json data.
package.json must be actual JSON, not just JavaScript.

This is not a bug in npm.
Tell the package author to fix their package.json file. JSON.parse

What am I doing wrong?

 sudo npm install -g express

OS is Ubuntu 12.04 (precise) armhf

Body:
I had the same problem but "npm cache clean" didnt resolve it for me. I had to go back to my package.json and realize i had comma where it shouldn't i suppose as shown below:

},
  "devDependencies": {
    "axios": "^0.15.3",
    "bootstrap-sass": "^3.3.7",
    "cross-env": "^3.2.4",
    "jquery": "^3.1.1",
    "laravel-mix": "0.*",
    "lodash": "^4.17.4",
    "vue": "^2.1.10",
  }

after  the "vue..." so I deleted that and every went back to normal. So it is worth checking the package.json file first before running npm cache clean


问:
postdeploy schema changes
In my sql project I have such scripts. This files has build action = Build.
It means that this sql code  will place in model file (sql server dac Package file).

```<code>CREATE TABLE [dbo].[Class] (
        [Id]   SMALLINT      NOT NULL,
        [Name] NVARCHAR (50) NOT NULL,
    );
</code>```

I want to make build action = None and place this code to post deploy file of dacpac.

But when I deploy this dacpac to db the second time I will get an error.

"There is already an object named 'Class' in the database"

When this code is placed in model dacpac file I don't get this error.

How I can push changes of schema to db via postdeploy file?

Should I use manual migration scripts?

答:
```<code>IF NOT EXISTS(
SELECT 1 FROM sys.objects where name='Class'
AND type='U'
)
Begin

CREATE TABLE [dbo].[Class] (
        [Id]   SMALLINT      NOT NULL,
        [Name] NVARCHAR (50) NOT NULL,
    );
END
</code>```

Title: postdeploy schema changes

Body:
In my sql project I have such scripts. This files has build action = Build.
It means that this sql code  will place in model file (sql server dac Package file).

CREATE TABLE [dbo].[Class] (
        [Id]   SMALLINT      NOT NULL,
        [Name] NVARCHAR (50) NOT NULL,
    );

I want to make build action = None and place this code to post deploy file of dacpac.

But when I deploy this dacpac to db the second time I will get an error.

"There is already an object named 'Class' in the database"

When this code is placed in model dacpac file I don't get this error.

How I can push changes of schema to db via postdeploy file?

Should I use manual migration scripts?


问:
Is there an inverse to Git's octopus merge?
Git has a much-touted(?) octopus-merge capability that can merge many heads into one.

But is there something that would do just the opposite, make several simultaneous branches out of one node?

Let's assume that I have a bunch of code for a project, and I just started using Git. Some of the features are complete in that project, others are still work-in-progress. What I'd want is to get those unfinished features moved into their own respective and separate branch, and have the master as 'complete' as possible, with no unfinished code.

Now, I could of course do all of this in single steps: Create a "unfinished feature #1" branch, and delete the files from the master that are specific to that feature. Then I'd re-branch the master into "unfinished feature #2" and again remove feature #2 specific files from the master, but also from the first branch. And thus the workload increases for each split I do.

Is there something that would help me in such a scenario?

答:
Side note: the octopus merge and the octopus branchpoint scenarios are very different. Please remember that pointers in DAG (directed acyclic graph) of commits point from child (newer commit) to parent or parents. So in the case of octopus merge you have commit (commit object) which has more than two parents; in the case of "octopus branchpoint" you simply have a few commits pointing to the same commit as its parent.

octopus merge:

```<code>1 <---- M
2 <----/ |
3 <------|
</code>```

octopus branchpoint:

```<code>P <----- 1
^-------- 2
^-------- 3
</code>```

So I think naming of this question is simply wrong

The answer

Now, if what you want to do is to split modifications in your working area between different branches, to put each feature in separate topic branch, you can make use of explicit staging area (aka index) in Git.

Let's assume that you modified two files, 'a' and 'b', and you want modification to file 'a' to go to branch 'A', and modification in file 'b' to go to branch 'B'. Let's assume that the branch you are currently on, the branching point you want to be base of many branches you want to create, is named 'master'.

First, lets create branch 'A'

```<code>$ git checkout -b A master
</code>```

Git replies with:

```<code>M       a
M       b
Switched to a new branch "A"
</code>```

The "M" means that the files 'a' and 'b' are modified with respect to the point you based branch 'A' on (the 'master' branch). (Below, I will simply put git response below commandline invocation, instead of separately noting what's a reply.)

Let us add contents of file 'a' to the staging area (index).

```<code>$ git add a
</code>```

Note that if you want to add only some subset of changes in file 'a' to branch 'A', you could use "git add --interactive" (abbreviated as "-i") or "git gui" to do per-hunk addition of changes to the staging area and other such manipulations.

Now we commit changes to branch 'A'

```<code>$ git commit
Created commit 35d0061: Commit description...
 1 files changed, 1 insertions(+), 0 deletions(-)
</code>```

Note that we didn't use the '-a' option to git-commit!

By the way, if you want to test changes before comitting from staging area, you can use "git stash save --keep-index" to get working area to the state you are to commit using "git commit", test changes, then go back to previous state using "git stash pop --index" (or "git stash pop"; I don't remember which one do you need here).

Now we create the other branch, branch 'B', based on branch 'master'

```<code>$ git checkout -b B master
M       b
Switched to a new branch "B"
</code>```

You can easily see that the changes you have left for branch 'B' (the changes you didn't commit to branch 'A') goes to newly created branch 'B'. No need to delete files, or remove changes. No need to know what is in other branches. Everything is automatic.

Once again, add contents of file 'b' to staging area (index), and commit on branch 'B':

```<code>$ git add B
$ git commit
</code>```

You can repeat this as often as necessary, and it doesn't get harder with the new branch.

HTH

OwnerDisplayName: wolfie

Body:
Side note: the octopus merge and the octopus branchpoint scenarios are very different. Please remember that pointers in DAG (directed acyclic graph) of commits point from child (newer commit) to parent or parents. So in the case of octopus merge you have commit (commit object) which has more than two parents; in the case of "octopus branchpoint" you simply have a few commits pointing to the same commit as its parent.

octopus merge:

1 <---- M
2 <----/ |
3 <------|

octopus branchpoint:

P <----- 1
^-------- 2
^-------- 3

So I think naming of this question is simply wrong

The answer

Now, if what you want to do is to split modifications in your working area between different branches, to put each feature in separate topic branch, you can make use of explicit staging area (aka index) in Git.

Let's assume that you modified two files, 'a' and 'b', and you want modification to file 'a' to go to branch 'A', and modification in file 'b' to go to branch 'B'. Let's assume that the branch you are currently on, the branching point you want to be base of many branches you want to create, is named 'master'.

First, lets create branch 'A'

$ git checkout -b A master

Git replies with:

M       a
M       b
Switched to a new branch "A"

The "M" means that the files 'a' and 'b' are modified with respect to the point you based branch 'A' on (the 'master' branch). (Below, I will simply put git response below commandline invocation, instead of separately noting what's a reply.)

Let us add contents of file 'a' to the staging area (index).

$ git add a

Note that if you want to add only some subset of changes in file 'a' to branch 'A', you could use "git add --interactive" (abbreviated as "-i") or "git gui" to do per-hunk addition of changes to the staging area and other such manipulations.

Now we commit changes to branch 'A'

$ git commit
Created commit 35d0061: Commit description...
 1 files changed, 1 insertions(+), 0 deletions(-)

Note that we didn't use the '-a' option to git-commit!

By the way, if you want to test changes before comitting from staging area, you can use "git stash save --keep-index" to get working area to the state you are to commit using "git commit", test changes, then go back to previous state using "git stash pop --index" (or "git stash pop"; I don't remember which one do you need here).

Now we create the other branch, branch 'B', based on branch 'master'

$ git checkout -b B master
M       b
Switched to a new branch "B"

You can easily see that the changes you have left for branch 'B' (the changes you didn't commit to branch 'A') goes to newly created branch 'B'. No need to delete files, or remove changes. No need to know what is in other branches. Everything is automatic.

Once again, add contents of file 'b' to staging area (index), and commit on branch 'B':

$ git add B
$ git commit

You can repeat this as often as necessary, and it doesn't get harder with the new branch.

HTH

OwnerDisplayName: Jakub Narębski

LastEditorDisplayName: Jakub Narębski


问:
Can't include both subject AND body using mailto via Mac OS X "open" command
I just figured here out how to open a pre-populated new email message window using c++ on Mac OS X via the "open" command.
Unfortunately I couldn't get it to insert both a message body and a subject.

This code should open a new message with a recipient, a subject and a body filled in but it doesn't. Only the recipient and subject are filled in.

```<code>mailto:obama@whitehouse.gov?subject=Congrats%20Obama&body=Hello
</code>```

If I remove the subject, it would successfully include the recipient and body such as in this code so the body itself doesn't seem to be incorrectly formatted.

```<code>mailto:obama@whitehouse.gov?body=Hello
</code>```

Please let me know if you can figure out how to open a "new message" window with both a subject AND a body message.

答:
The ampersand (&) is the culprit; everything before it executes in the background and body=... executes separately.

Escape it with a backslash.

Since this is a C++ string, you also need to escape the backslash itself; \\&.

Body:
I just figured here out how to open a pre-populated new email message window using c++ on Mac OS X via the "open" command.
Unfortunately I couldn't get it to insert both a message body and a subject.

This code should open a new message with a recipient, a subject and a body filled in but it doesn't. Only the recipient and subject are filled in.

mailto:obama@whitehouse.gov?subject=Congrats%20Obama&body=Hello

If I remove the subject, it would successfully include the recipient and body such as in this code so the body itself doesn't seem to be incorrectly formatted.

mailto:obama@whitehouse.gov?body=Hello

Please let me know if you can figure out how to open a "new message" window with both a subject AND a body message.


问:
Property 'first' does not exist on type 'FirebaseListObservable<any[]>'
I am using ionic 2

I installed angular fire2

Version: "angularfire2": "^2.0.0-beta.7-pre",

I am getting this err

```<code>Property 'first' does not exist on type 'FirebaseListObservable<any[]>'
</code>```

I remove my nodemodules.

again npm install

Still getting same err.

How can I fix this issue.

答:
if you want to get the first element in your FirebaseListObservable< any[]> in html file, then you can do like following:

```<code><div *ngFor="let item of items | async | slice:0:1">{{item}}</div>
</code>```

where "items" is FirebaseListObservable< any[]>

if you want to get the first element in your .ts file, then you should do like this:

```<code>firstItem: any;
...
this.items.subscribe((allItems) => {this.firstItem = allItems[0]});
</code>```

Body:
I am using ionic 2

I installed angular fire2

Version: "angularfire2": "^2.0.0-beta.7-pre",

I am getting this err

Property 'first' does not exist on type 'FirebaseListObservable<any[]>'

I remove my nodemodules.

again npm install

Still getting same err.

How can I fix this issue.

Body:
if you want to get the first element in your FirebaseListObservable< any[]> in html file, then you can do like following:

<div *ngFor="let item of items | async | slice:0:1">{{item}}</div>

where "items" is FirebaseListObservable< any[]>

if you want to get the first element in your .ts file, then you should do like this:

firstItem: any;
...
this.items.subscribe((allItems) => {this.firstItem = allItems[0]});


问:
Codeigniter - Adding Code to Constructor without affected to Specific Controller Function
Short Version of this question

How to write something like this (if(Controller Function is Not "Login()" Function)) in Codeigniter Constructor?

```<code>if(Controller Function is Not "Login()" Function)
{
    if(empty($this->session->userdata('user_id'))){
        redirect(base_url());
    }
}
</code>```

Long Version of this question if is not clear the short version

This is Admin controller of my codeigniter project

```<code>class Admin extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        /**
        *
        *
        *  Here - I am going to check session is set or not.....
        *
        *
        */

    }

    public function login(){

    }

    public function update(){

    }

    public function edit(){

    }

    public function insert(){

    }

        /**
        *
        *
        *  And Many More Functions
        *
        *
        */

}
</code>```

I am going to add following code part to constructor.

```<code>if(empty($this->session->userdata('user_id'))){
    redirect(base_url());
}
</code>```

When I write this even I can't go to the login() function without session. How to write above code in constructor which not affect to the login function.

I am looking something like this,

```<code>if(Controller Function is Not "Login()" Function)
{
    if(empty($this->session->userdata('user_id'))){
        redirect(base_url());
    }
}
</code>```

答:
You can use something like this </p>

```<code>function __construct()
{
    if(!($this->session->has_userdata('user_id')) && $this->router->fetch_method()!='login'){
        redirect(base_url());
    }
}
</code>```

Body:
Short Version of this question

How to write something like this (if(Controller Function is Not "Login()" Function)) in Codeigniter Constructor?

if(Controller Function is Not "Login()" Function)
{
    if(empty($this->session->userdata('user_id'))){
        redirect(base_url());
    }
}

Long Version of this question if is not clear the short version

This is Admin controller of my codeigniter project

class Admin extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        /**
        *
        *
        *  Here - I am going to check session is set or not.....
        *
        *
        */

    }

    public function login(){

    }

    public function update(){

    }

    public function edit(){

    }

    public function insert(){

    }

        /**
        *
        *
        *  And Many More Functions
        *
        *
        */

}

I am going to add following code part to constructor.

if(empty($this->session->userdata('user_id'))){
    redirect(base_url());
}

When I write this even I can't go to the login() function without session. How to write above code in constructor which not affect to the login function.

I am looking something like this,

if(Controller Function is Not "Login()" Function)
{
    if(empty($this->session->userdata('user_id'))){
        redirect(base_url());
    }
}

Body:
You can use something like this

function __construct()
{
    if(!($this->session->has_userdata('user_id')) && $this->router->fetch_method()!='login'){
        redirect(base_url());
    }
}


问:
Show image in a popup when I click button
I have a button and i need to show an image in a popup when i click this button.

Why this code doesn't work? I try with a window.open in onclick event but it doesn't work

```<code><input type="button" value="Mostra Immagine" onclick=window.open(src="../img/mypicture.jpg")>
</code>```

Where is my error?

答:
you are missing the " in onclick  and add with _blank for new page .passing the argument with in function using ' quotes

```<code><input type="button" value="Mostra Immagine" onclick="window.open('../img/mypicture.jpg','_blank')">
</code>```

Body:
I have a button and i need to show an image in a popup when i click this button.

Why this code doesn't work? I try with a window.open in onclick event but it doesn't work

<input type="button" value="Mostra Immagine" onclick=window.open(src="../img/mypicture.jpg")>

Where is my error?

Body:
you are missing the " in onclick  and add with _blank for new page .passing the argument with in function using ' quotes

<input type="button" value="Mostra Immagine" onclick="window.open('../img/mypicture.jpg','_blank')">


问:
Non numeric for x-axis in scatter chart in CHART.js
I am trying to generate a scatter chart using chartjs. In my scatter chart i want the x-axis scale label to be a string. But if i try the below code i get numbers in my x-axis label scale

```<code>datasets: [{
        label: 'Scatter Dataset',
        data: [{
            x: "a",
            y: 0
        }, {
            x: "b",
            y: 3
        }, {
            x: "",
            y: 5
        }]
    }]
</code>```

How to set my x-axis scale as string values and make the graph work?

答: I do not believe what you are asking is achievable with scatter chart. Documentation says it only accepts data in a point format. Hence your data definition is even incorrect. You can use line chart and give data in an array format (only y-axis values) and provide labels property as array of strings you wish to display as x-axis labels. See the starting example for an illustration.

Body:
I am trying to generate a scatter chart using chartjs. In my scatter chart i want the x-axis scale label to be a string. But if i try the below code i get numbers in my x-axis label scale

datasets: [{
        label: 'Scatter Dataset',
        data: [{
            x: "a",
            y: 0
        }, {
            x: "b",
            y: 3
        }, {
            x: "",
            y: 5
        }]
    }]

How to set my x-axis scale as string values and make the graph work?


问:
Page didn't redirect in Angularjs
I've created an authentication process with firebase and angularjs.

After the authentication process, the page must redirect to the htmlnew.html Using $routeprovider. But it doesn't redirect after authentication.

index.html

```<code><html ng-app="appName">
 <body>
 <div ng-controller="loginCtrl" id="message">
    <a ng-click="googleSignin()">SignIn into App</a>
 </div>
   <p id="load">Firebase SDK Loading…</p>
 </body>
</html>
</code>```

htmlnew.html

```<code><body>
<div id="message" ng-controller="loginpage">
    <h1>Welcome</h1>
    <a ng-click="googleSignout()">Signout</a>
</div>
</body>
</code>```

app.js

```<code> var app = angular.module("appName", ["ngRoute", "firebase"]);
 app.config(function ($routeProvider) {
 $routeProvider
    .when("/", {
        templateUrl: 'public/index.html',
        controller: 'loginCtrl'
    })
    .when('/login', {
        templateUrl: 'public/htmlnew.html',
        controller: 'loginpage'
    })
  });

  app.controller('loginCtrl', function ($scope) {
  var provider = new firebase.auth.GoogleAuthProvider();
  $scope.googleSignin = function () {
  firebase.auth()
        .signInWithPopup(provider).then(function (result) {
    var token = result.credential.accessToken;
    var user = result.user;
    console.log(token);
    console.log(user);

  }).catch(function (error) {
    var errorCode = error.code;
    var errorMessage = error.message;
    console.log(errorCode);
    console.log(errorMessage);
    });
   }
 });

 app.controller('loginpage', function ($scope) {
 $scope.googleSignout = function () {
  firebase.auth().signOut()
        .then(function () {
            console.log('Signout Succesfull');
        }, function (error) {
            console.log('Signout Failed');
        });
   }
 });
</code>```

Project documentation

For demo check on this Project link

Thanks in advance

答:
Redirect to path using $location. Inject it in the controller dependencies and use as below

```<code>firebase.auth()
    .signInWithPopup(provider).then(function (result) {
        $location.path('/login');
})
</code>```

Title: Page didn't redirect in Angularjs

Body:
I've created an authentication process with firebase and angularjs.

After the authentication process, the page must redirect to the htmlnew.html Using $routeprovider. But it doesn't redirect after authentication.

index.html

    SignIn into App

Firebase SDK Loading…

htmlnew.html

Welcome

    Signout

app.js

 var app = angular.module("appName", ["ngRoute", "firebase"]);
 app.config(function ($routeProvider) {
 $routeProvider
    .when("/", {
        templateUrl: 'public/index.html',
        controller: 'loginCtrl'
    })
    .when('/login', {
        templateUrl: 'public/htmlnew.html',
        controller: 'loginpage'
    })
  });

  app.controller('loginCtrl', function ($scope) {
  var provider = new firebase.auth.GoogleAuthProvider();
  $scope.googleSignin = function () {
  firebase.auth()
        .signInWithPopup(provider).then(function (result) {
    var token = result.credential.accessToken;
    var user = result.user;
    console.log(token);
    console.log(user);

  }).catch(function (error) {
    var errorCode = error.code;
    var errorMessage = error.message;
    console.log(errorCode);
    console.log(errorMessage);
    });
   }
 });

 app.controller('loginpage', function ($scope) {
 $scope.googleSignout = function () {
  firebase.auth().signOut()
        .then(function () {
            console.log('Signout Succesfull');
        }, function (error) {
            console.log('Signout Failed');
        });
   }
 });

Project documentation

For demo check on this Project link

Thanks in advance

Body:
Redirect to path using $location. Inject it in the controller dependencies and use as below

firebase.auth()
    .signInWithPopup(provider).then(function (result) {
        $location.path('/login');
})


问:
Jupyter Notebook 5.0 - Revert old Table style
Is it possible to revert to the old style of the table view as shown in this changelog?

http://blog.jupyter.org/2017/04/04/jupyter-notebook-5-0/

I would really like to use the table style shown in 'Before:' but I don't know what I need to tweak to achieve this.

Thanks!

答:
After doing an upgrade to Jupyter 5, autocomplete didn't work and everything was super-slow, I also wanted the old table format back. What I did to downgrade to Jupyter 4 was this:

Do pip install package==version for all of these packages:

jupyter (1.0.0)

jupyter-client (4.4.0)

jupyter-console (5.0.0)

jupyter-core (4.2.0)

qtconsole (4.2.1)

nbconvert (4.2.0)

ipywidgets (5.2.2)

ipykernel (4.5.0)

notebook (4.2.3)

e.g. pip install qtconsole==4.2.1

This will revert to an older version that has the previous table format.

In order to solve the missing autocomplete feature downgrade jedi by:

pip install jedi==0.9.0

solution found here: https://github.com/ipython/ipython/issues/10493#issuecomment-298966390

This worked for me, but I am sure there are many different combinations of these packages and versions that will do the trick.


问:
How do I select a specific record from Many-to-many relationships which does not contain a specific item in Rails 2?
I am stuck with this for a couple of hours. It could be a quick solution but my brain is overheated now. Ok here it is.

I have Session and SessionType models which have many-to-many relationships to each other as follows.

```<code>class Session < ActiveRecord::Base
  ...
  has_and_belongs_to_many :session_types
  ...
end

class SessionType < ActiveRecord::Base
  ...
  has_and_belongs_to_many :sessions
  ...
end
</code>```

What I want is to get a session which doesn't contain any specific session_type, eg.,

```<code>Session.find(:all, :joins => [:session_types], :conditions => ["session_types.id <> 44"])
</code>```

It doesn't work for me since the above query will still give me the sessions which have session_types.id "44" in many of its associations because of the nature of many-to-many relationships.

Also the following mysql code doesn't work as well.

```<code>select sessions.* from sessions
INNER JOIN `session_types_sessions` ON `session_types_sessions`.session_id = `sessions`.id
WHERE (  session_types_sessions.session_type_id NOT IN (44))
GROUP BY sessions.id
</code>```

Any help will be appreciated.

Thanks.

答:
Try this:</p>

```<code>SELECT sessions.*
FROM sessions
LEFT JOIN session_types_sessions ON session_types_sessions.session_id = sessions.id AND session_types_sessions.session_type_id = 44
WHERE session_types_sessions.session_id IS NULL
</code>```

Body:
I am stuck with this for a couple of hours. It could be a quick solution but my brain is overheated now. Ok here it is.

I have Session and SessionType models which have many-to-many relationships to each other as follows.

class Session < ActiveRecord::Base
  ...
  has_and_belongs_to_many :session_types
  ...
end

class SessionType < ActiveRecord::Base
  ...
  has_and_belongs_to_many :sessions
  ...
end

What I want is to get a session which doesn't contain any specific session_type, eg.,

Session.find(:all, :joins => [:session_types], :conditions => ["session_types.id <> 44"])

It doesn't work for me since the above query will still give me the sessions which have session_types.id "44" in many of its associations because of the nature of many-to-many relationships.

Also the following mysql code doesn't work as well.

select sessions.* from sessions
INNER JOIN `session_types_sessions` ON `session_types_sessions`.session_id = `sessions`.id
WHERE (  session_types_sessions.session_type_id NOT IN (44))
GROUP BY sessions.id

Any help will be appreciated.

Thanks.

Body:
Try this:

SELECT sessions.*
FROM sessions
LEFT JOIN session_types_sessions ON session_types_sessions.session_id = sessions.id AND session_types_sessions.session_type_id = 44
WHERE session_types_sessions.session_id IS NULL


问:
Why after using strcat function original string changed?
well i have two char array . when i try to concatenate both string using strcat function.
Then my string "a" length reduced from 9 to 6.
i also lost my string "a" .string b changed too.See in the output. why this is happening ???

here is what i have done

```<code>#include <bits/stdc++.h>

using namespace std;
int main() {
    char a[]="roomies!!";
    char b[]="hey kammo DJ ";
    char *c;
    c=new char[50];
    cout<<"before:-\n";
    cout<<"len of a is "<<strlen(a)<<'\n';
    cout<<"len of b is "<<strlen(b)<<'\n';
    cout<<"len of c is "<<strlen(c)<<'\n';
    cout<<"string a is = "<<a<<'\n';
    cout<<"string b is = "<<b<<'\n';
    cout<<"string c is = "<<c<<'\n';
    c=strcat(b,a);
    cout<<"\nafter:-\n";
    cout<<"len of a is "<<strlen(a)<<'\n';
    cout<<"len of b is "<<strlen(b)<<'\n';
    cout<<"len of c is "<<strlen(c)<<'\n';
    cout<<"string a is = "<<a<<'\n';
    cout<<"string b is = "<<b<<'\n';
    cout<<"string c is = "<<c<<'\n';
return 0;
}
</code>```

output:-

```<code>before:-
len of a is 9
len of b is 13
len of c is 3
string a is = roomies!!
string b is = hey kammo DJ
string c is = =

after:-
len of a is 6
len of b is 22
len of c is 22
string a is = mies!!
string b is = hey kammo DJ roomies!!
string c is = hey kammo DJ roomies!!
</code>```

答:
strcat on C++ reference

Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first
  character of source, and a null-character is included at the end of
  the new string formed by the concatenation of both in destination.

You may use std::string for desired results.

Body:
well i have two char array . when i try to concatenate both string using strcat function.
Then my string "a" length reduced from 9 to 6.
i also lost my string "a" .string b changed too.See in the output. why this is happening ???

here is what i have done

#include <bits/stdc++.h>

using namespace std;
int main() {
    char a[]="roomies!!";
    char b[]="hey kammo DJ ";
    char *c;
    c=new char[50];
    cout<<"before:-\n";
    cout<<"len of a is "<<strlen(a)<<'\n';
    cout<<"len of b is "<<strlen(b)<<'\n';
    cout<<"len of c is "<<strlen(c)<<'\n';
    cout<<"string a is = "<<a<<'\n';
    cout<<"string b is = "<<b<<'\n';
    cout<<"string c is = "<<c<<'\n';
    c=strcat(b,a);
    cout<<"\nafter:-\n";
    cout<<"len of a is "<<strlen(a)<<'\n';
    cout<<"len of b is "<<strlen(b)<<'\n';
    cout<<"len of c is "<<strlen(c)<<'\n';
    cout<<"string a is = "<<a<<'\n';
    cout<<"string b is = "<<b<<'\n';
    cout<<"string c is = "<<c<<'\n';
return 0;
}

output:-

before:-
len of a is 9
len of b is 13
len of c is 3
string a is = roomies!!
string b is = hey kammo DJ
string c is = =

after:-
len of a is 6
len of b is 22
len of c is 22
string a is = mies!!
string b is = hey kammo DJ roomies!!
string c is = hey kammo DJ roomies!!


答:
For redirection after successfully signwithpopup u should provide state change in function(result) and if error it will catch in function(error)

$location.path('/login);

as you are using ngRoute. u can use $location.path for routing your state.

Hope this will help you.

```<code>app.controller('loginCtrl', function ($scope,$location) {
  var provider = new firebase.auth.GoogleAuthProvider();
  $scope.googleSignin = function () {
  firebase.auth()
        .signInWithPopup(provider).then(function (result) {
    var token = result.credential.accessToken;
    var user = result.user;
    $location.path('/login');
    console.log(token);
    console.log(user);

  }).catch(function (error) {
    var errorCode = error.code;
    var errorMessage = error.message;
    console.log(errorCode);
    console.log(errorMessage);
    });
   }
 });
</code>```

Title: Page didn't redirect in Angularjs

Body:
For redirection after successfully signwithpopup u should provide state change in function(result) and if error it will catch in function(error)

$location.path('/login);

as you are using ngRoute. u can use $location.path for routing your state.

Hope this will help you.

app.controller('loginCtrl', function ($scope,$location) {
  var provider = new firebase.auth.GoogleAuthProvider();
  $scope.googleSignin = function () {
  firebase.auth()
        .signInWithPopup(provider).then(function (result) {
    var token = result.credential.accessToken;
    var user = result.user;
    $location.path('/login');
    console.log(token);
    console.log(user);

  }).catch(function (error) {
    var errorCode = error.code;
    var errorMessage = error.message;
    console.log(errorCode);
    console.log(errorMessage);
    });
   }
 });


问:
ASP.NET MVC Dictionary<string,string> output in view
Controller / C#:

```<code>public Action GetData()
{
    ViewBag.InputData = new Dictionary<string, string>
    {
         ["Name"] = "Simon Lin",
         ["Age"] = "18"
    };
    return View();
}
</code>```

View / HTML:

```<code>@foreach (var keyValuePair in (ViewBag.InputData as Dictionary<string, string>))
{
     <input type="text" name=@keyValuePair.Key value="" placeholder=@keyValuePair.Value />
}
</code>```

But in the result, first input's placeholder only show "Simon", Final HTML:

```<code><input type="text" name="Name" value="" placeholder="Simon" Lin="">
</code>```

答:
You are missing quotes around the variables in your view:</p>

```<code><input type="text" name="@keyValuePair.Key" value="" placeholder="@keyValuePair.Value" />
                        ^                 ^                      ^                   ^
</code>```

Body:
Controller / C#:

public Action GetData()
{
    ViewBag.InputData = new Dictionary<string, string>
    {
         ["Name"] = "Simon Lin",
         ["Age"] = "18"
    };
    return View();
}

View / HTML:

@foreach (var keyValuePair in (ViewBag.InputData as Dictionary<string, string>))
{
     <input type="text" name=@keyValuePair.Key value="" placeholder=@keyValuePair.Value />
}

But in the result, first input's placeholder only show "Simon", Final HTML:

<input type="text" name="Name" value="" placeholder="Simon" Lin="">

Body:
You are missing quotes around the variables in your view:

<input type="text" name="@keyValuePair.Key" value="" placeholder="@keyValuePair.Value" />
                        ^                 ^                      ^                   ^


问:
String copy using character pointers
Consider the following code, which works fine asusual for copying string

```<code>#include<stdio.h>

void strcp(char *s1, char *s2);

int main() {

    char s1[]="Hai, I am a good boy";                   //1
    char s2[]="Really I am a good boy";                 //2

    strcp(s1,s2);

    printf("%s",s1);
    return 0;
}

void strcp(char *s1, char *s2) {

    while(*s1++=*s2++);
}
</code>```

What changes I have to made if I want to declare s1, s2 as pointers to char inside main()?

```<code>char *s1="Hai, I am a good boy";                   //1
char *s2="Really I am a good boy";                 //2
</code>```

I tried to copy pointer values as shown below

```<code>void strcp(char *s1, char *s2) {

s1=s2;
}
</code>```

But it didn't work.

答:
Both versions, even the one you state that it works fine, yield undefined behaviour, which may become apparent as a segmentation fault.
Generally, accessing memory requires the addressed memory to be valid, i.e. properly allocated. This is particularly true for writing to memory, as any sort of strcpy does.

In the first case, you define a variable char s1[]="Hai, I am a good boy", which implicitly reserves a memory block of about 21 one bytes and copies the string literal provided into it. If you now copy another string into s1, and the other string is longer than 21 bytes, you actually address memory that is not reserved for s1, thereby yielding undefined behaviour.

In the second case, when you define variable char *s1="Hai, I am a good boy", then no memory block to which you may write is reserved, but s1 will rather point to a memory block in a non-writeable data segment where literal "Hai, I am a good boy" resides. Copying something to this address again yields undefined behaviour, yet for a different reason.

So allocate memory for s1, e.g using malloc, and then copy content to it.

Title: String copy using character pointers

Body:
Consider the following code, which works fine asusual for copying string

#include<stdio.h>

void strcp(char *s1, char *s2);

int main() {

    char s1[]="Hai, I am a good boy";                   //1
    char s2[]="Really I am a good boy";                 //2

    strcp(s1,s2);

    printf("%s",s1);
    return 0;
}

void strcp(char *s1, char *s2) {

    while(*s1++=*s2++);
}

What changes I have to made if I want to declare s1, s2 as pointers to char inside main()?

char *s1="Hai, I am a good boy";                   //1
char *s2="Really I am a good boy";                 //2

I tried to copy pointer values as shown below

void strcp(char *s1, char *s2) {

s1=s2;
}

But it didn't work.


问:
LinkButton onclick event is not triggering for dynamically created buttons c#
I'm trying to create LinkButtons controls dynamically OnClick of another button i.e after the page load. For example: I have a button called Add Controls which functionality is to add Link Buttons dynamically, and attach an event handler for all this dynamically create Link Buttons. But unfortunately for me the events are not be triggered. The below is the piece of code that I have worked on.

Assume DomainList.Items is a collection of five elements.

```<code>protected void AddControls_Click(object sender, EventArgs e)
{
    foreach (ListItem item in DomainList.Items)
    {
        LinkButton deleteDomain = new LinkButton();

        deleteDomain.Text = "Delete";
        deleteDomain.Click += new System.EventHandler(deleteDomain_Click);
        deleteDomain.ClientIDMode = ClientIDMode.Static;
        deleteDomain.CommandArgument = item.Text;
        divEditDomainName.Controls.Add(deleteDomain);

    }
}

void deleteDomain_Click(object sender, EventArgs e)
{
    //Some Code;
}
</code>```

The below is my page load code.

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Label lblEvent = this.Master.FindControl("SpEvent") as Label;
            if (Session["eventname"] != null)
            {
                lblEvent.Text = Session["eventname"].ToString() + " " + "<i class='fa fa-angle-down'></i>";
            }
            Image imgEvent = this.Master.FindControl("ImageEvent") as Image;
            imgEvent.ImageUrl = Convert.ToString(Session["ImageURL"]);
            lblCreateOrganization.Text = Convert.ToString(Session["eventname"]);

            BindOrganization();
            EditOrganizationID.Attributes.Add("readonly", "readonly");
        }

    }
</code>```

The deleteDomain_Click event is not been triggered. I want the click event should be triggered.

答:
when Click event triggers, post back will occur so they recreated and attached to the event handler again.

The best place to create (and re-create) dynamic controls is in the page_load or page_init event handler.

try this

```<code>    public bool AddControlsClicked
    {
        get
        {
            return Convert.ToBoolean(ViewState["AddControlsClicked"]);
        }
        set
        {
            ViewState["AddControlsClicked"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if(AddControlsClicked)
        {
            for (int i = 0; i < 5; i++)
            {
                LinkButton deleteDomain = new LinkButton();

                deleteDomain.Text = "Delete";
                deleteDomain.Click += new System.EventHandler(deleteDomain_Click);
                //deleteDomain.ClientIDMode = ClientIDMode.Static;
                //deleteDomain.CommandArgument = item.Text;
                divEditDomainName.Controls.Add(deleteDomain);
            }
        }
    }

    void deleteDomain_Click(object sender, EventArgs e)
    {
        //Some Code;
    }

    protected void AddControls_Click(object sender, EventArgs e)
    {
        AddControlsClicked = true;
        Page_Load(sender, e);
    }
</code>```

Body:
I'm trying to create LinkButtons controls dynamically OnClick of another button i.e after the page load. For example: I have a button called Add Controls which functionality is to add Link Buttons dynamically, and attach an event handler for all this dynamically create Link Buttons. But unfortunately for me the events are not be triggered. The below is the piece of code that I have worked on.

Assume DomainList.Items is a collection of five elements.

protected void AddControls_Click(object sender, EventArgs e)
{
    foreach (ListItem item in DomainList.Items)
    {
        LinkButton deleteDomain = new LinkButton();

        deleteDomain.Text = "Delete";
        deleteDomain.Click += new System.EventHandler(deleteDomain_Click);
        deleteDomain.ClientIDMode = ClientIDMode.Static;
        deleteDomain.CommandArgument = item.Text;
        divEditDomainName.Controls.Add(deleteDomain);

    }
}

void deleteDomain_Click(object sender, EventArgs e)
{
    //Some Code;
}

The below is my page load code.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Label lblEvent = this.Master.FindControl("SpEvent") as Label;
            if (Session["eventname"] != null)
            {
                lblEvent.Text = Session["eventname"].ToString() + " " + "";
            }
            Image imgEvent = this.Master.FindControl("ImageEvent") as Image;
            imgEvent.ImageUrl = Convert.ToString(Session["ImageURL"]);
            lblCreateOrganization.Text = Convert.ToString(Session["eventname"]);

            BindOrganization();
            EditOrganizationID.Attributes.Add("readonly", "readonly");
        }

    }

The deleteDomain_Click event is not been triggered. I want the click event should be triggered.

Body:
when Click event triggers, post back will occur so they recreated and attached to the event handler again.

The best place to create (and re-create) dynamic controls is in the page_load or page_init event handler.

try this

    public bool AddControlsClicked
    {
        get
        {
            return Convert.ToBoolean(ViewState["AddControlsClicked"]);
        }
        set
        {
            ViewState["AddControlsClicked"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if(AddControlsClicked)
        {
            for (int i = 0; i < 5; i++)
            {
                LinkButton deleteDomain = new LinkButton();

                deleteDomain.Text = "Delete";
                deleteDomain.Click += new System.EventHandler(deleteDomain_Click);
                //deleteDomain.ClientIDMode = ClientIDMode.Static;
                //deleteDomain.CommandArgument = item.Text;
                divEditDomainName.Controls.Add(deleteDomain);
            }
        }
    }

    void deleteDomain_Click(object sender, EventArgs e)
    {
        //Some Code;
    }

    protected void AddControls_Click(object sender, EventArgs e)
    {
        AddControlsClicked = true;
        Page_Load(sender, e);
    }


问:
How to merge Aeson objects?
I have a list of aeson objects like this

```<code>[object ["key1" .= "value1"], object ["key2" .= "value2"]]
</code>```

and I want to merge them as a single aeson object like this

```<code>object ["key1" .= "value1", "key2" .= "value2"]
</code>```

This is quite standard when working with JSON data in other languages (merge operation) but I don't see anything similar in the Aeson library.

Am I just missing something and can this be done with some standard haskell function? I tried using sequence but it seems that JSON Value is not a monad so I cannot do that.

I don't need to deal with deep merging or duplicate keys, I just want to generate something like

```<code>{
  "key1": value1,
  "key2": value2
}
</code>```

from

```<code>[{ "key1": value1 }, { "key2": value2 }]
</code>```

答:
Given the list contains only of JSON objects (thus elements that have key-value pairs or elements with the Object constructor), you can write your own:

```<code>import Data.Aeson(Value(Object))
import qualified Data.HashMap.Lazy as HML

merge_aeson :: [Value] -> Value
merge_aeson = Object . HML.unions . map (\(Object x) -> x)
</code>```

If we test the above function with the given sample input, we obtain:

```<code>Prelude Data.Aeson HML> merge_aeson [object ["key1" .= "value1"], object ["key2" .= "value2"]]
Object (fromList [("key2",String "value2"),("key1",String "value1")])
</code>```

Title: How to merge Aeson objects?

Body:
I have a list of aeson objects like this

[object ["key1" .= "value1"], object ["key2" .= "value2"]]

and I want to merge them as a single aeson object like this

object ["key1" .= "value1", "key2" .= "value2"]

This is quite standard when working with JSON data in other languages (merge operation) but I don't see anything similar in the Aeson library.

Am I just missing something and can this be done with some standard haskell function? I tried using sequence but it seems that JSON Value is not a monad so I cannot do that.

I don't need to deal with deep merging or duplicate keys, I just want to generate something like

{
  "key1": value1,
  "key2": value2
}

from

[{ "key1": value1 }, { "key2": value2 }]

Body:
Given the list contains only of JSON objects (thus elements that have key-value pairs or elements with the Object constructor), you can write your own:

import Data.Aeson(Value(Object))
import qualified Data.HashMap.Lazy as HML

merge_aeson :: [Value] -> Value
merge_aeson = Object . HML.unions . map (\(Object x) -> x)

If we test the above function with the given sample input, we obtain:

Prelude Data.Aeson HML> merge_aeson [object ["key1" .= "value1"], object ["key2" .= "value2"]]
Object (fromList [("key2",String "value2"),("key1",String "value1")])


问:
How to display .txt file in a TextView from ListView onClickItem?
I am working on the below but I am finding troubles in reading a .txt file from a ListView, displaying it in a TextView.

The code is:

```<code>    ArrayList<String> AcqList = GetFiles("/sdcard/Muse");

    lv.setAdapter(new ArrayAdapter<>(getContext(),
android.R.layout.simple_list_item_1, AcqList));
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View vr, int position, long id) {
    **????**
    }
    private boolean checkResults(String fileName){

    File file = new File("/sdcard/MuSe/"+fileName);

    if(file.exists()) return true;

    else return false;
}

});
return vr;
}
</code>```

I need to complete the ??? part with the code who reads the file .txt and display it in the TextView with id AcqText. In the ListView I show a list of .txt file in a specific directory.

答:
You should store those files in assets or raw directory and after that you can get inputstream from those files by using ,

If using assets

```<code>AssetManager am = context.getAssets();
InputStream is = am.open("yourfilename.txt");
</code>```

OR if you use raw directory then ,

```<code>InputStream is = getResources().openRawResource(R.raw.yourfilename);
</code>```

Body:
I am working on the below but I am finding troubles in reading a .txt file from a ListView, displaying it in a TextView.

The code is:

    ArrayList<String> AcqList = GetFiles("/sdcard/Muse");

    lv.setAdapter(new ArrayAdapter<>(getContext(),
android.R.layout.simple_list_item_1, AcqList));
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View vr, int position, long id) {
    **????**
    }
    private boolean checkResults(String fileName){

    File file = new File("/sdcard/MuSe/"+fileName);

    if(file.exists()) return true;

    else return false;
}

});
return vr;
}

I need to complete the ??? part with the code who reads the file .txt and display it in the TextView with id AcqText. In the ListView I show a list of .txt file in a specific directory.

Body:
You should store those files in assets or raw directory and after that you can get inputstream from those files by using ,

If using assets

AssetManager am = context.getAssets();
InputStream is = am.open("yourfilename.txt");

OR if you use raw directory then ,

InputStream is = getResources().openRawResource(R.raw.yourfilename);


问:
How to positionate in Tkinter?
I'm new with Tkinter and i want to create a "form" ( i doesnt really know how to call it) which write into database. I'm done with it, but i'm fustrated because of the layout.

I have this code which make the "form":

```<code>    self.parent.title("Pozi")
    self.pack(fill = BOTH, expand=True)

    frame1 = Frame(self)
    frame1.pack(side = LEFT)

    lbl1 = Label(frame1, text = "ĂtadĂł kĂˇrtyĂˇja", width = 15)
    lbl1.pack(side = TOP, padx=5)

    atadoText = StringVar()
    atadoText.set('')
    self.entry1 = Entry(frame1, textvariable=atadoText)
    self.entry1.pack(side = BOTTOM, padx=5)
    atadoText.trace('w',atado_enter)
    self.atadoText = atadoText
    self.entry1.focus()

    frame2 = Frame(self)
    frame2.pack(side = RIGHT)

    lbl2 = Label(frame2, text = "ĂtvevĹ‘ kĂˇrtyĂˇja", width = 15)
    lbl2.pack(side = TOP, padx=5, expand=True)

    atvevoText = StringVar()
    atvevoText.set('')
    self.entry2 = Entry(frame2, textvariable = atvevoText)
    self.entry2.pack(side = BOTTOM, padx=5)
    atvevoText.trace('w', atvevo_enter)
    self.atvevoText = atvevoText

    frame3 = Frame(self)
    frame3.pack(side = RIGHT)

    lbl3 = Label(frame3, text = "ĂrvevĹ‘ kĂˇrtyĂˇja", width = 15)
    lbl3.pack(side = TOP, padx=5, expand=True)

    lblText = StringVar()
    lblText.set('')
    self.entry3 = Entry(frame3, textvariable = lblText)
    self.entry3.pack(side = TOP, padx=5, expand=True)
    lblText.trace('w', lbl_count)
    self.lblText = lblText

    lbl4 = Label(frame3, text = "Title", width = 15)
    lbl4.pack(side = TOP, anchor=N, padx=5, pady=5)

    self.txt = Text(frame3)
    self.txt.pack(fill = BOTH, side = TOP, padx=5, pady=5, expand=True)
</code>```

It creates something like this:

And i want something looks like this. But i appriciate every idea:

答:
First of all, don't be afraid of googling about pack manager and especially about packer algorithm, and after that try to understand why you get what you get.

Because of relatyvity in pack logic, it's not an easy task for beginner to control horizontal and vertical positioning of widgets. Hence, remember the "divide and conquer" principle and treat your program layout as a set of blocks, in any of which we place widget in horizontal order or in vertical order, without mixing.

Consider your layout, it looks like:

Where each red block is a Frame widget + Root (or "master" Frame, feel free to create one) with one placing order.

To represent something like this try this snippet:

```<code>try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk

root = tk.Tk()

frame1 = tk.Frame()
frame1.pack()

for _ in range(2):
    i_frame = tk.Frame(frame1)

    label = tk.Label(i_frame, text='Sample%d' % _)
    label.pack(padx=200)

    entry = tk.Entry(i_frame)
    entry.pack(padx=200)

    i_frame.pack(side='left', ipady=25)

frame2 = tk.Frame()
frame2.pack()

label = tk.Label(frame2, text='Sample3')
label.pack()

entry = tk.Entry(frame2)
entry.pack()

label = tk.Label(frame2, text='Title', width=15)
label.pack()

txt = tk.Text(frame2)
txt.pack()

root.mainloop()
</code>```

Also, remember, there's a grid manager! With this manager you can treat layout as a table, so try it out too!

Title: How to positionate in Tkinter?

Body:
I'm new with Tkinter and i want to create a "form" ( i doesnt really know how to call it) which write into database. I'm done with it, but i'm fustrated because of the layout.

I have this code which make the "form":

    self.parent.title("Pozi")
    self.pack(fill = BOTH, expand=True)

    frame1 = Frame(self)
    frame1.pack(side = LEFT)

    lbl1 = Label(frame1, text = "ĂtadĂł kĂˇrtyĂˇja", width = 15)
    lbl1.pack(side = TOP, padx=5)

    atadoText = StringVar()
    atadoText.set('')
    self.entry1 = Entry(frame1, textvariable=atadoText)
    self.entry1.pack(side = BOTTOM, padx=5)
    atadoText.trace('w',atado_enter)
    self.atadoText = atadoText
    self.entry1.focus()

    frame2 = Frame(self)
    frame2.pack(side = RIGHT)

    lbl2 = Label(frame2, text = "ĂtvevĹ‘ kĂˇrtyĂˇja", width = 15)
    lbl2.pack(side = TOP, padx=5, expand=True)

    atvevoText = StringVar()
    atvevoText.set('')
    self.entry2 = Entry(frame2, textvariable = atvevoText)
    self.entry2.pack(side = BOTTOM, padx=5)
    atvevoText.trace('w', atvevo_enter)
    self.atvevoText = atvevoText

    frame3 = Frame(self)
    frame3.pack(side = RIGHT)

    lbl3 = Label(frame3, text = "ĂrvevĹ‘ kĂˇrtyĂˇja", width = 15)
    lbl3.pack(side = TOP, padx=5, expand=True)

    lblText = StringVar()
    lblText.set('')
    self.entry3 = Entry(frame3, textvariable = lblText)
    self.entry3.pack(side = TOP, padx=5, expand=True)
    lblText.trace('w', lbl_count)
    self.lblText = lblText

    lbl4 = Label(frame3, text = "Title", width = 15)
    lbl4.pack(side = TOP, anchor=N, padx=5, pady=5)

    self.txt = Text(frame3)
    self.txt.pack(fill = BOTH, side = TOP, padx=5, pady=5, expand=True)

It creates something like this:

And i want something looks like this. But i appriciate every idea:

Body:
First of all, don't be afraid of googling about pack manager and especially about packer algorithm, and after that try to understand why you get what you get.

Because of relatyvity in pack logic, it's not an easy task for beginner to control horizontal and vertical positioning of widgets. Hence, remember the "divide and conquer" principle and treat your program layout as a set of blocks, in any of which we place widget in horizontal order or in vertical order, without mixing.

Consider your layout, it looks like:

Where each red block is a Frame widget + Root (or "master" Frame, feel free to create one) with one placing order.

To represent something like this try this snippet:

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk

root = tk.Tk()

frame1 = tk.Frame()
frame1.pack()

for _ in range(2):
    i_frame = tk.Frame(frame1)

    label = tk.Label(i_frame, text='Sample%d' % _)
    label.pack(padx=200)

    entry = tk.Entry(i_frame)
    entry.pack(padx=200)

    i_frame.pack(side='left', ipady=25)

frame2 = tk.Frame()
frame2.pack()

label = tk.Label(frame2, text='Sample3')
label.pack()

entry = tk.Entry(frame2)
entry.pack()

label = tk.Label(frame2, text='Title', width=15)
label.pack()

txt = tk.Text(frame2)
txt.pack()

root.mainloop()

Also, remember, there's a grid manager! With this manager you can treat layout as a table, so try it out too!


问:
New Tab does not open the new url in Firefox using selenium
The part of the code which opens a new tab and opens a url in that new tab does not work. It opens the new tab but opens the new url in the previous tab itself. Can anyone help?    </p>

```<code>public class PractiseSession1
{
public static void main(String[] args)

{
    // TODO Auto-generated method stub
    String URL="http://www.google.com";

    System.setProperty("webdriver.gecko.driver", "D:\\Sourav Mukherjee\\BP-Oyster\\S2\\Selenium Server\\geckodriver-v0.16.1-win64\\geckodriver.exe");
    DesiredCapabilities dc = DesiredCapabilities.firefox();
    dc.setCapability("marionette", true);
    WebDriver driver =  new FirefoxDriver(dc);
    driver.get(URL);

    //Open a url in a new tab
    driver.findElement(By.cssSelector("Body")).sendKeys(Keys.CONTROL+ "t");
    driver.get("http://facebook.com/");

}
}
</code>```

答:
EDIT: The question isn't about moving to the new tab, but directly opening a link in the tab

You must move the driver to the new tab. To do this, you use this method:

```<code>ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs2.get(1));
driver.close();
driver.switchTo().window(tabs2.get(0));
</code>```

Body:
The part of the code which opens a new tab and opens a url in that new tab does not work. It opens the new tab but opens the new url in the previous tab itself. Can anyone help?

public class PractiseSession1
{
public static void main(String[] args)

{
    // TODO Auto-generated method stub
    String URL="http://www.google.com";

    System.setProperty("webdriver.gecko.driver", "D:\\Sourav Mukherjee\\BP-Oyster\\S2\\Selenium Server\\geckodriver-v0.16.1-win64\\geckodriver.exe");
    DesiredCapabilities dc = DesiredCapabilities.firefox();
    dc.setCapability("marionette", true);
    WebDriver driver =  new FirefoxDriver(dc);
    driver.get(URL);

    //Open a url in a new tab
    driver.findElement(By.cssSelector("Body")).sendKeys(Keys.CONTROL+ "t");
    driver.get("http://facebook.com/");

}
}

Body:
EDIT: The question isn't about moving to the new tab, but directly opening a link in the tab

You must move the driver to the new tab. To do this, you use this method:

ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs2.get(1));
driver.close();
driver.switchTo().window(tabs2.get(0));


问:
What is more efficient in terms of data consumption. GET or POST?
Assuming we want to send the some data from a device (IOT) to our server. Small no. of variables (say 10 to 20) but updated per second.
So sent to the server a large no. of times. (Say 60 times a minute)
What should I use so that minimum of my data pack is used. (Sending using GPRS)
GET or POST?</p>

答:
UPDATE :

You should check this thread : Why GET method is faster than POST?

In fact POST use a little bit more data because the header contain some more info like the type of content and it's length

```<code>POST /blog/ HTTP/1.1
Host: host.com
Content-Length: 27
Content-Type: application/x-www-form-urlencoded

name1=value1&name2=value2
</code>```

OLD :

GET requests:

```<code>GET /blog/?name1=value1&name2=value2 HTTP/1.1
Host: host.com
</code>```

POST requests:

```<code>POST /blog/ HTTP/1.1
Host: host.com
name1=value1&name2=value2
</code>```

As you can see there is no big difference in term of length so both request should use the same ammount of data.
GET have some limitaion for the url length (2048) and it can only contain ASCII

Source : http://blog.teamtreehouse.com/the-definitive-guide-to-get-vs-post

Body:
UPDATE :

You should check this thread : Why GET method is faster than POST?

In fact POST use a little bit more data because the header contain some more info like the type of content and it's length

POST /blog/ HTTP/1.1
Host: host.com
Content-Length: 27
Content-Type: application/x-www-form-urlencoded

name1=value1&name2=value2

OLD :

GET requests:

GET /blog/?name1=value1&name2=value2 HTTP/1.1
Host: host.com

POST requests:

POST /blog/ HTTP/1.1
Host: host.com
name1=value1&name2=value2

As you can see there is no big difference in term of length so both request should use the same ammount of data.
GET have some limitaion for the url length (2048) and it can only contain ASCII

Source : http://blog.teamtreehouse.com/the-definitive-guide-to-get-vs-post


问:
Create cell phone number authentication with Firebase
At present, the options on the Firebase website limit you to prepackaged solutions for authenticating users through Facebook or a person's email, etc. I wish to allow user to login and authenticate using their cell phone number, much like Snapchat allows.

Is there a pre-packaged solution for this? How can this be built out?

答:
It is possible. But currently only for iOS/Web. The implementation for Android should be done soon as well. Check firebase docs.
https://firebase.google.com/docs/auth/web/phone-auth</p>


问:
UltraID3 C# Lib, Coverart FLAC
I use UltraID3 to get the Coverart of a mp3 file. Is there anyway that UltraID3 can do the same with flac files?

Or is there any other lib which can do this?
This is my MP3 code:

```<code>        UltraID3 myMp3 = new UltraID3();
        myMp3.Read(path);
        ID3FrameCollection myArtworkCollection =
        myMp3.ID3v2Tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v23Picture);

        if (myArtworkCollection.Count > 0)
        {
            ID3v23PictureFrame ra = (ID3v23PictureFrame)myArtworkCollection[0];
            (ra.Picture).Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
            return true;
        }
</code>```

答:
As I can see UltraID3 only supports mp3.

I hope this helps: How to use libFLAC to read FLAC tags in c#

Title: UltraID3 C# Lib, Coverart FLAC

Body:
I use UltraID3 to get the Coverart of a mp3 file. Is there anyway that UltraID3 can do the same with flac files?

Or is there any other lib which can do this?
This is my MP3 code:

        UltraID3 myMp3 = new UltraID3();
        myMp3.Read(path);
        ID3FrameCollection myArtworkCollection =
        myMp3.ID3v2Tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v23Picture);

        if (myArtworkCollection.Count > 0)
        {
            ID3v23PictureFrame ra = (ID3v23PictureFrame)myArtworkCollection[0];
            (ra.Picture).Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
            return true;
        }


问:
c# delete excel sheets using for loop
I am trying to delete excel sheets using for loop except selected sheet by User using Dropdown menu in asp.net web application. So, I have written a code in c#.

```<code>int index = DropDownList1.SelectedIndex;
int max = DropDownList1.Items.Count;
int i=3;
for (i=1; i <= max; i++)
{
    if (i != index+1)
    {
        Excel.Worksheet worksheets = (Excel.Worksheet)xlWorkBook.Sheets[i];
        worksheets.Delete();
    }

}
</code>```

And I am getting an error like this -

System.Runtime.InteropServices.COMException: 'Invalid index.
  (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))'

答:
Both xlWorkBook.Sheets and DropDownList1.SelectedIndex indexes starts at 0, not 1, so you need to change your loop like this:

```<code>int index = DropDownList1.SelectedIndex;
int max = DropDownList1.Items.Count;

for (int i = 0; i < max; i++)
{
    if (i != index)
    {
        Excel.Worksheet worksheets = (Excel.Worksheet)xlWorkBook.Sheets[i];
        worksheets.Delete();
    }
}
</code>```

Title: c# delete excel sheets using for loop

Body:
I am trying to delete excel sheets using for loop except selected sheet by User using Dropdown menu in asp.net web application. So, I have written a code in c#.

int index = DropDownList1.SelectedIndex;
int max = DropDownList1.Items.Count;
int i=3;
for (i=1; i <= max; i++)
{
    if (i != index+1)
    {
        Excel.Worksheet worksheets = (Excel.Worksheet)xlWorkBook.Sheets[i];
        worksheets.Delete();
    }

}

And I am getting an error like this -

System.Runtime.InteropServices.COMException: 'Invalid index.
  (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))'

Body:
Both xlWorkBook.Sheets and DropDownList1.SelectedIndex indexes starts at 0, not 1, so you need to change your loop like this:

int index = DropDownList1.SelectedIndex;
int max = DropDownList1.Items.Count;

for (int i = 0; i < max; i++)
{
    if (i != index)
    {
        Excel.Worksheet worksheets = (Excel.Worksheet)xlWorkBook.Sheets[i];
        worksheets.Delete();
    }
}


问:
Show image in a popup when I click button
I have a button and i need to show an image in a popup when i click this button.

Why this code doesn't work? I try with a window.open in onclick event but it doesn't work

```<code><input type="button" value="Mostra Immagine" onclick=window.open(src="../img/mypicture.jpg")>
</code>```

Where is my error?

答:
You are using the attribute and function wrong:

```<code>onclick="window.open('../img/mypicture.jpg');"
</code>```

Always quote an attribute value like you did for type and value.

And the window.open function needs a path, you don't need to write "src=".

MDN - window.open()

Body:
I have a button and i need to show an image in a popup when i click this button.

Why this code doesn't work? I try with a window.open in onclick event but it doesn't work

<input type="button" value="Mostra Immagine" onclick=window.open(src="../img/mypicture.jpg")>

Where is my error?

Body:
You are using the attribute and function wrong:

onclick="window.open('../img/mypicture.jpg');"

Always quote an attribute value like you did for type and value.

And the window.open function needs a path, you don't need to write "src=".

MDN - window.open()


问:
how to find subitems of a row in cell array matlab?
I have cell array that is as follow:

```<code>S{1} = [10,20,30,40,50];
S{2} = [10,20,40,50];
S{3} = [10,50,510];
S{4} = [10,20,70,40,60];
S{5} = [20,40];
</code>```

and, i need to find rows of cell that are subitem of:

```<code>[10,20,30,40,50,60]
</code>```

for above example result is :

```<code>1,2,5
</code>```

because row 1 and row 2 and and row 5 only have subitems of [10,20,30,40,50,60] .

in my work cell array is big. and i need a fast code.

答:
Let

```<code>S{1} = [10,20,30,40,50];
S{2} = [10,20,40,50];
S{3} = [10,50,510];
S{4} = [10,20,70,40,60];
S{5} = [20,40];            % data
t = [10,20,30,40,50,60];   % target values
</code>```

Then, you can apply ismember and all to each cell's contents via cellfun. The result is a logical vector, from which you obtain the desired indices with find:

```<code>result = find(cellfun(@(x) all(ismember(x, t)), S));
</code>```

An alternative (I don't know which one will be faster in your case) is to replace ismember by computing all pairwise comparisons with bsxfun and then applying any:

```<code>result = find(cellfun(@(x) all(any(bsxfun(@eq, t(:), x(:).'), 1)), S));
</code>```

Body:
I have cell array that is as follow:

S{1} = [10,20,30,40,50];
S{2} = [10,20,40,50];
S{3} = [10,50,510];
S{4} = [10,20,70,40,60];
S{5} = [20,40];

and, i need to find rows of cell that are subitem of:

[10,20,30,40,50,60]

for above example result is :

1,2,5

because row 1 and row 2 and and row 5 only have subitems of [10,20,30,40,50,60] .

in my work cell array is big. and i need a fast code.

Body:
Let

S{1} = [10,20,30,40,50];
S{2} = [10,20,40,50];
S{3} = [10,50,510];
S{4} = [10,20,70,40,60];
S{5} = [20,40];            % data
t = [10,20,30,40,50,60];   % target values

Then, you can apply ismember and all to each cell's contents via cellfun. The result is a logical vector, from which you obtain the desired indices with find:

result = find(cellfun(@(x) all(ismember(x, t)), S));

An alternative (I don't know which one will be faster in your case) is to replace ismember by computing all pairwise comparisons with bsxfun and then applying any:

result = find(cellfun(@(x) all(any(bsxfun(@eq, t(:), x(:).'), 1)), S));


问:
How to mount servlet.jar in the classpath of an integration test run by Ant (that also uses Jetty and RestAssured)
I've a project https://github.com/paul-hammant/helloworld-war (fork of someone else's, value added).  It's a really quick build, and should serve as a demonstration of integration tests for teams that have not flipped to Maven/Gradle etc.

It has an integration test that brings up Jetty, and runs an Integration test that uses the excellent Rest-Assured to confirm that a /helloworld end-point does its "Hello World" business.

```<code>@Before
public void beforeAll() throws Exception {
    Server server = new Server(8080);
    WebAppContext context = new WebAppContext();
    context.setResourceBase("./web");
    loadAnnotations(context);
    server.setHandler(context);
    server.start();
}

@Test
public void testSomething() {
    when()
        .get("/helloworld")
    .then()
        .statusCode(200)
        .body(equalTo("Hello, world\n"));
}
</code>```

It all works in Intellij, just fine.

Ant barfs though, saying it can't find the servlet API.  It is definitely in the classpath.  I've tried changing the order of the the Jetty jars and servlet-api jar (didn't work). I've tried nixing the servlet jar from the classpath (didn't work). I'm not sure what else I could do, other than push the servlet jar to ant_home/lib/ which would suck.  Advice?

答:
Well, Ant is a bit cryptic it seems. The root cause has been fixed in https://github.com/paul-hammant/helloworld-war. It was that some jars had to taken out of the regular Ant <classpath/> directives, and put in Ant's lib/ folder itself.

Specifically:

hamcrest-core-1.3.jar

hamcrest-library-1.3.jar

junit-4.12.jar

It is ten years since I last used Ant. I had a hazy memory of something hokey with Junit. It seems in the passage of time, Hamcrest has joined JUnit in needing a hokey setup.

Body:
I've a project https://github.com/paul-hammant/helloworld-war (fork of someone else's, value added).  It's a really quick build, and should serve as a demonstration of integration tests for teams that have not flipped to Maven/Gradle etc.

It has an integration test that brings up Jetty, and runs an Integration test that uses the excellent Rest-Assured to confirm that a /helloworld end-point does its "Hello World" business.

@Before
public void beforeAll() throws Exception {
    Server server = new Server(8080);
    WebAppContext context = new WebAppContext();
    context.setResourceBase("./web");
    loadAnnotations(context);
    server.setHandler(context);
    server.start();
}

@Test
public void testSomething() {
    when()
        .get("/helloworld")
    .then()
        .statusCode(200)
        .body(equalTo("Hello, world\n"));
}

It all works in Intellij, just fine.

Ant barfs though, saying it can't find the servlet API.  It is definitely in the classpath.  I've tried changing the order of the the Jetty jars and servlet-api jar (didn't work). I've tried nixing the servlet jar from the classpath (didn't work). I'm not sure what else I could do, other than push the servlet jar to ant_home/lib/ which would suck.  Advice?


问:
How to retrieve high quality compass orientation (as in Google Maps)?
All of the guides to getting compass orientation in Android I've found have a bug: when you hold the phone in portrait mode and "look" above the horizon, the compass arrow turns 180 degrees from the correct direction.

Google Maps orientation indicator doesn't have this problem.

Another nice thing that Google Maps have is that they somehow estimate compass accuracy. Any idea how they do this?

答:
OK, i figured it out myself. first you need to calculate the bearing from the compass. then the Maps api-2 camera can be rotated.

```<code>public void updateCamera(float bearing) {
            CameraPosition currentPlace = new CameraPosition.Builder()
                    .target(new LatLng(centerLatitude, centerLongitude))
                    .bearing(bearing).tilt(65.5f).zoom(18f).build();
            googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(currentPlace));

    }
</code>```

set SensorListener in your code and call this method in onSensorChanged event. i have added a tilt value so the map will rotate in 3D.

[Reference:] [Android Maps v2 rotate mapView with compass1

if you can know about more details http://www.techotopia.com/index.php/Working_with_the_Google_Maps_Android_API_in_Android_Studio

Body:
OK, i figured it out myself. first you need to calculate the bearing from the compass. then the Maps api-2 camera can be rotated.

public void updateCamera(float bearing) {
            CameraPosition currentPlace = new CameraPosition.Builder()
                    .target(new LatLng(centerLatitude, centerLongitude))
                    .bearing(bearing).tilt(65.5f).zoom(18f).build();
            googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(currentPlace));

    }

set SensorListener in your code and call this method in onSensorChanged event. i have added a tilt value so the map will rotate in 3D.

[Reference:] [Android Maps v2 rotate mapView with compass1

if you can know about more details http://www.techotopia.com/index.php/Working_with_the_Google_Maps_Android_API_in_Android_Studio


问:
Django - how can i filter a list of objects checking a foreign key attribute?
First of all sorry for my bad English.

I have to filter a query but using a foreign key attribute. I have a WorkOrder model and have other model with the order movements.

this is the model

```<code>class OrderMovements(models.Model):
    workorder = models.ForeignKey(
            WorkOrder,
            verbose_name=_('order'),
        )
    status = models.IntegerField(
            choices=FULL_CHOICES,
            default=1,
            verbose_name=_('status'),
        )
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
</code>```

Well like you see a work order can have a lot of movements, the queryset that i need to make is a query that take the last 10 WorkOrders that have a OrderMovement with status 3 or 4 included in any of the movements of that WorkOrder.

I really don't know how can a make this.

Hope you can understand me.

Thanks!

答:
As usual, you start with the model you want to get, and follow the relationships via double underscores.</p>

```<code>WorkOrder.objects.order_by('-timestamp').filter(ordermovements__status__in=[3, 4])[:10]
</code>```

Body:
First of all sorry for my bad English.

I have to filter a query but using a foreign key attribute. I have a WorkOrder model and have other model with the order movements.

this is the model

class OrderMovements(models.Model):
    workorder = models.ForeignKey(
            WorkOrder,
            verbose_name=_('order'),
        )
    status = models.IntegerField(
            choices=FULL_CHOICES,
            default=1,
            verbose_name=_('status'),
        )
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

Well like you see a work order can have a lot of movements, the queryset that i need to make is a query that take the last 10 WorkOrders that have a OrderMovement with status 3 or 4 included in any of the movements of that WorkOrder.

I really don't know how can a make this.

Hope you can understand me.

Thanks!

Body:
As usual, you start with the model you want to get, and follow the relationships via double underscores.

WorkOrder.objects.order_by('-timestamp').filter(ordermovements__status__in=[3, 4])[:10]