问:
Jquery, can't update attribute previously created
I'm just trying to work on new slider menu but I've a problem with Jquery.

I've a link. When I click on I use .css('left', -230) and all is okay but when i want to reverse by another clicked link like .css('left', 0) nothing happen.

I show you some code :

```<code>// The open part "target.width()" = 230
$('.nav-item').on('click', function () {
    if( 0 < $(this).find('.navbar-nav__sub').length ) {
        var target = $('.navbar-nav');

        target.css('left', -target.width());
    }
});

// The close part
$('.navbar-nav__sub .go-back').on('click', function () {
    console.log('HERE');
    var target = $('.navbar-nav');

    console.log(target);
    console.log(target.css('left'));

    target.css('left', 0);

    console.log(target.css('left'));

    console.log('END');
});
</code>```

A strange thing in this problem is that I've this in my console :

```<code>HERE
Object { 0: ul.navbar-nav.flex-column, length: 1, prevObject: […] }
-230px
0px
END
</code>```

It seem that the code work well but in my page the left attribute is always to -230px.

Someone have an idea ?

Thank you.

PS: As asked the JSfiddle who reproduce my problem

https://jsfiddle.net/w7Lknsxg/

If you click on "Menu01" Color turn to red and when you click on "<=" in submenu you have the execution in the console but the color don't change.
You can see the class navbar-nav get new class "toto" but don't lost when I try to remove it in the second case.

答:
Because the .go-back is nested within the .nav-item you are firing both event listeners due to event bubbling. You can stop this with event.stopPropagation(); from within the listener placed on the child item. (or be more specific in what you target as not to include subelements)

var ftl = window.ftl || {};

ftl.navbar = {
  config: {
    targetName: '.nav',
    target: null,
  },

  init: function init() {
    this.config.target = $(this.config.targetName);

    $('.navbar-toggle').on('click', function () { ftl.navbar.toggle(); });

    $('.nav-item').on('click', function () {
      if( !ftl.navbar.config.target.hasClass('open') ) {
        ftl.navbar.open();
      }

      // test la présence d'un sous menu
      if( 0 < $(this).find('.navbar-nav__sub').length ) {
        var target = $('.navbar-nav');

        target.addClass('toto');
        target.css('color', 'red');
      }
    });

    $('.navbar-nav__sub .go-back').on('click', function (event) {
      event.stopPropagation();
      console.log('HERE');
      var target = $('.navbar-nav');

      console.log(target);
      console.log(target.hasClass('toto'));

      target.removeClass('toto');
      target.css('color', "green");

      console.log('END');
    })

  },

  open: function open() {
    this.config.target.addClass('open').one('transitionend', function () {
      ftl.navbar.config.target.addClass('opened');
    });
  },

  close: function close() {
    this.config.target.removeClass('opened')
      .removeClass('open');
  },

  toggle: function toggle() {
    if( this.config.target.hasClass('open') ) {
      this.close();
    } else {
      this.open();
    }
  }

}

$(document).ready(function() {
    ftl.navbar.init();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="nav">

    <nav class="navbar" role="navigation">

        <div class="container-nav flex-column">

            <div class="navbar__header">

                    <i class="fa fa-comment-o fa-2x navbar__icon" aria-hidden="true"></i>
                    <span class="navbar__text"><strong class="text-primary">web</strong>tutu</span>

            </div>

            <div class="navbar__divider"></div>

            <ul class="navbar-nav flex-column">

                <li id="nav-item--one" class="nav-item">

                        <i class="fa fa-user-circle-o navbar__icon" aria-hidden="true"></i>
                        <span class="navbar__text">Menu01</span>

                    <ul class="navbar-nav__sub">
                        <li>link 01</li>
                        <li>link 02</li>
                        <li> <= </li>
                    </ul>
                </li>

                <li id="nav-item--two" class="nav-item">

                        <i class="fa fa-user-circle-o navbar__icon" aria-hidden="true"></i>
                        <span class="navbar__text">Menu02</span>

                </li>

                <li id="nav-item--three" class="nav-item">

                        <i class="fa fa-user-circle-o navbar__icon" aria-hidden="true"></i>
                        <span class="navbar__text">Menu03</span>

                </li>

                <li class="mt-auto">
                    <i class="fa fa-angle-double-right fa-2x navbar-toggle" aria-hidden="true"></i>
                </li>

            </ul>

        </div>

    </nav>

</nav></code>```

Body:
I'm just trying to work on new slider menu but I've a problem with Jquery.

I've a link. When I click on I use .css('left', -230) and all is okay but when i want to reverse by another clicked link like .css('left', 0) nothing happen.

I show you some code :

// The open part "target.width()" = 230
$('.nav-item').on('click', function () {
    if( 0 < $(this).find('.navbar-nav__sub').length ) {
        var target = $('.navbar-nav');

        target.css('left', -target.width());
    }
});

// The close part
$('.navbar-nav__sub .go-back').on('click', function () {
    console.log('HERE');
    var target = $('.navbar-nav');

    console.log(target);
    console.log(target.css('left'));

    target.css('left', 0);

    console.log(target.css('left'));

    console.log('END');
});

A strange thing in this problem is that I've this in my console :

HERE
Object { 0: ul.navbar-nav.flex-column, length: 1, prevObject: […] }
-230px
0px
END

It seem that the code work well but in my page the left attribute is always to -230px.

Someone have an idea ?

Thank you.

PS: As asked the JSfiddle who reproduce my problem

https://jsfiddle.net/w7Lknsxg/

If you click on "Menu01" Color turn to red and when you click on "<=" in submenu you have the execution in the console but the color don't change.
You can see the class navbar-nav get new class "toto" but don't lost when I try to remove it in the second case.

Body:
Because the .go-back is nested within the .nav-item you are firing both event listeners due to event bubbling. You can stop this with event.stopPropagation(); from within the listener placed on the child item. (or be more specific in what you target as not to include subelements)

var ftl = window.ftl || {};

ftl.navbar = {
  config: {
    targetName: '.nav',
    target: null,
  },

  init: function init() {
    this.config.target = $(this.config.targetName);

    $('.navbar-toggle').on('click', function () { ftl.navbar.toggle(); });

    $('.nav-item').on('click', function () {
      if( !ftl.navbar.config.target.hasClass('open') ) {
        ftl.navbar.open();
      }

      // test la présence d'un sous menu
      if( 0 < $(this).find('.navbar-nav__sub').length ) {
        var target = $('.navbar-nav');

        target.addClass('toto');
        target.css('color', 'red');
      }
    });

    $('.navbar-nav__sub .go-back').on('click', function (event) {
      event.stopPropagation();
      console.log('HERE');
      var target = $('.navbar-nav');

      console.log(target);
      console.log(target.hasClass('toto'));

      target.removeClass('toto');
      target.css('color', "green");

      console.log('END');
    })

  },

  open: function open() {
    this.config.target.addClass('open').one('transitionend', function () {
      ftl.navbar.config.target.addClass('opened');
    });
  },

  close: function close() {
    this.config.target.removeClass('opened')
      .removeClass('open');
  },

  toggle: function toggle() {
    if( this.config.target.hasClass('open') ) {
      this.close();
    } else {
      this.open();
    }
  }

}

$(document).ready(function() {
    ftl.navbar.init();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="nav">

    <nav class="navbar" role="navigation">

        <div class="container-nav flex-column">

            <div class="navbar__header">
                <a href="#" class="no-style">
                    <i class="fa fa-comment-o fa-2x navbar__icon" aria-hidden="true"></i>
                    <span class="navbar__text"><strong class="text-primary">web</strong>tutu</span>
                </a>
            </div>

            <div class="navbar__divider"></div>

            <ul class="navbar-nav flex-column">

                <li id="nav-item--one" class="nav-item">
                    <a href="#nav-item--one">
                        <i class="fa fa-user-circle-o navbar__icon" aria-hidden="true"></i>
                        <span class="navbar__text">Menu01</span>
                    </a>

                    <ul class="navbar-nav__sub">
                        <li><a href="#">link 01</a></li>
                        <li><a href="#">link 02</a></li>
                        <li><a class="go-back" href="#"> <= </a></li>
                    </ul>
                </li>

                <li id="nav-item--two" class="nav-item">
                    <a href="#nav-item--two">
                        <i class="fa fa-user-circle-o navbar__icon" aria-hidden="true"></i>
                        <span class="navbar__text">Menu02</span>
                    </a>
                </li>

                <li id="nav-item--three" class="nav-item">
                    <a href="#nav-item--three">
                        <i class="fa fa-user-circle-o navbar__icon" aria-hidden="true"></i>
                        <span class="navbar__text">Menu03</span>
                    </a>
                </li>

                <li class="mt-auto">
                    <i class="fa fa-angle-double-right fa-2x navbar-toggle" aria-hidden="true"></i>
                </li>

            </ul>

        </div>

    </nav>

</nav>


来源: stackexchange

问:
How to export the admin theme settings on Drupal 7 and push it to the server with GIT?
On the admin environment of Drupal 7, I have changed the Administration theme by going to the Appearance page. Under section ADMINISTRATION THEME, I have selected a theme from the dropdown list and clicked on Save configuration.

The selected theme is applied. This is on my localhost. I would like to export this settings or configuration and push it to my git repository to apply this theme settings or configuration on my testing server. How can I export this theme settings on Drupal 7?

答:
The best option here would be to install the Features module. You can then configure it to export all of your site-wide (including theme) settings and also have the added benefit of 'reverting' to the exported settings if anything were to change.

Give it a try and drop a comment if you get stuck.

ContentLicense: CC BY-SA 3.0


问:
SQL select individual data from two tables
I have two tables User and booking

User

```<code> Id    userphone
 1        11111111
 2        22222222
 3        33333333
</code>```

Booking

```<code> ID      bookingphone
  1       22222222
  2       11111111
  3       44444444
</code>```

I want to get every individual phonenumbers from both tables
Like this:

```<code> 1111111
 2222222
 3333333
 4444444
</code>```

How do I do this without getting duplicates? Only individual phonenumers as in my example

答:
Try this

UNION

```<code>SELECT
  userphone
FROM user
UNION
SELECT
  bookingphone
FROM booking
</code>```

Body:
I have two tables User and booking

User

 Id    userphone
 1        11111111
 2        22222222
 3        33333333

Booking

 ID      bookingphone
  1       22222222
  2       11111111
  3       44444444

I want to get every individual phonenumbers from both tables
Like this:

 1111111
 2222222
 3333333
 4444444

How do I do this without getting duplicates? Only individual phonenumers as in my example

Body:
Try this

UNION

SELECT
  userphone
FROM user
UNION
SELECT
  bookingphone
FROM booking


答:
Use a UNION:

```<code>SELECT userphone FROM User
UNION
SELECT bookingphone FROM booking;
</code>```

A UNION will, by default, remove duplicate phone numbers, which seems to be what you want to do.  If you want to retain all records from both sides, then replace UNION with UNION ALL.

Title: SQL select individual data from two tables

Body:
Use a UNION:

SELECT userphone FROM User
UNION
SELECT bookingphone FROM booking;

A UNION will, by default, remove duplicate phone numbers, which seems to be what you want to do.  If you want to retain all records from both sides, then replace UNION with UNION ALL.


问:
Can you get this same Java SHA-1 in PHP please?
I find myself in a need to change website platforms from Java to PHP but I'd like to keep all my user's passwords...

I had this code do the password hashing prior to writting the hashed value as the password to the website:

```<code>MessageDigest md = null;
md = MessageDigest.getInstance("SHA");
md.update(plaintext.getBytes("UTF-8"));
byte raw[] = md.digest();
hash = new Base64().encodeToString(raw).replaceAll("\n", "").replaceAll("\r", "");
</code>```

I think the Java code did SHA-1 hashing of the password but just prior to that it was byte encoded to UTF-8 and afterwards it was Base64 encoded.

I'd like to have a PHP code do the same, i.e. return the same value of a hash for the same password as in Java, only it seems that the PHP code doing SHA-1 hashing I have won't return the same SHA(-1, not Base64 encoded, I think?) value when compared to a Java Base64 decoded value of the hash...could it have something to do with the fact that my passwords in PHP are not UTF-8 byte encoded first (and how can I do that in PHP) please?

p.s.

Another strange thing...my passwords in Java are all 28characters long (usually something like this rnwn4zTNgH30l4pP8V05lRVGmF4=)...but the Base64().decode(hash) value of those password hashes is 10 characters long (an example [B@14e1f2b).

I thought Base64 did an additional 1 character to each 3 charters (28 or 27, excluding the padding = charter, is much more that a third larger than those 10 charcters) so am I doing the decoding call wrong somehow maybe???

And on top of all that the SHA-1 password hashed values in PHP are 40 characters long (in a UTF-8 mysql database) like so dd94709528bb1c83d08f3088d4043f4742891f4f?

答:
PHP's sha1() encodes each byte of the output as hexadecimal by default, but you can get the raw output by passing true as the second argument:

```<code>$digest = sha1($password, true); // This returns the same string of bytes as md.digest()
</code>```

Then pass the digest to base64_encode and you are done:

```<code>base64_encode(sha1($password, true));
</code>```

This returns the exact same SHA-1 hash as your java code.

ContentLicense: CC BY-SA 2.5

Body:
I find myself in a need to change website platforms from Java to PHP but I'd like to keep all my user's passwords...

I had this code do the password hashing prior to writting the hashed value as the password to the website:

MessageDigest md = null;
md = MessageDigest.getInstance("SHA");
md.update(plaintext.getBytes("UTF-8"));
byte raw[] = md.digest();
hash = new Base64().encodeToString(raw).replaceAll("\n", "").replaceAll("\r", "");

I think the Java code did SHA-1 hashing of the password but just prior to that it was byte encoded to UTF-8 and afterwards it was Base64 encoded.

I'd like to have a PHP code do the same, i.e. return the same value of a hash for the same password as in Java, only it seems that the PHP code doing SHA-1 hashing I have won't return the same SHA(-1, not Base64 encoded, I think?) value when compared to a Java Base64 decoded value of the hash...could it have something to do with the fact that my passwords in PHP are not UTF-8 byte encoded first (and how can I do that in PHP) please?

p.s.

Another strange thing...my passwords in Java are all 28characters long (usually something like this rnwn4zTNgH30l4pP8V05lRVGmF4=)...but the Base64().decode(hash) value of those password hashes is 10 characters long (an example [B@14e1f2b).

I thought Base64 did an additional 1 character to each 3 charters (28 or 27, excluding the padding = charter, is much more that a third larger than those 10 charcters) so am I doing the decoding call wrong somehow maybe???

And on top of all that the SHA-1 password hashed values in PHP are 40 characters long (in a UTF-8 mysql database) like so dd94709528bb1c83d08f3088d4043f4742891f4f?

Body:
PHP's sha1() encodes each byte of the output as hexadecimal by default, but you can get the raw output by passing true as the second argument:

$digest = sha1($password, true); // This returns the same string of bytes as md.digest()

Then pass the digest to base64_encode and you are done:

base64_encode(sha1($password, true));

This returns the exact same SHA-1 hash as your java code.


问:
How to create a list of conditions?
I am trying to create an if else code where there is about 20conditions for the elif, how do I create a list of conditions where i can just type something such as:

```<code>uno= <9
lol= >20
crad= =<3
list={uno,lol,crad}
if 13=list:
    print("yay")
elif 13!=list:
    print("nay")
</code>```

That's my current code
It should print "yay", instead there is syntax error

答:
It's not actually simpler than writing a chain of if/elif/elif etc, but something like this seems to do what you are asking:

```<code>predicates = [lambda x: x<9, lambda x: x>20, lambda x: x<=3]
if all(y(13) for y in predicates):
    print("yay")
else:
    print("nay")
</code>```

Each predicate is a small anonymous function (a lambda) which receives a single argument and evaluates to either True or False.  If you have a large number of arguments you want to check against a large set of predicates, it's nice to be able to encapsulate the predicates like this. The ability to programmatically add or remove predicates from the list truly extends the versatility of this construct beyond what you can (easily, naturally) do with if/elif/elif.

This particular set of predicates can't all be true for a single number. Maybe you want any() instead of all()...?

Title: How to create a list of conditions?

Body:
I am trying to create an if else code where there is about 20conditions for the elif, how do I create a list of conditions where i can just type something such as:

uno= <9
lol= >20
crad= =<3
list={uno,lol,crad}
if 13=list:
    print("yay")
elif 13!=list:
    print("nay")

That's my current code
It should print "yay", instead there is syntax error

Body:
It's not actually simpler than writing a chain of if/elif/elif etc, but something like this seems to do what you are asking:

predicates = [lambda x: x<9, lambda x: x>20, lambda x: x<=3]
if all(y(13) for y in predicates):
    print("yay")
else:
    print("nay")

Each predicate is a small anonymous function (a lambda) which receives a single argument and evaluates to either True or False.  If you have a large number of arguments you want to check against a large set of predicates, it's nice to be able to encapsulate the predicates like this. The ability to programmatically add or remove predicates from the list truly extends the versatility of this construct beyond what you can (easily, naturally) do with if/elif/elif.

This particular set of predicates can't all be true for a single number. Maybe you want any() instead of all()...?


问:
GraphQL schema equivalent of this Json?
I'm newbie to GraphQL, and was wondering if someone could help me figure out what is the equivalent of below JSON into GraphQL schema:

```<code>[
 {
   "id": "1",
   "name": "A",
   "fldDef": [
    {
      "name": "f1",
      "type": "str",
      "opt": false
    },
    {
      "name": "f2",
      "type": "bool"
    }]
 },
 {
    "id": "2",
    "name": "B",
    "fldDef": [
     {
       "name": "f3",
       "type": "str",
       "opt": true
     },
     {
       "name": "f4",
       "type": "str",
       "opt": true
     }]
  }
]
</code>```

So far I managed to map above response to below object:

```<code>  public class FldDef {

     private String name, type;
     private boolean opt;
     // getters & setters
 }

 public class Product {

    private String id, name;
    private Map<String, FldDef> fldDef;

   // getters & setters

 }
</code>```

Then my schema looks like below, but the problem I'm having is as a part of Product object, I've a Map which I would like to get the schema right for it, but I'm having difficulty getting the schema right!

```<code>type FldDef {
   name: String!
   type: String!
   opt: Boolean!
}

type Product {
   id: String!
   name: String!
   fldDef: FldDef! // now here I don't know what is the syntax for representing MAP, do you know how to achieve this?
 }
</code>```

I get below exception:

Causedby:com.coxautodev.graphql.tools.TypeClassMatcher$RawClassRequiredForGraphQLMappingException: Type java.util.Map<java.lang.String, com.grapql.research.domain.FldDef> cannot be mapped to a GraphQL type!  Since GraphQL-Java deals with erased types at runtime, only non-parameterized classes can represent a GraphQL type.  This allows for reverse-lookup by java class in interfaces and union types.

Note: I'm working with Java eco-system (graphql-java)

答: giving you a schema from your JSON is not really possible because a schema contains much more information than just simply the shape of your data. I think the best for you would be to learn the basics of GraphQL, designing simple schemas is then very easy and fun! Maybe start with the learning section on graphql.org. They have a section about the schema. Basically you build your schema from scalars (aka primitives) and object types. All types can additionally be wrapped in the non-nullable type and/or of the list type. GraphQL was designed for clients. The easiest way of understanding GraphQL is making some queries against an existing API. Launchpad has a lot of examples that you can use (and modify when you know some JavaScript).</p>

Title: GraphQL schema equivalent of this Json?

Body:
I'm newbie to GraphQL, and was wondering if someone could help me figure out what is the equivalent of below JSON into GraphQL schema:

[
 {
   "id": "1",
   "name": "A",
   "fldDef": [
    {
      "name": "f1",
      "type": "str",
      "opt": false
    },
    {
      "name": "f2",
      "type": "bool"
    }]
 },
 {
    "id": "2",
    "name": "B",
    "fldDef": [
     {
       "name": "f3",
       "type": "str",
       "opt": true
     },
     {
       "name": "f4",
       "type": "str",
       "opt": true
     }]
  }
]

So far I managed to map above response to below object:

  public class FldDef {

     private String name, type;
     private boolean opt;
     // getters & setters
 }

 public class Product {

    private String id, name;
    private Map<String, FldDef> fldDef;

   // getters & setters

 }

Then my schema looks like below, but the problem I'm having is as a part of Product object, I've a Map which I would like to get the schema right for it, but I'm having difficulty getting the schema right!

type FldDef {
   name: String!
   type: String!
   opt: Boolean!
}

type Product {
   id: String!
   name: String!
   fldDef: FldDef! // now here I don't know what is the syntax for representing MAP, do you know how to achieve this?
 }

I get below exception:

Causedby:com.coxautodev.graphql.tools.TypeClassMatcher$RawClassRequiredForGraphQLMappingException: Type java.util.Map<java.lang.String, com.grapql.research.domain.FldDef> cannot be mapped to a GraphQL type!  Since GraphQL-Java deals with erased types at runtime, only non-parameterized classes can represent a GraphQL type.  This allows for reverse-lookup by java class in interfaces and union types.

Note: I'm working with Java eco-system (graphql-java)


问:
Combining Galen and Protractor frameworks

The Story

We've been using Protractor framework extensively and have established a rather large test codebase. We've also been following the Page Object pattern to organize our tests.

Recently, we've started to use the Galen framework to fill the gap of visual/layout/responsive design testing. We really like the framework and would like to proceed with using it more.

The biggest problem right now is Page Objects. Both frameworks have its own ways of defining page objects.

Here is an example Protractor page object:

```<code>var LoginPage = function () {
    this.username = element(by.id("username"));
    this.password = element(by.id("password"));

    this.loginButton = element(by.binding("buttonText"));
};

module.exports = new LoginPage();
</code>```

And, here is a sample Galen page object:

```<code>this.LoginPage = $page("Login page", {
    username: '#username',
    password: '#password',
    loginButton: 'button[ng-click*=login]'
});
</code>```

Currently, we are duplicating the locators and repeating ourselves - violating the DRY principle. And, the other follow-up issue is that Galen only supports "by css", "by id" or "by xpath" location techniques at the moment - which means page objects don't map one-to-one.

The Question

Is there a way to avoid repeating page objects and element locators combining both Protractor and Galen together?

答:
Given the information available, I don't see a direct way to combine it.

However, Galen and Protractor are available on Github and I don't see any bigger obstacle from aligning/forking/modifying them to what you need.

The best shot I see is to contribute to Galen framework and extend their GalenPages.js with a mapping functionality to Protractor Page Objects. Though there are 600+ lines of code in that .js-file, it seems doable within reasonable efforts.

At least to open an issue in the Galen GitHub project in that direction would sure be worth the effort.

Body:
The Story

We've been using Protractor framework extensively and have established a rather large test codebase. We've also been following the Page Object pattern to organize our tests.

Recently, we've started to use the Galen framework to fill the gap of visual/layout/responsive design testing. We really like the framework and would like to proceed with using it more.

The biggest problem right now is Page Objects. Both frameworks have its own ways of defining page objects.

Here is an example Protractor page object:

var LoginPage = function () {
    this.username = element(by.id("username"));
    this.password = element(by.id("password"));

    this.loginButton = element(by.binding("buttonText"));
};

module.exports = new LoginPage();

And, here is a sample Galen page object:

this.LoginPage = $page("Login page", {
    username: '#username',
    password: '#password',
    loginButton: 'button[ng-click*=login]'
});

Currently, we are duplicating the locators and repeating ourselves - violating the DRY principle. And, the other follow-up issue is that Galen only supports "by css", "by id" or "by xpath" location techniques at the moment - which means page objects don't map one-to-one.

The Question

Is there a way to avoid repeating page objects and element locators combining both Protractor and Galen together?


问:
Error: Conversion from string "x" to type Integer is not valid. How do I turn an integer into a string?
So I am making a program in which you can select products from a combo box, select the quantity and it will return with the price and the quantity in a list box as well as the total price. It then inputs the data in the listbox into a Microsoft Access database.

When I click the button btnOrderProducts, I receive an error that reads:

Error: Conversion from string "x" to type Integer is not valid

I am unsure what this error means and how to figure out a resolution. Changing my access database data types from integers into short texts didn't fix it, so it is something to do with the code.

 Here is an image of the form for reference

Here is the code:

```<code>Private Sub btnOrderProducts_Click(sender As Object, e As EventArgs) Handles btnOrderProducts.Click

        Dim numberOfItems = ListBoxCart.Items.Count
        For Each item As String In ListBoxCart.Items

            Try

                cm = New OleDbCommand
                With cm
                    .Connection = cn
                    .CommandType = CommandType.Text
                    .CommandText = "INSERT INTO tblOrders ([ProductName],[Quantity],[PriceEach],[TotalPrice],[Username]) VALUES (@ProductName,@Quantity,@PriceEach,@TotalPrice,@Username)"

                    prod_list = item.Split(" ").ToList
                    Dim prod_name = prod_list.ElementAt(1)
                    Dim prod_quantity = Integer.Parse(prod_list.ElementAt(0).Remove("x"))
                    Dim price_each = prod_list.ElementAt(2)

                    .Parameters.Add(New OleDbParameter("@ProductName", OleDbType.VarChar, 255, prod_name))
                    .Parameters.Add(New OleDbParameter("@Quantity", OleDbType.VarChar, 255, prod_quantity))
                    .Parameters.Add(New OleDbParameter("@PriceEach", OleDbType.VarChar, 255, price_each))
                    .Parameters.Add(New OleDbParameter("@TotalPrice", OleDbType.VarChar, 255, Total))
                    .Parameters.Add(New OleDbParameter("@Username", OleDbType.VarChar, 255, txtUsername.Text))
                    prod_list = New List(Of String)

                    cm.Parameters("@ProductName").Value = prod_name
                    cm.Parameters("@Quanity").Value = prod_quantity
                    cm.Parameters("@PriceEach").Value = price_each
                    cm.Parameters("@TotalPrice").Value = Total
                    cm.Parameters("@Username").Value = txtUsername.Text

                    cm.ExecuteNonQuery()
                    MsgBox("Record saved.", MsgBoxStyle.Information)
                    cmboxProduct.SelectedItem = ""
                    txtQuantity.Text = ListBoxCart.Text = ""
                    txtTotalPrice.Text = ""

                    Exit Sub
                End With
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical)
            End Try

        Next

    End Sub
</code>```

答:
Unfortunately the String.Remove method does not do what you think it does.

From the link:

Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted

The "x" cannot be converted into an integer.

Body:
So I am making a program in which you can select products from a combo box, select the quantity and it will return with the price and the quantity in a list box as well as the total price. It then inputs the data in the listbox into a Microsoft Access database.

When I click the button btnOrderProducts, I receive an error that reads:

Error: Conversion from string "x" to type Integer is not valid

I am unsure what this error means and how to figure out a resolution. Changing my access database data types from integers into short texts didn't fix it, so it is something to do with the code.

 Here is an image of the form for reference

Here is the code:

Private Sub btnOrderProducts_Click(sender As Object, e As EventArgs) Handles btnOrderProducts.Click

        Dim numberOfItems = ListBoxCart.Items.Count
        For Each item As String In ListBoxCart.Items

            Try

                cm = New OleDbCommand
                With cm
                    .Connection = cn
                    .CommandType = CommandType.Text
                    .CommandText = "INSERT INTO tblOrders ([ProductName],[Quantity],[PriceEach],[TotalPrice],[Username]) VALUES (@ProductName,@Quantity,@PriceEach,@TotalPrice,@Username)"

                    prod_list = item.Split(" ").ToList
                    Dim prod_name = prod_list.ElementAt(1)
                    Dim prod_quantity = Integer.Parse(prod_list.ElementAt(0).Remove("x"))
                    Dim price_each = prod_list.ElementAt(2)

                    .Parameters.Add(New OleDbParameter("@ProductName", OleDbType.VarChar, 255, prod_name))
                    .Parameters.Add(New OleDbParameter("@Quantity", OleDbType.VarChar, 255, prod_quantity))
                    .Parameters.Add(New OleDbParameter("@PriceEach", OleDbType.VarChar, 255, price_each))
                    .Parameters.Add(New OleDbParameter("@TotalPrice", OleDbType.VarChar, 255, Total))
                    .Parameters.Add(New OleDbParameter("@Username", OleDbType.VarChar, 255, txtUsername.Text))
                    prod_list = New List(Of String)

                    cm.Parameters("@ProductName").Value = prod_name
                    cm.Parameters("@Quanity").Value = prod_quantity
                    cm.Parameters("@PriceEach").Value = price_each
                    cm.Parameters("@TotalPrice").Value = Total
                    cm.Parameters("@Username").Value = txtUsername.Text

                    cm.ExecuteNonQuery()
                    MsgBox("Record saved.", MsgBoxStyle.Information)
                    cmboxProduct.SelectedItem = ""
                    txtQuantity.Text = ListBoxCart.Text = ""
                    txtTotalPrice.Text = ""

                    Exit Sub
                End With
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical)
            End Try

        Next

    End Sub


问:
Set the height of Details section Crystal Reports
The no of items in my invoice never gets more than 10. When its only one item in invoice(one row in details section) the report footer shows very up.

I want that I should fix 10 rows for the details section, when there are less rows, the remaining rows to make it 10 should be showed as blank lines.

I need the footer to appear at the same place all the time, irrespective of how many items are there in the invoice(never gets more than 10).

Please suggest solution.

答:
to fix height of detail section ..suppose i want size of 8 rows/records then
right click on detail section ->section expert ->on paging tab-> check on New page before beside button (x+2) write formula below given..

IF Remainder (RecordNumber, 8) = 0 THEN
    TRUE
ELSE
    FALSE


问:
Javascript Stops Running Past $(.class).html(result)
I have the following code which loads a group of products from a category when the .expandproducts button is clicked:

```<code>$('.expandproducts').click(function(){
    id = $(this).attr("data-id");
    urlajax = document.location.origin + "/ajaxproducts?category=" + id;
    $.ajax({url: urlajax, success: function(result){
        $("." + id).html(result);
        //code seems to stop here! Cannot figure out why YAY is not displayed, no errors in console.
        alert("Yay");
    }});
})
</code>```

The ajax side seems to work fine and content is loaded into the div via ajax. My ID is taken from the button and loads the correct category from my controller and puts into correct containing div on my page however any functions i add after $("." + id).html(result); just do not fire so alert("Yay"); does not work.

I cannot see any errors in the log and am confused as to why this is and wondering if anyone else can suggest what i may have done wrong?

Ok this snippet works but i put it here anyway:

$('.expandproducts').click(function(){
  id = $(this).attr("data-id");
  urlajax = "https://jsonplaceholder.typicode.com/posts/" + id;
  $.ajax({url: urlajax, success: function(result){
   result = "result: " + result;
      $(".container-" + id).html(result);
      //code seems to stop here! Cannot figure out why YAY is not displayed, no errors in console.
   alert("Yay");
  }});
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Products load under here:</p><button data-id="1" class="expandproducts">EXPAND</button>
<div class="container-1">
</div></code>```

Why would this not work in my context?

答:
As you are saying

It seems to work prefectly and content is loaded into the div via ajax

You are not reloading page properly , hard refresh page by Ctrl+F5, This could be the problem.

Except reloading issue there is no issue here.

Or It might be with your ajax content issue.

Body:
I have the following code which loads a group of products from a category when the .expandproducts button is clicked:

$('.expandproducts').click(function(){
    id = $(this).attr("data-id");
    urlajax = document.location.origin + "/ajaxproducts?category=" + id;
    $.ajax({url: urlajax, success: function(result){
        $("." + id).html(result);
        //code seems to stop here! Cannot figure out why YAY is not displayed, no errors in console.
        alert("Yay");
    }});
})

The ajax side seems to work fine and content is loaded into the div via ajax. My ID is taken from the button and loads the correct category from my controller and puts into correct containing div on my page however any functions i add after $("." + id).html(result); just do not fire so alert("Yay"); does not work.

I cannot see any errors in the log and am confused as to why this is and wondering if anyone else can suggest what i may have done wrong?

Ok this snippet works but i put it here anyway:

$('.expandproducts').click(function(){
  id = $(this).attr("data-id");
  urlajax = "https://jsonplaceholder.typicode.com/posts/" + id;
  $.ajax({url: urlajax, success: function(result){
   result = "result: " + result;
      $(".container-" + id).html(result);
      //code seems to stop here! Cannot figure out why YAY is not displayed, no errors in console.
   alert("Yay");
  }});
})

Products load under here:
<button data-id="1" class="expandproducts">EXPAND</button>

Why would this not work in my context?


问:
AND/OR operator between numbers in Python
How do and/or operators work between numbers (or even strings)?

```<code>5 and 7  # this returns 7
7 and 5  # this returns 5
21 and 4 # this returns 4
4 and 21 # this returns 21
</code>```

How does the and operator work in such cases?

答:
It returns the last value which is True (if there is any True value).

For an and python needs to check every value, so if they are all true then it returns the last one, if one of them is False, then it returns that value. If all of them are False it returns the first one because Python doesn't need to check the second one as well.

For an or python checks first the first one until he gets True sometime, so if the first value is True it returns this value, if the first one is False but the second one is True, it returns the second one. If they are all False it returns the last one.

The values which are equivalent to False: "",0,False,0j, 0.0, [], {}, set().

Body:
How do and/or operators work between numbers (or even strings)?

5 and 7  # this returns 7
7 and 5  # this returns 5
21 and 4 # this returns 4
4 and 21 # this returns 21

How does the and operator work in such cases?


答:
This line does not remove the "x" from the string

```<code>Dim prod_quantity = Integer.Parse(prod_list.ElementAt(0).Remove("x"))
</code>```

It should rather be:

```<code>Dim prod_quantity = Integer.Parse(prod_list.ElementAt(0).Remove(0,1))
</code>```

But i would not recommend to concatenate the items-properties to a string and  later split the string to get the items-properties back.
Give my answer to your previous question a chance. So you will not have these problems.

Furthermore i would recommend to set Option Strict to On in the project properties.

Title: Error: Conversion from string "x" to type Integer is not valid. How do I turn an integer into a string?

Body:
This line does not remove the "x" from the string

Dim prod_quantity = Integer.Parse(prod_list.ElementAt(0).Remove("x"))

It should rather be:

Dim prod_quantity = Integer.Parse(prod_list.ElementAt(0).Remove(0,1))

But i would not recommend to concatenate the items-properties to a string and  later split the string to get the items-properties back.
Give my answer to your previous question a chance. So you will not have these problems.

Furthermore i would recommend to set Option Strict to On in the project properties.


问:
Android application must not run on rooted devices
I'm writing an application that must not run on rooted devices. I want to store some secure data and which is possible only on non-rooted devices as nobody can access files in /data/data/package-name.

Does anyone know:

1) Is it possible to prevent the installation of an application on rooted devices? I read something about the "copy-protection mechanism" of Android Market. This feature seems to be outdated and replaced by the licensing feature. However, licensing is only possible for paid application and mine is free...

2) Is it possible to check programmatically whether a device is rooted or not? If it would be possible to do so I could simply stop the application if the device is rooted.

Any help regarding this topic is appreciated!

答:
I think your approach is a bit flawed. First of all, the user can first install your application and data, then "root" the device (even if rooting wipes the data, one can make the backup first). Next, the general rule is that whatever is in user's hands is not yours anymore. The hacker will find a way to get to your data sooner or later.

If you care about secure data, don't put it to device. As Android is net-centric device (yes, I know, that's subjective, but it was initially developed and positioned as such), accessing the data online is not uncommon.


问:
FSL doesn't install on Ubuntu 16.04 from NeuroDebian
I am trying to install FSL on Ubuntu 16.04 64-bit.

I followed procedure at neurodebian website, selected the correct package, specified ALL software.

When I copy-paste the commands in my terminal the pipe hangs without prompting for my sudo password:

```<code>wget -O- http://neuro.debian.net/lists/xenial.de-m.full | sudo tee /etc/apt/sources.list.d/neurodebian.sources.list
</code>```

I also tried to separate the pipe in the two commands. The first one runs, the second asks for my password and then hangs. I con't know how to connect their outputs though.

If I use CTRL+Z it stops (of course) and then I type

```<code>sudo apt-key adv --recv-keys --keyserver hkp://pool.sks-keyservers.net:80 0xA5D32F012649A5A9
sudo apt-get update
sudo apt-get install fsl-complete
</code>```

but the package is not found. Also the package fsl-5.0-complete is not found.

I tried the mirror in Japan and the mirror in Munich, with no success.
The advice posted in the comments on NeuroDebian just repeats the instructions, and it doesn't help.

答:
The solution to this was probably trivial, but not to unexperienced users like me.
Splitting up the pipe of course didn't work because there was no redirecting of the output.

One just needs to type the pipe as it is, and when it seems to be hanging, type in his/her user password and press enter.

Body:
I am trying to install FSL on Ubuntu 16.04 64-bit.

I followed procedure at neurodebian website, selected the correct package, specified ALL software.

When I copy-paste the commands in my terminal the pipe hangs without prompting for my sudo password:

wget -O- http://neuro.debian.net/lists/xenial.de-m.full | sudo tee /etc/apt/sources.list.d/neurodebian.sources.list

I also tried to separate the pipe in the two commands. The first one runs, the second asks for my password and then hangs. I con't know how to connect their outputs though.

If I use CTRL+Z it stops (of course) and then I type

sudo apt-key adv --recv-keys --keyserver hkp://pool.sks-keyservers.net:80 0xA5D32F012649A5A9
sudo apt-get update
sudo apt-get install fsl-complete

but the package is not found. Also the package fsl-5.0-complete is not found.

I tried the mirror in Japan and the mirror in Munich, with no success.
The advice posted in the comments on NeuroDebian just repeats the instructions, and it doesn't help.


问:
Capturing image using camera in nougat using .fileprovider getting null image in Crop Dialog box
HERE is my code

MAINIFEST

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

 <provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"/>
</provider>
</code>```

provider_path.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
</code>```

Here checking if Naugat do this

```<code>if (haswritePermission == PackageManager.PERMISSION_GRANTED && hasWriteContactsPermission == PackageManager.PERMISSION_GRANTED) {
                ++imageId;

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        String imageFilePath = Environment.getExternalStorageDirectory().toString() + "/Images/Profile/profile.jpg";
        File imageFile = new File(imageFilePath);
        imageUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider", imageFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        startActivityForResult(intent, PICK_FROM_CAMERA);
    }
}
</code>```

onActivityResult

```<code>public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

               if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case PICK_FROM_CAMERA:
                    mCropImageView.setImageUriAsync(imageUri);
                    [crop_dialog][1].show();
                    break;

            }
    }
}
</code>```

for crop image I am using this Library

```<code>compile 'com.theartofdev.edmodo:android-image-cropper:2.5.+'
</code>```

Getting this kind of null image or Empty image

答:
```<code>I just change code for Nougat .add separate case for nougat

**for less than M**

 case PICK_FROM_CAMERA:
                        mCropImageView.setImageUriAsync(imageUri);
                        path=getRealPathFromURI(imageUri);
                        Bitmap bitmap=rotateBitmapOrientation(path);
                        mCropImageView.setImageBitmap(bitmap);
                        crop_dialog.show();
                        break;

**for Nougat **

case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
                        mCropImageView.setImageUriAsync(imageUri);
                        selectedImage);
                        crop_dialog.show();
                        break;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
HERE is my code

MAINIFEST

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

 <provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"/>
</provider>

provider_path.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>

Here checking if Naugat do this

if (haswritePermission == PackageManager.PERMISSION_GRANTED && hasWriteContactsPermission == PackageManager.PERMISSION_GRANTED) {
                ++imageId;

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        String imageFilePath = Environment.getExternalStorageDirectory().toString() + "/Images/Profile/profile.jpg";
        File imageFile = new File(imageFilePath);
        imageUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider", imageFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        startActivityForResult(intent, PICK_FROM_CAMERA);
    }
}

onActivityResult

public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

               if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case PICK_FROM_CAMERA:
                    mCropImageView.setImageUriAsync(imageUri);
                    [crop_dialog][1].show();
                    break;

            }
    }
}

for crop image I am using this Library

compile 'com.theartofdev.edmodo:android-image-cropper:2.5.+'

Getting this kind of null image or Empty image


问:
Minio on Symfony
So one of my colleagues recommended me to use Minio as my File Storage.

I research about it but there is not enough resources on the net to keep me going. I found KNPGaufretteBundle which has Amazon S3 Adapter. Minio is compatible with Amazon S3, so can I use it?

Thanks!

答:
aws-sdk-php works fine with minio so you should be able to use KNPGaufretteBundle with minio.

You can also look at laralvel support as well.

Title: Minio on Symfony


问:
How can I extract a filename from a path using Perl?
I have a Perl variable I populate from the database. Its name is $path. I need to get another variable $file which has just the filename from the pathname.

I tried:

```<code>$file = $path =~ s/.*\///;
</code>```

I am very new to Perl.

答:
Path::Class may seem like overkill at first—making objects of file and dir paths—but it can really pay off in complicated scripts and offers lots of bonuses that will prevent spaghetti when you get backed into a corner by scope creep. File::Spec is used in the first example for fun to resolve path.</p>

```<code>use warnings;
use strict;
use Path::Class qw( file );
use File::Spec;

# Get the name of the current script with the procedural interface-
my $self_file = file( File::Spec->rel2abs(__FILE__) );
print
    " Full path: $self_file", $/,
    "Parent dir: ", $self_file->parent, $/,
    " Just name: ", $self_file->basename, $/;

# OO
my $other = Path::Class::File->new("/tmp/some.weird/path-.unk#");
print "Other file: ", $other->basename, $/;
</code>```

Body:
I have a Perl variable I populate from the database. Its name is $path. I need to get another variable $file which has just the filename from the pathname.

I tried:

$file = $path =~ s/.*\///;

I am very new to Perl.

Body:
Path::Class may seem like overkill at first—making objects of file and dir paths—but it can really pay off in complicated scripts and offers lots of bonuses that will prevent spaghetti when you get backed into a corner by scope creep. File::Spec is used in the first example for fun to resolve path.

use warnings;
use strict;
use Path::Class qw( file );
use File::Spec;

# Get the name of the current script with the procedural interface-
my $self_file = file( File::Spec->rel2abs(__FILE__) );
print
    " Full path: $self_file", $/,
    "Parent dir: ", $self_file->parent, $/,
    " Just name: ", $self_file->basename, $/;

# OO
my $other = Path::Class::File->new("/tmp/some.weird/path-.unk#");
print "Other file: ", $other->basename, $/;


问:
Android Studio 3.0.1 gradle build pkix pathbuilding failed
I have created a new project in android studio 3.0.1 setup the proxy settings of company and added the self sighned certificate unser server sertificates. When I try to build the following error is listed and the build fails.

Error:

```<code>Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support:appcompat-v7:26.1.0.
Required by:
    project :app
 > Could not resolve com.android.support:appcompat-v7:26.1.0.
    > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
          > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
                   > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                               > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                              > unable to find valid certification path to requested target
</code>```

Could somebody help me?

答:
Solved this by adding the self signed certificate of my company to the cacerts file of Android Studio. The cacerts file is located here: C:\Program Files\Android\Android Studio\jre\jre\lib\security\cacerts

I have also added the proxy details for http/https to gradle.properties.

Body:
I have created a new project in android studio 3.0.1 setup the proxy settings of company and added the self sighned certificate unser server sertificates. When I try to build the following error is listed and the build fails.

Error:

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support:appcompat-v7:26.1.0.
Required by:
    project :app
 > Could not resolve com.android.support:appcompat-v7:26.1.0.
    > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
          > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
                   > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                               > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                              > unable to find valid certification path to requested target

Could somebody help me?


问:
i have created mysql connection in nodejs it is showing database connected but showing an error as undefined database
var mysql = require('mysql');

var connection = mysql.createConnection({

```<code>host : 'localhost',
user : 'root',
port : '3306',
password : 'root',
database : 'test'
</code>```

});

connection.connect(function(err){

```<code>if(!err) {

    console.log("database is connected"+database);
} else {
    console.log("database is not connected"+err.message);
}
</code>```

});

this is the error i got

答:
Change your connect function to look like this: (Replacing function with fat arrow function "=>")

```<code>connection.connect((err) => {
    if (!err) {
        console.log("database is connected"+database);
    } else {
        console.log("database is not connected"+err.message);
    }
});
</code>```

This below link explains why:

What is the difference between () => {} and function() {} in react-native javascript?

Body:
var mysql = require('mysql');

var connection = mysql.createConnection({

host : 'localhost',
user : 'root',
port : '3306',
password : 'root',
database : 'test'

});

connection.connect(function(err){

if(!err) {

    console.log("database is connected"+database);
} else {
    console.log("database is not connected"+err.message);
}

});

this is the error i got

Body:
Change your connect function to look like this: (Replacing function with fat arrow function "=>")

connection.connect((err) => {
    if (!err) {
        console.log("database is connected"+database);
    } else {
        console.log("database is not connected"+err.message);
    }
});

This below link explains why:

What is the difference between () => {} and function() {} in react-native javascript?


问:
Python - Fill a table MSSQL with data from Excel
I have an xlsx file with 4 column and 68k+ lines. And i want to put all data in a table in MSSQL server. I made this.

```<code>def jb_treat_attributes(dicoval):
conn = pymssql.connect(dicoval['MSSQL_erver'],dicoval['MSSQL_Login'],dicoval['MSSQL_Password'],dicoval['MSSQL_Database_DELTA'])
    cursor = conn.cursor()
    cursor.execute('TRUNCATE TABLE delta.Attribute')
    for row in load_workbook(dicoval['path_root']+'Delta/attributes/excel.xlsx').worksheets[0].iter_rows():
        row = [cell.value.strip() if cell.value is not None else '' for cell in row]
        cursor.execute("INSERT INTO delta.Attribute VALUES (%s,%s,%s,%s)",(row[0],row[1],row[2],row[3]))
    conn.commit()
    conn.close()
</code>```

And it's working, but with 340s of execution time. Does it exist a way to do it faster ?

答:
How about calling python to execute .sql file directly?
You have a .sql file do the import excel to database like here https://learn.microsoft.com/en-us/sql/relational-databases/import-export/import-data-from-excel-to-sql</p>

Body:
I have an xlsx file with 4 column and 68k+ lines. And i want to put all data in a table in MSSQL server. I made this.

def jb_treat_attributes(dicoval):
conn = pymssql.connect(dicoval['MSSQL_erver'],dicoval['MSSQL_Login'],dicoval['MSSQL_Password'],dicoval['MSSQL_Database_DELTA'])
    cursor = conn.cursor()
    cursor.execute('TRUNCATE TABLE delta.Attribute')
    for row in load_workbook(dicoval['path_root']+'Delta/attributes/excel.xlsx').worksheets[0].iter_rows():
        row = [cell.value.strip() if cell.value is not None else '' for cell in row]
        cursor.execute("INSERT INTO delta.Attribute VALUES (%s,%s,%s,%s)",(row[0],row[1],row[2],row[3]))
    conn.commit()
    conn.close()

And it's working, but with 340s of execution time. Does it exist a way to do it faster ?


问:
SynchronousQueue in ThreadPoolExecutor
I'm trying to understand the behavior of queues in ThreadPoolExecutor. In the below program, when I use LinkedBlockingQueue, I can submit only one task to the thread pool at a time. But if I replace the LinkedBlockingQueue with SynchronousQueue, I could submit all the 5 tasks to the pool at an instant. How SynchronousQueue differs from LinkedBlockingQueue in this case ?

Java program :

```<code>import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Sample {
    public static void main(String[] args) throws InterruptedException {
        LinkedBlockingQueue<Runnable> threadPoolQueue = new LinkedBlockingQueue<>();
//      SynchronousQueue<Runnable> threadPoolQueue = new SynchronousQueue<>();
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, threadPoolQueue, threadFactory);
        Runnable np;

        for (int i = 1; i <= 5; i++) {
            np = new SampleWorker("ThreadPoolWorker " + i);
            tpe.submit(np);
        }

        System.out.println(tpe.getCorePoolSize());
        System.out.println(tpe.getPoolSize());
        System.out.println(tpe.getActiveCount());

        tpe.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        tpe.shutdown();
        System.out.println("Main task finished");
    }
}

class SampleWorker implements Runnable {
    private String workerName;

    SampleWorker(String tName) {
        workerName = tName;
    }

    @Override
    public void run() {
        try {
            for (int i = 1; i <= 10; i++) {
                Thread.sleep(3000);
                System.out.println(this.workerName);
            }
            System.out.println(this.workerName + " finished");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
</code>```

答:
When you submit a task to ThreadPoolExecutor, it works like this :

```<code>if (numberOfWorkingThreads < corePoolSize) {
   startNewThreadAndRunTask();
} else if (workQueue.offer(task)) {
   if (numberOfWorkingThreads == 0) {
       startNewThreadAndRunTask();
   }
} else if (numberOfWorkingThreads < maxPoolSize)
    startNewThreadAndRunTask();
} else {
    rejectTask();
}
</code>```

When using LinkedBlockingQueue with no initial value,
workQueue.offer(task) will always success, resulting only one
thread started.

When calling SynchronousQueue.offer(task), it successes only when
another thread is waiting to receive it. Since there is no waiting
thread, false will be returned and new thread is created every
time.

Title: SynchronousQueue in ThreadPoolExecutor

Body:
I'm trying to understand the behavior of queues in ThreadPoolExecutor. In the below program, when I use LinkedBlockingQueue, I can submit only one task to the thread pool at a time. But if I replace the LinkedBlockingQueue with SynchronousQueue, I could submit all the 5 tasks to the pool at an instant. How SynchronousQueue differs from LinkedBlockingQueue in this case ?

Java program :

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Sample {
    public static void main(String[] args) throws InterruptedException {
        LinkedBlockingQueue<Runnable> threadPoolQueue = new LinkedBlockingQueue<>();
//      SynchronousQueue<Runnable> threadPoolQueue = new SynchronousQueue<>();
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, threadPoolQueue, threadFactory);
        Runnable np;

        for (int i = 1; i <= 5; i++) {
            np = new SampleWorker("ThreadPoolWorker " + i);
            tpe.submit(np);
        }

        System.out.println(tpe.getCorePoolSize());
        System.out.println(tpe.getPoolSize());
        System.out.println(tpe.getActiveCount());

        tpe.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        tpe.shutdown();
        System.out.println("Main task finished");
    }
}

class SampleWorker implements Runnable {
    private String workerName;

    SampleWorker(String tName) {
        workerName = tName;
    }

    @Override
    public void run() {
        try {
            for (int i = 1; i <= 10; i++) {
                Thread.sleep(3000);
                System.out.println(this.workerName);
            }
            System.out.println(this.workerName + " finished");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Body:
When you submit a task to ThreadPoolExecutor, it works like this :

if (numberOfWorkingThreads < corePoolSize) {
   startNewThreadAndRunTask();
} else if (workQueue.offer(task)) {
   if (numberOfWorkingThreads == 0) {
       startNewThreadAndRunTask();
   }
} else if (numberOfWorkingThreads < maxPoolSize)
    startNewThreadAndRunTask();
} else {
    rejectTask();
}

When using LinkedBlockingQueue with no initial value,
workQueue.offer(task) will always success, resulting only one
thread started.

When calling SynchronousQueue.offer(task), it successes only when
another thread is waiting to receive it. Since there is no waiting
thread, false will be returned and new thread is created every
time.


问:
ListView item LongClick state for selector
On the default ListViews if you long press on an item the background fades from dark blue to light blue(on Galaxy Tab. Its orange to light orange on some other devices) during the time it takes to register a LongClick. I am assuming this is done somehow with a selector but thus far I've only seen how to use selectors for state:selected, state:focused, and state:pressed.

This page doesn't seem to show anything about a LongClick state so perhaps my assumption that this is accomplished with a selector is incorrect?

Can anyone fill me in on how the default ListView gets this effect and how I can apply it to other views?

答:
http://developer.android.com/guide/topics/ui/menus.html#context-menu

When the user performs a long-press on an item in a ListView and the list is registered to provide a context menu, the list item signals to the user that a context menu is available by animating its background color—it transitions from orange to white before opening the context menu. (The Contacts application demonstrates this feature.)

So its an animation that is used. I believe it uses the View's own default On...() methods to display it. You may need to worry about giving it clickable="true" or longClickable="true" attributes.


问:
Uncaught TypeError in getting json value
Below the code is working but I am getting

Uncaught TypeError: Cannot read property 'searchname' of undefined

Why am I getting this error message? I do not know how to resolve this issue.

var selectedVal = "calendar";
$.getJSON("/js/datas.json", function(jsonData) {
  for (var j = 0; j <= jsonData.nameSearch.length; j++) {
    if (jsonData.nameSearch[j].searchname == selectedVal) {
      var linkname = jsonData.nameSearch[j].namelink;
      alert(linkname);
    }
  }
});
```

<p>This is the JSON:</p>

```{
  "nameSearch": [{
    "searchname": "calendar",
    "namelink": "holidays"
  }, {
    "searchname": "date",
    "namelink": "kilo"
  }]
}
```

答:
You need to use < instead of <=.

Reason:-

Because jsonData.nameSearch indexs start from 0 like 0,1,.....so on

when you are using jsonData.nameSearch.length it gives you 2.

So loop will become:-

for (var j = 0; j <= 2; j++) {

but index 2  inside jsonData.nameSearch doesn't not exist at all. so you are getting error.

So the solution is removed = from loop like below:-

```<code>for (var j = 0; j < jsonData.nameSearch.length; j++)
</code>```

Body:
Below the code is working but I am getting

Uncaught TypeError: Cannot read property 'searchname' of undefined

Why am I getting this error message? I do not know how to resolve this issue.

var selectedVal = "calendar";
$.getJSON("/js/datas.json", function(jsonData) {
  for (var j = 0; j <= jsonData.nameSearch.length; j++) {
    if (jsonData.nameSearch[j].searchname == selectedVal) {
      var linkname = jsonData.nameSearch[j].namelink;
      alert(linkname);
    }
  }
});

This is the JSON:

{
  "nameSearch": [{
    "searchname": "calendar",
    "namelink": "holidays"
  }, {
    "searchname": "date",
    "namelink": "kilo"
  }]
}

Body:
You need to use < instead of <=.

Reason:-

Because jsonData.nameSearch indexs start from 0 like 0,1,.....so on

when you are using jsonData.nameSearch.length it gives you 2.

So loop will become:-

for (var j = 0; j <= 2; j++) {

but index 2  inside jsonData.nameSearch doesn't not exist at all. so you are getting error.

So the solution is removed = from loop like below:-

for (var j = 0; j < jsonData.nameSearch.length; j++)


答:
First Quick Thoughts: Use Begin Transaction to tell that you are adding inserts

Put this line before you start cursor.execute

```<code>cursor.begin()
</code>```

Packing Inserts:

There is no direct evidence, but packing values sometimes help uploading Inserts as a batch. (Which is basically what cursor.begin() is for.

I can't test it, but that's the idea. You collect your values all in a list of tuples and convert them to a string, which you finally execute it ones delivering all the Values

```<code>def jb_treat_attributes(dicoval):
    values = []
    conn = pymssql.connect(dicoval['MSSQL_erver'],dicoval['MSSQL_Login'],dicoval['MSSQL_Password'],dicoval['MSSQL_Database_DELTA'])
    cursor = conn.cursor()
    cursor.execute('TRUNCATE TABLE delta.Attribute')
    for row in load_workbook(dicoval['path_root']+'Delta/attributes/excel.xlsx').worksheets[0].iter_rows():
        row = [cell.value.strip() if cell.value is not None else '' for cell in row]
        values.append((row[0],row[1],row[2],row[3]))
    valueTuples = str(values)[1:-1]
    cursor.execute("INSERT INTO delta.Attribute VALUES " + valueTuples)
    conn.commit()
    conn.close()
</code>```

Title: Python - Fill a table MSSQL with data from Excel

Body:
First Quick Thoughts: Use Begin Transaction to tell that you are adding inserts

Put this line before you start cursor.execute

cursor.begin()

Packing Inserts:

There is no direct evidence, but packing values sometimes help uploading Inserts as a batch. (Which is basically what cursor.begin() is for.

I can't test it, but that's the idea. You collect your values all in a list of tuples and convert them to a string, which you finally execute it ones delivering all the Values

def jb_treat_attributes(dicoval):
    values = []
    conn = pymssql.connect(dicoval['MSSQL_erver'],dicoval['MSSQL_Login'],dicoval['MSSQL_Password'],dicoval['MSSQL_Database_DELTA'])
    cursor = conn.cursor()
    cursor.execute('TRUNCATE TABLE delta.Attribute')
    for row in load_workbook(dicoval['path_root']+'Delta/attributes/excel.xlsx').worksheets[0].iter_rows():
        row = [cell.value.strip() if cell.value is not None else '' for cell in row]
        values.append((row[0],row[1],row[2],row[3]))
    valueTuples = str(values)[1:-1]
    cursor.execute("INSERT INTO delta.Attribute VALUES " + valueTuples)
    conn.commit()
    conn.close()


问:
Is Minio supports MIME type check?
Is Minio supports MIME type check? For example, when uploading file user can specify what MIME type should be for this file. Than Minio analyzes this file and if it is a correct (e.g it's valid image) save, if not response with an error.</p>

答: Minio supports AWS S3 API which doesn't implement any MIME type based checking. But you can definitely set Content-Type of the object while uploading and it will be preserved by Minio. </p>

Title: Is Minio supports MIME type check?


问:
How do I fill a rectangle with the exception of a area
I am trying to fill a rectangle in a winforms application less a ellipse in the center that allows the image in the background to show through.

can anyone give me a hint on which way to go on this,

thanks.

this is what I have come up with so far:

```<code>  path.AddRectangle(new Rectangle(30, 30, 100, 100));
  path.AddEllipse(new Rectangle(50, 50, 60, 60));
  gfx.FillPath(new SolidBrush(Color.Black), path);
</code>```

答:
The easy way:

Fill the Reacngle first

Then Fill the Ellipse (with a Transparant brush)

Body:
I am trying to fill a rectangle in a winforms application less a ellipse in the center that allows the image in the background to show through.

can anyone give me a hint on which way to go on this,

thanks.

this is what I have come up with so far:

  path.AddRectangle(new Rectangle(30, 30, 100, 100));
  path.AddEllipse(new Rectangle(50, 50, 60, 60));
  gfx.FillPath(new SolidBrush(Color.Black), path);


问:
Docker Swarm Redis and Sentinel with master - slave replication IP resolution client failure
I am running into an issue and I am not sure how to resolve this.
My redis sentinel eco system is as follows:

3 sentinel cluster -->  Managing 1 master and 2 slaves using docker-compose

I have created a docker overlay network for the eco system and using docker stack deploy to run the docker compose yml.  The redis-cli on each node displays the correct INFO configuration.  However external clients are running into an issue.

When I supply the sentinel address to the client application (in my case it's a spring redis app)  I am getting the overlay network's internal IP address for the master redis.  This is not recognizable to the client and it fails.  How can I get an IP address that can be resolved externally?  Secondly is it even possible since docker swarm manages the IP addresses on the overlay network.  Is this the right approach i.e. using docker swarm?  Any feedback would be greatly appreciated.

```<code>version: '3'

services:
  redis-master:
    image: redis:latest
    volumes:
      - "/docker-service-data/master:/data"
      - /redis-docker/redis.conf:/etc/redis.conf
    command: redis-server /etc/redis.conf
    ports:
      - 6379:6379
    deploy:
      mode: replicated
      replicas: 1
      placement:
        constraints: [node.role == manager]
    networks:
       - rev_proxy
  redis-slave:
    image: redis:latest
    volumes:
      - "/docker-service-data/slave:/data"
      - /redis-docker/redis.conf:/etc/redis.conf
    command: redis-server /etc/redis.conf --slaveof redis-master 6379
    deploy:
      mode: replicated
      replicas: 2
      placement:
        constraints: [node.role == worker]
    networks:
       - rev_proxy
  sentinel_1:
    image: <private-registry>/redis-sentinel:1
    deploy:
      mode: replicated
      replicas: 3
    ports:
      - 26379:26379
    depends_on:
      - redis-master
    networks:
      - rev_proxy
networks:
  rev_proxy:
     external:
       name: rev_proxy_net
</code>```

redis.conf:

I have commented the bind statement so that the replica listens to all interfaces
protected mode is no
There is no authentication at this point.

sentinel.conf:

```<code>sentinel monitor master redis-master 6379 2
sentinel down-after-milliseconds master 1000
sentinel parallel-syncs master 1
sentinel failover-timeout master 1000
</code>```

答:
You might need version: '3.3' and endpoint_mode: vip option.
Refer to this link, https://docs.docker.com/compose/compose-file/#endpoint_mode

Body:
I am running into an issue and I am not sure how to resolve this.
My redis sentinel eco system is as follows:

3 sentinel cluster -->  Managing 1 master and 2 slaves using docker-compose

I have created a docker overlay network for the eco system and using docker stack deploy to run the docker compose yml.  The redis-cli on each node displays the correct INFO configuration.  However external clients are running into an issue.

When I supply the sentinel address to the client application (in my case it's a spring redis app)  I am getting the overlay network's internal IP address for the master redis.  This is not recognizable to the client and it fails.  How can I get an IP address that can be resolved externally?  Secondly is it even possible since docker swarm manages the IP addresses on the overlay network.  Is this the right approach i.e. using docker swarm?  Any feedback would be greatly appreciated.

version: '3'

services:
  redis-master:
    image: redis:latest
    volumes:
      - "/docker-service-data/master:/data"
      - /redis-docker/redis.conf:/etc/redis.conf
    command: redis-server /etc/redis.conf
    ports:
      - 6379:6379
    deploy:
      mode: replicated
      replicas: 1
      placement:
        constraints: [node.role == manager]
    networks:
       - rev_proxy
  redis-slave:
    image: redis:latest
    volumes:
      - "/docker-service-data/slave:/data"
      - /redis-docker/redis.conf:/etc/redis.conf
    command: redis-server /etc/redis.conf --slaveof redis-master 6379
    deploy:
      mode: replicated
      replicas: 2
      placement:
        constraints: [node.role == worker]
    networks:
       - rev_proxy
  sentinel_1:
    image: <private-registry>/redis-sentinel:1
    deploy:
      mode: replicated
      replicas: 3
    ports:
      - 26379:26379
    depends_on:
      - redis-master
    networks:
      - rev_proxy
networks:
  rev_proxy:
     external:
       name: rev_proxy_net

redis.conf:

I have commented the bind statement so that the replica listens to all interfaces
protected mode is no
There is no authentication at this point.

sentinel.conf:

sentinel monitor master redis-master 6379 2
sentinel down-after-milliseconds master 1000
sentinel parallel-syncs master 1
sentinel failover-timeout master 1000


问:
Android Run Service inside a Service for every 30 seconds?
I followed this to Run a Service for Every 5 Min

Till now Its working fine.. But I have added a Intent for Next service in TimeDisplay But its working fine only for the First Time But the second Activity is not running for Every 30 seconds...Its only Working on First Run..

this is MyService

```<code>    public class ServMain1 extends Service {

    private static final String TAG = "ServMain1";

    public static final int notify = 30000;
    private Handler mHandler = new Handler();
    private Timer mTimer = null;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Not yet implemented");
    }

   @Override
   public void onCreate() {

       if (mTimer != null) // Cancel if already existed
           mTimer.cancel();
       else
           mTimer = new Timer();   //recreate new
           mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);

   }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTimer.cancel();    //For Cancel Timer
        Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
    }

    //class TimeDisplay for handling task
    class **TimeDisplay** extends TimerTask {
        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // display toast
                    Toast.makeText(ServMain1.this, "ServMain1 : Service is running", Toast.LENGTH_SHORT).show();
                    startService(new Intent(ServMain1.this, ServMain2.class));
                }
            });
        }
    }
}
</code>```

Here at TimeDisplay I am using this to start second service startService(new Intent(ServMain1.this, ServMain2.class));

How ever I am getting Toast for Every 30 Seconds But Along with that toast I am using a intent is not working...

Its working only for the first time... but I am getting toast of every 30seconds

Can Any one suggest me How to using this kind of activity

答:
A service will only run once even after you call startService multiple times.

If you want to keep restarting the service in your handler, you need to first check if it already running, kill it if it is already running and call startService post that.

You can check if the service is running using

```<code>private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}
</code>```

And inside your handler make these changes

```<code>       mHandler.post(new Runnable() {
    @Override
    public void run() {
        // display toast
        Toast.makeText(ServMain1.this, "ServMain1 : Service is running", Toast.LENGTH_SHORT).show();
        if(!isMyServiceRunning(ServMain2.class)){

            startService(new Intent(ServMain1.this, ServMain2.class));
        } else{
            stopService(ServMain2.class);
            startService(new Intent(ServMain1.this, ServMain2.class));

        }

    }
});
</code>```

Body:
I followed this to Run a Service for Every 5 Min

Till now Its working fine.. But I have added a Intent for Next service in TimeDisplay But its working fine only for the First Time But the second Activity is not running for Every 30 seconds...Its only Working on First Run..

this is MyService

    public class ServMain1 extends Service {

    private static final String TAG = "ServMain1";

    public static final int notify = 30000;
    private Handler mHandler = new Handler();
    private Timer mTimer = null;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Not yet implemented");
    }

   @Override
   public void onCreate() {

       if (mTimer != null) // Cancel if already existed
           mTimer.cancel();
       else
           mTimer = new Timer();   //recreate new
           mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);

   }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTimer.cancel();    //For Cancel Timer
        Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
    }

    //class TimeDisplay for handling task
    class **TimeDisplay** extends TimerTask {
        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // display toast
                    Toast.makeText(ServMain1.this, "ServMain1 : Service is running", Toast.LENGTH_SHORT).show();
                    startService(new Intent(ServMain1.this, ServMain2.class));
                }
            });
        }
    }
}

Here at TimeDisplay I am using this to start second service startService(new Intent(ServMain1.this, ServMain2.class));

How ever I am getting Toast for Every 30 Seconds But Along with that toast I am using a intent is not working...

Its working only for the first time... but I am getting toast of every 30seconds

Can Any one suggest me How to using this kind of activity

Body:
A service will only run once even after you call startService multiple times.

If you want to keep restarting the service in your handler, you need to first check if it already running, kill it if it is already running and call startService post that.

You can check if the service is running using

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

And inside your handler make these changes

       mHandler.post(new Runnable() {
    @Override
    public void run() {
        // display toast
        Toast.makeText(ServMain1.this, "ServMain1 : Service is running", Toast.LENGTH_SHORT).show();
        if(!isMyServiceRunning(ServMain2.class)){

            startService(new Intent(ServMain1.this, ServMain2.class));
        } else{
            stopService(ServMain2.class);
            startService(new Intent(ServMain1.this, ServMain2.class));

        }

    }
});


问:
Android App Coded in Java using internet Call doesn't display data
I am writing an app for a course I'm taking online. The app is supposed to display data in a grid pattern that can be updated with the press of a button in the menu. I thought I finished writing the code and I ran the app but all I'm seeing is a white background and a menu option that I wrote in. I am removing the API code in the question, it is not missing in my code

Main Activity "Launcher Activity"

```<code>public class MainMenu extends AppCompatActivity {

MovieAdapter mV = new MovieAdapter(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);
    updateMovie();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if(id == R.id.action_refresh){
        updateMovie();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

void updateMovie(){
    FetchMovieTask movieTask = new FetchMovieTask();
    movieTask.execute();
}
@SuppressLint("StaticFieldLeak")
class FetchMovieTask extends AsyncTask<Void,Void,List<String>>{
    private final String LOG_TAG = FetchMovieTask.class.getSimpleName();

    @Override
    protected List<String> doInBackground(Void... params) {
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        String movieJsonStr;

        try{
            URL url = new URL("http://api.themoviedb.org/3/discover/movie?" +
                    "sort_by=popularity.desc&api_key=InsertAPIHERe");

            urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuilder buffer = new StringBuilder();
            if(inputStream == null){
                return null;
            }

            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while((line = reader.readLine())!= null){
                buffer.append(line).append("\n");
            }
            if(buffer.length() == 0){
                return null;
            }
            movieJsonStr = buffer.toString();
        }catch (IOException e){
            Log.e(LOG_TAG,"Error",e);
            return null;
        }finally {
            if(urlConnection != null){
                urlConnection.disconnect();
            }
            if(reader != null){
                try{
                    reader.close();
                }catch (final IOException e){
                    Log.e(LOG_TAG,"Error closing Stream",e);
                }
            }
        }
        try{
            return getMovieDataFromJson(movieJsonStr);
        }catch (JSONException j){
            Log.e(LOG_TAG,"JSON Error", j);
        }
        return null;
    }

    private List<String>getMovieDataFromJson(String mVJsonStr)
        throws JSONException{
        JSONObject movieJson = new JSONObject((mVJsonStr));
        JSONArray movieArray = movieJson.getJSONArray("results");
        List<String> urls = new ArrayList<>();
        for (int i = 0;i < movieArray.length();i++){
            JSONObject movie = movieArray.getJSONObject(i);
            urls.add("http://image.tmdb.org/t/p/w185" + movie.getString("poster_path"));
        }
        return urls;
    }

    @Override
    protected void onPostExecute(List<String> strings) {
        mV.replace(strings);
    }
}
</code>```

}

Grid View CLass

```<code>public class MovieFragment extends Fragment{

MovieAdapter mA = new MovieAdapter(getActivity());

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_movie,container,false);
    GridView mL = (GridView)rootView.findViewById(R.id.movie_grid);
    mL.setAdapter(mA);
    return rootView;
}
}
</code>```

The adapter class

```<code>public class MovieAdapter extends BaseAdapter{

private final String LOG_TAG = MovieAdapter.class.getSimpleName();
private final Context context;
private final List<String> urls = new ArrayList<String>();

MovieAdapter(Context context) {
    this.context = context;
    Collections.addAll(urls);
}

@Override
public int getCount() {
    return urls.size();
}

@Override
public Object getItem(int position) {
    return urls.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null){
        convertView = new ImageView(context);
    }
    ImageView iV = (ImageView)convertView;

    String url = (String) getItem(position);

    Log.e(LOG_TAG,"URL" + url);
    Picasso.with(context).load(url).into(iV);
    return convertView;
}

void replace(List<String> urls){
    this.urls.clear();
    this.urls.addAll(urls);
    notifyDataSetChanged();
}
</code>```

}

With these three classes I thought I had everything I needed for the app to work but it didn't. Am I missing a piece of code to connect the inflowing information to the grid view or is there just a flaw in my logic?

There aren't any error messages, the app is functioning but there are no functions.

Edit

activity_main_xml

```<code> <fragment
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/fragment"
        android:name="com.example.djadu.discovermovies.MovieFragment"
        tools:layout="@layout/fragment_movie"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true" />
</code>```

Fragment_movie

```<code><?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/movie_grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    tools:context=".MovieFragment"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp">
</GridView>
</code>```

答:
There can be several reasons. The most obvious is that you use different instances of the MovieAdapter in MainMenu and MovieFragment classes. You makes request and sets data to adapter inside MainMenu, but to GridView attached another instance of MovieAdapter created inside MovieFragment. If you want to control MovieAdapter inside MainMenu you need to share it with MovieFragment.

MainMenu class

```<code>...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);
    ((MyFragment) getFragmentManager().findFragmentById(R.id.fragment)).setAdapter(mV);
    updateMovie();
}
...
</code>```

MovieFragment class

```<code>...
GridView mGridView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_movie, container, false);
    mGridView = view.findViewById(R.id.movie_grid);
    return view;
}

public void setAdapter(BaseAdapter adapter) {
    mGridView.setAdapter(adapter);
}
...
</code>```

Body:
I am writing an app for a course I'm taking online. The app is supposed to display data in a grid pattern that can be updated with the press of a button in the menu. I thought I finished writing the code and I ran the app but all I'm seeing is a white background and a menu option that I wrote in. I am removing the API code in the question, it is not missing in my code

Main Activity "Launcher Activity"

public class MainMenu extends AppCompatActivity {

MovieAdapter mV = new MovieAdapter(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);
    updateMovie();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if(id == R.id.action_refresh){
        updateMovie();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

void updateMovie(){
    FetchMovieTask movieTask = new FetchMovieTask();
    movieTask.execute();
}
@SuppressLint("StaticFieldLeak")
class FetchMovieTask extends AsyncTask<Void,Void,List<String>>{
    private final String LOG_TAG = FetchMovieTask.class.getSimpleName();

    @Override
    protected List<String> doInBackground(Void... params) {
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        String movieJsonStr;

        try{
            URL url = new URL("http://api.themoviedb.org/3/discover/movie?" +
                    "sort_by=popularity.desc&api_key=InsertAPIHERe");

            urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuilder buffer = new StringBuilder();
            if(inputStream == null){
                return null;
            }

            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while((line = reader.readLine())!= null){
                buffer.append(line).append("\n");
            }
            if(buffer.length() == 0){
                return null;
            }
            movieJsonStr = buffer.toString();
        }catch (IOException e){
            Log.e(LOG_TAG,"Error",e);
            return null;
        }finally {
            if(urlConnection != null){
                urlConnection.disconnect();
            }
            if(reader != null){
                try{
                    reader.close();
                }catch (final IOException e){
                    Log.e(LOG_TAG,"Error closing Stream",e);
                }
            }
        }
        try{
            return getMovieDataFromJson(movieJsonStr);
        }catch (JSONException j){
            Log.e(LOG_TAG,"JSON Error", j);
        }
        return null;
    }

    private List<String>getMovieDataFromJson(String mVJsonStr)
        throws JSONException{
        JSONObject movieJson = new JSONObject((mVJsonStr));
        JSONArray movieArray = movieJson.getJSONArray("results");
        List<String> urls = new ArrayList<>();
        for (int i = 0;i < movieArray.length();i++){
            JSONObject movie = movieArray.getJSONObject(i);
            urls.add("http://image.tmdb.org/t/p/w185" + movie.getString("poster_path"));
        }
        return urls;
    }

    @Override
    protected void onPostExecute(List<String> strings) {
        mV.replace(strings);
    }
}

}

Grid View CLass

public class MovieFragment extends Fragment{

MovieAdapter mA = new MovieAdapter(getActivity());

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_movie,container,false);
    GridView mL = (GridView)rootView.findViewById(R.id.movie_grid);
    mL.setAdapter(mA);
    return rootView;
}
}

The adapter class

public class MovieAdapter extends BaseAdapter{

private final String LOG_TAG = MovieAdapter.class.getSimpleName();
private final Context context;
private final List<String> urls = new ArrayList<String>();

MovieAdapter(Context context) {
    this.context = context;
    Collections.addAll(urls);
}

@Override
public int getCount() {
    return urls.size();
}

@Override
public Object getItem(int position) {
    return urls.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null){
        convertView = new ImageView(context);
    }
    ImageView iV = (ImageView)convertView;

    String url = (String) getItem(position);

    Log.e(LOG_TAG,"URL" + url);
    Picasso.with(context).load(url).into(iV);
    return convertView;
}

void replace(List<String> urls){
    this.urls.clear();
    this.urls.addAll(urls);
    notifyDataSetChanged();
}

}

With these three classes I thought I had everything I needed for the app to work but it didn't. Am I missing a piece of code to connect the inflowing information to the grid view or is there just a flaw in my logic?

There aren't any error messages, the app is functioning but there are no functions.

Edit

activity_main_xml

 <fragment
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/fragment"
        android:name="com.example.djadu.discovermovies.MovieFragment"
        tools:layout="@layout/fragment_movie"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true" />

Fragment_movie

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/movie_grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    tools:context=".MovieFragment"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp">
</GridView>

Body:
There can be several reasons. The most obvious is that you use different instances of the MovieAdapter in MainMenu and MovieFragment classes. You makes request and sets data to adapter inside MainMenu, but to GridView attached another instance of MovieAdapter created inside MovieFragment. If you want to control MovieAdapter inside MainMenu you need to share it with MovieFragment.

MainMenu class

...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);
    ((MyFragment) getFragmentManager().findFragmentById(R.id.fragment)).setAdapter(mV);
    updateMovie();
}
...

MovieFragment class

...
GridView mGridView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_movie, container, false);
    mGridView = view.findViewById(R.id.movie_grid);
    return view;
}

public void setAdapter(BaseAdapter adapter) {
    mGridView.setAdapter(adapter);
}
...


问:
dynamically update comments next to pivot table
I have a pivot table which shows a list of products. Each product shows info such as current stock level, current demand for that product, etc.
What I would like to do is to make notes next to that overview (so outside of the pivot table) for each product stating for example the reason why stock is low for a certain product, what we will do about it and who will be responsible for that (3 columns).

However I would like to have these comments "linked" to each product. Meaning, if I adjust the filter in the pivot table, that the comments I just wrote, shift to the right product line in the pivot. The comments which are not relevant to the current filter selection should not be lost, but should appear whenever the linked product pops up again in the pivot table.

Any ideas?

Thanks!

答: Store comments in the separate sheet, in a table containing product names in the first column and comments in the following. Then use VLOOKUP to display comments in right places next to the pivot table. Turn off Generate GetPivotData from the pivot table options before you construct relevant VLOOKUP formula. </p>